@exulu/backend 5.12.0 → 5.13.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 {
2
2
  SandboxManager,
3
3
  type SandboxRuntimeConfig,
4
4
  } from '@anthropic-ai/sandbox-runtime'
5
- import { mkdir, rm, writeFile, readFile as fsReadFile, readdir, stat } from 'node:fs/promises'
5
+ import { mkdir, rm, readdir, stat, lstat } from 'node:fs/promises'
6
6
  import { existsSync } from 'node:fs'
7
7
  import { join, dirname, resolve, relative, posix } from 'node:path'
8
8
  import { exec, spawn } from 'node:child_process'
@@ -23,6 +23,10 @@ import { z } from "zod";
23
23
  import { type Variable } from "@EXULU_TYPES/models/variable";
24
24
  import CryptoJS from "crypto-js";
25
25
  import { postgresClient } from "@SRC/postgres/client";
26
+ import { PROJECT_DIR } from "@SRC/exulu/project-files.ts";
27
+ import { ORIGIN_METADATA_KEY } from "@SRC/exulu/file-origin.ts";
28
+ import { syncProjectDir, clearProjectSyncMarker } from "./project-sync";
29
+ import { readRegularFileInside, writeFileInside, ensureRealDirectory, removeEntryInside, UnsafeSessionPathError } from "./safe-fs";
26
30
 
27
31
  /**
28
32
  * Load the variables an administrator has explicitly granted to the skill
@@ -212,10 +216,20 @@ export interface SessionSandboxHandle {
212
216
  cleanup: () => Promise<void>
213
217
  }
214
218
 
219
+ /**
220
+ * Per-sandbox, mutable: the cached sandbox outlives a turn, and the session's
221
+ * project can change between turns (detach, re-attach, access revoked). The
222
+ * write-back closures read it at call time, so it must not be captured once.
223
+ */
224
+ interface ProjectState {
225
+ projectId: string | null
226
+ }
227
+
215
228
  interface CachedSandbox {
216
229
  handle: SessionSandboxHandle
217
230
  /** skill id -> installed version */
218
231
  installedSkills: Map<string, number>
232
+ projectState: ProjectState
219
233
  }
220
234
 
221
235
  const sandboxCache = new Map<string, CachedSandbox>()
@@ -248,6 +262,11 @@ async function downloadSkill(
248
262
  );
249
263
  }
250
264
 
265
+ // The agent can replace skills/ or skills/<name> with a link; make both real
266
+ // directories again (a link is unlinked, never followed) before writing.
267
+ const sessionDir = dirname(skillsDirectory)
268
+ await ensureRealDirectory(sessionDir, `skills/${skill.name}`)
269
+
251
270
  for (const file of files) {
252
271
  // Extract the path relative to the version prefix, accounting for any S3 general prefix
253
272
  const prefixIndex = file.key.indexOf(versionPrefix)
@@ -257,30 +276,72 @@ async function downloadSkill(
257
276
 
258
277
  if (!relativePath) continue // skip directory markers
259
278
 
260
- const localPath = join(skillsDirectory, skill.name, relativePath)
261
- await mkdir(dirname(localPath), { recursive: true })
262
-
263
279
  // Binary-safe download — skill bundles can ship images, fonts, and
264
280
  // other non-text assets alongside the SKILL.md / scripts.
265
281
  const bytes = await getS3ObjectBytes(file.key, config)
266
- await writeFile(localPath, bytes)
282
+ try {
283
+ await writeFileInside(sessionDir, `skills/${skill.name}/${relativePath}`, bytes)
284
+ } catch (err) {
285
+ if (!(err instanceof UnsafeSessionPathError)) throw err
286
+ console.error(`[SKILLS] Skipping skill file ${file.key}: ${err.message}`)
287
+ }
267
288
  }
268
289
  }
269
290
 
