@mastra/factory 0.25.0-alpha.2 → 0.25.0-alpha.4

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 +1 @@
1
- {"version":3,"file":"fs.js","names":["posixPath"],"sources":["../../src/routes/fs.ts"],"sourcesContent":["import { lstat, open, readdir, realpath, stat } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { isAbsolute, join, posix as posixPath, resolve, sep } from 'node:path';\n\nimport { SETUP_MARKER_DIR } from '@internal/workspace';\nimport { SandboxFilesystem } from '@mastra/code-sdk/agents/sandbox-filesystem';\nimport { detectProject, getResourceIdOverride } from '@mastra/code-sdk/utils/project';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { ApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\n\nimport { requireExec } from '../sandbox/materialization.js';\nimport type { ExecutableSandbox } from '../sandbox/materialization.js';\nimport { peekSessionSandbox, sessionLayout } from '../sandbox/session-sandbox.js';\nimport type { SessionLayout, SessionLayoutRepository } from '../sandbox/session-sandbox.js';\nimport { peekSessionEnvironment } from '../session/environment-state-processor.js';\nimport type { SourceControlSession } from '../storage/domains/source-control/base.js';\nimport type { RouteAuth } from './route.js';\n\n/**\n * Server-side directory browser for the web project picker.\n *\n * The browser cannot read absolute filesystem paths (the File System Access API\n * only exposes a directory *name*), so the picker must ask the server — which\n * does have filesystem access — to enumerate directories. The result is real\n * absolute paths the user can select without typing.\n *\n * All access is confined to a configured `root` (default: the user's home\n * directory). Requests that try to escape the root via `..` or symlinks are\n * clamped back to the root.\n */\n\nexport interface DirectoryEntry {\n name: string;\n /** Absolute path to the entry. */\n path: string;\n}\n\nexport interface DirectoryListing {\n /** The allowed root; clients cannot browse above this. */\n root: string;\n /** The absolute path that was listed. */\n path: string;\n /** Parent directory path, or null when `path` is the root. */\n parent: string | null;\n /** Subdirectories of `path` (directories only, sorted, hidden excluded). */\n entries: DirectoryEntry[];\n}\n\nexport interface WorkspaceRenderedEntry {\n name: string;\n /** Path relative to the configured rendered root. */\n path: string;\n type: 'file' | 'directory';\n size: number;\n updatedAt: string;\n}\n\nexport interface WorkspaceRenderedListing {\n /** The confined workspace/project root. */\n workspacePath: string;\n /** Configured workspace-relative rendered root, e.g. `.artifacts`. */\n root: string;\n /** The confined absolute path for the rendered root. */\n rootPath: string;\n entries: WorkspaceRenderedEntry[];\n}\n\nexport interface WorkspaceFile {\n /** The confined workspace/project root. */\n workspacePath: string;\n /** Workspace-relative file path. */\n path: string;\n name: string;\n size: number;\n updatedAt: string;\n contentType: 'text' | 'unsupported';\n content?: string;\n truncated?: boolean;\n}\n\nexport interface WorkspaceTreeEntry {\n name: string;\n /** Path from the session's layout root, the form the file route takes. */\n path: string;\n type: 'file' | 'directory';\n size?: number;\n /** Set when the entry is a symlink: where it points, as written in the link. */\n symlinkTarget?: string;\n /** Set when the entry is a symlink: the tree path of what it resolves to. */\n linkedPath?: string;\n}\n\n/** One directory of a session's checkouts, read live from its sandbox. */\nexport interface WorkspaceTreeListing {\n workspacePath: string;\n /** The listed directory; empty for the top level. */\n path: string;\n /** False when this process holds no sandbox for the session, so nothing was read. */\n available: boolean;\n entries: WorkspaceTreeEntry[];\n}\n\nexport type WorkspaceChangeStatus =\n | 'modified'\n | 'added'\n | 'deleted'\n | 'renamed'\n | 'copied'\n | 'untracked'\n | 'conflicted';\n\nexport interface WorkspaceChange {\n path: string;\n previousPath?: string;\n status: WorkspaceChangeStatus;\n additions?: number;\n deletions?: number;\n binary?: boolean;\n}\n\nexport interface WorkspaceChangesRepository {\n slug: string;\n /** The path prefix of this repository's changes in the flat list, e.g. `platform/`. */\n prefix: string;\n /** False when the checkout could not be inspected (missing, or git failed). */\n available: boolean;\n changes: WorkspaceChange[];\n additions?: number;\n deletions?: number;\n}\n\nexport interface WorkspaceChanges {\n workspacePath: string;\n available: boolean;\n /** Every repository's changes, paths prefixed by the repository directory in a multi-repository session. */\n changes: WorkspaceChange[];\n additions?: number;\n deletions?: number;\n /**\n * One group per environment repository, in position order. Present only\n * when the session's environment holds two or more repositories.\n */\n repositories?: WorkspaceChangesRepository[];\n}\n\nexport interface WorkspaceDiff {\n workspacePath: string;\n path: string;\n patch: string;\n truncated: boolean;\n}\n\nexport type ArtifactEntry = WorkspaceRenderedEntry;\n\nexport interface ArtifactListing {\n /** The confined workspace/project root. */\n rootPath: string;\n /** The workspace artifact directory. */\n artifactsPath: string;\n entries: ArtifactEntry[];\n}\n\nconst MAX_TEXT_FILE_BYTES = 512 * 1024;\nconst MAX_DIFF_BYTES = 512 * 1024;\nconst WORKSPACE_NUMSTAT_SCRIPT = `\nset -e\nworkdir=$1\nbase=$2\nindex_file=$(mktemp)\nuntracked_file=$(mktemp)\nobject_dir=$(mktemp -d)\ntrap 'rm -f \"$index_file\" \"$untracked_file\"; rm -rf \"$object_dir\"' EXIT\nrm -f \"$index_file\"\ngit -C \"$workdir\" diff --numstat -z --find-renames --no-ext-diff --no-textconv \"$base\"\ngit -C \"$workdir\" ls-files --others --exclude-standard -z >\"$untracked_file\"\ngit_dir=$(git -C \"$workdir\" rev-parse --absolute-git-dir)\nexport GIT_INDEX_FILE=\"$index_file\"\nexport GIT_OBJECT_DIRECTORY=\"$object_dir\"\nexport GIT_ALTERNATE_OBJECT_DIRECTORIES=\"$git_dir/objects\"\ngit -C \"$workdir\" read-tree --empty\ngit -C \"$workdir\" update-index --add -z --stdin <\"$untracked_file\"\nempty_tree=$(git -C \"$workdir\" hash-object -t tree /dev/null)\ngit -C \"$workdir\" diff --cached --numstat -z --no-ext-diff --no-textconv \"$empty_tree\"\n`;\nconst BOUNDED_GIT_DIFF_SCRIPT = `\nallow_exit_one=$1\nshift\nstatus_file=$(mktemp)\nstderr_file=$(mktemp)\ntrap 'rm -f \"$status_file\" \"$stderr_file\"' EXIT\n(\n git \"$@\" 2>\"$stderr_file\"\n printf '%s' \"$?\" >\"$status_file\"\n) | head -c ${MAX_DIFF_BYTES + 1}\nstatus=$(cat \"$status_file\")\ncase \"$status\" in\n 0|141) exit 0 ;;\n 1) [ \"$allow_exit_one\" = \"1\" ] && exit 0 ;;\nesac\ncat \"$stderr_file\" >&2\nexit \"\\${status:-1}\"\n`;\nconst TEXT_DECODER = new TextDecoder('utf-8', { fatal: true });\nconst APPROVED_RENDERED_ROOTS = new Set(['.artifacts']);\n\n/** Erase a route handler's path-parameterized context to a plain `Context`. */\nfunction loose(c: unknown): Context {\n return c as Context;\n}\n\n/** Resolve the browsable root, defaulting to the user's home directory. */\nexport function resolveFsRoot(root?: string): string {\n return resolve(root && root.trim() ? root : homedir());\n}\n\n/** True when `candidate` is `root` or nested under it. */\nfunction isWithinRoot(candidate: string, root: string): boolean {\n if (candidate === root) return true;\n const rootWithSep = root.endsWith(sep) ? root : root + sep;\n return candidate.startsWith(rootWithSep);\n}\n\nasync function realOrResolved(path: string): Promise<string> {\n try {\n return await realpath(path);\n } catch {\n return path;\n }\n}\n\n/**\n * Resolve a path's real location (following symlinks) and confirm it stays\n * within `root`. Returns the real path when confined, or `null` when it escapes\n * the root or does not exist. Used so a symlink inside the root that points\n * outside it cannot be browsed or selected.\n */\nasync function realPathWithinRoot(candidate: string, root: string): Promise<string | null> {\n try {\n const real = await realpath(candidate);\n return isWithinRoot(real, root) ? real : null;\n } catch {\n return null;\n }\n}\n\nfunction assertRelativePath(path: string, label: string): string {\n // Names may start or end with spaces; only a blank path is missing.\n if (!path.trim()) throw new Error(`Missing required query param: ${label}`);\n if (isAbsolute(path)) throw new Error(`${label} must be relative`);\n if (path.split(/[\\\\/]+/).includes('..')) throw new Error(`${label} escapes workspace`);\n const normalized = resolve('/', path).slice(1);\n if (!normalized || normalized === '..' || normalized.startsWith(`..${sep}`))\n throw new Error(`${label} escapes workspace`);\n return normalized;\n}\n\nfunction assertApprovedRenderedRoot(renderedRoot: string): string {\n const safeRoot = assertRelativePath(renderedRoot, 'root');\n if (!APPROVED_RENDERED_ROOTS.has(safeRoot)) throw new Error('Root is not approved for rendered workspace access');\n return safeRoot;\n}\n\nasync function confinedWorkspacePath(\n root: string,\n workspacePath: string,\n): Promise<{ resolvedRoot: string; workspace: string }> {\n const resolvedRoot = await realOrResolved(resolveFsRoot(root));\n const candidate = isAbsolute(workspacePath) ? resolve(workspacePath) : resolve(resolvedRoot, workspacePath);\n const workspace = await realPathWithinRoot(candidate, resolvedRoot);\n if (!workspace) throw new Error('Path is outside the browsable root');\n return { resolvedRoot, workspace };\n}\n\nasync function confinedWorkspaceRelativePath(\n root: string,\n workspacePath: string,\n relativePath: string,\n): Promise<{ workspace: string; path: string; relativePath: string }> {\n const safeRelativePath = assertRelativePath(relativePath, 'path');\n const { workspace } = await confinedWorkspacePath(root, workspacePath);\n const candidate = resolve(workspace, safeRelativePath);\n if (!isWithinRoot(candidate, workspace)) throw new Error('Path escapes workspace');\n const confinedPath = await realPathWithinRoot(candidate, workspace);\n if (!confinedPath) throw new Error('Path is outside the workspace');\n return { workspace, path: confinedPath, relativePath: safeRelativePath };\n}\n\n/**\n * List the directories inside `requestedPath`, confined to `root`. An absent or\n * out-of-root path is clamped to the root, so the worst a malicious client can\n * do is browse within the allowed root.\n */\nexport async function listDirectory(root: string, requestedPath?: string): Promise<DirectoryListing> {\n // Resolve the root through symlinks so all confinement checks compare real\n // paths; a symlink that escapes the root is then reliably detectable.\n const resolvedRoot = await realOrResolved(resolveFsRoot(root));\n\n let target = resolvedRoot;\n if (requestedPath && requestedPath.trim()) {\n const candidate = isAbsolute(requestedPath) ? resolve(requestedPath) : resolve(resolvedRoot, requestedPath);\n // Follow symlinks and re-confirm the real target stays within the root.\n target = (await realPathWithinRoot(candidate, resolvedRoot)) ?? resolvedRoot;\n }\n\n // Confirm the target is a real directory; fall back to root otherwise.\n try {\n const info = await stat(target);\n if (!info.isDirectory()) target = resolvedRoot;\n } catch {\n target = resolvedRoot;\n }\n\n const dirents = await readdir(target, { withFileTypes: true });\n const entries: DirectoryEntry[] = [];\n for (const dirent of dirents) {\n if (dirent.name.startsWith('.')) continue; // skip dotfiles/dirs\n const entryPath = join(target, dirent.name);\n let isDir = dirent.isDirectory();\n if (dirent.isSymbolicLink()) {\n // Only surface symlinks whose real target is a directory inside the root,\n // so a link pointing outside the root can't be browsed or selected.\n const real = await realPathWithinRoot(entryPath, resolvedRoot);\n isDir = real ? (await stat(real).catch(() => null))?.isDirectory() === true : false;\n }\n if (isDir) entries.push({ name: dirent.name, path: entryPath });\n }\n entries.sort((a, b) => a.name.localeCompare(b.name));\n\n const parent = target === resolvedRoot ? null : resolve(target, '..');\n\n return { root: resolvedRoot, path: target, parent, entries };\n}\n\nasync function listRenderedEntries(rootPath: string, currentPath = rootPath): Promise<WorkspaceRenderedEntry[]> {\n const dirents = await readdir(currentPath, { withFileTypes: true });\n const entries: WorkspaceRenderedEntry[] = [];\n\n for (const dirent of dirents) {\n const entryPath = join(currentPath, dirent.name);\n const info = await lstat(entryPath);\n const relativePath = entryPath.slice(rootPath.length + 1);\n\n if (info.isDirectory()) {\n entries.push({\n name: dirent.name,\n path: relativePath,\n type: 'directory',\n size: info.size,\n updatedAt: info.mtime.toISOString(),\n });\n entries.push(...(await listRenderedEntries(rootPath, entryPath)));\n continue;\n }\n\n if (info.isFile()) {\n entries.push({\n name: dirent.name,\n path: relativePath,\n type: 'file',\n size: info.size,\n updatedAt: info.mtime.toISOString(),\n });\n }\n }\n\n return entries.sort((a, b) => a.path.localeCompare(b.path));\n}\n\nexport async function listWorkspaceRenderedPath(\n root: string,\n workspacePath: string,\n renderedRoot: string,\n): Promise<WorkspaceRenderedListing> {\n const safeRoot = assertApprovedRenderedRoot(renderedRoot);\n const { workspace } = await confinedWorkspacePath(root, workspacePath);\n const renderedPath = resolve(workspace, safeRoot);\n if (!isWithinRoot(renderedPath, workspace)) throw new Error('Root escapes workspace');\n\n const confinedRootPath = await realPathWithinRoot(renderedPath, workspace);\n if (!confinedRootPath) return { workspacePath: workspace, root: safeRoot, rootPath: renderedPath, entries: [] };\n\n const info = await stat(confinedRootPath);\n if (!info.isDirectory()) return { workspacePath: workspace, root: safeRoot, rootPath: confinedRootPath, entries: [] };\n\n return {\n workspacePath: workspace,\n root: safeRoot,\n rootPath: confinedRootPath,\n entries: await listRenderedEntries(confinedRootPath),\n };\n}\n\nexport async function readWorkspaceFile(root: string, workspacePath: string, path: string): Promise<WorkspaceFile> {\n const safePath = assertRelativePath(path, 'path');\n const relativeRoot = safePath.split('/')[0] ?? '';\n assertApprovedRenderedRoot(relativeRoot);\n const {\n workspace,\n path: confinedPath,\n relativePath,\n } = await confinedWorkspaceRelativePath(root, workspacePath, path);\n const info = await lstat(confinedPath);\n if (info.isDirectory()) throw new Error('Path is a directory');\n if (!info.isFile()) throw new Error('Unsupported file type');\n\n const bytesToRead = Math.min(info.size, MAX_TEXT_FILE_BYTES);\n const contentBuffer = Buffer.alloc(bytesToRead);\n const handle = await open(confinedPath, 'r');\n try {\n await handle.read(contentBuffer, 0, bytesToRead, 0);\n } finally {\n await handle.close();\n }\n\n try {\n const content = TEXT_DECODER.decode(contentBuffer);\n return {\n workspacePath: workspace,\n path: relativePath,\n name: relativePath.split('/').pop() ?? relativePath,\n size: info.size,\n updatedAt: info.mtime.toISOString(),\n contentType: 'text',\n content,\n truncated: info.size > MAX_TEXT_FILE_BYTES,\n };\n } catch {\n return {\n workspacePath: workspace,\n path: relativePath,\n name: relativePath.split('/').pop() ?? relativePath,\n size: info.size,\n updatedAt: info.mtime.toISOString(),\n contentType: 'unsupported',\n };\n }\n}\n\nexport async function listArtifacts(root: string, workspacePath: string): Promise<ArtifactListing> {\n const listing = await listWorkspaceRenderedPath(root, workspacePath, '.artifacts');\n return {\n rootPath: listing.workspacePath,\n artifactsPath: listing.rootPath,\n entries: listing.entries,\n };\n}\n\n// ── Session-backed workspace access ──────────────────────────────────────────\n//\n// The web UI identifies a Factory session workspace by its session id (a UUID),\n// not by a server-local filesystem path — the session's files live inside the\n// session's sandbox (a remote VM on deployed factories). These helpers resolve\n// the session, enforce that the caller owns it, reattach to its sandbox, and\n// serve the approved rendered roots through `SandboxFilesystem`.\n\n/** Dependencies for resolving a `workspacePath` that is a Factory session id. */\nexport interface SessionFsDeps {\n auth: RouteAuth;\n sessions: { getBySessionId(sessionId: string): Promise<SourceControlSession | null> };\n}\n\n/**\n * Resolve a `workspacePath` query param as a Factory session id. Returns the\n * session when one exists and the caller owns it, `null` when no session\n * matches (the caller should fall back to local-path handling), and throws\n * when a session exists but belongs to another tenant.\n */\nasync function resolveAuthorizedSession(\n c: Context,\n deps: SessionFsDeps | undefined,\n workspacePath: string,\n): Promise<SourceControlSession | null> {\n if (!deps) return null;\n const session = await deps.sessions.getBySessionId(workspacePath);\n if (!session) return null;\n if (deps.auth.enabled()) {\n await deps.auth.ensureUser(c);\n const tenant = deps.auth.tenant(c);\n if (!tenant || tenant.orgId !== session.orgId || tenant.userId !== session.userId) {\n throw new Error('Session is not available to the current user');\n }\n }\n return session;\n}\n\ninterface SessionSandboxHandle {\n sandbox: ExecutableSandbox;\n filesystem: SandboxFilesystem;\n layout: SessionLayout;\n /** The branch each layout repository is compared against, by slug. */\n baseBranches: Map<string, string>;\n}\n\n/**\n * Resolve the session's sandbox from the per-process memo and wrap the\n * session layout's root in a `SandboxFilesystem`: the checkout for a\n * one-repository session, the workspace root (one directory per repository)\n * otherwise. Returns `null` when the session has no sandbox in this process\n * (never opened here, or evicted by retirement). This is a passive read path,\n * so it never constructs or provisions: the session's files come back the\n * next time the workspace is actually opened (e.g. by sending a message).\n */\nasync function sessionSandbox(session: SourceControlSession): Promise<SessionSandboxHandle | null> {\n const entry = peekSessionSandbox(session.id);\n // An unresolved workdir means the sandbox never started in this process —\n // nothing is materialized, so there are no files to browse.\n const layout = sessionLayout(entry);\n if (!entry || !layout) return null;\n const sandbox = requireExec(entry.sandbox);\n return {\n sandbox,\n // Session viewers read these files over HTTP, so a symlink must not lead\n // them outside the checkout.\n filesystem: new SandboxFilesystem({ sandbox, workdir: layout.root, verifySymlinks: true }),\n layout,\n baseBranches: repositoryBaseBranches(session, layout, entry.ownRepo),\n };\n}\n\n/**\n * The branch each layout repository is compared against: the session base\n * branch for the session's own repository (session branch vs base), the\n * default branch the boot recorded for every other one, `HEAD` (the checkout's\n * own `origin/HEAD`) until the boot has recorded it.\n */\nfunction repositoryBaseBranches(\n session: SourceControlSession,\n layout: SessionLayout,\n ownRepo: string,\n): Map<string, string> {\n const environment = layout.repos.length > 1 ? peekSessionEnvironment(session.sessionId) : undefined;\n const bases = new Map<string, string>();\n for (const repo of layout.repos) {\n if (layout.repos.length === 1 || repo.slug.toLowerCase() === ownRepo.toLowerCase()) {\n bases.set(repo.slug, session.baseBranch);\n continue;\n }\n const state = environment?.repositories.find(candidate => candidate.slug.toLowerCase() === repo.slug.toLowerCase());\n // The boot records the state at its end, after every setup command; until\n // then a secondary checkout compares against its own `origin/HEAD`.\n bases.set(repo.slug, state?.defaultBranch ?? 'HEAD');\n }\n return bases;\n}\n\n/**\n * Split a client path into the layout repository it belongs to and the path\n * inside that checkout. Longest prefix wins; the inside path is validated\n * again so a prefix cannot smuggle a traversal. A path matching no repository\n * (including a bare prefix) is not available: the file routes only serve the\n * checkouts, never the workspace root itself.\n */\nfunction resolveLayoutPath(\n layout: SessionLayout,\n path: string,\n label: string,\n): { repo: SessionLayoutRepository; relative: string } {\n const safePath = assertRelativePath(path, label);\n if (layout.repos.length === 1) return { repo: layout.repos[0]!, relative: safePath };\n const repo = layout.repos\n .filter(candidate => safePath.startsWith(candidate.prefix) && safePath.length > candidate.prefix.length)\n .toSorted((a, b) => b.prefix.length - a.prefix.length)[0];\n if (!repo) throw new Error(`${label} is not available in this session's repositories`);\n return { repo, relative: assertRelativePath(safePath.slice(repo.prefix.length), label) };\n}\n\n/** List an approved rendered root inside a Factory session's sandbox workdir. */\nexport async function listSessionRenderedPath(\n session: SourceControlSession,\n renderedRoot: string,\n): Promise<WorkspaceRenderedListing> {\n const safeRoot = assertApprovedRenderedRoot(renderedRoot);\n const handle = await sessionSandbox(session);\n const rootPath = posixPath.join(handle?.layout.root ?? '', safeRoot);\n const empty: WorkspaceRenderedListing = { workspacePath: session.sessionId, root: safeRoot, rootPath, entries: [] };\n if (!handle) return empty;\n\n // One round trip: emit \"type\\tsize\\tmtime\\tpath\" per entry. `safeRoot` comes\n // from a fixed allowlist so interpolating it (quoted) is safe. The listing is\n // parsed line by line, so retain all of it rather than the default 1 MiB tail.\n const quotedRoot = `'${rootPath.replace(/'/g, `'\\\\''`)}'`;\n const result = await handle.sandbox.executeCommand(\n 'sh',\n [\n '-c',\n `test -d ${quotedRoot} && find ${quotedRoot} -mindepth 1 -printf '%y\\\\t%s\\\\t%T@\\\\t%p\\\\n' 2>/dev/null || true`,\n ],\n { timeout: 30_000, maxRetainedBytes: Infinity },\n );\n if (result.exitCode !== 0) return empty;\n\n const entries: WorkspaceRenderedEntry[] = [];\n for (const line of result.stdout.split('\\n')) {\n if (!line) continue;\n const [type, sizeStr, mtimeStr, ...pathParts] = line.split('\\t');\n const fullPath = pathParts.join('\\t');\n if (!fullPath || !fullPath.startsWith(`${rootPath}/`)) continue;\n const relativePath = fullPath.slice(rootPath.length + 1);\n entries.push({\n name: posixPath.basename(relativePath),\n path: relativePath,\n type: type === 'd' ? 'directory' : 'file',\n size: type === 'd' ? 0 : Number(sizeStr) || 0,\n updatedAt: new Date((Number(mtimeStr) || 0) * 1000).toISOString(),\n });\n }\n entries.sort((a, b) => a.path.localeCompare(b.path));\n\n return { workspacePath: session.sessionId, root: safeRoot, rootPath, entries };\n}\n\n/**\n * Directory entries the file tree never shows or serves: git internals and the\n * sandbox's own setup markers.\n */\nconst HIDDEN_TREE_ENTRIES = new Set(['.git', SETUP_MARKER_DIR]);\n\n/**\n * Where a tree path lives. Inside a checkout: that checkout and the path within\n * it (a bare repository directory resolves to its root). Elsewhere in the\n * working directory (a multi-repository session's root, `.artifacts`): no\n * checkout, so no ignore rules apply.\n */\nfunction treeLocation(\n layout: SessionLayout,\n path: string,\n): { repo: SessionLayoutRepository; relative: string } | { repo: undefined; relative: string } {\n const safePath = path ? assertRelativePath(path, 'path') : '';\n if (safePath.split('/').some(segment => HIDDEN_TREE_ENTRIES.has(segment))) {\n throw new Error('Path is not available in this session');\n }\n if (layout.repos.length === 1) return { repo: layout.repos[0]!, relative: safePath };\n const repo = layout.repos\n .filter(candidate => `${safePath}/`.startsWith(candidate.prefix))\n .toSorted((a, b) => b.prefix.length - a.prefix.length)[0];\n return repo ? { repo, relative: safePath.slice(repo.prefix.length) } : { repo: undefined, relative: safePath };\n}\n\n/**\n * The checkout-relative paths git ignores, in one `git check-ignore` call.\n * Ignored files (`.env`, build output, `node_modules`) are neither listed nor\n * served: viewers of a session shouldn't read its local secrets. Fails closed\n * when git can't answer.\n */\nasync function ignoredPaths(sandbox: ExecutableSandbox, repoDir: string, paths: string[]): Promise<Set<string>> {\n if (paths.length === 0) return new Set();\n // Paths go in as positional arguments, never into the script text, and back\n // NUL-separated so no filename needs quoting either way.\n const result = await sandbox.executeCommand(\n 'sh',\n ['-c', 'cd \"$1\" && shift && printf \\'%s\\\\0\\' \"$@\" | git check-ignore -z --stdin', 'sh', repoDir, ...paths],\n { timeout: 30_000, maxRetainedBytes: Infinity },\n );\n // 0: some paths are ignored, 1: none are.\n if (result.exitCode === 1) return new Set();\n if (result.exitCode !== 0) throw new Error(`Unable to check ignored files: ${result.stderr.trim() || 'git failed'}`);\n return new Set(result.stdout.split('\\0').filter(Boolean));\n}\n\n/**\n * The real absolute location of each path (relative to `root`), following\n * every symlink, or `''` when it doesn't exist; plus `root`'s own. Paths go in\n * as positional arguments and come back NUL-separated.\n */\nasync function realPaths(\n sandbox: ExecutableSandbox,\n root: string,\n paths: string[],\n): Promise<{ root: string; paths: string[] }> {\n const result = await sandbox.executeCommand(\n 'sh',\n [\n '-c',\n 'cd \"$1\" && shift && printf \\'%s\\\\0\\' \"$(pwd -P)\" && for p; do printf \\'%s\\\\0\\' \"$([ -e \"$p\" ] && readlink -f -- \"$p\")\"; done',\n 'sh',\n root,\n ...paths,\n ],\n { timeout: 30_000, maxRetainedBytes: Infinity },\n );\n if (result.exitCode !== 0) throw new Error(`Unable to resolve symlinks: ${result.stderr.trim() || 'failed'}`);\n const [physicalRoot = '', ...resolved] = result.stdout.split('\\0');\n return { root: physicalRoot, paths: resolved.slice(0, paths.length) };\n}\n\n/** The first `bytes` bytes of a file, base64-encoded in the sandbox so binary content survives. */\nasync function readFilePrefix(sandbox: ExecutableSandbox, path: string, bytes: number): Promise<Buffer> {\n const result = await sandbox.executeCommand(\n 'sh',\n // Not a pipe: sh reports only the last command's status, so a failed head\n // would read as an empty file.\n [\n '-c',\n 't=$(mktemp) && trap \\'rm -f \"$t\"\\' EXIT && head -c \"$1\" -- \"$2\" >\"$t\" && base64 <\"$t\"',\n 'sh',\n String(bytes),\n path,\n ],\n { timeout: 30_000, maxRetainedBytes: Infinity },\n );\n if (result.exitCode !== 0) throw new Error(`Unable to read file: ${result.stderr.trim() || 'failed'}`);\n return Buffer.from(result.stdout, 'base64');\n}\n\n/**\n * Where a real absolute path sits in the tree, or `undefined` when the tree\n * can't show it: missing, outside the working directory, or inside git\n * internals or setup markers.\n */\nfunction treePathOf(layout: SessionLayout, physicalRoot: string, real: string): string | undefined {\n if (!real) return undefined;\n const relative = posixPath.relative(physicalRoot, real);\n if (relative === '..' || relative.startsWith('../') || posixPath.isAbsolute(relative)) return undefined;\n try {\n treeLocation(layout, relative);\n } catch {\n return undefined;\n }\n return relative;\n}\n\n/** Which tree paths their checkout ignores: one `git check-ignore` per checkout involved. */\nasync function ignoredTreePaths(\n sandbox: ExecutableSandbox,\n layout: SessionLayout,\n paths: string[],\n): Promise<Set<string>> {\n const byRepo = new Map<SessionLayoutRepository, Map<string, string>>();\n for (const path of paths) {\n const { repo, relative } = treeLocation(layout, path);\n if (!repo || !relative) continue;\n const inRepo = byRepo.get(repo) ?? new Map<string, string>();\n inRepo.set(relative, path);\n byRepo.set(repo, inRepo);\n }\n const ignored = new Set<string>();\n for (const [repo, inRepo] of byRepo) {\n for (const relative of await ignoredPaths(sandbox, repo.dir, [...inRepo.keys()])) {\n ignored.add(inRepo.get(relative)!);\n }\n }\n return ignored;\n}\n\n/**\n * List one directory of a session's working directory from its sandbox,\n * without git internals or entries a checkout ignores. Passive like every\n * session read: a session with no sandbox in this process comes back\n * `available: false` instead of starting one.\n */\nexport async function listSessionWorkspaceTree(\n session: SourceControlSession,\n path = '',\n): Promise<WorkspaceTreeListing> {\n const requested = path.trim() ? path : '';\n const handle = await sessionSandbox(session);\n const listing = { workspacePath: session.sessionId, path: requested };\n if (!handle) return { ...listing, available: false, entries: [] };\n\n const { layout, sandbox, filesystem } = handle;\n const location = treeLocation(layout, requested);\n const dir = (location.repo ? location.repo.prefix + location.relative : location.relative).replace(/\\/$/, '');\n const children = (await filesystem.readdir(dir || '.')).filter(entry => !HIDDEN_TREE_ENTRIES.has(entry.name));\n const childPath = (name: string) => (dir ? `${dir}/${name}` : name);\n\n // A symlink is shown (not expanded) only when what it leads to could be\n // shown itself; it's judged by its target, since that is what a read serves.\n // The folder itself must be where its path says: the tree doesn't go\n // through symlinked folders.\n const links = children.filter(entry => entry.isSymlink);\n const resolve = [...(dir ? [dir] : []), ...links.map(entry => childPath(entry.name))];\n const real = resolve.length > 0 ? await realPaths(sandbox, layout.root, resolve) : undefined;\n const linkTargets = real ? real.paths.slice(dir ? 1 : 0) : [];\n if (dir && real!.paths[0] !== posixPath.join(real!.root, dir)) {\n throw new Error('Path is not available in this session');\n }\n const targets = new Map(links.map((entry, i) => [entry.name, treePathOf(layout, real!.root, linkTargets[i]!)]));\n const ignored = await ignoredTreePaths(sandbox, layout, [\n ...(dir ? [dir] : []),\n ...children.map(entry => childPath(entry.name)),\n ...[...targets.values()].filter((target): target is string => target !== undefined),\n ]);\n if (dir && ignored.has(dir)) throw new Error('Path is not available in this session');\n const visible = children.filter(entry => {\n if (ignored.has(childPath(entry.name))) return false;\n if (!entry.isSymlink) return true;\n const target = targets.get(entry.name);\n return target !== undefined && !ignored.has(target);\n });\n\n const entries = visible\n .map(\n (entry): WorkspaceTreeEntry => ({\n name: entry.name,\n path: childPath(entry.name),\n type: entry.type,\n ...(entry.type === 'file' && entry.size !== undefined && { size: entry.size }),\n ...(entry.isSymlink && {\n symlinkTarget: entry.symlinkTarget ?? targets.get(entry.name)!,\n linkedPath: targets.get(entry.name)!,\n }),\n }),\n )\n .toSorted((a, b) => (a.type === b.type ? a.name.localeCompare(b.name) : a.type === 'directory' ? -1 : 1));\n return { ...listing, available: true, entries };\n}\n\n/**\n * Read a file inside a session's sandbox: anything under an approved rendered\n * root, or anything the tree would list (not git internals, not ignored by its\n * checkout).\n */\nexport async function readSessionWorkspaceFile(session: SourceControlSession, path: string): Promise<WorkspaceFile> {\n const safePath = assertRelativePath(path, 'path');\n\n const handle = await sessionSandbox(session);\n if (!handle) throw new Error('Session workspace is not available');\n const { layout, sandbox } = handle;\n treeLocation(layout, safePath);\n // Judge the file by where it really is as well as by the path asked for: a\n // symlink to `.env` must not serve it. Rendered roots (plans, reports) are\n // served even when a checkout ignores them, but not through such a symlink.\n const parent = posixPath.dirname(safePath);\n const real = await realPaths(sandbox, layout.root, parent === '.' ? [safePath] : [safePath, parent]);\n const target = treePathOf(layout, real.root, real.paths[0]!);\n // The file itself may be a symlink, but not a folder on the way to it.\n const throughLink = parent !== '.' && real.paths[1] !== posixPath.join(real.root, parent);\n if (target === undefined || throughLink) throw new Error('Path is not available in this session');\n const trusted = APPROVED_RENDERED_ROOTS.has(safePath.split('/')[0] ?? '');\n const checked = [...new Set([...(trusted ? [] : [safePath]), ...(target === safePath ? [] : [target])])];\n if ((await ignoredTreePaths(sandbox, layout, checked)).size > 0) {\n throw new Error('Path is not available in this session');\n }\n const { filesystem } = handle;\n const info = await filesystem.stat(safePath);\n if (info.type === 'directory') throw new Error('Path is a directory');\n\n // Only the shown prefix of a large file leaves the sandbox.\n const truncated = info.size > MAX_TEXT_FILE_BYTES;\n const buffer = truncated\n ? await readFilePrefix(sandbox, real.paths[0]!, MAX_TEXT_FILE_BYTES)\n : ((await filesystem.readFile(safePath)) as Buffer);\n const base = {\n workspacePath: session.sessionId,\n path: safePath,\n name: posixPath.basename(safePath),\n size: info.size,\n updatedAt: info.modifiedAt.toISOString(),\n };\n try {\n const content = TEXT_DECODER.decode(buffer);\n return { ...base, contentType: 'text', content, truncated };\n } catch {\n return { ...base, contentType: 'unsupported' };\n }\n}\n\nfunction changeStatus(code: string): WorkspaceChangeStatus {\n if (code === '??') return 'untracked';\n if (code.includes('U') || code === 'AA' || code === 'DD') return 'conflicted';\n if (code.includes('R')) return 'renamed';\n if (code.includes('C')) return 'copied';\n if (code.includes('D')) return 'deleted';\n if (code.includes('A')) return 'added';\n return 'modified';\n}\n\nexport function parseWorkspaceChanges(output: string): WorkspaceChange[] {\n const records = output.split('\\0');\n const changes: WorkspaceChange[] = [];\n\n for (let index = 0; index < records.length; index += 1) {\n const record = records[index];\n if (!record || record.length < 4) continue;\n const code = record.slice(0, 2);\n const path = record.slice(3);\n const status = changeStatus(code);\n if (status === 'renamed' || status === 'copied') {\n const previousPath = records[index + 1];\n if (previousPath) index += 1;\n changes.push({ path, previousPath: previousPath || undefined, status });\n continue;\n }\n changes.push({ path, status });\n }\n\n return changes.toSorted((a, b) => a.path.localeCompare(b.path));\n}\nexport function parseWorkspaceTrackedChanges(output: string): WorkspaceChange[] {\n const records = output.split('\\0');\n const changes: WorkspaceChange[] = [];\n for (let index = 0; index < records.length;) {\n const code = records[index++];\n if (!code) continue;\n const status = changeStatus(code);\n if (status === 'renamed' || status === 'copied') {\n const previousPath = records[index++];\n const path = records[index++];\n if (path) changes.push({ path, previousPath: previousPath || undefined, status });\n continue;\n }\n const path = records[index++];\n if (path) changes.push({ path, status });\n }\n return changes.toSorted((a, b) => a.path.localeCompare(b.path));\n}\n\nexport function parseWorkspaceChangeStats(output: string) {\n const records = output.split('\\0');\n const stats = new Map<string, { additions?: number; deletions?: number; binary?: boolean }>();\n\n for (let index = 0; index < records.length; index += 1) {\n const record = records[index];\n if (!record) continue;\n const firstTab = record.indexOf('\\t');\n const secondTab = record.indexOf('\\t', firstTab + 1);\n if (firstTab < 0 || secondTab < 0) continue;\n\n const additionsText = record.slice(0, firstTab);\n const deletionsText = record.slice(firstTab + 1, secondTab);\n let path = record.slice(secondTab + 1);\n if (!path) {\n const renamedPath = records[index + 2];\n if (!renamedPath) continue;\n path = renamedPath;\n index += 2;\n }\n if (path.startsWith('./')) path = path.slice(2);\n\n if (additionsText === '-' || deletionsText === '-') {\n stats.set(path, { binary: true });\n continue;\n }\n\n const additions = Number(additionsText);\n const deletions = Number(deletionsText);\n if (Number.isFinite(additions) && Number.isFinite(deletions)) stats.set(path, { additions, deletions });\n }\n\n return stats;\n}\n\nfunction unavailableWorkspaceChanges(workspacePath: string): WorkspaceChanges {\n return { workspacePath, available: false, changes: [] };\n}\n\nasync function resolveSessionComparisonBase(\n sandbox: ExecutableSandbox,\n workdir: string,\n baseBranch: string,\n): Promise<string> {\n const result = await sandbox.executeCommand('git', ['-C', workdir, 'merge-base', 'HEAD', `origin/${baseBranch}`], {\n timeout: 30_000,\n });\n const sha = result.stdout.trim();\n return result.exitCode === 0 && /^[0-9a-f]{40,64}$/i.test(sha) ? sha : 'HEAD';\n}\n\ntype RepositoryChanges = Pick<WorkspaceChangesRepository, 'available' | 'changes' | 'additions' | 'deletions'>;\n\n/** The changes of one checkout against its comparison base; `available: false` when git cannot inspect it. */\nasync function listRepositoryChanges(\n sandbox: ExecutableSandbox,\n workdir: string,\n baseBranch: string,\n): Promise<RepositoryChanges> {\n const comparisonBase = await resolveSessionComparisonBase(sandbox, workdir, baseBranch);\n\n // These outputs are parsed record by record (-z) and per path, so retain all\n // of them rather than the default 1 MiB tail, which would drop or split entries.\n const [statusResult, trackedResult, statsResult] = await Promise.all([\n sandbox.executeCommand('git', ['-C', workdir, 'status', '--porcelain=v1', '-z', '--untracked-files=all'], {\n timeout: 30_000,\n maxRetainedBytes: Infinity,\n }),\n sandbox.executeCommand('git', ['-C', workdir, 'diff', '--name-status', '-z', '--find-renames', comparisonBase], {\n timeout: 30_000,\n maxRetainedBytes: Infinity,\n }),\n sandbox.executeCommand('sh', ['-c', WORKSPACE_NUMSTAT_SCRIPT, 'mastracode-numstat', workdir, comparisonBase], {\n timeout: 30_000,\n maxRetainedBytes: Infinity,\n }),\n ]);\n if (statusResult.exitCode !== 0) return { available: false, changes: [] };\n\n const statusChanges = parseWorkspaceChanges(statusResult.stdout);\n const trackedChanges = trackedResult.exitCode === 0 ? parseWorkspaceTrackedChanges(trackedResult.stdout) : [];\n const changesByPath = new Map(trackedChanges.map(change => [change.path, change]));\n for (const change of statusChanges) {\n if (trackedResult.exitCode !== 0 || change.status === 'untracked' || change.status === 'conflicted') {\n changesByPath.set(change.path, change);\n }\n }\n const changes = [...changesByPath.values()].toSorted((a, b) => a.path.localeCompare(b.path));\n if (statsResult.exitCode !== 0) return { available: true, changes };\n\n const stats = parseWorkspaceChangeStats(statsResult.stdout);\n let additions = 0;\n let deletions = 0;\n const changesWithStats = changes.map(change => {\n const changeStats = stats.get(change.path);\n additions += changeStats?.additions ?? 0;\n deletions += changeStats?.deletions ?? 0;\n return { ...change, ...changeStats };\n });\n return { available: true, changes: changesWithStats, additions, deletions };\n}\n\nfunction prefixChange(change: WorkspaceChange, prefix: string): WorkspaceChange {\n if (!prefix) return change;\n return {\n ...change,\n path: `${prefix}${change.path}`,\n ...(change.previousPath ? { previousPath: `${prefix}${change.previousPath}` } : {}),\n };\n}\n\nexport async function listSessionWorkspaceChanges(session: SourceControlSession): Promise<WorkspaceChanges> {\n const handle = await sessionSandbox(session);\n if (!handle) return unavailableWorkspaceChanges(session.sessionId);\n const { layout, baseBranches: bases } = handle;\n\n // One repository: the response is exactly what it was before layouts.\n if (layout.repos.length === 1) {\n const repo = layout.repos[0]!;\n const result = await listRepositoryChanges(handle.sandbox, repo.dir, bases.get(repo.slug) ?? session.baseBranch);\n if (!result.available) return unavailableWorkspaceChanges(session.sessionId);\n return { workspacePath: session.sessionId, ...result };\n }\n\n // Several: inspect every checkout in parallel, one group each. A failing\n // one (missing checkout, git error) is unavailable on its own, the others\n // still answer.\n const groups: WorkspaceChangesRepository[] = await Promise.all(\n layout.repos.map(async repo => {\n const result = await listRepositoryChanges(handle.sandbox, repo.dir, bases.get(repo.slug)!);\n return {\n slug: repo.slug,\n prefix: repo.prefix,\n ...result,\n changes: result.changes.map(change => prefixChange(change, repo.prefix)),\n };\n }),\n );\n const available = groups.filter(group => group.available);\n const changes = available.flatMap(group => group.changes).toSorted((a, b) => a.path.localeCompare(b.path));\n const counted = available.filter(group => group.additions !== undefined);\n const totals =\n counted.length > 0\n ? {\n additions: counted.reduce((sum, group) => sum + (group.additions ?? 0), 0),\n deletions: counted.reduce((sum, group) => sum + (group.deletions ?? 0), 0),\n }\n : {};\n return {\n workspacePath: session.sessionId,\n available: available.length > 0,\n changes,\n ...totals,\n repositories: groups,\n };\n}\n\nasync function executeBoundedGitDiff(sandbox: ExecutableSandbox, args: string[], allowExitOne = false) {\n return sandbox.executeCommand(\n 'sh',\n ['-c', BOUNDED_GIT_DIFF_SCRIPT, 'mastracode-diff', allowExitOne ? '1' : '0', ...args],\n { timeout: 30_000 },\n );\n}\n\nfunction truncatePatch(patchBuffer: Buffer): string {\n const patch = patchBuffer.subarray(0, MAX_DIFF_BYTES).toString('utf8');\n const lastNewline = patch.lastIndexOf('\\n');\n if (lastNewline >= 0) return patch.slice(0, lastNewline + 1);\n return patch.replace(/\\uFFFD+$/, '');\n}\n\nexport async function readSessionWorkspaceDiff(\n session: SourceControlSession,\n path: string,\n previousPath?: string,\n): Promise<WorkspaceDiff> {\n const safePath = assertRelativePath(path, 'path');\n if (previousPath) assertRelativePath(previousPath, 'previousPath');\n const handle = await sessionSandbox(session);\n if (!handle) throw new Error('Session workspace is not available');\n // The client sends the prefixed paths it was listed; git runs inside the\n // checkout they belong to, on the paths relative to it. A rename never\n // crosses checkouts, so both halves must resolve to the same repository.\n const target = resolveLayoutPath(handle.layout, safePath, 'path');\n const previous = previousPath ? resolveLayoutPath(handle.layout, previousPath, 'previousPath') : undefined;\n if (previous && previous.repo !== target.repo) {\n throw new Error('previousPath is not available in the repository of path');\n }\n const workdir = target.repo.dir;\n const comparisonBase = await resolveSessionComparisonBase(\n handle.sandbox,\n workdir,\n handle.baseBranches.get(target.repo.slug)!,\n );\n\n const pathspecs = previous ? [previous.relative, target.relative] : [target.relative];\n let result = await executeBoundedGitDiff(handle.sandbox, [\n '--literal-pathspecs',\n '-C',\n workdir,\n 'diff',\n '--find-renames',\n '--no-ext-diff',\n '--no-color',\n '--unified=3',\n comparisonBase,\n '--',\n ...pathspecs,\n ]);\n if (result.exitCode !== 0) throw new Error(result.stderr || 'Unable to read workspace diff');\n\n if (!result.stdout) {\n const untracked = await handle.sandbox.executeCommand(\n 'git',\n ['--literal-pathspecs', '-C', workdir, 'ls-files', '--others', '--exclude-standard', '--', target.relative],\n { timeout: 30_000, maxRetainedBytes: Infinity },\n );\n if (untracked.exitCode === 0 && untracked.stdout.trim()) {\n result = await executeBoundedGitDiff(\n handle.sandbox,\n [\n '-C',\n workdir,\n 'diff',\n '--no-index',\n '--no-ext-diff',\n '--no-color',\n '--unified=3',\n '--',\n '/dev/null',\n target.relative,\n ],\n true,\n );\n if (result.exitCode !== 0 && result.exitCode !== 1) {\n throw new Error(result.stderr || 'Unable to read workspace diff');\n }\n }\n }\n\n const patchBuffer = Buffer.from(result.stdout);\n const truncated = patchBuffer.length > MAX_DIFF_BYTES;\n return {\n workspacePath: session.sessionId,\n path: safePath,\n patch: truncated ? truncatePatch(patchBuffer) : result.stdout,\n truncated,\n };\n}\n\nexport interface ResolvedCodebase {\n /**\n * The resourceId the TUI would use for this path — derived identically so a\n * project opened in the terminal and in the web app resolve to the SAME\n * session (and therefore the same threads).\n */\n resourceId: string;\n name: string;\n rootPath: string;\n gitUrl?: string;\n gitBranch?: string;\n}\n\n/**\n * Resolve a project path to the same resourceId the TUI uses. Mirrors\n * `createMastraCode`: detect the project, then apply any resourceId override\n * (MASTRA_RESOURCE_ID env var or `.mastracode/database.json`). This is the\n * shared continuity point — start in the TUI, continue on the web, same path\n * → same resourceId → same session.\n */\nexport function resolveCodebase(projectPath: string): ResolvedCodebase {\n const info = detectProject(projectPath);\n const override = getResourceIdOverride(info.rootPath);\n return {\n resourceId: override ?? info.resourceId,\n name: info.name,\n rootPath: info.rootPath,\n gitUrl: info.gitUrl,\n gitBranch: info.gitBranch,\n };\n}\n\n/**\n * Build the web filesystem routes as Mastra `apiRoutes`:\n * - `GET /web/fs/list?path=...` — browse directories (confined to root)\n * - `GET /web/codebase/resolve?path=...` — TUI-compatible codebase resourceId\n */\nexport function buildFsRoutes(options: { root?: string; sessionFs?: SessionFsDeps } = {}): ApiRoute[] {\n const root = resolveFsRoot(options.root);\n const sessionFs = options.sessionFs;\n\n return [\n registerApiRoute('/web/fs/list', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const path = c.req.query('path');\n try {\n const listing = await listDirectory(root, path);\n return c.json(listing);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return c.json({ error: message }, 500);\n }\n },\n }),\n registerApiRoute('/web/artifacts/list', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const path = c.req.query('path');\n if (!path) return c.json({ error: 'Missing required query param: path' }, 400);\n try {\n return c.json(await listArtifacts(root, path));\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n const status = message === 'Path is outside the browsable root' ? 403 : 500;\n return c.json({ error: message }, status);\n }\n },\n }),\n registerApiRoute('/web/workspace/rendered/list', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const workspacePath = c.req.query('workspacePath');\n const renderedRoot = c.req.query('root');\n if (!workspacePath) return c.json({ error: 'Missing required query param: workspacePath' }, 400);\n if (!renderedRoot) return c.json({ error: 'Missing required query param: root' }, 400);\n try {\n const session = await resolveAuthorizedSession(loose(c), sessionFs, workspacePath);\n if (session && sessionFs) {\n return c.json(await listSessionRenderedPath(session, renderedRoot));\n }\n return c.json(await listWorkspaceRenderedPath(root, workspacePath, renderedRoot));\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n const status =\n message.includes('outside') ||\n message.includes('relative') ||\n message.includes('escapes') ||\n message.includes('not approved') ||\n message.includes('not available')\n ? 403\n : 500;\n return c.json({ error: message }, status);\n }\n },\n }),\n registerApiRoute('/web/workspace/changes', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const workspacePath = c.req.query('workspacePath');\n if (!workspacePath) return c.json({ error: 'Missing required query param: workspacePath' }, 400);\n try {\n const session = await resolveAuthorizedSession(loose(c), sessionFs, workspacePath);\n if (!session || !sessionFs) return c.json(unavailableWorkspaceChanges(workspacePath));\n return c.json(await listSessionWorkspaceChanges(session));\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return c.json({ error: message }, message.includes('not available') ? 403 : 500);\n }\n },\n }),\n registerApiRoute('/web/workspace/changes/diff', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const workspacePath = c.req.query('workspacePath');\n const path = c.req.query('path');\n const previousPath = c.req.query('previousPath');\n if (!workspacePath) return c.json({ error: 'Missing required query param: workspacePath' }, 400);\n if (!path) return c.json({ error: 'Missing required query param: path' }, 400);\n try {\n const session = await resolveAuthorizedSession(loose(c), sessionFs, workspacePath);\n if (!session || !sessionFs) return c.json({ error: 'Session workspace is not available' }, 403);\n return c.json(await readSessionWorkspaceDiff(session, path, previousPath));\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n const status =\n message.includes('relative') || message.includes('escapes') || message.includes('not available')\n ? 403\n : 500;\n return c.json({ error: message }, status);\n }\n },\n }),\n registerApiRoute('/web/workspace/tree', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const workspacePath = c.req.query('workspacePath');\n if (!workspacePath) return c.json({ error: 'Missing required query param: workspacePath' }, 400);\n try {\n const session = await resolveAuthorizedSession(loose(c), sessionFs, workspacePath);\n if (!session || !sessionFs) return c.json({ error: 'Session workspace is not available' }, 403);\n return c.json(await listSessionWorkspaceTree(session, c.req.query('path') ?? ''));\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n const status =\n message.includes('relative') || message.includes('escapes') || message.includes('not available')\n ? 403\n : message.includes('not found')\n ? 404\n : 500;\n return c.json({ error: message }, status);\n }\n },\n }),\n registerApiRoute('/web/workspace/file', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const workspacePath = c.req.query('workspacePath');\n const path = c.req.query('path');\n if (!workspacePath) return c.json({ error: 'Missing required query param: workspacePath' }, 400);\n if (!path) return c.json({ error: 'Missing required query param: path' }, 400);\n try {\n const session = await resolveAuthorizedSession(loose(c), sessionFs, workspacePath);\n if (session && sessionFs) return c.json(await readSessionWorkspaceFile(session, path));\n return c.json(await readWorkspaceFile(root, workspacePath, path));\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n const status =\n message.includes('outside') ||\n message.includes('relative') ||\n message.includes('escapes') ||\n message.includes('not approved') ||\n message.includes('not available')\n ? 403\n : message.includes('directory')\n ? 400\n : message.includes('not found')\n ? 404\n : 500;\n return c.json({ error: message }, status);\n }\n },\n }),\n registerApiRoute('/web/codebase/resolve', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const path = c.req.query('path');\n if (!path) return c.json({ error: 'Missing required query param: path' }, 400);\n // Confine resolution to the browsable root (following symlinks), so this\n // endpoint can't be used to probe arbitrary filesystem paths. The web UI\n // only ever resolves directories the user picked via the root-confined\n // browser, so legitimate requests are always within the root.\n const confined = await realPathWithinRoot(isAbsolute(path) ? resolve(path) : resolve(root, path), root);\n if (!confined) return c.json({ error: 'Path is outside the browsable root' }, 403);\n try {\n return c.json(resolveCodebase(confined));\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return c.json({ error: message }, 500);\n }\n },\n }),\n ];\n}\n"],"mappings":";;;;;;;;;;;AAmKA,MAAM,sBAAsB;AAC5B,MAAM,iBAAiB;AACvB,MAAM,2BAA2B;;;;;;;;;;;;;;;;;;;;AAoBjC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;IAClB,MAAM,OAAO,EAAE,IAAI,MAAM,MAAM;IAC/B,IAAI,CAAC,MAAM,OAAO,EAAE,KAAK,EAAE,OAAO,qCAAqC,GAAG,GAAG;IAK7E,MAAM,WAAW,MAAM,mBAAmB,WAAW,IAAI,IAAI,QAAQ,IAAI,IAAI,QAAQ,MAAM,IAAI,GAAG,IAAI;IACtG,IAAI,CAAC,UAAU,OAAO,EAAE,KAAK,EAAE,OAAO,qCAAqC,GAAG,GAAG;IACjF,IAAI;KACF,OAAO,EAAE,KAAK,gBAAgB,QAAQ,CAAC;IACzC,SAAS,OAAO;KACd,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;KACrE,OAAO,EAAE,KAAK,EAAE,OAAO,QAAQ,GAAG,GAAG;IACvC;GACF;EACF,CAAC;CACH;AACF"}
1
+ {"version":3,"file":"fs.js","names":["posixPath"],"sources":["../../src/routes/fs.ts"],"sourcesContent":["import { lstat, open, readdir, realpath, stat } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { isAbsolute, join, posix as posixPath, resolve, sep } from 'node:path';\n\nimport { SETUP_MARKER_DIR } from '@internal/workspace';\nimport { SandboxFilesystem } from '@mastra/code-sdk/agents/sandbox-filesystem';\nimport { detectProject, getResourceIdOverride } from '@mastra/code-sdk/utils/project';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { ApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\n\nimport { requireExec } from '../sandbox/materialization.js';\nimport type { ExecutableSandbox } from '../sandbox/materialization.js';\nimport { peekSessionSandbox, sessionLayout } from '../sandbox/session-sandbox.js';\nimport type { SessionLayout, SessionLayoutRepository } from '../sandbox/session-sandbox.js';\nimport { peekSessionEnvironment } from '../session/environment-state-processor.js';\nimport type { SourceControlSession } from '../storage/domains/source-control/base.js';\nimport type { RouteAuth } from './route.js';\n\n/**\n * Server-side directory browser for the web project picker.\n *\n * The browser cannot read absolute filesystem paths (the File System Access API\n * only exposes a directory *name*), so the picker must ask the server — which\n * does have filesystem access — to enumerate directories. The result is real\n * absolute paths the user can select without typing.\n *\n * All access is confined to a configured `root` (default: the user's home\n * directory). Requests that try to escape the root via `..` or symlinks are\n * clamped back to the root.\n */\n\nexport interface DirectoryEntry {\n name: string;\n /** Absolute path to the entry. */\n path: string;\n}\n\nexport interface DirectoryListing {\n /** The allowed root; clients cannot browse above this. */\n root: string;\n /** The absolute path that was listed. */\n path: string;\n /** Parent directory path, or null when `path` is the root. */\n parent: string | null;\n /** Subdirectories of `path` (directories only, sorted, hidden excluded). */\n entries: DirectoryEntry[];\n}\n\nexport interface WorkspaceRenderedEntry {\n name: string;\n /** Path relative to the configured rendered root. */\n path: string;\n type: 'file' | 'directory';\n size: number;\n updatedAt: string;\n}\n\nexport interface WorkspaceRenderedListing {\n /** The confined workspace/project root. */\n workspacePath: string;\n /** Configured workspace-relative rendered root, e.g. `.artifacts`. */\n root: string;\n /** The confined absolute path for the rendered root. */\n rootPath: string;\n entries: WorkspaceRenderedEntry[];\n}\n\nexport interface WorkspaceFile {\n /** The confined workspace/project root. */\n workspacePath: string;\n /** Workspace-relative file path. */\n path: string;\n name: string;\n size: number;\n updatedAt: string;\n contentType: 'text' | 'unsupported';\n content?: string;\n truncated?: boolean;\n}\n\nexport interface WorkspaceTreeEntry {\n name: string;\n /** Path from the session's layout root, the form the file route takes. */\n path: string;\n type: 'file' | 'directory';\n size?: number;\n /** Set when the entry is a symlink: where it points, as written in the link. */\n symlinkTarget?: string;\n /** Set when the entry is a symlink: the tree path of what it resolves to. */\n linkedPath?: string;\n}\n\n/** One directory of a session's checkouts, read live from its sandbox. */\nexport interface WorkspaceTreeListing {\n workspacePath: string;\n /** The listed directory; empty for the top level. */\n path: string;\n /** False when this process holds no sandbox for the session, so nothing was read. */\n available: boolean;\n entries: WorkspaceTreeEntry[];\n}\n\nexport type WorkspaceChangeStatus =\n | 'modified'\n | 'added'\n | 'deleted'\n | 'renamed'\n | 'copied'\n | 'untracked'\n | 'conflicted';\n\nexport interface WorkspaceChange {\n path: string;\n previousPath?: string;\n status: WorkspaceChangeStatus;\n additions?: number;\n deletions?: number;\n binary?: boolean;\n}\n\nexport interface WorkspaceChangesRepository {\n slug: string;\n /** The path prefix of this repository's changes in the flat list, e.g. `platform/`. */\n prefix: string;\n /** False when the checkout could not be inspected (missing, or git failed). */\n available: boolean;\n changes: WorkspaceChange[];\n additions?: number;\n deletions?: number;\n}\n\nexport interface WorkspaceChanges {\n workspacePath: string;\n available: boolean;\n /** Every repository's changes, paths prefixed by the repository directory in a multi-repository session. */\n changes: WorkspaceChange[];\n additions?: number;\n deletions?: number;\n /**\n * One group per environment repository, in position order. Present only\n * when the session's environment holds two or more repositories.\n */\n repositories?: WorkspaceChangesRepository[];\n}\n\nexport type WorkspaceChangesScope = 'branch' | 'uncommitted';\n\nexport type WorkspacePatchOmission = 'file-too-large' | 'total-too-large';\n\nexport interface WorkspaceChangePatches extends WorkspaceChanges {\n scope: WorkspaceChangesScope;\n /** Each change's unified diff, keyed by its `path` in `changes`. */\n patches: Record<string, string>;\n /** Why a change has no entry in `patches`; a change in neither map is one git could not diff. */\n omittedPatches: Record<string, WorkspacePatchOmission>;\n /** Git's first error line when it could not diff changed files, prefixed by the slug with several repositories. */\n diffError?: string;\n}\n\nexport type ArtifactEntry = WorkspaceRenderedEntry;\n\nexport interface ArtifactListing {\n /** The confined workspace/project root. */\n rootPath: string;\n /** The workspace artifact directory. */\n artifactsPath: string;\n entries: ArtifactEntry[];\n}\n\nconst MAX_TEXT_FILE_BYTES = 512 * 1024;\nconst MAX_DIFF_BYTES = 512 * 1024;\nconst MAX_PATCH_SET_BYTES = 8 * 1024 * 1024;\n/** Diffs the worktree against `$2`, untracked files as added through a throwaway index so the real one stays untouched. */\nconst WORKSPACE_DIFF_SCRIPT = `\nset -e\nworkdir=$1\nbase=$2\nshift 2\nindex_file=$(mktemp)\nuntracked_file=$(mktemp)\nobject_dir=$(mktemp -d)\ntrap 'rm -f \"$index_file\" \"$untracked_file\"; rm -rf \"$object_dir\"' EXIT\nrm -f \"$index_file\"\ngit -C \"$workdir\" -c core.quotePath=false diff --no-ext-diff --no-textconv --find-renames \"$@\" \"$base\"\ngit -C \"$workdir\" ls-files --others --exclude-standard -z >\"$untracked_file\"\ngit_dir=$(git -C \"$workdir\" rev-parse --absolute-git-dir)\nexport GIT_INDEX_FILE=\"$index_file\"\nexport GIT_OBJECT_DIRECTORY=\"$object_dir\"\nexport GIT_ALTERNATE_OBJECT_DIRECTORIES=\"$git_dir/objects\"\ngit -C \"$workdir\" read-tree --empty\ngit -C \"$workdir\" update-index --add -z --stdin <\"$untracked_file\"\nempty_tree=$(git -C \"$workdir\" hash-object -t tree /dev/null)\ngit -C \"$workdir\" -c core.quotePath=false diff --cached --no-ext-diff --no-textconv \"$@\" \"$empty_tree\"\n`;\nconst NUMSTAT_FORMAT = ['--numstat', '-z'];\nconst PATCH_FORMAT = ['--patch', '--no-color', '--unified=3', '--src-prefix=a/', '--dst-prefix=b/'];\n/** Keeps the first `$1` bytes of the command in the remaining arguments; being cut short is not a failure. */\nconst BOUNDED_OUTPUT_SCRIPT = `\nlimit=$1\nshift\nstatus_file=$(mktemp)\ntrap 'rm -f \"$status_file\"' EXIT\n(\n \"$@\"\n printf '%s' \"$?\" >\"$status_file\"\n) | head -c \"$limit\"\nstatus=$(cat \"$status_file\")\ncase \"$status\" in\n 0|141) exit 0 ;;\nesac\nexit \"\\${status:-1}\"\n`;\nconst TEXT_DECODER = new TextDecoder('utf-8', { fatal: true });\nconst APPROVED_RENDERED_ROOTS = new Set(['.artifacts']);\n\n/** Erase a route handler's path-parameterized context to a plain `Context`. */\nfunction loose(c: unknown): Context {\n return c as Context;\n}\n\n/** Resolve the browsable root, defaulting to the user's home directory. */\nexport function resolveFsRoot(root?: string): string {\n return resolve(root && root.trim() ? root : homedir());\n}\n\n/** True when `candidate` is `root` or nested under it. */\nfunction isWithinRoot(candidate: string, root: string): boolean {\n if (candidate === root) return true;\n const rootWithSep = root.endsWith(sep) ? root : root + sep;\n return candidate.startsWith(rootWithSep);\n}\n\nasync function realOrResolved(path: string): Promise<string> {\n try {\n return await realpath(path);\n } catch {\n return path;\n }\n}\n\n/**\n * Resolve a path's real location (following symlinks) and confirm it stays\n * within `root`. Returns the real path when confined, or `null` when it escapes\n * the root or does not exist. Used so a symlink inside the root that points\n * outside it cannot be browsed or selected.\n */\nasync function realPathWithinRoot(candidate: string, root: string): Promise<string | null> {\n try {\n const real = await realpath(candidate);\n return isWithinRoot(real, root) ? real : null;\n } catch {\n return null;\n }\n}\n\nfunction assertRelativePath(path: string, label: string): string {\n // Names may start or end with spaces; only a blank path is missing.\n if (!path.trim()) throw new Error(`Missing required query param: ${label}`);\n if (isAbsolute(path)) throw new Error(`${label} must be relative`);\n if (path.split(/[\\\\/]+/).includes('..')) throw new Error(`${label} escapes workspace`);\n const normalized = resolve('/', path).slice(1);\n if (!normalized || normalized === '..' || normalized.startsWith(`..${sep}`))\n throw new Error(`${label} escapes workspace`);\n return normalized;\n}\n\nfunction assertApprovedRenderedRoot(renderedRoot: string): string {\n const safeRoot = assertRelativePath(renderedRoot, 'root');\n if (!APPROVED_RENDERED_ROOTS.has(safeRoot)) throw new Error('Root is not approved for rendered workspace access');\n return safeRoot;\n}\n\nasync function confinedWorkspacePath(\n root: string,\n workspacePath: string,\n): Promise<{ resolvedRoot: string; workspace: string }> {\n const resolvedRoot = await realOrResolved(resolveFsRoot(root));\n const candidate = isAbsolute(workspacePath) ? resolve(workspacePath) : resolve(resolvedRoot, workspacePath);\n const workspace = await realPathWithinRoot(candidate, resolvedRoot);\n if (!workspace) throw new Error('Path is outside the browsable root');\n return { resolvedRoot, workspace };\n}\n\nasync function confinedWorkspaceRelativePath(\n root: string,\n workspacePath: string,\n relativePath: string,\n): Promise<{ workspace: string; path: string; relativePath: string }> {\n const safeRelativePath = assertRelativePath(relativePath, 'path');\n const { workspace } = await confinedWorkspacePath(root, workspacePath);\n const candidate = resolve(workspace, safeRelativePath);\n if (!isWithinRoot(candidate, workspace)) throw new Error('Path escapes workspace');\n const confinedPath = await realPathWithinRoot(candidate, workspace);\n if (!confinedPath) throw new Error('Path is outside the workspace');\n return { workspace, path: confinedPath, relativePath: safeRelativePath };\n}\n\n/**\n * List the directories inside `requestedPath`, confined to `root`. An absent or\n * out-of-root path is clamped to the root, so the worst a malicious client can\n * do is browse within the allowed root.\n */\nexport async function listDirectory(root: string, requestedPath?: string): Promise<DirectoryListing> {\n // Resolve the root through symlinks so all confinement checks compare real\n // paths; a symlink that escapes the root is then reliably detectable.\n const resolvedRoot = await realOrResolved(resolveFsRoot(root));\n\n let target = resolvedRoot;\n if (requestedPath && requestedPath.trim()) {\n const candidate = isAbsolute(requestedPath) ? resolve(requestedPath) : resolve(resolvedRoot, requestedPath);\n // Follow symlinks and re-confirm the real target stays within the root.\n target = (await realPathWithinRoot(candidate, resolvedRoot)) ?? resolvedRoot;\n }\n\n // Confirm the target is a real directory; fall back to root otherwise.\n try {\n const info = await stat(target);\n if (!info.isDirectory()) target = resolvedRoot;\n } catch {\n target = resolvedRoot;\n }\n\n const dirents = await readdir(target, { withFileTypes: true });\n const entries: DirectoryEntry[] = [];\n for (const dirent of dirents) {\n if (dirent.name.startsWith('.')) continue; // skip dotfiles/dirs\n const entryPath = join(target, dirent.name);\n let isDir = dirent.isDirectory();\n if (dirent.isSymbolicLink()) {\n // Only surface symlinks whose real target is a directory inside the root,\n // so a link pointing outside the root can't be browsed or selected.\n const real = await realPathWithinRoot(entryPath, resolvedRoot);\n isDir = real ? (await stat(real).catch(() => null))?.isDirectory() === true : false;\n }\n if (isDir) entries.push({ name: dirent.name, path: entryPath });\n }\n entries.sort((a, b) => a.name.localeCompare(b.name));\n\n const parent = target === resolvedRoot ? null : resolve(target, '..');\n\n return { root: resolvedRoot, path: target, parent, entries };\n}\n\nasync function listRenderedEntries(rootPath: string, currentPath = rootPath): Promise<WorkspaceRenderedEntry[]> {\n const dirents = await readdir(currentPath, { withFileTypes: true });\n const entries: WorkspaceRenderedEntry[] = [];\n\n for (const dirent of dirents) {\n const entryPath = join(currentPath, dirent.name);\n const info = await lstat(entryPath);\n const relativePath = entryPath.slice(rootPath.length + 1);\n\n if (info.isDirectory()) {\n entries.push({\n name: dirent.name,\n path: relativePath,\n type: 'directory',\n size: info.size,\n updatedAt: info.mtime.toISOString(),\n });\n entries.push(...(await listRenderedEntries(rootPath, entryPath)));\n continue;\n }\n\n if (info.isFile()) {\n entries.push({\n name: dirent.name,\n path: relativePath,\n type: 'file',\n size: info.size,\n updatedAt: info.mtime.toISOString(),\n });\n }\n }\n\n return entries.sort((a, b) => a.path.localeCompare(b.path));\n}\n\nexport async function listWorkspaceRenderedPath(\n root: string,\n workspacePath: string,\n renderedRoot: string,\n): Promise<WorkspaceRenderedListing> {\n const safeRoot = assertApprovedRenderedRoot(renderedRoot);\n const { workspace } = await confinedWorkspacePath(root, workspacePath);\n const renderedPath = resolve(workspace, safeRoot);\n if (!isWithinRoot(renderedPath, workspace)) throw new Error('Root escapes workspace');\n\n const confinedRootPath = await realPathWithinRoot(renderedPath, workspace);\n if (!confinedRootPath) return { workspacePath: workspace, root: safeRoot, rootPath: renderedPath, entries: [] };\n\n const info = await stat(confinedRootPath);\n if (!info.isDirectory()) return { workspacePath: workspace, root: safeRoot, rootPath: confinedRootPath, entries: [] };\n\n return {\n workspacePath: workspace,\n root: safeRoot,\n rootPath: confinedRootPath,\n entries: await listRenderedEntries(confinedRootPath),\n };\n}\n\nexport async function readWorkspaceFile(root: string, workspacePath: string, path: string): Promise<WorkspaceFile> {\n const safePath = assertRelativePath(path, 'path');\n const relativeRoot = safePath.split('/')[0] ?? '';\n assertApprovedRenderedRoot(relativeRoot);\n const {\n workspace,\n path: confinedPath,\n relativePath,\n } = await confinedWorkspaceRelativePath(root, workspacePath, path);\n const info = await lstat(confinedPath);\n if (info.isDirectory()) throw new Error('Path is a directory');\n if (!info.isFile()) throw new Error('Unsupported file type');\n\n const bytesToRead = Math.min(info.size, MAX_TEXT_FILE_BYTES);\n const contentBuffer = Buffer.alloc(bytesToRead);\n const handle = await open(confinedPath, 'r');\n try {\n await handle.read(contentBuffer, 0, bytesToRead, 0);\n } finally {\n await handle.close();\n }\n\n try {\n const content = TEXT_DECODER.decode(contentBuffer);\n return {\n workspacePath: workspace,\n path: relativePath,\n name: relativePath.split('/').pop() ?? relativePath,\n size: info.size,\n updatedAt: info.mtime.toISOString(),\n contentType: 'text',\n content,\n truncated: info.size > MAX_TEXT_FILE_BYTES,\n };\n } catch {\n return {\n workspacePath: workspace,\n path: relativePath,\n name: relativePath.split('/').pop() ?? relativePath,\n size: info.size,\n updatedAt: info.mtime.toISOString(),\n contentType: 'unsupported',\n };\n }\n}\n\nexport async function listArtifacts(root: string, workspacePath: string): Promise<ArtifactListing> {\n const listing = await listWorkspaceRenderedPath(root, workspacePath, '.artifacts');\n return {\n rootPath: listing.workspacePath,\n artifactsPath: listing.rootPath,\n entries: listing.entries,\n };\n}\n\n// ── Session-backed workspace access ──────────────────────────────────────────\n//\n// The web UI identifies a Factory session workspace by its session id (a UUID),\n// not by a server-local filesystem path — the session's files live inside the\n// session's sandbox (a remote VM on deployed factories). These helpers resolve\n// the session, enforce that the caller owns it, reattach to its sandbox, and\n// serve the approved rendered roots through `SandboxFilesystem`.\n\n/** Dependencies for resolving a `workspacePath` that is a Factory session id. */\nexport interface SessionFsDeps {\n auth: RouteAuth;\n sessions: { getBySessionId(sessionId: string): Promise<SourceControlSession | null> };\n}\n\n/**\n * Resolve a `workspacePath` query param as a Factory session id. Returns the\n * session when one exists and the caller owns it, `null` when no session\n * matches (the caller should fall back to local-path handling), and throws\n * when a session exists but belongs to another tenant.\n */\nasync function resolveAuthorizedSession(\n c: Context,\n deps: SessionFsDeps | undefined,\n workspacePath: string,\n): Promise<SourceControlSession | null> {\n if (!deps) return null;\n const session = await deps.sessions.getBySessionId(workspacePath);\n if (!session) return null;\n if (deps.auth.enabled()) {\n await deps.auth.ensureUser(c);\n const tenant = deps.auth.tenant(c);\n if (!tenant || tenant.orgId !== session.orgId || tenant.userId !== session.userId) {\n throw new Error('Session is not available to the current user');\n }\n }\n return session;\n}\n\ninterface SessionSandboxHandle {\n sandbox: ExecutableSandbox;\n filesystem: SandboxFilesystem;\n layout: SessionLayout;\n /** The branch each layout repository is compared against, by slug. */\n baseBranches: Map<string, string>;\n}\n\n/**\n * Resolve the session's sandbox from the per-process memo and wrap the\n * session layout's root in a `SandboxFilesystem`: the checkout for a\n * one-repository session, the workspace root (one directory per repository)\n * otherwise. Returns `null` when the session has no sandbox in this process\n * (never opened here, or evicted by retirement). This is a passive read path,\n * so it never constructs or provisions: the session's files come back the\n * next time the workspace is actually opened (e.g. by sending a message).\n */\nasync function sessionSandbox(session: SourceControlSession): Promise<SessionSandboxHandle | null> {\n const entry = peekSessionSandbox(session.id);\n // An unresolved workdir means the sandbox never started in this process —\n // nothing is materialized, so there are no files to browse.\n const layout = sessionLayout(entry);\n if (!entry || !layout) return null;\n const sandbox = requireExec(entry.sandbox);\n return {\n sandbox,\n // Session viewers read these files over HTTP, so a symlink must not lead\n // them outside the checkout.\n filesystem: new SandboxFilesystem({ sandbox, workdir: layout.root, verifySymlinks: true }),\n layout,\n baseBranches: repositoryBaseBranches(session, layout, entry.ownRepo),\n };\n}\n\n/**\n * The branch each layout repository is compared against: the session base\n * branch for the session's own repository (session branch vs base), the\n * default branch the boot recorded for every other one, `HEAD` (the checkout's\n * own `origin/HEAD`) until the boot has recorded it.\n */\nfunction repositoryBaseBranches(\n session: SourceControlSession,\n layout: SessionLayout,\n ownRepo: string,\n): Map<string, string> {\n const environment = layout.repos.length > 1 ? peekSessionEnvironment(session.sessionId) : undefined;\n const bases = new Map<string, string>();\n for (const repo of layout.repos) {\n if (layout.repos.length === 1 || repo.slug.toLowerCase() === ownRepo.toLowerCase()) {\n bases.set(repo.slug, session.baseBranch);\n continue;\n }\n const state = environment?.repositories.find(candidate => candidate.slug.toLowerCase() === repo.slug.toLowerCase());\n // The boot records the state at its end, after every setup command; until\n // then a secondary checkout compares against its own `origin/HEAD`.\n bases.set(repo.slug, state?.defaultBranch ?? 'HEAD');\n }\n return bases;\n}\n\n/** List an approved rendered root inside a Factory session's sandbox workdir. */\nexport async function listSessionRenderedPath(\n session: SourceControlSession,\n renderedRoot: string,\n): Promise<WorkspaceRenderedListing> {\n const safeRoot = assertApprovedRenderedRoot(renderedRoot);\n const handle = await sessionSandbox(session);\n const rootPath = posixPath.join(handle?.layout.root ?? '', safeRoot);\n const empty: WorkspaceRenderedListing = { workspacePath: session.sessionId, root: safeRoot, rootPath, entries: [] };\n if (!handle) return empty;\n\n // One round trip: emit \"type\\tsize\\tmtime\\tpath\" per entry. `safeRoot` comes\n // from a fixed allowlist so interpolating it (quoted) is safe. The listing is\n // parsed line by line, so retain all of it rather than the default 1 MiB tail.\n const quotedRoot = `'${rootPath.replace(/'/g, `'\\\\''`)}'`;\n const result = await handle.sandbox.executeCommand(\n 'sh',\n [\n '-c',\n `test -d ${quotedRoot} && find ${quotedRoot} -mindepth 1 -printf '%y\\\\t%s\\\\t%T@\\\\t%p\\\\n' 2>/dev/null || true`,\n ],\n { timeout: 30_000, maxRetainedBytes: Infinity },\n );\n if (result.exitCode !== 0) return empty;\n\n const entries: WorkspaceRenderedEntry[] = [];\n for (const line of result.stdout.split('\\n')) {\n if (!line) continue;\n const [type, sizeStr, mtimeStr, ...pathParts] = line.split('\\t');\n const fullPath = pathParts.join('\\t');\n if (!fullPath || !fullPath.startsWith(`${rootPath}/`)) continue;\n const relativePath = fullPath.slice(rootPath.length + 1);\n entries.push({\n name: posixPath.basename(relativePath),\n path: relativePath,\n type: type === 'd' ? 'directory' : 'file',\n size: type === 'd' ? 0 : Number(sizeStr) || 0,\n updatedAt: new Date((Number(mtimeStr) || 0) * 1000).toISOString(),\n });\n }\n entries.sort((a, b) => a.path.localeCompare(b.path));\n\n return { workspacePath: session.sessionId, root: safeRoot, rootPath, entries };\n}\n\n/**\n * Directory entries the file tree never shows or serves: git internals and the\n * sandbox's own setup markers.\n */\nconst HIDDEN_TREE_ENTRIES = new Set(['.git', SETUP_MARKER_DIR]);\n\n/**\n * Where a tree path lives. Inside a checkout: that checkout and the path within\n * it (a bare repository directory resolves to its root). Elsewhere in the\n * working directory (a multi-repository session's root, `.artifacts`): no\n * checkout, so no ignore rules apply.\n */\nfunction treeLocation(\n layout: SessionLayout,\n path: string,\n): { repo: SessionLayoutRepository; relative: string } | { repo: undefined; relative: string } {\n const safePath = path ? assertRelativePath(path, 'path') : '';\n if (safePath.split('/').some(segment => HIDDEN_TREE_ENTRIES.has(segment))) {\n throw new Error('Path is not available in this session');\n }\n if (layout.repos.length === 1) return { repo: layout.repos[0]!, relative: safePath };\n const repo = layout.repos\n .filter(candidate => `${safePath}/`.startsWith(candidate.prefix))\n .toSorted((a, b) => b.prefix.length - a.prefix.length)[0];\n return repo ? { repo, relative: safePath.slice(repo.prefix.length) } : { repo: undefined, relative: safePath };\n}\n\n/**\n * The checkout-relative paths git ignores, in one `git check-ignore` call.\n * Ignored files (`.env`, build output, `node_modules`) are neither listed nor\n * served: viewers of a session shouldn't read its local secrets. Fails closed\n * when git can't answer.\n */\nasync function ignoredPaths(sandbox: ExecutableSandbox, repoDir: string, paths: string[]): Promise<Set<string>> {\n if (paths.length === 0) return new Set();\n // Paths go in as positional arguments, never into the script text, and back\n // NUL-separated so no filename needs quoting either way.\n const result = await sandbox.executeCommand(\n 'sh',\n ['-c', 'cd \"$1\" && shift && printf \\'%s\\\\0\\' \"$@\" | git check-ignore -z --stdin', 'sh', repoDir, ...paths],\n { timeout: 30_000, maxRetainedBytes: Infinity },\n );\n // 0: some paths are ignored, 1: none are.\n if (result.exitCode === 1) return new Set();\n if (result.exitCode !== 0) throw new Error(`Unable to check ignored files: ${result.stderr.trim() || 'git failed'}`);\n return new Set(result.stdout.split('\\0').filter(Boolean));\n}\n\n/**\n * The real absolute location of each path (relative to `root`), following\n * every symlink, or `''` when it doesn't exist; plus `root`'s own. Paths go in\n * as positional arguments and come back NUL-separated.\n */\nasync function realPaths(\n sandbox: ExecutableSandbox,\n root: string,\n paths: string[],\n): Promise<{ root: string; paths: string[] }> {\n const result = await sandbox.executeCommand(\n 'sh',\n [\n '-c',\n 'cd \"$1\" && shift && printf \\'%s\\\\0\\' \"$(pwd -P)\" && for p; do printf \\'%s\\\\0\\' \"$([ -e \"$p\" ] && readlink -f -- \"$p\")\"; done',\n 'sh',\n root,\n ...paths,\n ],\n { timeout: 30_000, maxRetainedBytes: Infinity },\n );\n if (result.exitCode !== 0) throw new Error(`Unable to resolve symlinks: ${result.stderr.trim() || 'failed'}`);\n const [physicalRoot = '', ...resolved] = result.stdout.split('\\0');\n return { root: physicalRoot, paths: resolved.slice(0, paths.length) };\n}\n\n/** The first `bytes` bytes of a file, base64-encoded in the sandbox so binary content survives. */\nasync function readFilePrefix(sandbox: ExecutableSandbox, path: string, bytes: number): Promise<Buffer> {\n const result = await sandbox.executeCommand(\n 'sh',\n // Not a pipe: sh reports only the last command's status, so a failed head\n // would read as an empty file.\n [\n '-c',\n 't=$(mktemp) && trap \\'rm -f \"$t\"\\' EXIT && head -c \"$1\" -- \"$2\" >\"$t\" && base64 <\"$t\"',\n 'sh',\n String(bytes),\n path,\n ],\n { timeout: 30_000, maxRetainedBytes: Infinity },\n );\n if (result.exitCode !== 0) throw new Error(`Unable to read file: ${result.stderr.trim() || 'failed'}`);\n return Buffer.from(result.stdout, 'base64');\n}\n\n/**\n * Where a real absolute path sits in the tree, or `undefined` when the tree\n * can't show it: missing, outside the working directory, or inside git\n * internals or setup markers.\n */\nfunction treePathOf(layout: SessionLayout, physicalRoot: string, real: string): string | undefined {\n if (!real) return undefined;\n const relative = posixPath.relative(physicalRoot, real);\n if (relative === '..' || relative.startsWith('../') || posixPath.isAbsolute(relative)) return undefined;\n try {\n treeLocation(layout, relative);\n } catch {\n return undefined;\n }\n return relative;\n}\n\n/** Which tree paths their checkout ignores: one `git check-ignore` per checkout involved. */\nasync function ignoredTreePaths(\n sandbox: ExecutableSandbox,\n layout: SessionLayout,\n paths: string[],\n): Promise<Set<string>> {\n const byRepo = new Map<SessionLayoutRepository, Map<string, string>>();\n for (const path of paths) {\n const { repo, relative } = treeLocation(layout, path);\n if (!repo || !relative) continue;\n const inRepo = byRepo.get(repo) ?? new Map<string, string>();\n inRepo.set(relative, path);\n byRepo.set(repo, inRepo);\n }\n const ignored = new Set<string>();\n for (const [repo, inRepo] of byRepo) {\n for (const relative of await ignoredPaths(sandbox, repo.dir, [...inRepo.keys()])) {\n ignored.add(inRepo.get(relative)!);\n }\n }\n return ignored;\n}\n\n/**\n * List one directory of a session's working directory from its sandbox,\n * without git internals or entries a checkout ignores. Passive like every\n * session read: a session with no sandbox in this process comes back\n * `available: false` instead of starting one.\n */\nexport async function listSessionWorkspaceTree(\n session: SourceControlSession,\n path = '',\n): Promise<WorkspaceTreeListing> {\n const requested = path.trim() ? path : '';\n const handle = await sessionSandbox(session);\n const listing = { workspacePath: session.sessionId, path: requested };\n if (!handle) return { ...listing, available: false, entries: [] };\n\n const { layout, sandbox, filesystem } = handle;\n const location = treeLocation(layout, requested);\n const dir = (location.repo ? location.repo.prefix + location.relative : location.relative).replace(/\\/$/, '');\n const children = (await filesystem.readdir(dir || '.')).filter(entry => !HIDDEN_TREE_ENTRIES.has(entry.name));\n const childPath = (name: string) => (dir ? `${dir}/${name}` : name);\n\n // A symlink is shown (not expanded) only when what it leads to could be\n // shown itself; it's judged by its target, since that is what a read serves.\n // The folder itself must be where its path says: the tree doesn't go\n // through symlinked folders.\n const links = children.filter(entry => entry.isSymlink);\n const resolve = [...(dir ? [dir] : []), ...links.map(entry => childPath(entry.name))];\n const real = resolve.length > 0 ? await realPaths(sandbox, layout.root, resolve) : undefined;\n const linkTargets = real ? real.paths.slice(dir ? 1 : 0) : [];\n if (dir && real!.paths[0] !== posixPath.join(real!.root, dir)) {\n throw new Error('Path is not available in this session');\n }\n const targets = new Map(links.map((entry, i) => [entry.name, treePathOf(layout, real!.root, linkTargets[i]!)]));\n const ignored = await ignoredTreePaths(sandbox, layout, [\n ...(dir ? [dir] : []),\n ...children.map(entry => childPath(entry.name)),\n ...[...targets.values()].filter((target): target is string => target !== undefined),\n ]);\n if (dir && ignored.has(dir)) throw new Error('Path is not available in this session');\n const visible = children.filter(entry => {\n if (ignored.has(childPath(entry.name))) return false;\n if (!entry.isSymlink) return true;\n const target = targets.get(entry.name);\n return target !== undefined && !ignored.has(target);\n });\n\n const entries = visible\n .map(\n (entry): WorkspaceTreeEntry => ({\n name: entry.name,\n path: childPath(entry.name),\n type: entry.type,\n ...(entry.type === 'file' && entry.size !== undefined && { size: entry.size }),\n ...(entry.isSymlink && {\n symlinkTarget: entry.symlinkTarget ?? targets.get(entry.name)!,\n linkedPath: targets.get(entry.name)!,\n }),\n }),\n )\n .toSorted((a, b) => (a.type === b.type ? a.name.localeCompare(b.name) : a.type === 'directory' ? -1 : 1));\n return { ...listing, available: true, entries };\n}\n\n/**\n * Read a file inside a session's sandbox: anything under an approved rendered\n * root, or anything the tree would list (not git internals, not ignored by its\n * checkout).\n */\nexport async function readSessionWorkspaceFile(session: SourceControlSession, path: string): Promise<WorkspaceFile> {\n const safePath = assertRelativePath(path, 'path');\n\n const handle = await sessionSandbox(session);\n if (!handle) throw new Error('Session workspace is not available');\n const { layout, sandbox } = handle;\n treeLocation(layout, safePath);\n // Judge the file by where it really is as well as by the path asked for: a\n // symlink to `.env` must not serve it. Rendered roots (plans, reports) are\n // served even when a checkout ignores them, but not through such a symlink.\n const parent = posixPath.dirname(safePath);\n const real = await realPaths(sandbox, layout.root, parent === '.' ? [safePath] : [safePath, parent]);\n const target = treePathOf(layout, real.root, real.paths[0]!);\n // The file itself may be a symlink, but not a folder on the way to it.\n const throughLink = parent !== '.' && real.paths[1] !== posixPath.join(real.root, parent);\n if (target === undefined || throughLink) throw new Error('Path is not available in this session');\n const trusted = APPROVED_RENDERED_ROOTS.has(safePath.split('/')[0] ?? '');\n const checked = [...new Set([...(trusted ? [] : [safePath]), ...(target === safePath ? [] : [target])])];\n if ((await ignoredTreePaths(sandbox, layout, checked)).size > 0) {\n throw new Error('Path is not available in this session');\n }\n const { filesystem } = handle;\n const info = await filesystem.stat(safePath);\n if (info.type === 'directory') throw new Error('Path is a directory');\n\n // Only the shown prefix of a large file leaves the sandbox.\n const truncated = info.size > MAX_TEXT_FILE_BYTES;\n const buffer = truncated\n ? await readFilePrefix(sandbox, real.paths[0]!, MAX_TEXT_FILE_BYTES)\n : ((await filesystem.readFile(safePath)) as Buffer);\n const base = {\n workspacePath: session.sessionId,\n path: safePath,\n name: posixPath.basename(safePath),\n size: info.size,\n updatedAt: info.modifiedAt.toISOString(),\n };\n try {\n const content = TEXT_DECODER.decode(buffer);\n return { ...base, contentType: 'text', content, truncated };\n } catch {\n return { ...base, contentType: 'unsupported' };\n }\n}\n\nfunction changeStatus(code: string): WorkspaceChangeStatus {\n if (code === '??') return 'untracked';\n if (code.includes('U') || code === 'AA' || code === 'DD') return 'conflicted';\n if (code.includes('R')) return 'renamed';\n if (code.includes('C')) return 'copied';\n if (code.includes('D')) return 'deleted';\n if (code.includes('A')) return 'added';\n return 'modified';\n}\n\nexport function parseWorkspaceChanges(output: string): WorkspaceChange[] {\n const records = output.split('\\0');\n const changes: WorkspaceChange[] = [];\n\n for (let index = 0; index < records.length; index += 1) {\n const record = records[index];\n if (!record || record.length < 4) continue;\n const code = record.slice(0, 2);\n const path = record.slice(3);\n const status = changeStatus(code);\n if (status === 'renamed' || status === 'copied') {\n const previousPath = records[index + 1];\n if (previousPath) index += 1;\n changes.push({ path, previousPath: previousPath || undefined, status });\n continue;\n }\n changes.push({ path, status });\n }\n\n return changes.toSorted((a, b) => a.path.localeCompare(b.path));\n}\nexport function parseWorkspaceTrackedChanges(output: string): WorkspaceChange[] {\n const records = output.split('\\0');\n const changes: WorkspaceChange[] = [];\n for (let index = 0; index < records.length;) {\n const code = records[index++];\n if (!code) continue;\n const status = changeStatus(code);\n if (status === 'renamed' || status === 'copied') {\n const previousPath = records[index++];\n const path = records[index++];\n if (path) changes.push({ path, previousPath: previousPath || undefined, status });\n continue;\n }\n const path = records[index++];\n if (path) changes.push({ path, status });\n }\n return changes.toSorted((a, b) => a.path.localeCompare(b.path));\n}\n\nexport function parseWorkspaceChangeStats(output: string) {\n const records = output.split('\\0');\n const stats = new Map<string, { additions?: number; deletions?: number; binary?: boolean }>();\n\n for (let index = 0; index < records.length; index += 1) {\n const record = records[index];\n if (!record) continue;\n const firstTab = record.indexOf('\\t');\n const secondTab = record.indexOf('\\t', firstTab + 1);\n if (firstTab < 0 || secondTab < 0) continue;\n\n const additionsText = record.slice(0, firstTab);\n const deletionsText = record.slice(firstTab + 1, secondTab);\n let path = record.slice(secondTab + 1);\n if (!path) {\n const renamedPath = records[index + 2];\n if (!renamedPath) continue;\n path = renamedPath;\n index += 2;\n }\n if (path.startsWith('./')) path = path.slice(2);\n\n if (additionsText === '-' || deletionsText === '-') {\n stats.set(path, { binary: true });\n continue;\n }\n\n const additions = Number(additionsText);\n const deletions = Number(deletionsText);\n if (Number.isFinite(additions) && Number.isFinite(deletions)) stats.set(path, { additions, deletions });\n }\n\n return stats;\n}\n\nfunction unavailableWorkspaceChanges(workspacePath: string): WorkspaceChanges {\n return { workspacePath, available: false, changes: [] };\n}\n\nfunction isWorkspaceChangesScope(value: string): value is WorkspaceChangesScope {\n return value === 'branch' || value === 'uncommitted';\n}\n\nasync function resolveSessionComparisonBase(\n sandbox: ExecutableSandbox,\n workdir: string,\n baseBranch: string,\n scope: WorkspaceChangesScope,\n): Promise<string> {\n if (scope === 'uncommitted') return 'HEAD';\n const result = await sandbox.executeCommand('git', ['-C', workdir, 'merge-base', 'HEAD', `origin/${baseBranch}`], {\n timeout: 30_000,\n });\n const sha = result.stdout.trim();\n return result.exitCode === 0 && /^[0-9a-f]{40,64}$/i.test(sha) ? sha : 'HEAD';\n}\n\ntype RepositoryChanges = Pick<WorkspaceChangesRepository, 'available' | 'changes' | 'additions' | 'deletions'>;\n\n/** The changes of one checkout against its comparison base; `available: false` when git cannot inspect it. */\nasync function listRepositoryChanges(\n sandbox: ExecutableSandbox,\n workdir: string,\n comparisonBase: string,\n): Promise<RepositoryChanges> {\n // These outputs are parsed record by record (-z) and per path, so retain all\n // of them rather than the default 1 MiB tail, which would drop or split entries.\n const [statusResult, trackedResult, statsResult] = await Promise.all([\n sandbox.executeCommand('git', ['-C', workdir, 'status', '--porcelain=v1', '-z', '--untracked-files=all'], {\n timeout: 30_000,\n maxRetainedBytes: Infinity,\n }),\n sandbox.executeCommand('git', ['-C', workdir, 'diff', '--name-status', '-z', '--find-renames', comparisonBase], {\n timeout: 30_000,\n maxRetainedBytes: Infinity,\n }),\n sandbox.executeCommand(\n 'sh',\n ['-c', WORKSPACE_DIFF_SCRIPT, 'mastracode-numstat', workdir, comparisonBase, ...NUMSTAT_FORMAT],\n { timeout: 30_000, maxRetainedBytes: Infinity },\n ),\n ]);\n if (statusResult.exitCode !== 0) return { available: false, changes: [] };\n\n const statusChanges = parseWorkspaceChanges(statusResult.stdout);\n const trackedChanges = trackedResult.exitCode === 0 ? parseWorkspaceTrackedChanges(trackedResult.stdout) : [];\n const changesByPath = new Map(trackedChanges.map(change => [change.path, change]));\n for (const change of statusChanges) {\n if (trackedResult.exitCode !== 0 || change.status === 'untracked' || change.status === 'conflicted') {\n changesByPath.set(change.path, change);\n }\n }\n const changes = [...changesByPath.values()].toSorted((a, b) => a.path.localeCompare(b.path));\n if (statsResult.exitCode !== 0) return { available: true, changes };\n\n const stats = parseWorkspaceChangeStats(statsResult.stdout);\n let additions = 0;\n let deletions = 0;\n const changesWithStats = changes.map(change => {\n const changeStats = stats.get(change.path);\n additions += changeStats?.additions ?? 0;\n deletions += changeStats?.deletions ?? 0;\n return { ...change, ...changeStats };\n });\n return { available: true, changes: changesWithStats, additions, deletions };\n}\n\nfunction prefixChange(change: WorkspaceChange, prefix: string): WorkspaceChange {\n if (!prefix) return change;\n return {\n ...change,\n path: `${prefix}${change.path}`,\n ...(change.previousPath ? { previousPath: `${prefix}${change.previousPath}` } : {}),\n };\n}\n\ninterface InspectedRepository {\n repo: SessionLayoutRepository;\n changes: RepositoryChanges;\n}\n\nfunction assembleWorkspaceChanges(workspacePath: string, inspected: InspectedRepository[]): WorkspaceChanges {\n // One repository: the response is exactly what it was before layouts.\n if (inspected.length === 1) {\n const { changes } = inspected[0]!;\n if (!changes.available) return unavailableWorkspaceChanges(workspacePath);\n return { workspacePath, ...changes };\n }\n\n // A failing checkout is unavailable on its own; the others still answer.\n const groups: WorkspaceChangesRepository[] = inspected.map(({ repo, changes }) => ({\n slug: repo.slug,\n prefix: repo.prefix,\n ...changes,\n changes: changes.changes.map(change => prefixChange(change, repo.prefix)),\n }));\n const available = groups.filter(group => group.available);\n const changes = available.flatMap(group => group.changes).toSorted((a, b) => a.path.localeCompare(b.path));\n const counted = available.filter(group => group.additions !== undefined);\n const totals =\n counted.length > 0\n ? {\n additions: counted.reduce((sum, group) => sum + (group.additions ?? 0), 0),\n deletions: counted.reduce((sum, group) => sum + (group.deletions ?? 0), 0),\n }\n : {};\n return {\n workspacePath,\n available: available.length > 0,\n changes,\n ...totals,\n repositories: groups,\n };\n}\n\nexport async function listSessionWorkspaceChanges(session: SourceControlSession): Promise<WorkspaceChanges> {\n const handle = await sessionSandbox(session);\n if (!handle) return unavailableWorkspaceChanges(session.sessionId);\n const { sandbox, layout, baseBranches } = handle;\n\n const inspected = await Promise.all(\n layout.repos.map(async repo => {\n const comparisonBase = await resolveSessionComparisonBase(\n sandbox,\n repo.dir,\n baseBranches.get(repo.slug) ?? session.baseBranch,\n 'branch',\n );\n return { repo, changes: await listRepositoryChanges(sandbox, repo.dir, comparisonBase) };\n }),\n );\n return assembleWorkspaceChanges(session.sessionId, inspected);\n}\n\nconst GIT_C_ESCAPES: Record<string, string> = {\n '\"': '\\\\\"',\n '\\\\': '\\\\\\\\',\n '\\x07': '\\\\a',\n '\\b': '\\\\b',\n '\\t': '\\\\t',\n '\\n': '\\\\n',\n '\\v': '\\\\v',\n '\\f': '\\\\f',\n '\\r': '\\\\r',\n};\n\n/** A path as git writes it in a diff header: `core.quotePath=false` quotes only for quotes, backslashes and control characters. */\nfunction gitHeaderPath(path: string): string {\n let escaped = '';\n let quoted = false;\n for (const char of path) {\n const code = char.charCodeAt(0);\n const escape =\n GIT_C_ESCAPES[char] ?? (code < 0x20 || code === 0x7f ? `\\\\${code.toString(8).padStart(3, '0')}` : '');\n quoted ||= escape !== '';\n escaped += escape || char;\n }\n return quoted ? `\"${escaped}\"` : path;\n}\n\ninterface KeyedPatches {\n patches: Map<string, string>;\n omitted: Map<string, WorkspacePatchOmission>;\n}\n\nfunction keyWorkspacePatches(patch: string, changes: readonly WorkspaceChange[]): KeyedPatches {\n const sections = patch.split(/^(?=diff --git )/m);\n const budgetSpent = Buffer.byteLength(patch) > MAX_PATCH_SET_BYTES;\n if (budgetSpent) sections.pop();\n\n const sectionsByHeader = new Map<string, string>();\n for (const section of sections) {\n const headerEnd = section.indexOf('\\n');\n if (headerEnd >= 0) sectionsByHeader.set(section.slice(0, headerEnd), section);\n }\n\n const keyed: KeyedPatches = { patches: new Map(), omitted: new Map() };\n for (const change of changes) {\n const header = `diff --git ${gitHeaderPath(`a/${change.previousPath ?? change.path}`)} ${gitHeaderPath(`b/${change.path}`)}`;\n const section = sectionsByHeader.get(header);\n if (section === undefined) {\n if (budgetSpent) keyed.omitted.set(change.path, 'total-too-large');\n } else if (Buffer.byteLength(section) > MAX_DIFF_BYTES) {\n keyed.omitted.set(change.path, 'file-too-large');\n } else {\n keyed.patches.set(change.path, section);\n }\n }\n return keyed;\n}\n\nfunction prefixedEntries<T>(prefix: string, entries: Map<string, T>): [string, T][] {\n return Array.from(entries, ([path, value]): [string, T] => [`${prefix}${path}`, value]);\n}\n\nfunction unavailableWorkspacePatches(workspacePath: string, scope: WorkspaceChangesScope): WorkspaceChangePatches {\n return { ...unavailableWorkspaceChanges(workspacePath), scope, patches: {}, omittedPatches: {} };\n}\n\nexport async function listSessionWorkspacePatches(\n session: SourceControlSession,\n scope: WorkspaceChangesScope,\n): Promise<WorkspaceChangePatches> {\n const handle = await sessionSandbox(session);\n if (!handle) return unavailableWorkspacePatches(session.sessionId, scope);\n const { sandbox, layout, baseBranches } = handle;\n\n const inspected = await Promise.all(\n layout.repos.map(async repo => {\n const comparisonBase = await resolveSessionComparisonBase(\n sandbox,\n repo.dir,\n baseBranches.get(repo.slug) ?? session.baseBranch,\n scope,\n );\n const [changes, patch] = await Promise.all([\n listRepositoryChanges(sandbox, repo.dir, comparisonBase),\n sandbox.executeCommand(\n 'sh',\n [\n '-c',\n BOUNDED_OUTPUT_SCRIPT,\n 'mastracode-bounded',\n String(MAX_PATCH_SET_BYTES + 1),\n 'sh',\n '-c',\n WORKSPACE_DIFF_SCRIPT,\n 'mastracode-patch',\n repo.dir,\n comparisonBase,\n ...PATCH_FORMAT,\n ],\n { timeout: 30_000, maxRetainedBytes: Infinity },\n ),\n ]);\n if (patch.exitCode !== 0 && changes.changes.length > 0) {\n const diffError = patch.stderr.trim().split('\\n')[0] || `git diff exited with code ${patch.exitCode}`;\n const keyed: KeyedPatches = { patches: new Map(), omitted: new Map() };\n return { repo, changes, keyed, diffError };\n }\n return { repo, changes, keyed: keyWorkspacePatches(patch.stdout, changes.changes), diffError: undefined };\n }),\n );\n const diffErrors = inspected.flatMap(({ repo, diffError }) => {\n if (!diffError) return [];\n return [layout.repos.length > 1 ? `${repo.slug}: ${diffError}` : diffError];\n });\n return {\n ...assembleWorkspaceChanges(session.sessionId, inspected),\n scope,\n patches: Object.fromEntries(inspected.flatMap(({ repo, keyed }) => prefixedEntries(repo.prefix, keyed.patches))),\n omittedPatches: Object.fromEntries(\n inspected.flatMap(({ repo, keyed }) => prefixedEntries(repo.prefix, keyed.omitted)),\n ),\n ...(diffErrors.length > 0 ? { diffError: diffErrors.join('\\n') } : {}),\n };\n}\n\nexport interface ResolvedCodebase {\n /**\n * The resourceId the TUI would use for this path — derived identically so a\n * project opened in the terminal and in the web app resolve to the SAME\n * session (and therefore the same threads).\n */\n resourceId: string;\n name: string;\n rootPath: string;\n gitUrl?: string;\n gitBranch?: string;\n}\n\n/**\n * Resolve a project path to the same resourceId the TUI uses. Mirrors\n * `createMastraCode`: detect the project, then apply any resourceId override\n * (MASTRA_RESOURCE_ID env var or `.mastracode/database.json`). This is the\n * shared continuity point — start in the TUI, continue on the web, same path\n * → same resourceId → same session.\n */\nexport function resolveCodebase(projectPath: string): ResolvedCodebase {\n const info = detectProject(projectPath);\n const override = getResourceIdOverride(info.rootPath);\n return {\n resourceId: override ?? info.resourceId,\n name: info.name,\n rootPath: info.rootPath,\n gitUrl: info.gitUrl,\n gitBranch: info.gitBranch,\n };\n}\n\n/**\n * Build the web filesystem routes as Mastra `apiRoutes`:\n * - `GET /web/fs/list?path=...` — browse directories (confined to root)\n * - `GET /web/codebase/resolve?path=...` — TUI-compatible codebase resourceId\n */\nexport function buildFsRoutes(options: { root?: string; sessionFs?: SessionFsDeps } = {}): ApiRoute[] {\n const root = resolveFsRoot(options.root);\n const sessionFs = options.sessionFs;\n\n return [\n registerApiRoute('/web/fs/list', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const path = c.req.query('path');\n try {\n const listing = await listDirectory(root, path);\n return c.json(listing);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return c.json({ error: message }, 500);\n }\n },\n }),\n registerApiRoute('/web/artifacts/list', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const path = c.req.query('path');\n if (!path) return c.json({ error: 'Missing required query param: path' }, 400);\n try {\n return c.json(await listArtifacts(root, path));\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n const status = message === 'Path is outside the browsable root' ? 403 : 500;\n return c.json({ error: message }, status);\n }\n },\n }),\n registerApiRoute('/web/workspace/rendered/list', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const workspacePath = c.req.query('workspacePath');\n const renderedRoot = c.req.query('root');\n if (!workspacePath) return c.json({ error: 'Missing required query param: workspacePath' }, 400);\n if (!renderedRoot) return c.json({ error: 'Missing required query param: root' }, 400);\n try {\n const session = await resolveAuthorizedSession(loose(c), sessionFs, workspacePath);\n if (session && sessionFs) {\n return c.json(await listSessionRenderedPath(session, renderedRoot));\n }\n return c.json(await listWorkspaceRenderedPath(root, workspacePath, renderedRoot));\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n const status =\n message.includes('outside') ||\n message.includes('relative') ||\n message.includes('escapes') ||\n message.includes('not approved') ||\n message.includes('not available')\n ? 403\n : 500;\n return c.json({ error: message }, status);\n }\n },\n }),\n registerApiRoute('/web/workspace/changes', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const workspacePath = c.req.query('workspacePath');\n if (!workspacePath) return c.json({ error: 'Missing required query param: workspacePath' }, 400);\n try {\n const session = await resolveAuthorizedSession(loose(c), sessionFs, workspacePath);\n if (!session || !sessionFs) return c.json(unavailableWorkspaceChanges(workspacePath));\n return c.json(await listSessionWorkspaceChanges(session));\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return c.json({ error: message }, message.includes('not available') ? 403 : 500);\n }\n },\n }),\n registerApiRoute('/web/workspace/changes/patches', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const workspacePath = c.req.query('workspacePath');\n const scope = c.req.query('scope') ?? 'branch';\n if (!workspacePath) return c.json({ error: 'Missing required query param: workspacePath' }, 400);\n if (!isWorkspaceChangesScope(scope)) return c.json({ error: 'scope must be branch or uncommitted' }, 400);\n try {\n const session = await resolveAuthorizedSession(loose(c), sessionFs, workspacePath);\n if (!session || !sessionFs) return c.json(unavailableWorkspacePatches(workspacePath, scope));\n return c.json(await listSessionWorkspacePatches(session, scope));\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return c.json({ error: message }, message.includes('not available') ? 403 : 500);\n }\n },\n }),\n registerApiRoute('/web/workspace/tree', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const workspacePath = c.req.query('workspacePath');\n if (!workspacePath) return c.json({ error: 'Missing required query param: workspacePath' }, 400);\n try {\n const session = await resolveAuthorizedSession(loose(c), sessionFs, workspacePath);\n if (!session || !sessionFs) return c.json({ error: 'Session workspace is not available' }, 403);\n return c.json(await listSessionWorkspaceTree(session, c.req.query('path') ?? ''));\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n const status =\n message.includes('relative') || message.includes('escapes') || message.includes('not available')\n ? 403\n : message.includes('not found')\n ? 404\n : 500;\n return c.json({ error: message }, status);\n }\n },\n }),\n registerApiRoute('/web/workspace/file', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const workspacePath = c.req.query('workspacePath');\n const path = c.req.query('path');\n if (!workspacePath) return c.json({ error: 'Missing required query param: workspacePath' }, 400);\n if (!path) return c.json({ error: 'Missing required query param: path' }, 400);\n try {\n const session = await resolveAuthorizedSession(loose(c), sessionFs, workspacePath);\n if (session && sessionFs) return c.json(await readSessionWorkspaceFile(session, path));\n return c.json(await readWorkspaceFile(root, workspacePath, path));\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n const status =\n message.includes('outside') ||\n message.includes('relative') ||\n message.includes('escapes') ||\n message.includes('not approved') ||\n message.includes('not available')\n ? 403\n : message.includes('directory')\n ? 400\n : message.includes('not found')\n ? 404\n : 500;\n return c.json({ error: message }, status);\n }\n },\n }),\n registerApiRoute('/web/codebase/resolve', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const path = c.req.query('path');\n if (!path) return c.json({ error: 'Missing required query param: path' }, 400);\n // Confine resolution to the browsable root (following symlinks), so this\n // endpoint can't be used to probe arbitrary filesystem paths. The web UI\n // only ever resolves directories the user picked via the root-confined\n // browser, so legitimate requests are always within the root.\n const confined = await realPathWithinRoot(isAbsolute(path) ? resolve(path) : resolve(root, path), root);\n if (!confined) return c.json({ error: 'Path is outside the browsable root' }, 403);\n try {\n return c.json(resolveCodebase(confined));\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return c.json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G,IAAI,CAAC,UAAU,OAAO,EAAE,KAAK,EAAE,OAAO,qCAAqC,GAAG,GAAG;IACjF,IAAI;KACF,OAAO,EAAE,KAAK,gBAAgB,QAAQ,CAAC;IACzC,SAAS,OAAO;KACd,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;KACrE,OAAO,EAAE,KAAK,EAAE,OAAO,QAAQ,GAAG,GAAG;IACvC;GACF;EACF,CAAC;CACH;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mastra/factory",
3
- "version": "0.25.0-alpha.2",
3
+ "version": "0.25.0-alpha.4",
4
4
  "description": "Mastra Software Factory module: the server core behind the Mastra Software Factory — storage domains, integrations, and surfaces for agent-powered software delivery",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -58,25 +58,25 @@
58
58
  "hono": "^4.13.7",
59
59
  "posthog-node": "^5.46.1",
60
60
  "zod": "^4.6.7",
61
- "@mastra/auth-studio": "1.3.11-alpha.0",
62
- "@mastra/code-sdk": "1.15.1-alpha.2",
63
61
  "@mastra/auth-workos": "1.6.7",
64
- "@mastra/slack": "1.8.0-alpha.0",
65
- "@mastra/core": "1.80.0-alpha.2",
66
- "@mastra/mcp": "2.6.0-alpha.0"
62
+ "@mastra/code-sdk": "1.15.1-alpha.4",
63
+ "@mastra/auth-studio": "1.3.11-alpha.0",
64
+ "@mastra/core": "1.80.0-alpha.3",
65
+ "@mastra/mcp": "2.6.0-alpha.0",
66
+ "@mastra/slack": "1.8.0-alpha.0"
67
67
  },
68
68
  "devDependencies": {
69
69
  "@types/node": "22.20.5",
70
70
  "tsdown": "0.23.1",
71
71
  "typescript": "^6.0.3",
72
72
  "vitest": "4.1.12",
73
+ "@mastra/deployer": "1.80.0-alpha.3",
73
74
  "@mastra/libsql": "1.27.0",
74
- "@mastra/server": "1.80.0-alpha.2",
75
- "@mastra/deployer": "1.80.0-alpha.2",
76
75
  "@mastra/pg": "1.33.0-alpha.1",
76
+ "@mastra/server": "1.80.0-alpha.3",
77
77
  "@internal/types-builder": "0.0.120",
78
- "@internal/lint": "0.0.145",
79
- "@internal/workspace": "0.0.17"
78
+ "@internal/workspace": "0.0.17",
79
+ "@internal/lint": "0.0.145"
80
80
  },
81
81
  "engines": {
82
82
  "node": ">=22.19.0"