@exulu/backend 5.14.0 → 5.15.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.
- package/dist/{chunk-QU67ANL5.js → chunk-S4UXKMN5.js} +2148 -1397
- package/dist/{convert-exulu-tools-to-ai-sdk-tools-UT7TOLLD.js → convert-exulu-tools-to-ai-sdk-tools-GLRM3PM6.js} +1 -1
- package/dist/index.cjs +1972 -1157
- package/dist/index.js +20 -3
- package/ee/invoke-skills/artifact-filter.test.ts +42 -1
- package/ee/invoke-skills/artifact-filter.ts +37 -0
- package/ee/invoke-skills/create-sandbox.env.test.ts +7 -1
- package/ee/invoke-skills/create-sandbox.readonly-skills.sandbox.test.ts +221 -0
- package/ee/invoke-skills/create-sandbox.readonly-skills.test.ts +290 -0
- package/ee/invoke-skills/create-sandbox.run-command.test.ts +135 -0
- package/ee/invoke-skills/create-sandbox.skill-actions.test.ts +176 -0
- package/ee/invoke-skills/create-sandbox.ts +268 -88
- package/ee/invoke-skills/safe-fs.test.ts +59 -1
- package/ee/invoke-skills/safe-fs.ts +61 -2
- package/ee/invoke-skills/skill-actions/load.test.ts +88 -0
- package/ee/invoke-skills/skill-actions/load.ts +107 -0
- package/ee/invoke-skills/skill-actions/schema.test.ts +72 -0
- package/ee/invoke-skills/skill-actions/schema.ts +97 -0
- package/ee/invoke-skills/skill-actions/tool.test.ts +464 -0
- package/ee/invoke-skills/skill-actions/tool.ts +415 -0
- package/package.json +2 -1
|
@@ -8,9 +8,11 @@ import { join, dirname, resolve, relative, posix } from 'node:path'
|
|
|
8
8
|
import { exec, spawn } from 'node:child_process'
|
|
9
9
|
import { promisify } from 'node:util'
|
|
10
10
|
import { listS3ObjectsByPrefix, getS3ObjectBytes, uploadFile, getPresignedUrl, type S3FileObject } from '@SRC/uppy/index.ts'
|
|
11
|
-
import { isIgnoredArtifactPath, capArtifacts, needsDownload } from './artifact-filter'
|
|
11
|
+
import { isIgnoredArtifactPath, isActionInputsPath, capArtifacts, needsDownload, appendArtifactsBlock } from './artifact-filter'
|
|
12
12
|
import { getNpmGlobalRoot } from '@SRC/exulu/system-dependencies.ts'
|
|
13
13
|
import { buildSkillEnv } from './skill-env'
|
|
14
|
+
import { declarationFromBytes, type PinnedSkillActions } from './skill-actions/load'
|
|
15
|
+
import { ACTIONS_FILE } from './skill-actions/schema'
|
|
14
16
|
import { isBinaryDocumentPath, looksBinary, binaryReadHint } from './binary-file-guard'
|
|
15
17
|
import { selectGrantedVariables, selectRowsToDecrypt, deriveWithheldNames } from './variable-grants'
|
|
16
18
|
import { readLiteLLMOsEnvironNames } from '@SRC/exulu/litellm/os-environ-names'
|
|
@@ -26,7 +28,7 @@ import { postgresClient } from "@SRC/postgres/client";
|
|
|
26
28
|
import { PROJECT_DIR } from "@SRC/exulu/project-files.ts";
|
|
27
29
|
import { ORIGIN_METADATA_KEY } from "@SRC/exulu/file-origin.ts";
|
|
28
30
|
import { syncProjectDir, clearProjectSyncMarker } from "./project-sync";
|
|
29
|
-
import { readRegularFileInside, writeFileInside, ensureRealDirectory, removeEntryInside, UnsafeSessionPathError } from "./safe-fs";
|
|
31
|
+
import { readRegularFileInside, writeFileInside, ensureRealDirectory, removeEntryInside, landsInside, UnsafeSessionPathError } from "./safe-fs";
|
|
30
32
|
|
|
31
33
|
/**
|
|
32
34
|
* Load the variables an administrator has explicitly granted to the skill
|
|
@@ -212,6 +214,31 @@ export interface SessionSandboxHandle {
|
|
|
212
214
|
tools: Record<string, Tool<any, any>>
|
|
213
215
|
/** Wraps a shell command string so it runs inside the sandbox. */
|
|
214
216
|
wrapCommand: (command: string) => Promise<string>
|
|
217
|
+
/**
|
|
218
|
+
* Runs a shell command in the session sandbox (same wrapping, cwd = sessionDir) with
|
|
219
|
+
* `extraEnv` merged over the session env for this call only. A timeout kills the whole
|
|
220
|
+
* process group (timedOut = true, exitCode 124). Files the command creates are mirrored
|
|
221
|
+
* and listed in an [exulu-artifacts] block appended to stdout, exactly as `bash` does.
|
|
222
|
+
*/
|
|
223
|
+
runCommand: (
|
|
224
|
+
command: string,
|
|
225
|
+
options?: { extraEnv?: Record<string, string>; timeoutMs?: number },
|
|
226
|
+
) => Promise<{
|
|
227
|
+
stdout: string
|
|
228
|
+
stderr: string
|
|
229
|
+
exitCode: number
|
|
230
|
+
timedOut: boolean
|
|
231
|
+
artifacts: Array<{ path: string; relativePath: string; key?: string; url?: string }>
|
|
232
|
+
artifactsOmitted?: number
|
|
233
|
+
}>
|
|
234
|
+
/**
|
|
235
|
+
* skill id -> the skill's actions.yaml as parsed from the bytes downloaded from skill
|
|
236
|
+
* storage for its installed version. Set only by a (re)download, never re-read from the
|
|
237
|
+
* session directory: the agent can edit skills/<name>/actions.yaml (in degraded mode; the
|
|
238
|
+
* sandbox policy denies writes under skills/ otherwise), and that must not
|
|
239
|
+
* change which actions exist or what they read.
|
|
240
|
+
*/
|
|
241
|
+
skillActions: ReadonlyMap<string, PinnedSkillActions>
|
|
215
242
|
/** Tears down the sandbox and deletes the session directory. */
|
|
216
243
|
cleanup: () => Promise<void>
|
|
217
244
|
}
|
|
@@ -229,16 +256,22 @@ interface CachedSandbox {
|
|
|
229
256
|
handle: SessionSandboxHandle
|
|
230
257
|
/** skill id -> installed version */
|
|
231
258
|
installedSkills: Map<string, number>
|
|
259
|
+
/** skill id -> pinned actions declaration (the same map the handle exposes). */
|
|
260
|
+
skillActions: Map<string, PinnedSkillActions>
|
|
232
261
|
projectState: ProjectState
|
|
233
262
|
}
|
|
234
263
|
|
|
235
264
|
const sandboxCache = new Map<string, CachedSandbox>()
|
|
236
265
|
|
|
266
|
+
/**
|
|
267
|
+
* Downloads a skill version's files into skills/<name>/ and returns the bytes of its
|
|
268
|
+
* root actions.yaml as fetched from storage (undefined when the version has none).
|
|
269
|
+
*/
|
|
237
270
|
async function downloadSkill(
|
|
238
271
|
skill: SkillRef,
|
|
239
272
|
skillsDirectory: string,
|
|
240
273
|
config: ExuluConfig,
|
|
241
|
-
): Promise<
|
|
274
|
+
): Promise<Buffer | undefined> {
|
|
242
275
|
// Skills created via the standard /skills/:skillId/initialize route always
|
|
243
276
|
// get current_version=1. Older / manually-inserted rows may be missing it
|
|
244
277
|
// — fall back to v1 (where the auto-generated SKILL.md lives) and warn.
|
|
@@ -267,6 +300,7 @@ async function downloadSkill(
|
|
|
267
300
|
const sessionDir = dirname(skillsDirectory)
|
|
268
301
|
await ensureRealDirectory(sessionDir, `skills/${skill.name}`)
|
|
269
302
|
|
|
303
|
+
let actionsBytes: Buffer | undefined
|
|
270
304
|
for (const file of files) {
|
|
271
305
|
// Extract the path relative to the version prefix, accounting for any S3 general prefix
|
|
272
306
|
const prefixIndex = file.key.indexOf(versionPrefix)
|
|
@@ -279,6 +313,8 @@ async function downloadSkill(
|
|
|
279
313
|
// Binary-safe download — skill bundles can ship images, fonts, and
|
|
280
314
|
// other non-text assets alongside the SKILL.md / scripts.
|
|
281
315
|
const bytes = await getS3ObjectBytes(file.key, config)
|
|
316
|
+
// Root of the skill only: a nested actions.yaml declares nothing.
|
|
317
|
+
if (relativePath === ACTIONS_FILE) actionsBytes = Buffer.from(bytes)
|
|
282
318
|
try {
|
|
283
319
|
await writeFileInside(sessionDir, `skills/${skill.name}/${relativePath}`, bytes)
|
|
284
320
|
} catch (err) {
|
|
@@ -286,6 +322,28 @@ async function downloadSkill(
|
|
|
286
322
|
console.error(`[SKILLS] Skipping skill file ${file.key}: ${err.message}`)
|
|
287
323
|
}
|
|
288
324
|
}
|
|
325
|
+
return actionsBytes
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* Downloads a skill and pins its actions declaration from the downloaded bytes. The old pin
|
|
330
|
+
* is dropped first, so a download that fails part-way leaves the skill without actions
|
|
331
|
+
* (fail closed) rather than with the previous version's.
|
|
332
|
+
*/
|
|
333
|
+
async function installSkill(
|
|
334
|
+
skill: SkillRef,
|
|
335
|
+
skillsDirectory: string,
|
|
336
|
+
config: ExuluConfig,
|
|
337
|
+
skillActions: Map<string, PinnedSkillActions>,
|
|
338
|
+
): Promise<void> {
|
|
339
|
+
skillActions.delete(skill.id)
|
|
340
|
+
const actionsBytes = await downloadSkill(skill, skillsDirectory, config)
|
|
341
|
+
skillActions.set(skill.id, {
|
|
342
|
+
skillId: skill.id,
|
|
343
|
+
name: skill.name,
|
|
344
|
+
version: skill.current_version,
|
|
345
|
+
declaration: declarationFromBytes(actionsBytes),
|
|
346
|
+
})
|
|
289
347
|
}
|
|
290
348
|
|
|
291
349
|
/**
|
|
@@ -298,6 +356,13 @@ async function removeInstalledSkill(skillsDirectory: string, skillName: string):
|
|
|
298
356
|
await removeEntryInside(sessionDir, `skills/${skillName}`)
|
|
299
357
|
}
|
|
300
358
|
|
|
359
|
+
/** The writeFile refusal for a path that lands in skills/ (see writeFilesInternal). */
|
|
360
|
+
const SKILLS_READ_ONLY_MESSAGE = (path: string) =>
|
|
361
|
+
`writeFile refused: "${path}" is inside the skills/ folder, which is read-only in a session. ` +
|
|
362
|
+
'Write your files to the session directory instead (e.g. "./out/report.md"). ' +
|
|
363
|
+
'A skill changes only when a new version of it is saved (skill_update or the skill editor); ' +
|
|
364
|
+
'the session picks it up on the next turn or a reload of the skills.'
|
|
365
|
+
|
|
301
366
|
/**
|
|
302
367
|
* A file written inside the sandbox qualifies as a session artifact iff it lives
|
|
303
368
|
* under sessionDir but NOT under sessionDir/skills/. Skill source files are
|
|
@@ -314,6 +379,7 @@ export function isArtifactPath(
|
|
|
314
379
|
const resolved = resolve(absPath)
|
|
315
380
|
const rel = relative(sessionDir, resolved)
|
|
316
381
|
if (!rel || rel.startsWith('..')) return false
|
|
382
|
+
if (isActionInputsPath(rel)) return false
|
|
317
383
|
const first = rel.split('/')[0]
|
|
318
384
|
if (opts.hasProject && first === PROJECT_DIR) return false
|
|
319
385
|
return first !== 'skills'
|
|
@@ -379,13 +445,24 @@ function resolveSessionPath(inputPath: string, sessionDir: string): string {
|
|
|
379
445
|
if (resolved !== sessionDir && !resolved.startsWith(sessionDir + '/')) {
|
|
380
446
|
throw new Error(
|
|
381
447
|
`Path "${inputPath}" resolves outside the session directory. ` +
|
|
382
|
-
`Use a path inside "${sessionDir}" (relative paths recommended, e.g. "skills/<name>/SKILL.md").`,
|
|
448
|
+
`Use a path inside "${sessionDir}" (relative paths recommended, e.g. "out/report.md", or "skills/<name>/SKILL.md" to read a skill).`,
|
|
383
449
|
)
|
|
384
450
|
}
|
|
385
451
|
|
|
386
452
|
return resolved
|
|
387
453
|
}
|
|
388
454
|
|
|
455
|
+
/**
|
|
456
|
+
* Whether a session file from storage would land in skills/ (real-path judgement:
|
|
457
|
+
* `.`/`..` segments, links and, on a case-insensitive file system, case variants all
|
|
458
|
+
* resolve to the real folder). Logs the key, never the content, when it does.
|
|
459
|
+
*/
|
|
460
|
+
async function landsInSkills(sessionDir: string, localPath: string, key: string): Promise<boolean> {
|
|
461
|
+
if (!(await landsInside(sessionDir, localPath, 'skills'))) return false
|
|
462
|
+
console.warn(`[SKILLS] Not writing session file ${key} into the session: it lands in skills/, which only a saved skill version fills.`)
|
|
463
|
+
return true
|
|
464
|
+
}
|
|
465
|
+
|
|
389
466
|
async function restoreArtifactsFromS3(
|
|
390
467
|
sessionDir: string,
|
|
391
468
|
sessionId: string,
|
|
@@ -426,6 +503,9 @@ async function restoreArtifactsFromS3(
|
|
|
426
503
|
if (opts.skipProjectDir && relativePath.split('/')[0] === PROJECT_DIR) continue
|
|
427
504
|
|
|
428
505
|
const localPath = join(sessionDir, relativePath)
|
|
506
|
+
// skills/ changes only from a skill's saved version (installSkill), never from a
|
|
507
|
+
// session file: a key there would replace a script a later speaker runs.
|
|
508
|
+
if (await landsInSkills(sessionDir, localPath, obj.key)) continue
|
|
429
509
|
if (opts.onlyMissing) {
|
|
430
510
|
let localSize: number | undefined
|
|
431
511
|
try {
|
|
@@ -444,7 +524,7 @@ async function restoreArtifactsFromS3(
|
|
|
444
524
|
// bash-produced files). Reading as utf-8 would corrupt these.
|
|
445
525
|
const bytes = await getS3ObjectBytes(obj.key, config)
|
|
446
526
|
// Never writeFile into the agent-writable tree: it would follow links.
|
|
447
|
-
await writeFileInside(sessionDir, relativePath, bytes)
|
|
527
|
+
await writeFileInside(sessionDir, relativePath, bytes, { notUnder: 'skills' })
|
|
448
528
|
} catch (err) {
|
|
449
529
|
console.error(
|
|
450
530
|
`[SKILLS] Failed to restore artifact ${obj.key} -> ${localPath}; continuing.`,
|
|
@@ -492,10 +572,12 @@ export async function downloadKeyIntoSandbox(opts: {
|
|
|
492
572
|
}
|
|
493
573
|
const relativePath = fullS3Key.slice(idx + userPrefix.length)
|
|
494
574
|
if (!relativePath) return { written: false } // directory marker
|
|
575
|
+
// Never into skills/ (see restoreArtifactsFromS3).
|
|
576
|
+
if (await landsInSkills(sessionDir, join(sessionDir, relativePath), fullS3Key)) return { written: false }
|
|
495
577
|
|
|
496
578
|
const bytes = await getS3ObjectBytes(fullS3Key, config)
|
|
497
579
|
// Refuses ".." in the key suffix and never writes through an agent-planted link.
|
|
498
|
-
const localPath = await writeFileInside(sessionDir, relativePath, bytes)
|
|
580
|
+
const localPath = await writeFileInside(sessionDir, relativePath, bytes, { notUnder: 'skills' })
|
|
499
581
|
|
|
500
582
|
return { written: true, localPath }
|
|
501
583
|
}
|
|
@@ -548,7 +630,7 @@ export async function refreshSessionSkills(
|
|
|
548
630
|
let refreshed = 0
|
|
549
631
|
for (const skill of skills) {
|
|
550
632
|
await removeInstalledSkill(skillsDirectory, skill.name)
|
|
551
|
-
await
|
|
633
|
+
await installSkill(skill, skillsDirectory, config, cached.skillActions)
|
|
552
634
|
cached.installedSkills.set(skill.id, skill.current_version)
|
|
553
635
|
refreshed++
|
|
554
636
|
}
|
|
@@ -600,7 +682,7 @@ export async function createSessionSandbox(
|
|
|
600
682
|
await removeInstalledSkill(skillsDirectory, skill.name)
|
|
601
683
|
}
|
|
602
684
|
|
|
603
|
-
await
|
|
685
|
+
await installSkill(skill, skillsDirectory, config, cached.skillActions)
|
|
604
686
|
cached.installedSkills.set(skill.id, skill.current_version)
|
|
605
687
|
}
|
|
606
688
|
|
|
@@ -633,12 +715,19 @@ export async function createSessionSandbox(
|
|
|
633
715
|
await mkdir(sessionDir, { recursive: true })
|
|
634
716
|
|
|
635
717
|
const skillsDirectory = join(sessionDir, 'skills')
|
|
718
|
+
// Exists (as a real directory) before the sandbox policy below is first applied,
|
|
719
|
+
// even for a session without skills: the runtime resolves a deny path only when it
|
|
720
|
+
// exists — on macOS an unresolved /tmp/... path would never match the kernel's
|
|
721
|
+
// /private/tmp/... and the deny would silently not apply; on Linux a missing path
|
|
722
|
+
// gets a placeholder mount file created in the session dir on the host.
|
|
723
|
+
await ensureRealDirectory(sessionDir, 'skills')
|
|
636
724
|
|
|
637
725
|
const installedSkills = new Map<string, number>()
|
|
726
|
+
const skillActions = new Map<string, PinnedSkillActions>()
|
|
638
727
|
|
|
639
728
|
// Download each skill's files from S3 into the session directory
|
|
640
729
|
for (const skill of skills) {
|
|
641
|
-
await
|
|
730
|
+
await installSkill(skill, skillsDirectory, config, skillActions)
|
|
642
731
|
installedSkills.set(skill.id, skill.current_version)
|
|
643
732
|
}
|
|
644
733
|
|
|
@@ -742,7 +831,21 @@ export async function createSessionSandbox(
|
|
|
742
831
|
...(pythonVenvPath ? [pythonVenvPath] : []),
|
|
743
832
|
],
|
|
744
833
|
allowWrite: [sessionDir],
|
|
745
|
-
|
|
834
|
+
// Skill folders are read-only inside the sandbox; only the platform (this
|
|
835
|
+
// process: download, version re-sync, reload, removal) writes them. A script
|
|
836
|
+
// runs with the rights of whoever triggers it — in a shared session another
|
|
837
|
+
// speaker — so nothing run in the sandbox may change what a later run executes.
|
|
838
|
+
// The runtime layers this deny over the session-dir allow:
|
|
839
|
+
// - macOS (seatbelt): `deny file-write*` + `deny file-write-unlink` on the
|
|
840
|
+
// subpath come after the allow (later rules win), and unlink of each
|
|
841
|
+
// ancestor is denied, so a rename of skills/ or a skill's folder fails too.
|
|
842
|
+
// - Linux (bwrap): `--ro-bind skills skills` after the session-dir `--bind`;
|
|
843
|
+
// writes get EROFS, renaming the mount point EBUSY, links into it EXDEV.
|
|
844
|
+
// Paths are resolved through symlinks when each command is wrapped, which is
|
|
845
|
+
// why skills/ is created above before the first command.
|
|
846
|
+
// Not enforced in degraded mode (useDirectExec): nothing is. The writeFile
|
|
847
|
+
// tool refuses skills/ paths itself; bash and runCommand cannot be confined.
|
|
848
|
+
denyWrite: [skillsDirectory],
|
|
746
849
|
},
|
|
747
850
|
}
|
|
748
851
|
|
|
@@ -851,7 +954,10 @@ export async function createSessionSandbox(
|
|
|
851
954
|
|
|
852
955
|
// Either wrap a command with bwrap/sandbox-exec or return it unchanged when
|
|
853
956
|
// the host can't sandbox. In degraded mode the container itself is the
|
|
854
|
-
// isolation boundary; resolveSessionPath still scopes readFile/writeFile
|
|
957
|
+
// isolation boundary; resolveSessionPath still scopes readFile/writeFile, and
|
|
958
|
+
// writeFilesInternal still refuses skills/. A bash command or a skill action can
|
|
959
|
+
// then still change skills/ (or anything else the backend user may write): that
|
|
960
|
+
// limit is stated in the authoring guide and the docs.
|
|
855
961
|
const wrapIfNeeded = async (command: string): Promise<string> => {
|
|
856
962
|
if (useDirectExec) return command;
|
|
857
963
|
return SandboxManager.wrapWithSandbox(command, undefined, sessionSandboxConfig);
|
|
@@ -986,6 +1092,14 @@ export async function createSessionSandbox(
|
|
|
986
1092
|
): Promise<WriteResult[]> {
|
|
987
1093
|
const results: WriteResult[] = []
|
|
988
1094
|
|
|
1095
|
+
// All paths are checked before any is written, and before anything touches
|
|
1096
|
+
// disk: the refusal holds in degraded mode too, where no sandbox policy exists.
|
|
1097
|
+
for (const file of files) {
|
|
1098
|
+
if (await landsInside(sessionDir, file.path, 'skills')) {
|
|
1099
|
+
throw new Error(SKILLS_READ_ONLY_MESSAGE(file.path))
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
|
|
989
1103
|
for (const file of files) {
|
|
990
1104
|
// Pipe content via stdin so arbitrary file content (quotes, $, etc.)
|
|
991
1105
|
// doesn't need to be escaped into the shell command.
|
|
@@ -1083,7 +1197,9 @@ export async function createSessionSandbox(
|
|
|
1083
1197
|
description:
|
|
1084
1198
|
'Write content to a file in the sandbox. Creates parent directories if needed. ' +
|
|
1085
1199
|
'Paths are always resolved against the session sandbox root — both relative paths ' +
|
|
1086
|
-
'("
|
|
1200
|
+
'("report.md", "out/report.md") and leading-slash paths ("/out/report.md") work and reach the same file. ' +
|
|
1201
|
+
'The skills/ folder is read-only: a path inside it is refused. A skill changes only when a new version ' +
|
|
1202
|
+
'of it is saved (skill_update or the skill editor); write your own files to the session directory. ' +
|
|
1087
1203
|
'When the path is under the session artifact tree, the file is also uploaded to S3 ' +
|
|
1088
1204
|
'and a short-lived presigned URL is returned in the tool output.',
|
|
1089
1205
|
inputSchema: z.object({
|
|
@@ -1155,6 +1271,95 @@ export async function createSessionSandbox(
|
|
|
1155
1271
|
// 5. Returns an `artifacts` array on the tool result AND appends an
|
|
1156
1272
|
// [exulu-artifacts] block to stdout so the model surfaces the URLs
|
|
1157
1273
|
// naturally in its reply.
|
|
1274
|
+
// Shared by `bash` and `runCommand`: snapshot, run, snapshot, diff, mirror the changed
|
|
1275
|
+
// files to S3, and append the [exulu-artifacts] block to stdout (see the comment above).
|
|
1276
|
+
async function runWithArtifactMirroring<R extends { stdout?: string }>(
|
|
1277
|
+
execute: () => Promise<R>,
|
|
1278
|
+
): Promise<
|
|
1279
|
+
Omit<R, 'stdout'> & {
|
|
1280
|
+
stdout: string
|
|
1281
|
+
artifacts: Array<{ path: string; relativePath: string; key?: string; url?: string }>
|
|
1282
|
+
artifactsOmitted?: number
|
|
1283
|
+
}
|
|
1284
|
+
> {
|
|
1285
|
+
// Fixed for this command: both snapshots and the persist check use it.
|
|
1286
|
+
const hasProject = hasProjectNow()
|
|
1287
|
+
const before = persistenceEnabled
|
|
1288
|
+
? await snapshotSessionArtifacts(hasProject)
|
|
1289
|
+
: null
|
|
1290
|
+
const result = await execute()
|
|
1291
|
+
|
|
1292
|
+
// Determine new/modified files since the snapshot. mtimeMs strictly
|
|
1293
|
+
// greater than the before-value catches "modified"; absence in
|
|
1294
|
+
// `before` catches "new".
|
|
1295
|
+
const artifacts: Array<{
|
|
1296
|
+
path: string
|
|
1297
|
+
relativePath: string
|
|
1298
|
+
key?: string
|
|
1299
|
+
url?: string
|
|
1300
|
+
}> = []
|
|
1301
|
+
if (persistenceEnabled && before) {
|
|
1302
|
+
// Read once more after the command (see hasProjectNow).
|
|
1303
|
+
const skipProject = hasProject || hasProjectNow()
|
|
1304
|
+
const after = await snapshotSessionArtifacts(skipProject)
|
|
1305
|
+
const changedPaths: string[] = []
|
|
1306
|
+
for (const [path, mtime] of after) {
|
|
1307
|
+
const beforeMtime = before.get(path)
|
|
1308
|
+
if (beforeMtime === undefined || beforeMtime < mtime) {
|
|
1309
|
+
changedPaths.push(path)
|
|
1310
|
+
}
|
|
1311
|
+
}
|
|
1312
|
+
for (const path of changedPaths) {
|
|
1313
|
+
try {
|
|
1314
|
+
// Never fsReadFile here: the agent may have swapped the file (or a
|
|
1315
|
+
// parent directory) for a link to something the sandbox denies,
|
|
1316
|
+
// and this read runs with the backend's rights.
|
|
1317
|
+
const content = await readRegularFileInside(sessionDir, path)
|
|
1318
|
+
if (content === null) continue
|
|
1319
|
+
const persisted = await persistArtifactToS3(path, content, skipProject)
|
|
1320
|
+
artifacts.push({
|
|
1321
|
+
path,
|
|
1322
|
+
relativePath: relative(sessionDir, path),
|
|
1323
|
+
key: persisted.key,
|
|
1324
|
+
url: persisted.url,
|
|
1325
|
+
})
|
|
1326
|
+
} catch (err) {
|
|
1327
|
+
console.error(
|
|
1328
|
+
`[SKILLS] Failed to mirror bash-produced artifact ${path} to S3; continuing.`,
|
|
1329
|
+
err,
|
|
1330
|
+
)
|
|
1331
|
+
}
|
|
1332
|
+
}
|
|
1333
|
+
}
|
|
1334
|
+
|
|
1335
|
+
// Surface URLs in stdout so the agent sees them and includes them
|
|
1336
|
+
// in its reply. We append after bash-tool's truncation pass so the
|
|
1337
|
+
// marker block isn't truncated. Only files with a presigned URL
|
|
1338
|
+
// appear here; locally-only entries would just confuse the user.
|
|
1339
|
+
let stdout = result?.stdout ?? ''
|
|
1340
|
+
// Cap the listing: one command can touch thousands of files, and every
|
|
1341
|
+
// entry carries a presigned URL. The full set is still mirrored to S3.
|
|
1342
|
+
const { kept, omitted } = capArtifacts(artifacts)
|
|
1343
|
+
const withUrls = kept.filter((a) => a.url)
|
|
1344
|
+
if (withUrls.length > 0) {
|
|
1345
|
+
const lines: string[] = []
|
|
1346
|
+
for (const a of withUrls) {
|
|
1347
|
+
lines.push(` ${a.relativePath}: ${a.url}`)
|
|
1348
|
+
}
|
|
1349
|
+
if (omitted > 0) {
|
|
1350
|
+
lines.push(` … ${omitted} more file(s) were created and mirrored but are not listed here.`)
|
|
1351
|
+
}
|
|
1352
|
+
stdout = appendArtifactsBlock(stdout, lines)
|
|
1353
|
+
}
|
|
1354
|
+
|
|
1355
|
+
return {
|
|
1356
|
+
...result,
|
|
1357
|
+
stdout,
|
|
1358
|
+
artifacts: kept,
|
|
1359
|
+
...(omitted > 0 ? { artifactsOmitted: omitted } : {}),
|
|
1360
|
+
}
|
|
1361
|
+
}
|
|
1362
|
+
|
|
1158
1363
|
const originalBashTool = tools.bash
|
|
1159
1364
|
const bashTool = tool({
|
|
1160
1365
|
description: originalBashTool.description ?? '',
|
|
@@ -1162,11 +1367,6 @@ export async function createSessionSandbox(
|
|
|
1162
1367
|
command: z.string().describe('The bash command to execute.'),
|
|
1163
1368
|
}),
|
|
1164
1369
|
execute: async (args, opts) => {
|
|
1165
|
-
// Fixed for this command: both snapshots and the persist check use it.
|
|
1166
|
-
const hasProject = hasProjectNow()
|
|
1167
|
-
const before = persistenceEnabled
|
|
1168
|
-
? await snapshotSessionArtifacts(hasProject)
|
|
1169
|
-
: null
|
|
1170
1370
|
// Defer to bash-tool's bash tool so we keep its truncation, cwd
|
|
1171
1371
|
// pinning, and any future bash-tool behaviour for free.
|
|
1172
1372
|
const originalExecute = originalBashTool.execute as
|
|
@@ -1175,79 +1375,57 @@ export async function createSessionSandbox(
|
|
|
1175
1375
|
if (!originalExecute) {
|
|
1176
1376
|
throw new Error('bash tool execute is undefined')
|
|
1177
1377
|
}
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
// greater than the before-value catches "modified"; absence in
|
|
1182
|
-
// `before` catches "new".
|
|
1183
|
-
const artifacts: Array<{
|
|
1184
|
-
path: string
|
|
1185
|
-
relativePath: string
|
|
1186
|
-
key?: string
|
|
1187
|
-
url?: string
|
|
1188
|
-
}> = []
|
|
1189
|
-
if (persistenceEnabled && before) {
|
|
1190
|
-
// Read once more after the command (see hasProjectNow).
|
|
1191
|
-
const skipProject = hasProject || hasProjectNow()
|
|
1192
|
-
const after = await snapshotSessionArtifacts(skipProject)
|
|
1193
|
-
const changedPaths: string[] = []
|
|
1194
|
-
for (const [path, mtime] of after) {
|
|
1195
|
-
const beforeMtime = before.get(path)
|
|
1196
|
-
if (beforeMtime === undefined || beforeMtime < mtime) {
|
|
1197
|
-
changedPaths.push(path)
|
|
1198
|
-
}
|
|
1199
|
-
}
|
|
1200
|
-
for (const path of changedPaths) {
|
|
1201
|
-
try {
|
|
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)
|
|
1208
|
-
artifacts.push({
|
|
1209
|
-
path,
|
|
1210
|
-
relativePath: relative(sessionDir, path),
|
|
1211
|
-
key: persisted.key,
|
|
1212
|
-
url: persisted.url,
|
|
1213
|
-
})
|
|
1214
|
-
} catch (err) {
|
|
1215
|
-
console.error(
|
|
1216
|
-
`[SKILLS] Failed to mirror bash-produced artifact ${path} to S3; continuing.`,
|
|
1217
|
-
err,
|
|
1218
|
-
)
|
|
1219
|
-
}
|
|
1220
|
-
}
|
|
1221
|
-
}
|
|
1378
|
+
return runWithArtifactMirroring(() => originalExecute(args, opts))
|
|
1379
|
+
},
|
|
1380
|
+
})
|
|
1222
1381
|
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
//
|
|
1229
|
-
|
|
1230
|
-
const {
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
const
|
|
1234
|
-
|
|
1235
|
-
|
|
1382
|
+
// Programmatic command runner (skill actions): sandbox-wrapped, per-call extra env,
|
|
1383
|
+
// optional timeout. The env is a fresh object per call; sandboxedExecEnv is never mutated.
|
|
1384
|
+
const runCommand: SessionSandboxHandle['runCommand'] = (command, options = {}) =>
|
|
1385
|
+
runWithArtifactMirroring(async () => {
|
|
1386
|
+
// cd inside the wrapped command too (as bash-tool does): the spawn cwd alone
|
|
1387
|
+
// cannot be relied on under a real sandbox wrapper. sessionDir is platform-controlled.
|
|
1388
|
+
const wrapped = await wrapIfNeeded(`cd ${shellQuote(sessionDir)} && ${command}`)
|
|
1389
|
+
const callEnv = { ...sandboxedExecEnv, ...(options.extraEnv ?? {}) }
|
|
1390
|
+
return await new Promise<{ stdout: string; stderr: string; exitCode: number; timedOut: boolean }>((resolvePromise) => {
|
|
1391
|
+
// detached: own process group, so a timeout can kill the whole tree.
|
|
1392
|
+
const child = spawn('/bin/bash', ['-c', wrapped], { env: callEnv, cwd: sessionDir, detached: true })
|
|
1393
|
+
let stdout = ''
|
|
1394
|
+
let stderr = ''
|
|
1395
|
+
let timedOut = false
|
|
1396
|
+
let settled = false
|
|
1397
|
+
let timer: NodeJS.Timeout | undefined
|
|
1398
|
+
// setEncoding: the stream's decoder carries a multi-byte character split across
|
|
1399
|
+
// chunks over to the next one (chunk.toString would turn each half into U+FFFD).
|
|
1400
|
+
const append = (cur: string, chunk: string) =>
|
|
1401
|
+
cur.length >= EXEC_MAX_BUFFER ? cur : (cur + chunk).slice(0, EXEC_MAX_BUFFER)
|
|
1402
|
+
child.stdout?.setEncoding('utf8')
|
|
1403
|
+
child.stderr?.setEncoding('utf8')
|
|
1404
|
+
child.stdout?.on('data', (c: string) => { stdout = append(stdout, c) })
|
|
1405
|
+
child.stderr?.on('data', (c: string) => { stderr = append(stderr, c) })
|
|
1406
|
+
const finish = (exitCode: number) => {
|
|
1407
|
+
if (settled) return
|
|
1408
|
+
settled = true
|
|
1409
|
+
if (timer) clearTimeout(timer)
|
|
1410
|
+
resolvePromise({ stdout, stderr, exitCode: timedOut ? 124 : exitCode, timedOut })
|
|
1236
1411
|
}
|
|
1237
|
-
if (
|
|
1238
|
-
|
|
1412
|
+
if (options.timeoutMs !== undefined && options.timeoutMs > 0) {
|
|
1413
|
+
timer = setTimeout(() => {
|
|
1414
|
+
timedOut = true
|
|
1415
|
+
try {
|
|
1416
|
+
if (child.pid) process.kill(-child.pid, 'SIGKILL')
|
|
1417
|
+
} catch {
|
|
1418
|
+
child.kill('SIGKILL')
|
|
1419
|
+
}
|
|
1420
|
+
}, options.timeoutMs)
|
|
1239
1421
|
}
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
...(omitted > 0 ? { artifactsOmitted: omitted } : {}),
|
|
1248
|
-
}
|
|
1249
|
-
},
|
|
1250
|
-
})
|
|
1422
|
+
child.on('error', (err) => {
|
|
1423
|
+
stderr = `${stderr}${err.message}`
|
|
1424
|
+
finish(1)
|
|
1425
|
+
})
|
|
1426
|
+
child.on('close', (code, signal) => finish(typeof code === 'number' ? code : signal ? 128 : 1))
|
|
1427
|
+
})
|
|
1428
|
+
})
|
|
1251
1429
|
|
|
1252
1430
|
const wrappedTools = { ...tools, bash: bashTool, readFile: readFileTool, writeFile: writeFileTool }
|
|
1253
1431
|
|
|
@@ -1255,6 +1433,8 @@ export async function createSessionSandbox(
|
|
|
1255
1433
|
sessionDir,
|
|
1256
1434
|
tools: wrappedTools,
|
|
1257
1435
|
wrapCommand: (command: string) => wrapIfNeeded(command),
|
|
1436
|
+
runCommand,
|
|
1437
|
+
skillActions,
|
|
1258
1438
|
cleanup: async () => {
|
|
1259
1439
|
sandboxCache.delete(sessionId)
|
|
1260
1440
|
if (!useDirectExec) {
|
|
@@ -1265,7 +1445,7 @@ export async function createSessionSandbox(
|
|
|
1265
1445
|
},
|
|
1266
1446
|
}
|
|
1267
1447
|
|
|
1268
|
-
sandboxCache.set(sessionId, { handle, installedSkills, projectState })
|
|
1448
|
+
sandboxCache.set(sessionId, { handle, installedSkills, skillActions, projectState })
|
|
1269
1449
|
|
|
1270
1450
|
return handle
|
|
1271
1451
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { execFileSync } from "node:child_process";
|
|
2
2
|
import { closeSync, constants, openSync } from "node:fs";
|
|
3
|
-
import { mkdtemp, rm, truncate, writeFile } from "node:fs/promises";
|
|
3
|
+
import { mkdir, mkdtemp, rm, symlink, truncate, writeFile } from "node:fs/promises";
|
|
4
4
|
import { tmpdir } from "node:os";
|
|
5
5
|
import { join } from "node:path";
|
|
6
6
|
import { MAX_ADOPT_UPLOAD_BYTES } from "@SRC/exulu/session-file-adopt";
|
|
@@ -67,3 +67,61 @@ describe("readRegularFileInside: small and empty files", () => {
|
|
|
67
67
|
expect((await readRegularFileInside(dir, join(dir, "empty.txt")))?.length).toBe(0);
|
|
68
68
|
});
|
|
69
69
|
});
|
|
70
|
+
|
|
71
|
+
describe("landsInside", () => {
|
|
72
|
+
// Imported here so a missing export fails only this block.
|
|
73
|
+
const { landsInside } = jest.requireActual("./safe-fs") as typeof import("./safe-fs");
|
|
74
|
+
let skills: string;
|
|
75
|
+
beforeEach(async () => {
|
|
76
|
+
skills = join(dir, "skills");
|
|
77
|
+
await mkdir(join(skills, "demo"), { recursive: true });
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
it.each([
|
|
81
|
+
"skills",
|
|
82
|
+
"skills/demo/run.py",
|
|
83
|
+
"skills/new/deep/file.txt",
|
|
84
|
+
])("%p lands in skills/", async (rel) => {
|
|
85
|
+
expect(await landsInside(dir, join(dir, rel), "skills")).toBe(true);
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
it.each(["out.txt", "skillsx/a.txt", "a/skills/b.txt", "."])("%p does not land in skills/", async (rel) => {
|
|
89
|
+
expect(await landsInside(dir, join(dir, rel), "skills")).toBe(false);
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
it("follows a link in the session dir that points into skills/, also a dangling one", async () => {
|
|
93
|
+
await symlink(join(skills, "demo"), join(dir, "ldir"));
|
|
94
|
+
await symlink(join(skills, "demo", "missing.py"), join(dir, "dangling.py"));
|
|
95
|
+
await symlink("skills/demo/run.py", join(dir, "relative.py"));
|
|
96
|
+
expect(await landsInside(dir, join(dir, "ldir", "x.py"), "skills")).toBe(true);
|
|
97
|
+
expect(await landsInside(dir, join(dir, "ldir"), "skills")).toBe(true);
|
|
98
|
+
expect(await landsInside(dir, join(dir, "dangling.py"), "skills")).toBe(true);
|
|
99
|
+
expect(await landsInside(dir, join(dir, "relative.py"), "skills")).toBe(true);
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
it("a link out of skills/ is judged by its target", async () => {
|
|
103
|
+
await mkdir(join(dir, "elsewhere"));
|
|
104
|
+
await symlink(join(dir, "elsewhere"), join(dir, "out"));
|
|
105
|
+
expect(await landsInside(dir, join(dir, "out", "a.txt"), "skills")).toBe(false);
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
it("works when the session dir is reached through a link and when skills/ does not exist", async () => {
|
|
109
|
+
const alias = join(dir, "..", `alias-${process.pid}-${Math.random().toString(36).slice(2)}`);
|
|
110
|
+
await symlink(dir, alias);
|
|
111
|
+
try {
|
|
112
|
+
expect(await landsInside(alias, join(alias, "skills", "demo", "a"), "skills")).toBe(true);
|
|
113
|
+
expect(await landsInside(dir, join(alias, "skills", "demo", "a"), "skills")).toBe(true);
|
|
114
|
+
await rm(skills, { recursive: true, force: true });
|
|
115
|
+
expect(await landsInside(dir, join(dir, "skills", "a"), "skills")).toBe(true);
|
|
116
|
+
expect(await landsInside(dir, join(dir, "b"), "skills")).toBe(false);
|
|
117
|
+
} finally {
|
|
118
|
+
await rm(alias, { force: true });
|
|
119
|
+
}
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
it("a link cycle is treated as landing inside (refuse rather than guess)", async () => {
|
|
123
|
+
await symlink(join(dir, "loop2"), join(dir, "loop1"));
|
|
124
|
+
await symlink(join(dir, "loop1"), join(dir, "loop2"));
|
|
125
|
+
expect(await landsInside(dir, join(dir, "loop1", "x"), "skills")).toBe(true);
|
|
126
|
+
});
|
|
127
|
+
});
|