291
+ /**
292
+ * Remove an installed skill's folder before it is reinstalled. skills/ itself is
293
+ * made a real directory first, so the removal never runs through a link.
294
+ */
295
+ async function removeInstalledSkill(skillsDirectory: string, skillName: string): Promise<void> {
296
+ const sessionDir = dirname(skillsDirectory)
297
+ await ensureRealDirectory(sessionDir, 'skills')
298
+ await removeEntryInside(sessionDir, `skills/${skillName}`)
299
+ }
300
+
270
301
  /**
271
302
  * A file written inside the sandbox qualifies as a session artifact iff it lives
272
303
  * under sessionDir but NOT under sessionDir/skills/. Skill source files are
273
304
  * authored elsewhere and should never be mirrored back to the per-session
274
- * artifact tree.
305
+ * artifact tree. In a project session `project/` is the read-only copy of the
306
+ * project's shared files and is never written back either; without a project
307
+ * the name has no special meaning.
275
308
  */
276
- function isArtifactPath(absPath: string, sessionDir: string): boolean {
309
+ export function isArtifactPath(
310
+ absPath: string,
311
+ sessionDir: string,
312
+ opts: { hasProject?: boolean } = {},
313
+ ): boolean {
277
314
  const resolved = resolve(absPath)
278
315
  const rel = relative(sessionDir, resolved)
279
316
  if (!rel || rel.startsWith('..')) return false
280
317
  const first = rel.split('/')[0]
318
+ if (opts.hasProject && first === PROJECT_DIR) return false
281
319
  return first !== 'skills'
282
320
  }
283
321
 
322
+ /**
323
+ * Upload a file the agent produced in its sandbox. The origin marker is what the
324
+ * file lists use to badge agent-made files; only this path sets it, so user
325
+ * uploads (which go through other uploadFile callers) stay unmarked.
326
+ */
327
+ export async function uploadAgentArtifact(
328
+ content: Buffer,
329
+ s3Key: string,
330
+ config: ExuluConfig,
331
+ userId: number | string | undefined,
332
+ ): Promise<string> {
333
+ return uploadFile(
334
+ content,
335
+ s3Key,
336
+ config,
337
+ { metadata: { [ORIGIN_METADATA_KEY]: 'agent' } },
338
+ // uploadFile's user param is typed as number, but the
339
+ // addUserPrefixToKey helper it delegates to accepts
340
+ // number | string at runtime — pass through as-is.
341
+ userId as unknown as number,
342
+ )
343
+ }
344
+
284
345
  function artifactS3Key(sessionId: string, relPath: string): string {
285
346
  return `sessions/${sessionId}/${relPath}`
286
347
  }
@@ -330,7 +391,7 @@ async function restoreArtifactsFromS3(
330
391
  sessionId: string,
331
392
  userId: number | string,
332
393
  config: ExuluConfig,
333
- opts: { onlyMissing?: boolean } = {},
394
+ opts: { onlyMissing?: boolean; skipProjectDir?: boolean } = {},
334
395
  ): Promise<void> {
335
396
  const userPrefix = `user_${userId}/sessions/${sessionId}/`
336
397
  let objects: S3FileObject[]
@@ -359,12 +420,19 @@ async function restoreArtifactsFromS3(
359
420
  const relativePath = idx >= 0 ? obj.key.slice(idx + userPrefix.length) : ''
360
421
  if (!relativePath) continue // directory marker or unexpected key shape
361
422
  if (isIgnoredArtifactPath(relativePath)) continue // never pull dependency trees back
423
+ // In a project session project/ belongs to the project sync; a session file
424
+ // under that name (written before the session joined a project) would
425
+ // otherwise be pulled in and removed again on every turn.
426
+ if (opts.skipProjectDir && relativePath.split('/')[0] === PROJECT_DIR) continue
362
427
 
363
428
  const localPath = join(sessionDir, relativePath)
364
429
  if (opts.onlyMissing) {
365
430
  let localSize: number | undefined
366
431
  try {
367
- localSize = (await stat(localPath)).size
432
+ // lstat: a link the agent planted counts as missing (the write below
433
+ // replaces it) instead of reporting the size of whatever it points at.
434
+ const st = await lstat(localPath)
435
+ localSize = st.isFile() ? st.size : undefined
368
436
  } catch {
369
437
  localSize = undefined
370
438
  }
@@ -375,8 +443,8 @@ async function restoreArtifactsFromS3(
375
443
  // and other binary formats (from user uploads as well as agent
376
444
  // bash-produced files). Reading as utf-8 would corrupt these.
377
445
  const bytes = await getS3ObjectBytes(obj.key, config)
378
- await mkdir(dirname(localPath), { recursive: true })
379
- await writeFile(localPath, bytes)
446
+ // Never writeFile into the agent-writable tree: it would follow links.
447
+ await writeFileInside(sessionDir, relativePath, bytes)
380
448
  } catch (err) {
381
449
  console.error(
382
450
  `[SKILLS] Failed to restore artifact ${obj.key} -> ${localPath}; continuing.`,
@@ -425,11 +493,9 @@ export async function downloadKeyIntoSandbox(opts: {
425
493
  const relativePath = fullS3Key.slice(idx + userPrefix.length)
426
494
  if (!relativePath) return { written: false } // directory marker
427
495
 
428
- const localPath = join(sessionDir, relativePath)
429
-
430
496
  const bytes = await getS3ObjectBytes(fullS3Key, config)
431
- await mkdir(dirname(localPath), { recursive: true })
432
- await writeFile(localPath, bytes)
497
+ // Refuses ".." in the key suffix and never writes through an agent-planted link.
498
+ const localPath = await writeFileInside(sessionDir, relativePath, bytes)
433
499
 
434
500
  return { written: true, localPath }
435
501
  }
@@ -481,7 +547,7 @@ export async function refreshSessionSkills(
481
547
  const skillsDirectory = join(cached.handle.sessionDir, 'skills')
482
548
  let refreshed = 0
483
549
  for (const skill of skills) {
484
- await rm(join(skillsDirectory, skill.name), { recursive: true, force: true })
550
+ await removeInstalledSkill(skillsDirectory, skill.name)
485
551
  await downloadSkill(skill, skillsDirectory, config)
486
552
  cached.installedSkills.set(skill.id, skill.current_version)
487
553
  refreshed++
@@ -500,10 +566,29 @@ export async function createSessionSandbox(
500
566
  * callers outside the agent loop are unaffected.
501
567
  */
502
568
  agent?: { id?: string; name?: string; slug?: string },
569
+ opts: {
570
+ /**
571
+ * The session's project, already checked by the caller (session owner has
572
+ * read access); null/absent = no project. Applied on every call, cache hit
573
+ * included, because it can change between turns.
574
+ */
575
+ projectId?: string | null
576
+ } = {},
503
577
  ): Promise<SessionSandboxHandle> {
504
578
  const cached = sandboxCache.get(sessionId)
579
+ const projectId = opts.projectId ?? null
580
+
581
+ // After the session restore, so project/ wins over anything else of that name.
582
+ const syncProject = async (dir: string) => {
583
+ try {
584
+ await syncProjectDir({ sessionDir: dir, projectId, config })
585
+ } catch (err) {
586
+ console.error(`[SKILLS] Failed to sync project files into session ${sessionId}; continuing.`, err)
587
+ }
588
+ }
505
589
 
506
590
  if (cached) {
591
+ cached.projectState.projectId = projectId
507
592
  const skillsDirectory = join(cached.handle.sessionDir, 'skills')
508
593
 
509
594
  for (const skill of skills) {
@@ -512,7 +597,7 @@ export async function createSessionSandbox(
512
597
 
513
598
  if (installedVersion !== undefined) {
514
599
  // Different version installed — remove old files to avoid stale state
515
- await rm(join(skillsDirectory, skill.name), { recursive: true, force: true })
600
+ await removeInstalledSkill(skillsDirectory, skill.name)
516
601
  }
517
602
 
518
603
  await downloadSkill(skill, skillsDirectory, config)
@@ -524,11 +609,15 @@ export async function createSessionSandbox(
524
609
  // `ls` never sees them although the system prompt promises it will.
525
610
  if (userId && config.fileUploads) {
526
611
  try {
527
- await restoreArtifactsFromS3(cached.handle.sessionDir, sessionId, userId, config, { onlyMissing: true })
612
+ await restoreArtifactsFromS3(cached.handle.sessionDir, sessionId, userId, config, {
613
+ onlyMissing: true,
614
+ skipProjectDir: projectId !== null,
615
+ })
528
616
  } catch (err) {
529
617
  console.error(`[SKILLS] Failed to re-sync S3 session files for session ${sessionId}; continuing.`, err)
530
618
  }
531
619
  }
620
+ await syncProject(cached.handle.sessionDir)
532
621
  return cached.handle
533
622
  }
534
623
 
@@ -566,8 +655,14 @@ export async function createSessionSandbox(
566
655
  // unsaved-to-S3 writes from a prior process.
567
656
  if (userId && config.fileUploads) {
568
657
  // Cold start restores everything; a surviving on-disk dir only fetches what changed.
569
- await restoreArtifactsFromS3(sessionDir, sessionId, userId, config, { onlyMissing: dirExisted })
658
+ await restoreArtifactsFromS3(sessionDir, sessionId, userId, config, {
659
+ onlyMissing: dirExisted,
660
+ skipProjectDir: projectId !== null,
661
+ })
570
662
  }
663
+ await syncProject(sessionDir)
664
+
665
+ const projectState: ProjectState = { projectId }
571
666
 
572
667
  // Probe whether bwrap can actually create namespaces on this host. On a
573
668
  // failure, either throw (strict mode) or degrade to direct exec.
@@ -839,27 +934,27 @@ export async function createSessionSandbox(
839
934
  * bash wrapper (which scans for files the agent created via shell
840
935
  * commands like `node create_doc.js`).
841
936
  */
937
+ // Callers read this ONCE at the start of a tool call and pass it down: a
938
+ // concurrent detach can flip projectState mid-command, before its sync has
939
+ // removed project/, and a flag re-read in between would upload the project
940
+ // copy to the session as agent files. The reverse (an attach mid-command,
941
+ // whose sync writes project/ while the command runs) is covered by also
942
+ // checking the flag after the command: project/ is skipped if EITHER says so.
943
+ const hasProjectNow = () => projectState.projectId !== null
944
+
842
945
  async function persistArtifactToS3(
843
946
  absPath: string,
844
947
  content: Buffer,
948
+ hasProject: boolean,
845
949
  ): Promise<{ key?: string; url?: string }> {
846
- if (!persistenceEnabled || !isArtifactPath(absPath, sessionDir)) {
950
+ if (!persistenceEnabled || !isArtifactPath(absPath, sessionDir, { hasProject })) {
847
951
  return {}
848
952
  }
849
953
  const rel = relative(sessionDir, resolve(absPath))
850
954
  const s3Key = artifactS3Key(sessionId, rel)
851
955
  const out: { key?: string; url?: string } = {}
852
956
  try {
853
- const fullKey = await uploadFile(
854
- content,
855
- s3Key,
856
- config,
857
- {},
858
- // uploadFile's user param is typed as number, but the
859
- // addUserPrefixToKey helper it delegates to accepts
860
- // number | string at runtime — pass through as-is.
861
- userId as unknown as number,
862
- )
957
+ const fullKey = await uploadAgentArtifact(content, s3Key, config, userId)
863
958
  out.key = fullKey
864
959
  // uploadFile returns "<bucket>/<key>" — split to call
865
960
  // getPresignedUrl, which expects bucket and key separately.
@@ -887,6 +982,7 @@ export async function createSessionSandbox(
887
982
 
888
983
  async function writeFilesInternal(
889
984
  files: Array<{ path: string; content: string | Buffer }>,
985
+ hasProject: boolean = hasProjectNow(),
890
986
  ): Promise<WriteResult[]> {
891
987
  const results: WriteResult[] = []
892
988
 
@@ -916,6 +1012,7 @@ export async function createSessionSandbox(
916
1012
  const persisted = await persistArtifactToS3(
917
1013
  file.path,
918
1014
  Buffer.isBuffer(file.content) ? file.content : Buffer.from(file.content),
1015
+ hasProject || hasProjectNow(),
919
1016
  )
920
1017
  if (persisted.key) result.key = persisted.key
921
1018
  if (persisted.url) result.url = persisted.url
@@ -933,9 +1030,10 @@ export async function createSessionSandbox(
933
1030
  * does. The skills/ subdir is excluded — those are source-of-truth from
934
1031
  * S3 and shouldn't round-trip back as artifacts.
935
1032
  */
936
- async function snapshotSessionArtifacts(): Promise<Map<string, number>> {
1033
+ async function snapshotSessionArtifacts(hasProject: boolean): Promise<Map<string, number>> {
937
1034
  const map = new Map<string, number>()
938
1035
  const skillsDir = join(sessionDir, 'skills')
1036
+ const projectDir = hasProject ? join(sessionDir, PROJECT_DIR) : null
939
1037
  const walk = async (dir: string): Promise<void> => {
940
1038
  let entries
941
1039
  try {
@@ -946,6 +1044,7 @@ export async function createSessionSandbox(
946
1044
  for (const entry of entries) {
947
1045
  const full = join(dir, entry.name)
948
1046
  if (full === skillsDir) continue
1047
+ if (projectDir !== null && full === projectDir) continue
949
1048
  if (isIgnoredArtifactPath(relative(sessionDir, full))) continue
950
1049
  if (entry.isDirectory()) {
951
1050
  await walk(full)
@@ -992,8 +1091,9 @@ export async function createSessionSandbox(
992
1091
  content: z.string().describe('The content to write to the file'),
993
1092
  }),
994
1093
  execute: async ({ path, content }) => {
1094
+ const hasProject = hasProjectNow()
995
1095
  const resolvedPath = resolveSessionPath(path, sessionDir)
996
- const results = await writeFilesInternal([{ path: resolvedPath, content }])
1096
+ const results = await writeFilesInternal([{ path: resolvedPath, content }], hasProject)
997
1097
  const result = results[0]
998
1098
  if (!result) {
999
1099
  // writeFilesInternal always returns one entry per input file;
@@ -1062,8 +1162,10 @@ export async function createSessionSandbox(
1062
1162
  command: z.string().describe('The bash command to execute.'),
1063
1163
  }),
1064
1164
  execute: async (args, opts) => {
1165
+ // Fixed for this command: both snapshots and the persist check use it.
1166
+ const hasProject = hasProjectNow()
1065
1167
  const before = persistenceEnabled
1066
- ? await snapshotSessionArtifacts()
1168
+ ? await snapshotSessionArtifacts(hasProject)
1067
1169
  : null
1068
1170
  // Defer to bash-tool's bash tool so we keep its truncation, cwd
1069
1171
  // pinning, and any future bash-tool behaviour for free.
@@ -1085,7 +1187,9 @@ export async function createSessionSandbox(
1085
1187
  url?: string
1086
1188
  }> = []
1087
1189
  if (persistenceEnabled && before) {
1088
- const after = await snapshotSessionArtifacts()
1190
+ // Read once more after the command (see hasProjectNow).
1191
+ const skipProject = hasProject || hasProjectNow()
1192
+ const after = await snapshotSessionArtifacts(skipProject)
1089
1193
  const changedPaths: string[] = []
1090
1194
  for (const [path, mtime] of after) {
1091
1195
  const beforeMtime = before.get(path)
@@ -1095,8 +1199,12 @@ export async function createSessionSandbox(
1095
1199
  }
1096
1200
  for (const path of changedPaths) {
1097
1201
  try {
1098
- const content = await fsReadFile(path)
1099
- const persisted = await persistArtifactToS3(path, content)
1202
+ // Never fsReadFile here: the agent may have swapped the file (or a
1203
+ // parent directory) for a link to something the sandbox denies,
1204
+ // and this read runs with the backend's rights.
1205
+ const content = await readRegularFileInside(sessionDir, path)
1206
+ if (content === null) continue
1207
+ const persisted = await persistArtifactToS3(path, content, skipProject)
1100
1208
  artifacts.push({
1101
1209
  path,
1102
1210
  relativePath: relative(sessionDir, path),
@@ -1153,10 +1261,11 @@ export async function createSessionSandbox(
1153
1261
  await SandboxManager.reset()
1154
1262
  }
1155
1263
  await rm(sessionDir, { recursive: true, force: true })
1264
+ await clearProjectSyncMarker(sessionDir)
1156
1265
  },
1157
1266
  }
1158
1267
 
1159
- sandboxCache.set(sessionId, { handle, installedSkills })
1268
+ sandboxCache.set(sessionId, { handle, installedSkills, projectState })
1160
1269
 
1161
1270
  return handle
1162
1271
  }