Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

feat(artifacts): add private per-session screenshot storage and retention

Rahmanf6a3f016ed9a
diff --git a/.env.example b/.env.example
index 7db1d343..568b9af7 100644
--- a/.env.example
+++ b/.env.example
@@ -207,6 +207,8 @@ OS_SESSION_SECRET=
# OS_THREADS_DIR=~/.mso/threads # Alfa assistant chat threads (one file each)
# OS_AGENT_MEMORY_DIR=~/.mso/agent-memory # isolated MSO Agent USER.md/MEMORY.md stores
# OS_AGENT_SESSIONS_DIR=~/.mso/agent-sessions # durable CLI/MCP agent session records
+# Session artifacts use this same root: temp/<client-hash>/<session-id> (owner-only).
+# OS_AGENT_ARTIFACT_RETENTION_DAYS=7 # dormant artifacts only; clamped 1-30; active leases preserved
# OS_PROJECT_AGENT_TASKS_DIR=~/.mso/project-agent-tasks # private project-agent message/status records
# OS_SUBAGENT_MAX_TURNS=12 # server policy cap for one foreground subagent; default 12, absolute max 48 (each child still defaults to 6)
# Native Local Agents use private defaults; overrides are normally unnecessary.
diff --git a/README.md b/README.md
index 3b41ed42..3934d8c0 100644
--- a/README.md
+++ b/README.md
@@ -97,3 +97,5 @@ Use Node 22 and Bun >=1.2.15 with native audit support. [Contributing](./CONTRIB
[Development](./docs/DEVELOPMENT.md) · [Changelog](./docs/CHANGELOG.md) · [MIT license](./LICENSE)
[Native Integrations](./docs/INTEGRATIONS.md): temporary credential forms for browser, CLI and MCP Page.
+
+[Session screenshots](docs/SESSION-ARTIFACTS.md): private temp folders, descriptive artifact names, session discovery and automatic dormant-file cleanup.
diff --git a/app/api/v1/agent-sessions/route.ts b/app/api/v1/agent-sessions/route.ts
index 96b9b7f6..5d31e35e 100644
--- a/app/api/v1/agent-sessions/route.ts
+++ b/app/api/v1/agent-sessions/route.ts
@@ -1,3 +1,5 @@
+import type { AgentSession } from "@/lib/agent/session-types";
+import { artifactLocation } from "@/lib/agent/artifact-paths";
import { NextRequest, NextResponse } from "next/server";
import { getSessionContext } from "@/lib/auth/require-session";
import {
@@ -17,6 +19,10 @@ import {
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
+function sessionResponse({session}: {session: AgentSession}) {
+ return NextResponse.json({session:{...session,artifacts:artifactLocation(session)}});
+}
+
async function ownerPrincipal(): Promise<string | null> {
const context = await getSessionContext();
return context?.role === "owner" ? `cli:${context.session.device_id}` : null;
@@ -45,7 +51,7 @@ export async function GET(req: NextRequest) {
).trim();
if (ref) {
try {
- return NextResponse.json({
+ return sessionResponse({
session: await resolveAgentSessionOwnerRef(ref),
});
} catch (e) {
@@ -80,7 +86,7 @@ export async function POST(req: NextRequest) {
}
try {
if (body.action === "create") {
- return NextResponse.json({
+ return sessionResponse({
session: await createAgentSession(principal, "cli", {
title: body.title,
titleSource: body.title ? "manual" : "default",
@@ -102,7 +108,7 @@ export async function POST(req: NextRequest) {
body.title,
"auto",
);
- return NextResponse.json({
+ return sessionResponse({
session: body.cwd
? await updateAgentSessionLocation(principal, session.id, body.cwd)
: session,
@@ -115,7 +121,7 @@ export async function POST(req: NextRequest) {
{ error: "session_reference_required" },
{ status: 400 },
);
- return NextResponse.json({
+ return sessionResponse({
session: await resumeAgentSessionForOwner(principal, ref, body.cwd),
});
}
@@ -125,7 +131,7 @@ export async function POST(req: NextRequest) {
{ error: "id_and_name_required" },
{ status: 400 },
);
- return NextResponse.json({
+ return sessionResponse({
session: await renameAgentSessionName(principal, body.id, body.name),
});
}
@@ -135,7 +141,7 @@ export async function POST(req: NextRequest) {
{ error: "id_and_title_required" },
{ status: 400 },
);
- return NextResponse.json({
+ return sessionResponse({
session: await renameAgentSession(principal, body.id, body.title),
});
}
diff --git a/docs/MCP-FEATURE-IMPLEMENTATION.md b/docs/MCP-FEATURE-IMPLEMENTATION.md
index 84202a0e..a8157a7b 100644
--- a/docs/MCP-FEATURE-IMPLEMENTATION.md
+++ b/docs/MCP-FEATURE-IMPLEMENTATION.md
@@ -193,3 +193,7 @@ An MCP feature is complete only when:
- the exact live behavior is verified;
- affected external clients have refreshed their cached actions;
- the reusable pattern is captured without storing secrets or volatile host facts.
+
+## Session artifact boundary
+
+Session artifact tools share `lib/agent/artifact-*` and the existing private store/cross-process lock. Read stays read-scoped; registration and cleanup require write. CLI uses the existing approved agent-tools bridge; Alfa browser threads deliberately do not borrow durable MCP/CLI principals. No new unauthenticated HTTP file route or filesystem-denylist exception is introduced. [Storage and verification contract](./SESSION-ARTIFACTS.md).
diff --git a/docs/MCP.md b/docs/MCP.md
index d0c041ee..3d37fae8 100644
--- a/docs/MCP.md
+++ b/docs/MCP.md
@@ -706,3 +706,7 @@ MSO Integrations uses the existing Page at `/integrations`. The write-scoped
`integration_setup_open` tool opens a secure form without accepting secret values.
See [Native Integrations](INTEGRATIONS.md) for browser/CLI entrypoints, scope,
expiry, direct HTTPS submission, and verification limits.
+
+## Session artifact evidence
+
+`session_artifacts` lists or reads this client’s session screenshots/JSON reports. `session_artifact_register` registers bounded browser outputs from the injected `MSO_SCREENSHOT_DIR`; `session_artifacts_cleanup` previews or applies dormant-session retention. `agent_session_current` returns computed temp/manifest locations. See [Session artifacts](./SESSION-ARTIFACTS.md) for the single shared storage policy and trust boundary.
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index db4f7f00..a40c0ea0 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -2618,3 +2618,7 @@ by line, and they are one command away: `git show 421ab7f:docs/PROGRESS.md`.*
## 2026-08-20 — ChatGPT generated-file → VPS bridge (DONE)
MCP now exposes `fs_upload_file` with `_meta["openai/fileParams"]`, so ChatGPT can generate or receive an image first and then transfer the exact file bytes into an existing bounded VPS directory. The server accepts only temporary HTTPS OpenAI file references, caps imports at 20 MiB, validates image MIME types, inherits the existing write-root and credential denylist through `uploadInto`, audits as `fs.upload`, and returns byte count plus SHA-256 without persisting the temporary download URL.
+
+## 2026-09-05 — Session-scoped screenshot evidence
+
+Screenshot evidence previously lived in unrelated scratch directories or only in MCP image responses. Added one derived session path policy, a private manifest, explicit image/report reads, and bounded registration/retention. Exec receives non-secret session directories; original bytes remain private and session responses compute paths instead of persisting absolute homes. Cleanup is lazy, lease-aware and fail-closed for unknown files; it does not run during builds or remove durable history. User/client isolation, retry de-duplication and existing integration changes are preserved. See SESSION-ARTIFACTS.md for limits and verification scope.
diff --git a/docs/README.md b/docs/README.md
index 84dfe8d1..8879828b 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -85,3 +85,5 @@ the current-reference doc.
## Reset and removal
[Maintenance, factory reset and clean uninstall](./MAINTENANCE.md) · [Extended workspace reference](./reference/WORKSPACE-GUIDE.md)
+
+- [Session screenshots and temporary artifacts](./SESSION-ARTIFACTS.md) — private per-session paths, MCP/CLI reads, quotas and safe retention.
diff --git a/docs/SESSION-ARTIFACTS.md b/docs/SESSION-ARTIFACTS.md
new file mode 100644
index 00000000..5b5c0957
--- /dev/null
+++ b/docs/SESSION-ARTIFACTS.md
@@ -0,0 +1,85 @@
+# Session screenshots and temporary artifacts
+
+MSO owns one private artifact store for durable CLI/MCP sessions. Screenshot producers such as Playwright or Camoufox do not choose usernames, invent public file URLs, or maintain independent session catalogs.
+
+```text
+Authenticated session
+ -> session path policy
+ -> private incoming/ (browser producer)
+ -> session_artifact_register (validate, name, hash)
+ -> manifest.json + screenshots/ or reports/
+ -> session_artifacts (list or image/JSON read)
+ -> retention cleanup after inactivity
+```
+
+## Path and ownership contract
+
+The root is derived by `lib/agent/session-paths.ts`: `OS_AGENT_SESSIONS_DIR`, or the current operating-system user's `~/.mso/agent-sessions`. The same resolver supplies durable records and artifact paths.
+
+```text
+<session-root>/
+ <session-id>.json durable conversation record
+ temp/
+ <authenticated-principal-hash>/
+ <session-id>/
+ manifest.json sole artifact catalog
+ incoming/ browser-produced files
+ screenshots/ validated, named originals
+ reports/ validated JSON evidence
+```
+
+`agent_session_current`, CLI session API responses, and session summaries return an `artifacts` object containing `directory`, `incomingDirectory`, `screenshotsDirectory`, `manifestPath`, retention and limits. These absolute locations are computed when returned, not duplicated in saved session JSON. The manifest stores relative paths, so moving a configured root does not leave stale absolute file references. The CLI `/status` displays the returned temp and manifest locations.
+
+The authenticated client principal and exact session are separate identity boundaries. Another token principal cannot select arbitrary sessions by guessing their ID. MSO still runs as one Unix account: an owner-approved arbitrary shell has that Unix account's filesystem power. This feature does not claim to sandbox hostile programs running as the same OS user or to create a new multi-tenant operating system.
+
+## Browser workflow
+
+Session-bound `exec_run` and `exec_job_start` inject only these non-secret values:
+
+- `MSO_SESSION_ID`
+- `MSO_SESSION_TEMP_DIR`
+- `MSO_SCREENSHOT_DIR` — the session's `incoming/` directory
+- `MSO_ARTIFACT_MANIFEST`
+
+They are internal context, not an unrestricted user-supplied environment override. Use `umask 077` before producing files. A Playwright producer can use its existing browser setup:
+
+```js
+import { join } from "node:path";
+if (!process.env.MSO_SCREENSHOT_DIR) throw new Error("Run in an MSO session");
+await page.screenshot({
+ path: join(process.env.MSO_SCREENSHOT_DIR, "home-fr-mobile.png"),
+ fullPage: false,
+});
+```
+
+Then call `session_artifact_register` with the actual project, environment, producer and 1–40 file descriptors. Each descriptor contains a staged basename, feature, optional locale, actual viewport width/height and source page URL. No arbitrary source directory is accepted. Query strings, fragments and URL credentials are omitted from the stored source URL.
+
+Example final basename:
+
+```text
+mso__portfolio__home__production__fr__390x844__20260905t120000000z__a1b2c3d4.png
+```
+
+The manifest records artifact ID, descriptive filename, relative path, MIME type, byte length, SHA-256, creation time, producer, feature, viewport, locale and workflow ID. An identical registration retry returns the existing entry instead of accumulating duplicate originals. Raw staged input is retained until session retention cleanup; it is not removed during a registration retry, avoiding producer-file replacement races.
+
+`session_artifacts` lists metadata with pagination. Supply an `artifact_id` to return an image or bounded JSON evidence. Large images may be resized for the tool preview; the original file and its checksum remain unchanged. A missing/expired or modified artifact produces an explicit failure, not a successful empty image. JSON reports containing recognizable credential-shaped text must be redacted before registration. Images can still visually contain sensitive content: capture public pages or redact the relevant interface before storing them.
+
+`screen_capture` uses the same canonical store when a durable session exists. Its historical short-lived authenticated download link remains an export copy, not a second durable catalog. The existing filesystem credential denylist is not weakened to make `.mso` globally readable.
+
+## Retention and quotas
+
+Defaults: seven days of session/artifact inactivity, configurable through `OS_AGENT_ARTIFACT_RETENTION_DAYS` within 1–30 days. A prepared browser run gets a 30-minute lease, longer than the maximum 20-minute MSO exec job. New tool events update the durable session timestamp. Leased/recent sessions and the currently executing cleanup caller are preserved.
+
+Automatic cleanup starts lazily on the first authenticated artifact preparation/write in a production process, then runs every 30 minutes. It does not start during imports, unit tests, or a build that never executes an authenticated artifact operation. After a restart, the next artifact operation reactivates the maintenance loop. No extra system daemon, hardcoded home directory, or global `/tmp` deletion is introduced.
+
+Manual `session_artifacts_cleanup` defaults to dry-run. Explicit `dry_run:false` applies the same implementation to that client's dormant sessions. Cleanup validates ownership, directory/file types and expected names, and removes only known regular files in the fixed artifact subdirectories. It does not recursively delete an arbitrary path. Corrupt manifests, unknown files, symlinks, hard links, broad permissions and active locks are skipped for owner review. Durable session history is never deleted by artifact retention.
+
+Managed originals are capped at 12 MiB each, 200 entries/128 MiB per session, and 1 GiB across one principal's registered artifacts. Registration also bounds the principal's temporary-session inventory to 128 directories. These are application-level **registered artifact** quotas, not a disk quota for arbitrary exec commands or all unrelated temporary files. Staged copies occupy additional space until retention cleanup.
+
+## Shared implementation and verification
+
+`artifact-paths` resolves locations and policy; `artifact-io` handles private file reads; `artifact-manifest` reuses the established private JSON store; `artifact-session` validates session ownership and emits execution context; `artifacts` owns registration/read; `artifact-cleanup` owns retention. All writes reuse MSO's existing cross-process lock. MCP tools are thin adapters, available to the CLI through its existing approved agent-tools bridge.
+
+The catalog remains generic: no project-specific browser tool names are added. The new capabilities are `session_artifacts` (read), `session_artifact_register` (write), and `session_artifacts_cleanup` (write). Compact clients can need a tool-cache refresh after upgrading; changing MSO's toolset version does not remotely refresh ChatGPT.
+
+Tests cover owner/session separation, private modes, traversal, symlinks/hard links, corrupt manifests, checksum changes, concurrent registration, quotas, idempotent retries, URL sanitization, leases, dry-run and bounded removal. A screenshot file and a passing browser test are evidence; neither is proof that a page's copy has received professional editorial review or that every possible device/accessibility condition was tested.
diff --git a/docs/generated/MCP-CATALOG.md b/docs/generated/MCP-CATALOG.md
index 0d94a680..727ca0b7 100644
--- a/docs/generated/MCP-CATALOG.md
+++ b/docs/generated/MCP-CATALOG.md
@@ -4,21 +4,21 @@
## Full MSO catalog
-<!-- mcp-toolset: server=1.12.0 version=2026.09.05.4 tools=89 read=44 write=26 exec=19 -->
+<!-- mcp-toolset: server=1.12.0 version=2026.09.05.6 tools=92 read=45 write=28 exec=19 -->
| Fact | Current source value |
|---|---:|
| MCP server | `1.12.0` |
-| Toolset | `2026.09.05.4` |
-| Toolset changed at | `2026-09-05T11:59:00Z` |
-| Transport tools | **91** |
-| Model/operator tools | **89** |
-| Read | **44** |
-| Write | **26** |
+| Toolset | `2026.09.05.6` |
+| Toolset changed at | `2026-09-05T12:45:00Z` |
+| Transport tools | **94** |
+| Model/operator tools | **92** |
+| Read | **45** |
+| Write | **28** |
| Exec | **19** |
| App-only bridges | **2** |
-### Read (44)
+### Read (45)
- `a2a_agent_discover`
- `a2a_agents_list`
@@ -57,6 +57,7 @@
- `render_mso_block`
- `render_mso_page`
- `screen_capture`
+- `session_artifacts`
- `skills_list`
- `skills_read`
- `skills_search`
@@ -65,7 +66,7 @@
- `tool_forge_candidates`
- `vps_status`
-### Write (26)
+### Write (28)
- `a2a_agent_register`
- `a2a_agent_remove`
@@ -89,6 +90,8 @@
- `project_knowledge_set`
- `project_memory_upsert`
- `project_script_run`
+- `session_artifact_register`
+- `session_artifacts_cleanup`
- `tool_forge_propose`
- `workflow_cancel`
- `workflow_finish`
@@ -123,20 +126,20 @@
## ChatGPT static profile
-<!-- mcp-chatgpt-profile: server=1.12.0 version=2026.09.05.4 tools=65 read=35 write=18 exec=12 app-only=2 total=67 -->
+<!-- mcp-chatgpt-profile: server=1.12.0 version=2026.09.05.6 tools=68 read=36 write=20 exec=12 app-only=2 total=70 -->
The ChatGPT profile is a fail-closed static projection defined by `CHATGPT_TOOL_NAMES`. OAuth scope is still enforced independently; project-owned MCP tool names remain dynamic data behind the generic project bridge.
| Fact | Current source value |
|---|---:|
-| ChatGPT transport tools | **67** |
-| ChatGPT model/operator tools | **65** |
-| Read | **35** |
-| Write | **18** |
+| ChatGPT transport tools | **70** |
+| ChatGPT model/operator tools | **68** |
+| Read | **36** |
+| Write | **20** |
| Exec | **12** |
| App-only bridges | **2** |
-### ChatGPT read (35)
+### ChatGPT read (36)
- `agent_session_current`
- `apps_list`
@@ -167,6 +170,7 @@ The ChatGPT profile is a fail-closed static projection defined by `CHATGPT_TOOL_
- `render_mso_block`
- `render_mso_page`
- `screen_capture`
+- `session_artifacts`
- `skills_list`
- `skills_read`
- `skills_search`
@@ -174,7 +178,7 @@ The ChatGPT profile is a fail-closed static projection defined by `CHATGPT_TOOL_
- `sys_stats`
- `vps_status`
-### ChatGPT write (18)
+### ChatGPT write (20)
- `agent_session_rename`
- `apps_power`
@@ -191,6 +195,8 @@ The ChatGPT profile is a fail-closed static projection defined by `CHATGPT_TOOL_
- `local_agent_message_send`
- `local_agent_reply`
- `project_knowledge_set`
+- `session_artifact_register`
+- `session_artifacts_cleanup`
- `workflow_cancel`
- `workflow_finish`
- `workflow_start`
diff --git a/lib/agent/artifact-cleanup.ts b/lib/agent/artifact-cleanup.ts
new file mode 100644
index 00000000..749465f0
--- /dev/null
+++ b/lib/agent/artifact-cleanup.ts
@@ -0,0 +1,113 @@
+import path from "node:path";
+import { promises as fs } from "node:fs";
+import { withSecurityStoreLock } from "@/lib/security-store-lock";
+import { readSessionFile, listSessionRecords, principalHash } from "./session-files";
+import { artifactPaths, artifactRetentionDays, type ArtifactOwner } from "./artifact-paths";
+import { ensureArtifactDirectory } from "./artifact-io";
+import { readArtifactManifest, ARTIFACT_FILE } from "./artifact-manifest";
+
+/** Retention never recursively traverses an arbitrary directory. A corrupt manifest,
+ * unknown file, symlink or recently active session causes a fail-closed skip. */
+export async function pruneSessionArtifacts(owner: ArtifactOwner, dryRun = true, now = Date.now()) {
+ const p = artifactPaths(owner);
+ if (!(await ensureArtifactDirectory(p.directory, p.root, false))) return { sessionId: owner.id, state: "absent", bytes: 0 };
+ return withSecurityStoreLock(p.ownerLock, () =>
+ withSecurityStoreLock(p.lock, async () => {
+ const session = await readSessionFile(owner.id),
+ m = await readArtifactManifest(owner);
+ if (!session || session.principalHash !== owner.principalHash) throw new Error("artifact owner mismatch");
+ const latest = Math.max(Date.parse(session.updatedAt), Date.parse(m.updatedAt));
+ if (Date.parse(m.leaseUntil) > now || now - latest < artifactRetentionDays() * 86400000)
+ return { sessionId: owner.id, state: "active", bytes: 0 };
+ const rootEntries = await fs.readdir(p.directory);
+ if (rootEntries.some((n) => !["incoming", "screenshots", "reports", "manifest.json"].includes(n)))
+ return { sessionId: owner.id, state: "unknown-files", bytes: 0 };
+ const files: string[] = [];
+ let bytes = 0;
+ for (const dir of [p.incoming, p.screenshots, p.reports]) {
+ if (!(await ensureArtifactDirectory(dir, p.root, false))) continue;
+ const names = await fs.readdir(dir);
+ if (names.length > 500) return { sessionId: owner.id, state: "too-many-files", bytes: 0 };
+ for (const name of names) {
+ const known =
+ dir === p.incoming ? /^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,179}\.(png|jpe?g|webp|json)$/.test(name) : ARTIFACT_FILE.test(name);
+ const file = path.join(dir, name),
+ stat = await fs.lstat(file);
+ if (
+ !known ||
+ name.includes("..") ||
+ !stat.isFile() ||
+ stat.isSymbolicLink() ||
+ stat.nlink !== 1 ||
+ (stat.mode & 0o077) !== 0 ||
+ (typeof process.getuid === "function" && stat.uid !== process.getuid())
+ )
+ return { sessionId: owner.id, state: "unsafe-files", bytes: 0 };
+ if (now - stat.mtimeMs < artifactRetentionDays() * 86400000) return { sessionId: owner.id, state: "recent-files", bytes: 0 };
+ files.push(file);
+ bytes += stat.size;
+ }
+ }
+ if (dryRun) return { sessionId: owner.id, state: "would-remove", bytes, files: files.length };
+ for (const file of files) await fs.unlink(file);
+ for (const dir of [p.incoming, p.screenshots, p.reports])
+ await fs.rmdir(dir).catch((error: NodeJS.ErrnoException) => {
+ if (error.code !== "ENOENT") throw error;
+ });
+ await fs.unlink(p.manifest).catch((error: NodeJS.ErrnoException) => {
+ if (error.code !== "ENOENT") throw error;
+ });
+ await fs.rmdir(p.directory);
+ return { sessionId: owner.id, state: "removed", bytes, files: files.length };
+ }),
+ );
+}
+export async function cleanupSessionArtifacts(options: { principal?: string; currentSessionId?: string; dryRun?: boolean } = {}) {
+ const owner = options.principal ? principalHash(options.principal) : undefined;
+ const sessions = (await listSessionRecords())
+ .filter((s) => (!owner || s.principalHash === owner) && s.id !== options.currentSessionId)
+ .sort((a, b) => a.updatedAt.localeCompare(b.updatedAt));
+ const candidates = [];
+ for (const session of sessions) {
+ const p = artifactPaths(session);
+ if (
+ await fs.lstat(p.directory).then(
+ () => true,
+ () => false,
+ )
+ )
+ candidates.push(session);
+ }
+ const results = [];
+ for (const session of candidates.slice(0, 100)) {
+ try {
+ results.push(await pruneSessionArtifacts(session, options.dryRun !== false));
+ } catch {
+ results.push({ sessionId: session.id, state: "unsafe-or-busy", bytes: 0 });
+ }
+ }
+ return {
+ dryRun: options.dryRun !== false,
+ retentionDays: artifactRetentionDays(),
+ checked: results.length,
+ remaining: Math.max(0, candidates.length - results.length),
+ results,
+ };
+}
+let started = false;
+export function startArtifactMaintenance() {
+ if (started || process.env.VITEST || process.env.NODE_ENV !== "production") return;
+ started = true;
+ let running = false;
+ const run = async () => {
+ if (running) return;
+ running = true;
+ try {
+ await cleanupSessionArtifacts({ dryRun: false });
+ } finally {
+ running = false;
+ }
+ };
+ void run().catch(() => undefined);
+ setInterval(() => void run().catch(() => undefined), 30 * 60_000).unref();
+}
diff --git a/lib/agent/artifact-io.ts b/lib/agent/artifact-io.ts
new file mode 100644
index 00000000..1aa7be0a
--- /dev/null
+++ b/lib/agent/artifact-io.ts
@@ -0,0 +1,42 @@
+import { constants, promises as fs } from "node:fs";
+import path from "node:path";
+/** Artifact paths are private and never follow symbolic links. */
+export async function ensureArtifactDirectory(directory: string, privateRoot: string, create = true): Promise<boolean> {
+ const relative = path.relative(privateRoot, directory);
+ if (relative.startsWith("..") || path.isAbsolute(relative)) throw new Error("artifact directory outside session root");
+ let current = path.parse(directory).root;
+ for (const component of path.resolve(directory).split(path.sep).filter(Boolean)) {
+ current = path.join(current, component);
+ let stat = await fs.lstat(current).catch((error: NodeJS.ErrnoException) => {
+ if (error.code === "ENOENT") return null;
+ throw error;
+ });
+ if (!stat) {
+ if (!create) return false;
+ await fs.mkdir(current, { mode: 0o700 }).catch((error: NodeJS.ErrnoException) => {
+ if (error.code !== "EEXIST") throw error;
+ });
+ stat = await fs.lstat(current);
+ }
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("artifact directory must not be a symlink");
+ if (current === privateRoot || current.startsWith(privateRoot + path.sep)) {
+ if ((stat.mode & 0o077) !== 0) throw new Error("artifact directory must have owner-only permissions");
+ if (typeof process.getuid === "function" && stat.uid !== process.getuid()) throw new Error("artifact directory owner mismatch");
+ }
+ }
+ return true;
+}
+export async function readArtifactBytes(file: string, maxBytes: number): Promise<Buffer> {
+ const handle = await fs.open(file, constants.O_RDONLY | constants.O_NOFOLLOW);
+ try {
+ const stat = await handle.stat();
+ if (!stat.isFile() || stat.nlink !== 1 || stat.size < 1 || stat.size > maxBytes) throw new Error("invalid artifact file or size");
+ if ((stat.mode & 0o077) !== 0) throw new Error("artifact file must have owner-only permissions");
+ if (typeof process.getuid === "function" && stat.uid !== process.getuid()) throw new Error("artifact file owner mismatch");
+ const bytes = await handle.readFile();
+ if (bytes.length > maxBytes) throw new Error("artifact grew beyond the size limit");
+ return bytes;
+ } finally {
+ await handle.close();
+ }
+}
diff --git a/lib/agent/artifact-manifest.ts b/lib/agent/artifact-manifest.ts
new file mode 100644
index 00000000..c453906d
--- /dev/null
+++ b/lib/agent/artifact-manifest.ts
@@ -0,0 +1,49 @@
+import { artifactPaths, ARTIFACT_LIMITS, type ArtifactOwner } from "./artifact-paths";
+import { emptyArtifactManifest, type ArtifactManifest, type SessionArtifact } from "./artifact-types";
+import { readLocalAgentStore, writeLocalAgentStore } from "./local-agent-private-store";
+import { ensureArtifactDirectory, readArtifactBytes } from "./artifact-io";
+export const ARTIFACT_ID = /^shot_[a-f0-9]{24}$/;
+export const ARTIFACT_FILE = /^mso__[a-z0-9_.-]{1,210}\.(png|jpg|webp|json)$/;
+function validEntry(value: SessionArtifact): boolean {
+ return Boolean(
+ value &&
+ ARTIFACT_ID.test(value.id) &&
+ ARTIFACT_FILE.test(value.filename) &&
+ !value.filename.includes("..") &&
+ ["screenshots/" + value.filename, "reports/" + value.filename].includes(value.relativePath) &&
+ /^[a-f0-9]{64}$/.test(value.sha256) &&
+ Number.isInteger(value.bytes) &&
+ value.bytes > 0 &&
+ value.bytes <= ARTIFACT_LIMITS.fileBytes &&
+ ["image/png", "image/jpeg", "image/webp", "application/json"].includes(value.mimeType) &&
+ Number.isFinite(Date.parse(value.createdAt)),
+ );
+}
+export async function readArtifactManifest(owner: ArtifactOwner): Promise<ArtifactManifest> {
+ const p = artifactPaths(owner);
+ if (!(await ensureArtifactDirectory(p.directory, p.root, false))) return emptyArtifactManifest(owner);
+ // Existing shared JSON writer is reused; this adds the artifact-specific hard-link guard.
+ await readArtifactBytes(p.manifest, 768 * 1024).catch((e: NodeJS.ErrnoException) => {
+ if (e.code !== "ENOENT") throw e;
+ });
+ return readLocalAgentStore(p.manifest, 768 * 1024, emptyArtifactManifest(owner), (value): value is ArtifactManifest => {
+ const m = value as ArtifactManifest;
+ return Boolean(
+ m &&
+ m.version === 1 &&
+ m.sessionId === owner.id &&
+ m.principalHash === owner.principalHash &&
+ Number.isFinite(Date.parse(m.updatedAt)) &&
+ Number.isFinite(Date.parse(m.leaseUntil)) &&
+ Array.isArray(m.artifacts) &&
+ m.artifacts.length <= ARTIFACT_LIMITS.files &&
+ m.artifacts.every(validEntry) &&
+ new Set(m.artifacts.map((a) => a.id)).size === m.artifacts.length,
+ );
+ });
+}
+export async function writeArtifactManifest(owner: ArtifactOwner, value: ArtifactManifest) {
+ const p = artifactPaths(owner);
+ await ensureArtifactDirectory(p.directory, p.root);
+ await writeLocalAgentStore(p.manifest, value, 768 * 1024);
+}
diff --git a/lib/agent/artifact-paths.ts b/lib/agent/artifact-paths.ts
new file mode 100644
index 00000000..95f8ef5e
--- /dev/null
+++ b/lib/agent/artifact-paths.ts
@@ -0,0 +1,46 @@
+import path from "node:path";
+import { agentSessionsDir, SESSION_ID } from "./session-paths";
+export const ARTIFACT_LIMITS = {
+ fileBytes: 12 * 1024 * 1024,
+ sessionBytes: 128 * 1024 * 1024,
+ principalBytes: 1024 * 1024 * 1024,
+ files: 200,
+ sessions: 128,
+} as const;
+export function artifactRetentionDays(): number {
+ const n = Number(process.env.OS_AGENT_ARTIFACT_RETENTION_DAYS || 7);
+ return Number.isFinite(n) ? Math.max(1, Math.min(30, Math.trunc(n))) : 7;
+}
+export type ArtifactOwner = { id: string; principalHash: string };
+export function artifactPaths(owner: ArtifactOwner) {
+ if (!SESSION_ID.test(owner.id) || !/^[a-f0-9]{64}$/.test(owner.principalHash)) throw new Error("invalid artifact owner/session");
+ const root = agentSessionsDir(),
+ temp = path.join(root, "temp");
+ const principal = path.join(temp, owner.principalHash),
+ directory = path.join(principal, owner.id);
+ return {
+ root,
+ temp,
+ principal,
+ directory,
+ incoming: path.join(directory, "incoming"),
+ screenshots: path.join(directory, "screenshots"),
+ reports: path.join(directory, "reports"),
+ manifest: path.join(directory, "manifest.json"),
+ lock: path.join(principal, `.${owner.id}.artifacts`),
+ ownerLock: path.join(temp, `.${owner.principalHash}.quota`),
+ };
+}
+export function artifactLocation(owner: ArtifactOwner) {
+ const p = artifactPaths(owner);
+ return {
+ directory: p.directory,
+ incomingDirectory: p.incoming,
+ screenshotsDirectory: p.screenshots,
+ manifestPath: p.manifest,
+ retentionDays: artifactRetentionDays(),
+ limits: ARTIFACT_LIMITS,
+ readTool: "session_artifacts",
+ registerTool: "session_artifact_register",
+ };
+}
diff --git a/lib/agent/artifact-policy.ts b/lib/agent/artifact-policy.ts
new file mode 100644
index 00000000..b6df5b47
--- /dev/null
+++ b/lib/agent/artifact-policy.ts
@@ -0,0 +1,71 @@
+import { randomBytes } from "node:crypto";
+import type { ArtifactInput, SessionArtifact } from "./artifact-types";
+export function artifactFormat(bytes: Buffer): { extension: string; mimeType: SessionArtifact["mimeType"]; kind: SessionArtifact["kind"] } {
+ if (bytes.length >= 24 && bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])))
+ return { extension: "png", mimeType: "image/png", kind: "screenshot" };
+ if (bytes.length > 12 && bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255)
+ return { extension: "jpg", mimeType: "image/jpeg", kind: "screenshot" };
+ if (bytes.length > 12 && bytes.subarray(0, 4).toString() === "RIFF" && bytes.subarray(8, 12).toString() === "WEBP")
+ return { extension: "webp", mimeType: "image/webp", kind: "screenshot" };
+ try {
+ const data = JSON.parse(bytes.toString("utf8"));
+ if (data && typeof data === "object") return { extension: "json", mimeType: "application/json", kind: "report" };
+ } catch {
+ /* not an accepted artifact */
+ }
+ throw new Error("only PNG/JPEG/WebP images or JSON reports are accepted");
+}
+function slug(value: unknown, fallback: string, max = 40): string {
+ return (
+ String(value || fallback)
+ .normalize("NFKD")
+ .replace(/[^a-z0-9]+/gi, "-")
+ .replace(/^-|-$/g, "")
+ .toLowerCase()
+ .slice(0, max) || fallback
+ );
+}
+export function artifactMetadata(input: ArtifactInput): ArtifactInput {
+ if (typeof input.project !== "string" || !input.project.trim() || typeof input.feature !== "string" || !input.feature.trim())
+ throw new Error("artifact project and feature are required");
+ let url: string | undefined;
+ if (input.url) {
+ if (input.url.length > 2048) throw new Error("artifact URL is too long");
+ const parsed = new URL(input.url);
+ if (!["http:", "https:"].includes(parsed.protocol)) throw new Error("invalid artifact URL");
+ url = parsed.origin + parsed.pathname;
+ }
+ const dimension = (n: unknown) => (typeof n === "number" && Number.isInteger(n) && n >= 1 && n <= 20000 ? n : undefined);
+ return {
+ project: slug(input.project, "project"),
+ feature: slug(input.feature, "feature"),
+ environment: slug(input.environment, "local", 16),
+ locale: input.locale ? slug(input.locale, "und", 16) : undefined,
+ width: dimension(input.width),
+ height: dimension(input.height),
+ url,
+ producer: ["playwright", "camoufox", "mso", "other"].includes(input.producer || "") ? input.producer : "other",
+ workflowId: input.workflowId && /^[a-f0-9-]{36}$/.test(input.workflowId) ? input.workflowId : undefined,
+ };
+}
+export function artifactName(input: ArtifactInput, extension: string, now: Date) {
+ const id = "shot_" + randomBytes(12).toString("hex");
+ const stamp = now
+ .toISOString()
+ .replace(/[^0-9TZ]/g, "")
+ .toLowerCase();
+ const filename =
+ [
+ "mso",
+ input.project,
+ input.feature,
+ input.environment,
+ input.locale || "und",
+ input.width && input.height ? `${input.width}x${input.height}` : "native",
+ stamp,
+ id.slice(-8),
+ ].join("__") +
+ "." +
+ extension;
+ return { id, filename };
+}
diff --git a/lib/agent/artifact-session.ts b/lib/agent/artifact-session.ts
new file mode 100644
index 00000000..feb46d7e
--- /dev/null
+++ b/lib/agent/artifact-session.ts
@@ -0,0 +1,53 @@
+import { startArtifactMaintenance } from "./artifact-cleanup";
+import { promises as fs } from "node:fs";
+import { withSecurityStoreLock } from "@/lib/security-store-lock";
+import { principalHash, readSessionFile } from "./session-files";
+import { ARTIFACT_LIMITS, artifactLocation, artifactPaths, type ArtifactOwner } from "./artifact-paths";
+import { SESSION_ID } from "./session-paths";
+import { ensureArtifactDirectory } from "./artifact-io";
+import { readArtifactManifest, writeArtifactManifest } from "./artifact-manifest";
+export async function ownedArtifactSession(principal: string | undefined, sessionId: string | undefined): Promise<ArtifactOwner> {
+ if (!principal || !sessionId) throw new Error("artifacts require an authenticated MSO session");
+ const row = await readSessionFile(sessionId);
+ if (!row || row.principalHash !== principalHash(principal)) throw new Error("artifact session not found for this client");
+ return { id: row.id, principalHash: row.principalHash };
+}
+export async function checkedArtifactOwner(owner: ArtifactOwner) {
+ const row = await readSessionFile(owner.id);
+ if (!row || row.principalHash !== owner.principalHash) throw new Error("artifact session owner mismatch");
+ return artifactPaths(owner);
+}
+export async function artifactDirectories(owner: ArtifactOwner) {
+ const p = await checkedArtifactOwner(owner);
+ startArtifactMaintenance();
+ for (const directory of [p.incoming, p.screenshots, p.reports]) await ensureArtifactDirectory(directory, p.root);
+ return p;
+}
+export async function prepareSessionArtifacts(owner: ArtifactOwner) {
+ const p = await artifactDirectories(owner);
+ await withSecurityStoreLock(p.lock, async () => {
+ const m = await readArtifactManifest(owner);
+ m.leaseUntil = new Date(Date.now() + 30 * 60_000).toISOString();
+ m.updatedAt = new Date().toISOString();
+ await writeArtifactManifest(owner, m);
+ });
+ return artifactLocation(owner);
+}
+export async function sessionArtifactEnvironment(context: { principal?: string; sessionId?: string }): Promise<Record<string, string>> {
+ if (!context.principal || !context.sessionId) return {};
+ const location = await prepareSessionArtifacts(await ownedArtifactSession(context.principal, context.sessionId));
+ return {
+ MSO_SESSION_ID: context.sessionId,
+ MSO_SESSION_TEMP_DIR: location.directory,
+ MSO_SCREENSHOT_DIR: location.incomingDirectory,
+ MSO_ARTIFACT_MANIFEST: location.manifestPath,
+ };
+}
+export async function assertPrincipalArtifactQuota(owner: ArtifactOwner, incomingBytes: number) {
+ const p = artifactPaths(owner);
+ const names = (await fs.readdir(p.principal)).filter((n) => SESSION_ID.test(n));
+ if (names.length > ARTIFACT_LIMITS.sessions) throw new Error("too many temporary artifact sessions; clean up expired sessions");
+ let bytes = incomingBytes;
+ for (const id of names) bytes += (await readArtifactManifest({ ...owner, id })).artifacts.reduce((n, a) => n + a.bytes, 0);
+ if (bytes > ARTIFACT_LIMITS.principalBytes) throw new Error("principal artifact quota reached; clean up expired artifacts");
+}
diff --git a/lib/agent/artifact-types.ts b/lib/agent/artifact-types.ts
new file mode 100644
index 00000000..2f869afd
--- /dev/null
+++ b/lib/agent/artifact-types.ts
@@ -0,0 +1,40 @@
+import type { ArtifactOwner } from "./artifact-paths";
+export type ArtifactInput = {
+ project: string;
+ feature: string;
+ environment?: string;
+ locale?: string;
+ width?: number;
+ height?: number;
+ url?: string;
+ workflowId?: string;
+ producer?: "playwright" | "camoufox" | "mso" | "other";
+};
+export type SessionArtifact = ArtifactInput & {
+ id: string;
+ filename: string;
+ relativePath: string;
+ kind: "screenshot" | "report";
+ mimeType: "image/png" | "image/jpeg" | "image/webp" | "application/json";
+ bytes: number;
+ sha256: string;
+ createdAt: string;
+};
+export type ArtifactManifest = {
+ version: 1;
+ sessionId: string;
+ principalHash: string;
+ updatedAt: string;
+ leaseUntil: string;
+ artifacts: SessionArtifact[];
+};
+export function emptyArtifactManifest(owner: ArtifactOwner): ArtifactManifest {
+ return {
+ version: 1,
+ sessionId: owner.id,
+ principalHash: owner.principalHash,
+ updatedAt: new Date(0).toISOString(),
+ leaseUntil: new Date(0).toISOString(),
+ artifacts: [],
+ };
+}
diff --git a/lib/agent/artifacts.test.ts b/lib/agent/artifacts.test.ts
new file mode 100644
index 00000000..062452bf
--- /dev/null
+++ b/lib/agent/artifacts.test.ts
@@ -0,0 +1,94 @@
+import { beforeAll, beforeEach, afterAll, describe, expect, it } from "vitest";
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+const root=await fs.mkdtemp(path.join(os.tmpdir(),"mso-artifact-test-"));
+process.env.OS_AGENT_SESSIONS_DIR=path.join(root,"sessions");
+const {writeSessionFile,readSessionFile,principalHash}=await import("./session-files");
+const {artifactPaths,artifactLocation,artifactRetentionDays,ARTIFACT_LIMITS}=await import("./artifact-paths");
+const {prepareSessionArtifacts,ownedArtifactSession,sessionArtifactEnvironment}=await import("./artifact-session");
+const {saveSessionArtifact,registerIncomingArtifact,readSessionArtifact,listSessionArtifacts}=await import("./artifacts");
+const {pruneSessionArtifacts,cleanupSessionArtifacts}=await import("./artifact-cleanup");
+const {readArtifactManifest,writeArtifactManifest}=await import("./artifact-manifest");
+const {artifactMetadata}=await import("./artifact-policy");
+const {agentSessionSummary}=await import("./session-store");
+type Session=import("./session-types").AgentSession;
+const principal="mcp-client:artifact-test",other="mcp-client:other-test";
+const one={id:"20260905_120000_00000001",principalHash:principalHash(principal)},two={id:"20260905_120000_00000002",principalHash:principalHash(principal)},foreign={id:"20260905_120000_00000003",principalHash:principalHash(other)};
+const png=Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/lZsAAAAASUVORK5CYII=","base64");
+const meta={project:"portfolio",feature:"home",environment:"production",locale:"fr",width:390,height:844,producer:"playwright" as const,url:"https://visitor:[email protected]/fr?secret=drop#fragment"};
+async function seed(owner=one,updatedAt=new Date().toISOString()) {
+ const row={...owner,source:"mcp",name:"milo",title:"Artifact test",titleSource:"manual",createdAt:updatedAt,updatedAt,history:[],events:[],memorySnapshot:{},estimatedTokens:0,lifetimeEstimatedTokens:0,compactThresholdTokens:700000,compactionCount:0,archiveCount:0} as unknown as Session;
+ await writeSessionFile(row);return row;
+}
+beforeAll(async()=>{await seed();await seed(two);await seed(foreign);});
+beforeEach(async()=>{await fs.rm(artifactPaths(one).temp,{recursive:true,force:true});});
+afterAll(async()=>{delete process.env.OS_AGENT_SESSIONS_DIR;delete process.env.OS_AGENT_ARTIFACT_RETENTION_DAYS;await fs.rm(root,{recursive:true,force:true});});
+describe("session artifact storage",()=>{
+ it("derives paths from configured user root with distinct principal/session boundaries",()=>{
+ expect(artifactLocation(one).directory).toContain(path.join(root,"sessions","temp",one.principalHash,one.id));
+ expect(artifactPaths(one).directory).not.toBe(artifactPaths(two).directory);expect(artifactPaths(one).principal).not.toBe(artifactPaths(foreign).principal);
+ expect(()=>artifactPaths({...one,id:"../../escape"})).toThrow();
+ });
+ it("validates authenticated ownership",async()=>{expect(await ownedArtifactSession(principal,one.id)).toEqual(one);await expect(ownedArtifactSession(other,one.id)).rejects.toThrow();await expect(ownedArtifactSession(undefined,one.id)).rejects.toThrow();});
+ it("provides non-secret session env and derived summary locations",async()=>{
+ const env=await sessionArtifactEnvironment({principal,sessionId:one.id});expect(env.MSO_SCREENSHOT_DIR).toBe(artifactPaths(one).incoming);expect(Object.keys(env)).toHaveLength(4);
+ expect(agentSessionSummary((await readSessionFile(one.id))!).artifacts?.manifestPath).toBe(artifactPaths(one).manifest);
+ expect(await sessionArtifactEnvironment({})).toEqual({});
+ });
+ it("saves descriptive immutable names, private mode, relative manifest and matching hashes",async()=>{
+ const a=await saveSessionArtifact(one,png,meta);expect(a.filename).toMatch(/^mso__portfolio__home__production__fr__390x844__/);expect(a.url).toBe("https://example.com/fr");
+ const read=await readSessionArtifact(one,a.id);expect(read.bytes.equals(png)).toBe(true);expect((await fs.stat(read.path)).mode&0o777).toBe(0o600);
+ const listing=await listSessionArtifacts(one);expect(listing.total).toBe(1);expect(listing.artifacts[0].path).toBe(read.path);
+ const text=await fs.readFile(artifactPaths(one).manifest,"utf8");expect(text).not.toContain(root);expect(text).not.toContain("secret=drop");
+ await expect(readSessionArtifact(two,a.id)).rejects.toThrow();
+ });
+ it("deduplicates an identical registration retry",async()=>{const a=await saveSessionArtifact(one,png,meta);const b=await saveSessionArtifact(one,png,meta);expect(a.id).toBe(b.id);expect((await listSessionArtifacts(one)).total).toBe(1);});
+ it("serializes concurrent writes without lost entries",async()=>{
+ await Promise.all(Array.from({length:8},(_,i)=>saveSessionArtifact(one,png,{...meta,feature:`state-${i}`})));
+ expect((await listSessionArtifacts(one)).total).toBe(8);
+ });
+ it("registers only private staged basenames and rejects traversal, public permissions, symlinks and hardlinks",async()=>{
+ await prepareSessionArtifacts(one);const p=artifactPaths(one),staged=path.join(p.incoming,"home.png");await fs.writeFile(staged,png,{mode:0o600});
+ expect((await registerIncomingArtifact(one,"home.png",meta)).kind).toBe("screenshot");
+ for(const source of ["../home.png","/tmp/home.png","other/home.png","bad.html"])await expect(registerIncomingArtifact(one,source,meta)).rejects.toThrow();
+ await fs.writeFile(path.join(p.incoming,"public.png"),png,{mode:0o644});await expect(registerIncomingArtifact(one,"public.png",meta)).rejects.toThrow();
+ await fs.symlink(staged,path.join(p.incoming,"link.png"));await expect(registerIncomingArtifact(one,"link.png",meta)).rejects.toThrow();
+ await fs.link(staged,path.join(p.incoming,"hard.png"));await expect(registerIncomingArtifact(one,"hard.png",meta)).rejects.toThrow();
+ });
+ it("refuses a symlinked temp directory without touching its target",async()=>{
+ const outside=path.join(root,"outside");await fs.mkdir(outside,{mode:0o700});await fs.symlink(outside,artifactPaths(one).temp);
+ await expect(prepareSessionArtifacts(one)).rejects.toThrow(/symlink/);expect(await fs.readdir(outside)).toEqual([]);
+ });
+ it("fails closed for corruption, changed bytes, executable content and excessive sizes",async()=>{
+ await expect(saveSessionArtifact(one,Buffer.from("<html>not an image</html>"),meta)).rejects.toThrow();
+ await expect(saveSessionArtifact(one,Buffer.alloc(ARTIFACT_LIMITS.fileBytes+1),meta)).rejects.toThrow();
+ const a=await saveSessionArtifact(one,png,meta),p=artifactPaths(one);await fs.writeFile(path.join(p.directory,a.relativePath),Buffer.from("changed"));await expect(readSessionArtifact(one,a.id)).rejects.toThrow(/checksum/);
+ await fs.writeFile(p.manifest,"not-json");await expect(listSessionArtifacts(one)).rejects.toThrow();
+ });
+ it("enforces count and byte quotas before persisting more data",async()=>{
+ await prepareSessionArtifacts(one);const m=await readArtifactManifest(one);const a=await saveSessionArtifact(one,png,meta);
+ m.artifacts=Array.from({length:200},(_,i)=>({...a,id:"shot_"+i.toString(16).padStart(24,"0")}));await writeArtifactManifest(one,m);
+ await expect(saveSessionArtifact(one,png,{...meta,feature:"quota-extra"})).rejects.toThrow(/quota/);
+ });
+ it("accepts JSON evidence but rejects credential-shaped text",async()=>{
+ expect((await saveSessionArtifact(one,Buffer.from('{"checks":5,"errors":[]}'),{...meta,feature:"report"})).mimeType).toBe("application/json");
+ await expect(saveSessionArtifact(one,Buffer.from('{"password":"do-not-store"}'),meta)).rejects.toThrow(/credential/);
+ });
+ it("bounds configurable retention and sanitizes labels/URLs",()=>{
+ process.env.OS_AGENT_ARTIFACT_RETENTION_DAYS="900";expect(artifactRetentionDays()).toBe(30);process.env.OS_AGENT_ARTIFACT_RETENTION_DAYS="NaN";expect(artifactRetentionDays()).toBe(7);delete process.env.OS_AGENT_ARTIFACT_RETENTION_DAYS;
+ expect(artifactMetadata({...meta,project:"../a b"}).project).toBe("a-b");expect(()=>artifactMetadata({...meta,url:"file:///etc/passwd"})).toThrow();
+ });
+});
+describe("bounded artifact retention",()=>{
+ it("preserves live/leased files and defaults to a dry-run",async()=>{
+ await prepareSessionArtifacts(one);await saveSessionArtifact(one,png,meta);expect((await pruneSessionArtifacts(one)).state).toBe("active");
+ const future=Date.now()+9*86400000;expect((await pruneSessionArtifacts(one,true,future)).state).toBe("would-remove");expect((await listSessionArtifacts(one)).total).toBe(1);
+ expect((await pruneSessionArtifacts(one,false,future)).state).toBe("removed");expect(await readSessionFile(one.id)).not.toBeNull();
+ });
+ it("never follows foreign files during cleanup and never removes another principal's session",async()=>{
+ await prepareSessionArtifacts(one);await saveSessionArtifact(one,png,meta);const p=artifactPaths(one);await fs.writeFile(path.join(p.directory,"unknown.txt"),"preserve",{mode:0o600});
+ expect((await pruneSessionArtifacts(one,false,Date.now()+9*86400000)).state).toBe("unknown-files");
+ const report=await cleanupSessionArtifacts({principal:other,dryRun:false});expect(report.results.some(r=>r.sessionId===one.id)).toBe(false);
+ });
+});
diff --git a/lib/agent/artifacts.ts b/lib/agent/artifacts.ts
new file mode 100644
index 00000000..2d27ad86
--- /dev/null
+++ b/lib/agent/artifacts.ts
@@ -0,0 +1,111 @@
+import path from "node:path";
+import { promises as fs } from "node:fs";
+import { createHash } from "node:crypto";
+import { withSecurityStoreLock } from "@/lib/security-store-lock";
+import { redactText } from "@/lib/security/redact-text";
+import { ARTIFACT_LIMITS, artifactLocation, type ArtifactOwner } from "./artifact-paths";
+import { ensureArtifactDirectory, readArtifactBytes } from "./artifact-io";
+import { readArtifactManifest, writeArtifactManifest, ARTIFACT_ID } from "./artifact-manifest";
+import { artifactFormat, artifactMetadata, artifactName } from "./artifact-policy";
+import { artifactDirectories, checkedArtifactOwner, assertPrincipalArtifactQuota } from "./artifact-session";
+import type { ArtifactInput, SessionArtifact } from "./artifact-types";
+export async function saveSessionArtifact(owner: ArtifactOwner, bytes: Buffer, input: ArtifactInput): Promise<SessionArtifact> {
+ if (!bytes.length || bytes.length > ARTIFACT_LIMITS.fileBytes) throw new Error("artifact exceeds 12 MiB");
+ const format = artifactFormat(bytes),
+ meta = artifactMetadata(input);
+ if (format.kind === "report") {
+ const text = bytes.toString("utf8");
+ if (redactText(text, text.length) !== text) throw new Error("report contains credential-shaped content; redact before saving");
+ }
+ const p = await artifactDirectories(owner);
+ return withSecurityStoreLock(p.ownerLock, () =>
+ withSecurityStoreLock(p.lock, async () => {
+ const m = await readArtifactManifest(owner);
+ const digest = createHash("sha256").update(bytes).digest("hex");
+ const existing = m.artifacts.find(
+ (a) =>
+ a.sha256 === digest &&
+ a.project === meta.project &&
+ a.feature === meta.feature &&
+ a.environment === meta.environment &&
+ a.locale === meta.locale &&
+ a.width === meta.width &&
+ a.height === meta.height &&
+ a.url === meta.url &&
+ a.workflowId === meta.workflowId,
+ );
+ if (existing) return existing;
+ if (
+ m.artifacts.length >= ARTIFACT_LIMITS.files ||
+ m.artifacts.reduce((n, a) => n + a.bytes, 0) + bytes.length > ARTIFACT_LIMITS.sessionBytes
+ )
+ throw new Error("session artifact quota reached");
+ await assertPrincipalArtifactQuota(owner, bytes.length);
+ const now = new Date(),
+ { id, filename } = artifactName(meta, format.extension, now);
+ const relativePath = (format.kind === "screenshot" ? "screenshots/" : "reports/") + filename;
+ const entry: SessionArtifact = {
+ ...meta,
+ id,
+ filename,
+ relativePath,
+ kind: format.kind,
+ mimeType: format.mimeType,
+ bytes: bytes.length,
+ sha256: digest,
+ createdAt: now.toISOString(),
+ };
+ const target = path.join(p.directory, relativePath);
+ await fs.writeFile(target, bytes, { flag: "wx", mode: 0o600 });
+ try {
+ m.artifacts.push(entry);
+ m.updatedAt = now.toISOString();
+ await writeArtifactManifest(owner, m);
+ } catch (error) {
+ await fs.unlink(target).catch(() => undefined);
+ throw error;
+ }
+ return entry;
+ }),
+ );
+}
+export async function registerIncomingArtifact(owner: ArtifactOwner, source: string, input: ArtifactInput): Promise<SessionArtifact> {
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,179}\.(png|jpe?g|webp|json)$/.test(source) || source.includes(".."))
+ throw new Error("source must be one filename inside MSO_SCREENSHOT_DIR");
+ const p = await checkedArtifactOwner(owner);
+ await ensureArtifactDirectory(p.incoming, p.root, false);
+ const sourcePath = path.join(p.incoming, source),
+ bytes = await readArtifactBytes(sourcePath, ARTIFACT_LIMITS.fileBytes);
+ const entry = await saveSessionArtifact(owner, bytes, input);
+ // Staged input is deliberately retained: never unlink a concurrently replaced producer file.
+ // Dormant-session cleanup handles it together with the registered copy.
+ return entry;
+}
+export async function listSessionArtifacts(owner: ArtifactOwner, offset = 0, limit = 50) {
+ const p = await checkedArtifactOwner(owner),
+ m = await readArtifactManifest(owner);
+ const start = Math.max(0, Math.trunc(offset) || 0),
+ count = Math.max(1, Math.min(100, Math.trunc(limit) || 50));
+ return {
+ sessionId: owner.id,
+ ...artifactLocation(owner),
+ total: m.artifacts.length,
+ bytes: m.artifacts.reduce((n, a) => n + a.bytes, 0),
+ artifacts: m.artifacts.slice(start, start + count).map((a) => ({ ...a, path: path.join(p.directory, a.relativePath) })),
+ nextOffset: start + count < m.artifacts.length ? start + count : null,
+ };
+}
+export async function readSessionArtifact(owner: ArtifactOwner, id: string) {
+ if (!ARTIFACT_ID.test(id)) throw new Error("invalid artifact id");
+ const p = await checkedArtifactOwner(owner);
+ if (!(await ensureArtifactDirectory(p.directory, p.root, false))) throw new Error("artifact expired or not found");
+ return withSecurityStoreLock(p.lock, async () => {
+ const m = await readArtifactManifest(owner),
+ entry = m.artifacts.find((a) => a.id === id);
+ if (!entry) throw new Error("artifact expired or not found");
+ await ensureArtifactDirectory(path.join(p.directory, path.dirname(entry.relativePath)), p.root, false);
+ const bytes = await readArtifactBytes(path.join(p.directory, entry.relativePath), ARTIFACT_LIMITS.fileBytes);
+ if (createHash("sha256").update(bytes).digest("hex") !== entry.sha256) throw new Error("artifact checksum mismatch");
+ return { entry, path: path.join(p.directory, entry.relativePath), bytes };
+ });
+}
diff --git a/lib/agent/session-files.ts b/lib/agent/session-files.ts
index aa882b0c..c8922341 100644
--- a/lib/agent/session-files.ts
+++ b/lib/agent/session-files.ts
@@ -1,16 +1,16 @@
import { createHash, randomBytes, randomUUID } from "node:crypto";
import { constants as fsConstants, promises as fs } from "node:fs";
-import os from "node:os";
import path from "node:path";
import { compactThresholdTokens, inferredTitleSource, MAX_EVENTS, MAX_HISTORY, safeTitle, sessionContextTokens } from "./session-policy";
import type { AgentSession } from "./session-types";
import { legacyAgentSessionName, normalizeAgentSessionName } from "./session-name";
-const ROOT = path.resolve((process.env.OS_AGENT_SESSIONS_DIR || path.join(os.homedir(), ".mso", "agent-sessions")).replace(/^~(?=$|\/)/, os.homedir()));
+import { agentSessionsDir, SESSION_ID } from "./session-paths";
+export { SESSION_ID } from "./session-paths";
+const ROOT = agentSessionsDir();
const LOCK_ROOT = path.join(ROOT, ".locks");
const CONVERSATION_ROOT = path.join(ROOT, ".conversation-index");
const CONVERSATION_READY = path.join(CONVERSATION_ROOT, ".ready-v1");
-export const SESSION_ID = /^\d{8}_\d{6}_[a-f0-9]{8}$/;
const HASH64 = /^[a-f0-9]{64}$/;
const MAX_SESSION_BYTES = 16 * 1024 * 1024;
diff --git a/lib/agent/session-paths.ts b/lib/agent/session-paths.ts
new file mode 100644
index 00000000..ab130760
--- /dev/null
+++ b/lib/agent/session-paths.ts
@@ -0,0 +1,9 @@
+import os from "node:os";
+import path from "node:path";
+export const SESSION_ID = /^\d{8}_\d{6}_[a-f0-9]{8}$/;
+/** The same configured root owns session records and disposable session artifacts. */
+export function agentSessionsDir(): string {
+ return path.resolve(
+ (process.env.OS_AGENT_SESSIONS_DIR || path.join(os.homedir(), ".mso", "agent-sessions")).replace(/^~(?=$|\/)/, os.homedir()),
+ );
+}
diff --git a/lib/agent/session-store.ts b/lib/agent/session-store.ts
index 168cae28..7681bec9 100644
--- a/lib/agent/session-store.ts
+++ b/lib/agent/session-store.ts
@@ -1,3 +1,4 @@
+import { artifactLocation } from "./artifact-paths";
import { withSecurityStoreLock } from "@/lib/security-store-lock";
import { redactText } from "@/lib/security/redact-text";
import { normalizeAgentSessionCwd } from "./session-location";
@@ -85,6 +86,7 @@ function summary(record: AgentSession): AgentSessionSummary {
...(record.lastArchivedAt ? { lastArchivedAt: record.lastArchivedAt } : {}),
eventCount: record.events.length,
historyTurns: record.history.length,
+ artifacts: artifactLocation(record),
};
}
diff --git a/lib/agent/session-types.ts b/lib/agent/session-types.ts
index 22b2bde8..f0829267 100644
--- a/lib/agent/session-types.ts
+++ b/lib/agent/session-types.ts
@@ -1,3 +1,4 @@
+import type { artifactLocation } from "./artifact-paths";
import type { AgentMemorySnapshot } from "./memory-store";
export type AgentSessionSource = "cli" | "mcp" | "alfa";
@@ -46,6 +47,7 @@ export interface AgentSession {
}
export interface AgentSessionSummary {
+ artifacts?: ReturnType<typeof artifactLocation>;
id: string;
source: AgentSessionSource;
name: string;
diff --git a/lib/config/env-example.test.ts b/lib/config/env-example.test.ts
index c97d4e46..f1cd829e 100644
--- a/lib/config/env-example.test.ts
+++ b/lib/config/env-example.test.ts
@@ -20,6 +20,7 @@ const ROOT = path.join(__dirname, "..", "..");
const NOT_A_KNOB: Record<string, string> = {
// Injected by the framework or the runtime.
NEXT_RUNTIME: "set by Next itself",
+ NODE_ENV: "standard Node/Next process mode; artifact maintenance starts only in production",
NEXT_PUBLIC_BUILD_ID: "injected by next.config.mjs at build time",
MSO_RUNTIME_INSTANCE_ID: "injected by the installer-managed service to prove restart readiness",
// Private launcher-to-agent handoff. scripts/mso-cli-agent.sh owns these; users
diff --git a/lib/host/exec-jobs.ts b/lib/host/exec-jobs.ts
index 3cbca63a..a11ac11d 100644
--- a/lib/host/exec-jobs.ts
+++ b/lib/host/exec-jobs.ts
@@ -100,6 +100,7 @@ function terminate(job: ExecJob) {
export async function startExecJob(input: {
command: string;
+ artifactEnv?: Record<string, string>;
cwd?: string;
actor?: string;
workflowId?: string;
@@ -135,7 +136,7 @@ export async function startExecJob(input: {
const child = spawn(input.command, {
cwd,
- env: childEnv() as NodeJS.ProcessEnv,
+ env: { ...childEnv(), ...input.artifactEnv } as NodeJS.ProcessEnv,
shell: SHELL,
stdio: "pipe",
detached: process.platform !== "win32",
diff --git a/lib/host/exec.ts b/lib/host/exec.ts
index b346d681..ce038df2 100644
--- a/lib/host/exec.ts
+++ b/lib/host/exec.ts
@@ -47,7 +47,7 @@ export async function resolveCwd(requested?: string): Promise<string> {
return roots.some((r) => isUnderRoot(real, r)) ? real : home;
}
-export async function runCommand(cmd: string, cwd?: string): Promise<ExecResult> {
+export async function runCommand(cmd: string, cwd?: string, artifactEnv: Record<string, string> = {}): Promise<ExecResult> {
if (typeof cmd !== "string" || !cmd.trim()) throw new HostError("Empty command");
const blocked = destructiveReason(cmd);
if (blocked) {
@@ -63,7 +63,7 @@ export async function runCommand(cmd: string, cwd?: string): Promise<ExecResult>
cmd,
// childEnv preserves NODE_ENV (only the app's secrets are stripped), so the
// ProcessEnv cast is sound — the typed shape just demands NODE_ENV present.
- { cwd: dir, timeout: TIMEOUT_MS, maxBuffer: MAX_OUTPUT, env: childEnv() as NodeJS.ProcessEnv, shell: SHELL },
+ { cwd: dir, timeout: TIMEOUT_MS, maxBuffer: MAX_OUTPUT, env: { ...childEnv(), ...artifactEnv } as NodeJS.ProcessEnv, shell: SHELL },
(err: Error | null, stdout: string, stderr: string) => {
const e = err as (Error & { code?: number; killed?: boolean }) | null;
const code = e && typeof e.code === "number" ? e.code : e ? 1 : 0;
diff --git a/lib/mcp/parity.test.ts b/lib/mcp/parity.test.ts
index d41aba71..12e43a42 100644
--- a/lib/mcp/parity.test.ts
+++ b/lib/mcp/parity.test.ts
@@ -33,6 +33,9 @@ const ALFA_ONLY: Record<string, string> = {
};
const MCP_ONLY: Record<string, string> = {
+ "session.artifacts": "CLI/MCP durable-session artifact records use the authenticated client principal; Alfa browser threads have a separate identity and must not inherit another session's files",
+ "session.artifact.register": "same durable-session boundary; external browser producers stage files under session context rather than accepting arbitrary paths",
+ "session.artifacts.cleanup": "same session store; bounded retention is controlled by the authenticated external/CLI principal, not unrelated Alfa thread state",
"integration.setup.open": "ChatGPT needs a write-scoped UI-only capability; native owner browser and CLI use the same secure setup service without exposing secrets to Alfa tools",
"screen.capture": "external MCP clients need visual proof of the rendered OS; in-shell Alfa already runs inside that browser UI",
"projects.list": "an MCP client has no sidebar and no Files window, so it needs an explicit bounded enumeration of every project container; in-shell Alfa reads the same roots through fs.list and the Files app",
@@ -160,9 +163,11 @@ describe("MCP rate limits mirror the routes", () => {
"fs.delete": 60, "fs.upload": 20, "exec": 60, "managed-app": 12, "camoufox": 12,
};
const MCP_NATIVE_LIMITS: Record<string, number> = {
- // screen_capture has no HTTP route by design; it exists only for connected
- // MCP clients and is expensive enough to deserve a much smaller bucket.
+ // Native capabilities have independent bounded buckets (no matching HTTP route).
"screen.capture": 10,
+ "session.artifacts": 60,
+ "session.artifact.register": 30,
+ "session.artifact.cleanup": 6,
"workflow.memory": 30,
"project.memory.search": 60,
"project.memory.write": 60,
@@ -176,8 +181,7 @@ describe("MCP rate limits mirror the routes", () => {
"exec.job.start": 12,
"exec.job.status": 120,
"exec.job.cancel": 30,
- // Global discovery reads: no HTTP route mirrors them, and each one walks
- // every configured container, so they get their own small buckets.
+ // Global discovery reads use independent bounded buckets.
"projects.list": 30,
"projects.capabilities": 60,
"projects.function": 60,
diff --git a/lib/mcp/read-pipeline-engine.ts b/lib/mcp/read-pipeline-engine.ts
index f2ec96f4..600a952b 100644
--- a/lib/mcp/read-pipeline-engine.ts
+++ b/lib/mcp/read-pipeline-engine.ts
@@ -13,7 +13,7 @@ import {
type ReadPipelineInput,
} from "./read-pipeline-types";
-const EXCLUDED = new Set(["read_pipeline", "workflow_status", "screen_capture", "local_agent_request_wait"]);
+const EXCLUDED = new Set(["read_pipeline", "workflow_status", "screen_capture", "session_artifacts", "local_agent_request_wait"]);
function jsonBytes(value: unknown): number {
try { return Buffer.byteLength(JSON.stringify(value), "utf8"); }
diff --git a/lib/mcp/tool-contract.ts b/lib/mcp/tool-contract.ts
index 4b7dd8e1..e8d1dd1c 100644
--- a/lib/mcp/tool-contract.ts
+++ b/lib/mcp/tool-contract.ts
@@ -38,7 +38,7 @@ export const CHATGPT_TOOL_NAMES = new Set([
// Workflow/session intelligence. workflow_status and render_mso_surface stay app-only at presentation time.
"workflow_start", "workflow_status", "workflow_finish", "workflow_cancel",
"skills_search", "skills_list", "skills_read", "read_pipeline",
- "agent_session_current", "agent_session_rename",
+ "agent_session_current", "agent_session_rename", "session_artifacts", "session_artifact_register", "session_artifacts_cleanup",
"local_agents_list", "local_agent_inbox", "local_agent_message_send", "local_agent_reply", "local_agent_request_wait",
// Project-first operator surface. Project-owned names remain dynamic.
@@ -128,7 +128,8 @@ function compactSchema(value: unknown): unknown {
if (!value || typeof value !== "object") return value;
const out: Record<string, unknown> = {};
for (const [key, item] of Object.entries(value as Record<string, unknown>)) {
- if (key === "description" && typeof item === "string") out[key] = compactText(item, 105);
+ if (key === "workflow_id" && item && typeof item === "object") out[key] = { ...compactSchema(item) as Record<string, unknown>, description: "workflow_start id." };
+ else if (key === "description" && typeof item === "string") out[key] = compactText(item, 105);
else out[key] = compactSchema(item);
}
return out;
diff --git a/lib/mcp/tools-agent.ts b/lib/mcp/tools-agent.ts
index 83541e5a..9169b6dd 100644
--- a/lib/mcp/tools-agent.ts
+++ b/lib/mcp/tools-agent.ts
@@ -27,7 +27,7 @@ function sessionHash(sessionId?: string): string | undefined {
export const AGENT_TOOLS: McpTool[] = [
{
name: "agent_session_current",
- description: "Return this ChatGPT conversation's isolated durable MSO session, timestamps and estimated context-token budget.",
+ description: "Return this conversation's durable session, context budget and dynamic temp/screenshot/manifest locations. Use session_artifacts to list/read saved files.",
scope: "read", annotations: { readOnlyHint: true, idempotentHint: true }, inputSchema: S({}),
run: async (_a, context) => {
if (!context.sessionId) throw new Error("this tool call has no conversation-bound MSO session");
diff --git a/lib/mcp/tools-read.ts b/lib/mcp/tools-read.ts
index 0aa0cad8..5e789fa0 100644
--- a/lib/mcp/tools-read.ts
+++ b/lib/mcp/tools-read.ts
@@ -1,3 +1,7 @@
+import { ownedArtifactSession } from "@/lib/agent/artifact-session";
+import { saveSessionArtifact } from "@/lib/agent/artifacts";
+import { artifactPaths } from "@/lib/agent/artifact-paths";
+import path from "node:path";
import { listDir, readFile, searchFs, usage, sha256Text, utf8Bytes } from "@/lib/host/fs-api";
import { stats, processes } from "@/lib/host/system-api";
import { captureMsoScreen } from "@/lib/host/screenshot-api";
@@ -139,7 +143,7 @@ export const READ_TOOLS: McpTool[] = [
description:
"Capture the authenticated MSO desktop and return it as an image. This is intentionally limited to " +
"MSO itself (no arbitrary URL capture), so it can be used to show visual progress without turning a read token " +
- "into a browser exfiltration primitive. It also returns a 15-minute, session-gated temporary preview/download link. " +
+ "into a browser exfiltration primitive. It saves a session-scoped artifact when a durable session exists, plus a 15-minute authenticated preview/download link. " +
"Choose macos, windows or dashboard; default macos.",
scope: "read",
annotations: READ_ONLY,
@@ -149,7 +153,7 @@ export const READ_TOOLS: McpTool[] = [
width: { type: "number", minimum: 900, maximum: 1920, description: "Viewport width. Default 1440." },
height: { type: "number", minimum: 600, maximum: 1200, description: "Viewport height. Default 900." },
}),
- run: async (a) => {
+ run: async (a, context) => {
const shell = typeof a.shell === "string" && ["macos", "windows", "dashboard"].includes(a.shell)
? (a.shell as "macos" | "windows" | "dashboard")
: "macos";
@@ -158,6 +162,9 @@ export const READ_TOOLS: McpTool[] = [
width: typeof a.width === "number" ? a.width : undefined,
height: typeof a.height === "number" ? a.height : undefined,
});
+ const owner = context.principal && context.sessionId ? await ownedArtifactSession(context.principal,context.sessionId) : null;
+ const artifact = owner ? await saveSessionArtifact(owner,Buffer.from(shot.data,"base64"),{project:"mso",feature:`shell-${shell}`,environment:"local",width:shot.width,height:shot.height,producer:"mso",workflowId:context.workflowId}) : null;
+ const artifactPath = owner && artifact ? path.join(artifactPaths(owner).directory,artifact.relativePath) : undefined;
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
const share = await createTempShare({
data: Buffer.from(shot.data, "base64"),
@@ -174,12 +181,13 @@ export const READ_TOOLS: McpTool[] = [
type: "text",
text:
`MSO ${shot.shell} screenshot — ${shot.width}×${shot.height}\n` +
+ (artifactPath ? `Session artifact: ${artifactPath}\n` : "") +
`Temporary preview: ${previewUrl}\n` +
`Direct download: ${downloadUrl}\n` +
`Expires ${new Date(share.expiresAt).toISOString()} · ${share.downloadsLeft} authenticated downloads`,
},
], false, {
- result: { shell: shot.shell, width: shot.width, height: shot.height, mimeType: shot.mimeType, previewUrl, downloadUrl, expiresAt: share.expiresAt, downloadsLeft: share.downloadsLeft },
+ result: { artifact, artifactPath, shell: shot.shell, width: shot.width, height: shot.height, mimeType: shot.mimeType, previewUrl, downloadUrl, expiresAt: share.expiresAt, downloadsLeft: share.downloadsLeft },
});
},
},
diff --git a/lib/mcp/tools-session-artifacts.test.ts b/lib/mcp/tools-session-artifacts.test.ts
new file mode 100644
index 00000000..6ad97b1f
--- /dev/null
+++ b/lib/mcp/tools-session-artifacts.test.ts
@@ -0,0 +1,41 @@
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+const root=await fs.mkdtemp(path.join(os.tmpdir(),"mso-artifact-tools-"));
+process.env.OS_AGENT_SESSIONS_DIR=path.join(root,"sessions");
+const {writeSessionFile,principalHash}=await import("@/lib/agent/session-files");
+const {prepareSessionArtifacts}=await import("@/lib/agent/artifact-session");
+const {artifactPaths}=await import("@/lib/agent/artifact-paths");
+const {SESSION_ARTIFACT_TOOLS}=await import("./tools-session-artifacts");
+const sessionId="20260905_123000_ffffffff",principal="mcp-client:artifact-tools";
+const owner={id:sessionId,principalHash:principalHash(principal)};
+const context={principal,sessionId,scope:"write" as const};
+const get=(name:string)=>SESSION_ARTIFACT_TOOLS.find(t=>t.name===name)!;
+const png=Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/lZsAAAAASUVORK5CYII=","base64");
+beforeAll(async()=>{
+ const now=new Date().toISOString();
+ await writeSessionFile({...owner,source:"mcp",name:"milo",title:"Artifact tools",titleSource:"manual",createdAt:now,updatedAt:now,history:[],events:[],estimatedTokens:0,lifetimeEstimatedTokens:0,compactThresholdTokens:700000,compactionCount:0,archiveCount:0,memorySnapshot:{}} as unknown as import("@/lib/agent/session-types").AgentSession);
+ await prepareSessionArtifacts(owner);await fs.writeFile(path.join(artifactPaths(owner).incoming,"home.png"),png,{mode:0o600});
+});
+afterAll(async()=>{delete process.env.OS_AGENT_SESSIONS_DIR;await fs.rm(root,{recursive:true,force:true});});
+describe("native session artifact tools",()=>{
+ it("batch registration reports partial failures without losing successful entries",async()=>{
+ const result=await get("session_artifact_register").run({project:"portfolio",producer:"playwright",environment:"production",files:[{source:"home.png",feature:"home"},{source:"../foreign.png",feature:"invalid"}]},context) as {saved:number;results:Array<{ok:boolean}>};
+ expect(result.saved).toBe(1);expect(result.results.map(r=>r.ok)).toEqual([true,false]);
+ });
+ it("reads stored screenshot through direct MCP image content",async()=>{
+ const list=await get("session_artifacts").run({},context) as {artifacts:Array<{id:string}>};expect(list.artifacts).toHaveLength(1);
+ const read=await get("session_artifacts").run({artifact_id:list.artifacts[0].id},context) as {__mcpDirect:boolean;content:Array<{type:string;data?:string}>};
+ expect(read.__mcpDirect).toBe(true);expect(read.content[0]).toMatchObject({type:"image",data:png.toString("base64")});
+ });
+ it("rejects another principal, an absent session and filesystem path guesses",async()=>{
+ await expect(get("session_artifacts").run({}, {...context,principal:"foreign-client"})).rejects.toThrow();
+ await expect(get("session_artifacts").run({artifact_id:"../../file"},context)).rejects.toThrow();
+ await expect(get("session_artifacts").run({}, {scope:"read"})).rejects.toThrow();
+ });
+ it("keeps read and write capabilities distinct and cleanup defaults to dry-run",async()=>{
+ expect(get("session_artifacts").scope).toBe("read");expect(get("session_artifact_register").scope).toBe("write");expect(get("session_artifacts_cleanup").scope).toBe("write");
+ const result=await get("session_artifacts_cleanup").run({},context) as {dryRun:boolean;results:Array<{sessionId:string}>};expect(result.dryRun).toBe(true);expect(result.results.some(r=>r.sessionId===sessionId)).toBe(false);
+ });
+});
diff --git a/lib/mcp/tools-session-artifacts.ts b/lib/mcp/tools-session-artifacts.ts
new file mode 100644
index 00000000..3187c09e
--- /dev/null
+++ b/lib/mcp/tools-session-artifacts.ts
@@ -0,0 +1,129 @@
+import { appendAgentSessionEvent } from "@/lib/agent/session-store";
+import { listSessionArtifacts, readSessionArtifact, registerIncomingArtifact } from "@/lib/agent/artifacts";
+import { ownedArtifactSession } from "@/lib/agent/artifact-session";
+import { cleanupSessionArtifacts } from "@/lib/agent/artifact-cleanup";
+import type { ArtifactInput } from "@/lib/agent/artifact-types";
+import { mcpDirect, S, opt, str, type McpTool } from "./tool-kit";
+
+const FILE = {
+ type: "object",
+ additionalProperties: false,
+ required: ["source", "feature"],
+ properties: {
+ source: { type: "string", maxLength: 180, description: "One staged basename in MSO_SCREENSHOT_DIR; never an absolute path." },
+ feature: { type: "string", maxLength: 80 },
+ locale: { type: "string", maxLength: 24 },
+ width: { type: "integer", minimum: 1, maximum: 20000 },
+ height: { type: "integer", minimum: 1, maximum: 20000 },
+ url: { type: "string", maxLength: 2048, description: "Optional captured page; credentials, query and fragment are discarded." },
+ },
+};
+export const SESSION_ARTIFACT_TOOLS: McpTool[] = [
+ {
+ name: "session_artifacts",
+ scope: "read",
+ description:
+ "List this session's private screenshots/reports, or read one artifact_id as an image/JSON. Returns exact dynamic paths, checksum and retention; optional session_id must belong to the same authenticated client. No public URL is created.",
+ annotations: { readOnlyHint: true, idempotentHint: true },
+ limit: { key: "session.artifacts", max: 60, windowMs: 60000 },
+ inputSchema: S({
+ session_id: { type: "string" },
+ artifact_id: { type: "string" },
+ offset: { type: "integer", minimum: 0 },
+ limit: { type: "integer", minimum: 1, maximum: 100 },
+ }),
+ run: async (a, context) => {
+ const owner = await ownedArtifactSession(context.principal, opt(a, "session_id") || context.sessionId);
+ if (!a.artifact_id) return listSessionArtifacts(owner, Number(a.offset) || 0, Number(a.limit) || 50);
+ const artifact = await readSessionArtifact(owner, str(a, "artifact_id"));
+ const metadata = { ...artifact.entry, path: artifact.path, sessionId: owner.id };
+ if (artifact.entry.kind === "report")
+ return { artifact: metadata, text: artifact.bytes.toString("utf8").slice(0, 32000), truncated: artifact.bytes.length > 32000 };
+ let bytes = artifact.bytes,
+ mimeType = artifact.entry.mimeType;
+ if (bytes.length > 620 * 1024) {
+ const sharp = (await import("sharp")).default;
+ bytes = await sharp(bytes, { limitInputPixels: 40000000 })
+ .resize({ width: 1440, height: 1600, fit: "inside", withoutEnlargement: true })
+ .jpeg({ quality: 72 })
+ .toBuffer();
+ mimeType = "image/jpeg";
+ }
+ if (bytes.length > 620 * 1024)
+ throw new Error("Image preview remains too large; inspect the saved original using the owner terminal");
+ return mcpDirect(
+ [
+ { type: "image", data: bytes.toString("base64"), mimeType },
+ { type: "text", text: JSON.stringify(metadata) },
+ ],
+ false,
+ { result: { artifact: metadata, previewMimeType: mimeType } },
+ );
+ },
+ },
+ {
+ name: "session_artifact_register",
+ scope: "write",
+ description:
+ "Register 1-40 Playwright/Camoufox screenshots or JSON reports from this session's MSO_SCREENSHOT_DIR. Use umask 077 when producing files. Assigns descriptive project/feature/locale/viewport/time names, hashes and one session manifest; raw producer files remain until retention cleanup.",
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false },
+ audit: { action: "agent.session", targetArg: "project" },
+ limit: { key: "session.artifact.register", max: 30, windowMs: 60000 },
+ inputSchema: S(
+ {
+ project: { type: "string", maxLength: 80 },
+ environment: { type: "string", maxLength: 32 },
+ producer: { type: "string", enum: ["playwright", "camoufox", "mso", "other"] },
+ files: { type: "array", minItems: 1, maxItems: 40, items: FILE },
+ },
+ ["project", "files"],
+ ),
+ run: async (a, context) => {
+ const owner = await ownedArtifactSession(context.principal, context.sessionId);
+ if (!Array.isArray(a.files) || a.files.length < 1 || a.files.length > 40)
+ throw new Error("files must contain 1-40 artifact descriptors");
+ const results = [];
+ for (const value of a.files) {
+ const row = value as ArtifactInput & { source: string };
+ if (!row || typeof row !== "object") throw new Error("invalid artifact descriptor");
+ try {
+ const artifact = await registerIncomingArtifact(owner, row.source, {
+ ...row,
+ project: str(a, "project"),
+ environment: opt(a, "environment"),
+ producer: opt(a, "producer") as ArtifactInput["producer"],
+ workflowId: context.workflowId,
+ });
+ results.push({ ok: true, artifact });
+ } catch (error) {
+ results.push({
+ ok: false,
+ source: typeof row.source === "string" ? row.source.slice(0, 180) : "invalid",
+ error: error instanceof Error ? error.message : "artifact registration failed",
+ });
+ }
+ }
+ const saved = results.filter((r) => r.ok).length;
+ await appendAgentSessionEvent(context.principal!, owner.id, {
+ kind: "note",
+ workflowId: context.workflowId,
+ detail: `Artifacts: ${saved}/${results.length} saved; use session_artifacts for names and paths.`,
+ });
+ return { sessionId: owner.id, saved, results };
+ },
+ },
+ {
+ name: "session_artifacts_cleanup",
+ scope: "write",
+ description:
+ "Preview or remove expired dormant artifact folders owned by this client. Dry-run defaults true. Current session, recent/leased sessions, unknown files, symlinks and unsafe permissions are preserved; durable session records are never removed.",
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true },
+ audit: { action: "agent.session" },
+ limit: { key: "session.artifact.cleanup", max: 6, windowMs: 60000 },
+ inputSchema: S({ dry_run: { type: "boolean", description: "Default true: inspect only; false applies bounded retention cleanup." } }),
+ run: async (a, context) => {
+ await ownedArtifactSession(context.principal, context.sessionId);
+ return cleanupSessionArtifacts({ principal: context.principal, currentSessionId: context.sessionId, dryRun: a.dry_run !== false });
+ },
+ },
+];
diff --git a/lib/mcp/tools-workflow-start.ts b/lib/mcp/tools-workflow-start.ts
index a65eb9b4..d257f273 100644
--- a/lib/mcp/tools-workflow-start.ts
+++ b/lib/mcp/tools-workflow-start.ts
@@ -1,3 +1,4 @@
+import { ownedArtifactSession, prepareSessionArtifacts } from "@/lib/agent/artifact-session";
import { inspectProject, readProjectKnowledge, resolveProjectHint } from "@/lib/host/projects-api";
import { markRecipeUsed, startWorkflow, summarizeProjectContention } from "@/lib/workflow";
import { searchSkillMemory } from "@/lib/skills/search";
@@ -39,6 +40,7 @@ export const WORKFLOW_START_TOOL: McpTool =
const actor = context.workflowActor ?? context.actor;
const recipeOwner = context.recipeActor ?? context.actor;
if (!actor || !recipeOwner) throw new Error("workflow memory needs an authenticated session and client");
+ const artifactStorage = context.principal && context.sessionId ? await prepareSessionArtifacts(await ownedArtifactSession(context.principal,context.sessionId)) : undefined;
const intent = str(a, "intent");
const projectHint = opt(a, "project");
const project = projectHint ? await resolveProjectHint(projectHint).catch(() => null) : null;
@@ -153,6 +155,7 @@ export const WORKFLOW_START_TOOL: McpTool =
...started,
bootstrap: {
ready: true,
+ artifacts: artifactStorage,
toolset,
project: project ?? (projectHint ? { hint: projectHint, matchedBy: "unresolved" } : undefined),
repository,
diff --git a/lib/mcp/tools.ts b/lib/mcp/tools.ts
index 01f20737..41eac288 100644
--- a/lib/mcp/tools.ts
+++ b/lib/mcp/tools.ts
@@ -1,3 +1,5 @@
+import { SESSION_ARTIFACT_TOOLS } from "./tools-session-artifacts";
+import { sessionArtifactEnvironment } from "@/lib/agent/artifact-session";
import { writeFileGuarded, makeDir, remove, move, copy } from "@/lib/host/fs-api";
import { runCommand, startExecJob, getExecJob, cancelExecJob } from "@/lib/host/exec-api";
import { resolveProjectHint, runProjectFunction } from "@/lib/host/projects-api";
@@ -169,7 +171,8 @@ const MUTATE_TOOLS: McpTool[] = [
command: { type: "string", description: "The shell command line to run asynchronously." },
cwd: { type: "string", description: "Working directory. Defaults to the owner's home." },
}, ["command"]),
- run: (a, context) => startExecJob({
+ run: async (a, context) => startExecJob({
+ artifactEnv: await sessionArtifactEnvironment(context),
command: str(a, "command"), cwd: opt(a, "cwd"), actor: context.workflowActor ?? context.actor, workflowId: context.workflowId,
}),
},
@@ -223,8 +226,8 @@ const MUTATE_TOOLS: McpTool[] = [
command: { type: "string", description: "The shell command line to run." },
cwd: { type: "string", description: "Working directory. Defaults to the owner's home." },
}, ["command"]),
- run: (a) => runCommand(str(a, "command"), opt(a, "cwd")),
+ run: async (a, context) => runCommand(str(a, "command"), opt(a, "cwd"), await sessionArtifactEnvironment(context)),
},
];
-export const TOOLS: McpTool[] = [...READ_TOOLS, ...DISCOVERY_TOOLS, ...LEARNING_TOOLS, ...AGENT_TOOLS, ...LOCAL_AGENT_TOOLS, ...SUBAGENT_TOOLS, ...A2A_TOOLS, ...FORGE_TOOLS, ...READ_PIPELINE_TOOLS, ...PROJECT_MCP_TOOLS, ...PROJECT_EXPERIENCE_TOOLS, ...OPERATOR_DASHBOARD_TOOLS, ...BLOCK_TOOLS, ...SURFACE_TOOLS, ...INFRA_TOOLS, ...MUTATE_TOOLS, ...POWER_TOOLS].map(withWorkflowContext); export const TOOLS_BY_NAME = new Map(TOOLS.map((t) => [t.name, t]));
+export const TOOLS: McpTool[] = [...SESSION_ARTIFACT_TOOLS, ...READ_TOOLS, ...DISCOVERY_TOOLS, ...LEARNING_TOOLS, ...AGENT_TOOLS, ...LOCAL_AGENT_TOOLS, ...SUBAGENT_TOOLS, ...A2A_TOOLS, ...FORGE_TOOLS, ...READ_PIPELINE_TOOLS, ...PROJECT_MCP_TOOLS, ...PROJECT_EXPERIENCE_TOOLS, ...OPERATOR_DASHBOARD_TOOLS, ...BLOCK_TOOLS, ...SURFACE_TOOLS, ...INFRA_TOOLS, ...MUTATE_TOOLS, ...POWER_TOOLS].map(withWorkflowContext); export const TOOLS_BY_NAME = new Map(TOOLS.map((t) => [t.name, t]));
diff --git a/lib/mcp/toolset.ts b/lib/mcp/toolset.ts
index 5a8b08bf..79f46657 100644
--- a/lib/mcp/toolset.ts
+++ b/lib/mcp/toolset.ts
@@ -4,8 +4,8 @@ import type { McpTool } from "./tool-kit";
import { toolDescriptor, type McpToolProfile } from "./tool-contract";
export const MCP_SERVER_VERSION = "1.12.0";
-export const MCP_TOOLSET_VERSION = "2026.09.05.4";
-export const MCP_TOOLSET_CHANGED_AT = "2026-09-05T11:59:00Z";
+export const MCP_TOOLSET_VERSION = "2026.09.05.6";
+export const MCP_TOOLSET_CHANGED_AT = "2026-09-05T12:45:00Z";
export type McpToolsetInfo = {
serverVersion: string;
diff --git a/scripts/mso-agent-status.mjs b/scripts/mso-agent-status.mjs
index b1943023..d8109a76 100644
--- a/scripts/mso-agent-status.mjs
+++ b/scripts/mso-agent-status.mjs
@@ -111,6 +111,7 @@ function detailedStatus(session, cwd = process.cwd()) {
session: session?.agentSession?.id || null,
name: session?.agentSession?.name || null,
title: session?.agentSession?.title || null,
+ artifacts: session?.agentSession?.artifacts || null,
permission: session?.permission || "ask",
cwd: homeShort(cwd),
};
@@ -143,4 +144,6 @@ export function printDetailedStatus(session, C, cwd = process.cwd()) {
console.log(` name @${row.name || "agent"}`);
console.log(` title ${row.title || "MSO Agent session"}`);
console.log(` cwd ${row.cwd}`);
+ if (row.artifacts?.directory) console.log(` temp ${row.artifacts.directory}`);
+ if (row.artifacts?.manifestPath) console.log(` artifacts ${row.artifacts.manifestPath}`);
}