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(mcp): global project/skill discovery, drop image generation

rahmanef63a9c8764d8513
diff --git a/.env.example b/.env.example
index 3908bac8..dd4e98d4 100644
--- a/.env.example
+++ b/.env.example
@@ -55,19 +55,17 @@ OS_SESSION_SECRET=
# Bring your own Anthropic key. Can also be set in the OS via Settings → AI
# (stored in ~/.mso/config.json). If unset, the assistant returns 501.
# ANTHROPIC_API_KEY=
-# Official OpenAI Images API key. It may instead be saved through Settings → AI
-# under provider OpenAI; the 0600 host credential store wins over this env fallback.
+# Official OpenAI API key. It may instead be saved through Settings → AI under
+# provider OpenAI; the 0600 host credential store wins over this env fallback.
# OPENAI_API_KEY=
-# Image-generation sandbox configuration. Provider masters are always saved as
-# lossless PNG plus a provenance JSON sidecar; repository promotion is a separate step.
-# OS_IMAGE_MODEL=gpt-image-2
-# OS_IMAGE_OUTPUT_ROOT=~/generated-images
#
-# Provider-run tools the Codex backend may use, comma/space separated. Default:
-# `image_generation`. Set an explicit empty value to disable every built-in, or set
-# another allowlisted list to replace the default. Provider-run usage may bill the
-# connected ChatGPT account.
-# OS_CODEX_BUILTIN_TOOLS=image_generation
+# Provider-run tools the Codex backend may use, comma/space separated. EMPTY by
+# default — no provider built-in is declared unless you name one here. Allowed:
+# web_search, web_search_preview, file_search, code_interpreter,
+# computer_use_preview, local_shell. `image_generation` is NOT allowed: MSO has no
+# image generation on any surface, and a GPT client already carries its own.
+# Provider-run usage may bill the connected ChatGPT account.
+# OS_CODEX_BUILTIN_TOOLS=
# --- Managed apps: Hermes / OpenClaw (optional) ---
# The OS lists an upstream app's own dashboard pages by reading that app's built
diff --git a/README.md b/README.md
index 93b89666..3596d229 100644
--- a/README.md
+++ b/README.md
@@ -64,7 +64,7 @@ For a real deployment, put MSO behind **Tailscale, a VPN, or a TLS reverse proxy
**Extend** — Alfa AI, modular slices, and custom apps.
- **Use BYOK AI** — Alfa uses credentials stored on your server, not committed to the repo.
-- **Drive the box from ChatGPT, Claude.ai or Cursor** — an optional MCP server (OAuth 2.1 + PKCE) exposes files, system health, provider-backed image generation with durable provenance, and, if you grant it, a shell. Off unless you set `OS_MCP_ENABLED=1`, scoped read/write/exec per token, revocable from Settings. See [docs/MCP.md](./docs/MCP.md).
+- **Drive the box from ChatGPT, Claude.ai or Cursor** — an optional MCP server (OAuth 2.1 + PKCE) exposes files, system health, every project and every trusted skill across all of them, ChatGPT file import, and, if you grant it, a shell. A token sees the *whole* catalog for its tier: the read/write/exec ladder is the only thing that narrows it, never a per-project or per-agent filter. Off unless you set `OS_MCP_ENABLED=1`, revocable from Settings. See [docs/MCP.md](./docs/MCP.md).
- **Add app slices** — features are modular under `frontend/slices/<slug>/`.
- **Personalize the interface** — macOS, Windows, iOS, and Android shell layouts are UI preferences, not the core product.
diff --git a/app/api/skills/route.ts b/app/api/skills/route.ts
index e2b2b46c..abcd42f5 100644
--- a/app/api/skills/route.ts
+++ b/app/api/skills/route.ts
@@ -1,7 +1,7 @@
import { NextRequest, NextResponse } from "next/server";
import { requireSession } from "@/lib/auth/require-session";
import { IS_DEMO } from "@/lib/demo";
-import { catalogSkills, readSkillFile, type SkillInfo } from "@/lib/skills/catalog";
+import { catalogSkills, findSkill, readSkillFile, type SkillInfo } from "@/lib/skills/catalog";
import { listLearnedRecipes } from "@/lib/skills/memory";
import { searchSkillMemory } from "@/lib/skills/search";
@@ -9,8 +9,8 @@ export const runtime = "nodejs";
export const dynamic = "force-dynamic";
const demoSkills: SkillInfo[] = [
- { name: "camoufox-browse", path: "demo://camoufox-browse", description: "Browser automation playbook for Camoufox.", source: "bundled", trust: "verified" },
- { name: "vps-alfa", path: "demo://vps-alfa", description: "Patrol and assist VPS terminal panes.", source: "mso", trust: "official" },
+ { id: "camoufox-browse", name: "camoufox-browse", path: "demo://camoufox-browse", description: "Browser automation playbook for Camoufox.", source: "bundled", trust: "verified" },
+ { id: "vps-alfa", name: "vps-alfa", path: "demo://vps-alfa", description: "Patrol and assist VPS terminal panes.", source: "mso", trust: "official" },
];
export async function GET(req: NextRequest) {
@@ -24,10 +24,10 @@ export async function GET(req: NextRequest) {
query,
hits: demoSkills
.filter((s) => `${s.name} ${s.description}`.toLowerCase().includes(q))
- .map((s) => ({ kind: "skill", id: s.name, name: s.name, score: 1, description: s.description, source: s.source, trust: s.trust })),
+ .map((s) => ({ kind: "skill", id: s.id, name: s.name, score: 1, description: s.description, source: s.source, trust: s.trust })),
});
}
- const skill = name ? demoSkills.find((s) => s.name === name) : null;
+ const skill = name ? findSkill(demoSkills, name) : null;
return skill
? NextResponse.json({ skill, content: `# ${skill.name}\n\n${skill.description}\n\nDemo mode only lists this skill; it does not run host automation.` })
: NextResponse.json({ skills: demoSkills, recipes: [] });
@@ -52,7 +52,7 @@ export async function GET(req: NextRequest) {
return NextResponse.json({ skills, recipes });
}
- const skill = skills.find((s) => s.name === name);
+ const skill = findSkill(skills, name);
if (!skill) return NextResponse.json({ error: "not_found" }, { status: 404 });
const content = await readSkillFile(skill.path);
if (content === null) return NextResponse.json({ error: "not_found" }, { status: 404 });
diff --git a/bin/mso b/bin/mso
index c5cbb1d0..62de729f 100755
--- a/bin/mso
+++ b/bin/mso
@@ -55,7 +55,7 @@
# config * BYOK provider + model: show | set | rm
# prefs * UI preferences: show | set
# models * Model catalog: list | test
-# skills * Skill memory: list | read <name> | search <query>
+# skills * Skills across every project: list | read <id> | search <query>
# changelog What shipped, newest first (same text Settings → About shows)
# mcp * MCP tokens + live activity: list | activity [n] | revoke <id> | revoke all
# oauth <prov> * Provider sign-in (device code): start | poll
@@ -247,7 +247,7 @@ U_memory="memory list|add <text>|rm <id>"
U_config="config show|set <json>|rm <provider>"
U_prefs="prefs show|set <json>"
U_models="models list|test"
-U_skills="skills list|read <name>|search <query…>"
+U_skills="skills list|read <id>|search <query…>"
U_mcp="mcp list|activity [n]|revoke <id>|revoke all"
U_oauth="oauth <provider> start|poll e.g. mso oauth openai start"
U_audit="audit [n] [prefix] e.g. mso audit 20 exec."
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index b7230210..9f7e3ddd 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -8,11 +8,13 @@ this is the *what*, and it is what Settings → About shows as “What's new”.
**Added**
+- `mcp` global project/skill discovery, drop image generation
- `mcp` import ChatGPT generated files
- `mcp` add provider-backed image generation
**Fixed**
+- `mcp` make ChatGPT file imports region agnostic
- `mcp` allow ChatGPT India South Central file storage
- `mcp` allow ChatGPT New Zealand file storage
- `mcp` allow ChatGPT Australia file storage
diff --git a/docs/CLI.md b/docs/CLI.md
index 820abde9..784d5df7 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -89,7 +89,7 @@ Commands:
config * BYOK provider + model: show | set | rm
prefs * UI preferences: show | set
models * Model catalog: list | test
- skills * Skill memory: list | read <name> | search <query>
+ skills * Skills across every project: list | read <id> | search <query>
changelog What shipped, newest first (same text Settings → About shows)
mcp * MCP tokens + live activity: list | activity [n] | revoke <id> | revoke all
oauth <prov> * Provider sign-in (device code): start | poll
diff --git a/docs/CONNECTORS-GATEWAY-INTEGRATION.md b/docs/CONNECTORS-GATEWAY-INTEGRATION.md
index 57841718..f7a331bd 100644
--- a/docs/CONNECTORS-GATEWAY-INTEGRATION.md
+++ b/docs/CONNECTORS-GATEWAY-INTEGRATION.md
@@ -4,7 +4,7 @@
## Cross-repo contract
-MSO currently exposes **22 tool names**. The gateway manifest still maps **15** of them through literal `x-upstream` strings:
+MSO currently exposes **26 tool names** (server `1.5.0`, toolset `2026.08.20.3`). The gateway manifest still maps **15** of them through literal `x-upstream` strings:
```json
{ "id": "mso.fs.delete", "x-upstream": "fs_delete" }
@@ -23,7 +23,9 @@ A consumer CI should compare the upstream names it pins against this runtime man
## What the gateway exposes
-The gateway has not yet synchronized the seven tools added or deliberately withheld from its 15-action manifest:
+**Removed 2026-08-20 — a gateway that pinned either name must drop it:** `image_generation_status` and `image_generate`. MSO no longer generates images on any surface (a GPT client already carries its own; a second tool for the same job made the model choose wrong). Neither name was in the gateway's 15, so nothing breaks there today. `fs_upload_file` is unchanged and remains how a conversation-generated file reaches the VPS.
+
+The gateway has not yet synchronized the tools added or deliberately withheld from its 15-action manifest:
| Not mapped in gateway | Reason/status |
|---|---|
@@ -34,6 +36,10 @@ The gateway has not yet synchronized the seven tools added or deliberately withh
| `workflow_start` | added later; starts the actor-scoped task lease |
| `workflow_cancel` | added later; exact-id recovery for an interrupted run |
| `workflow_finish` | added later; exact-id verified recipe boundary |
+| `fs_upload_file` | added later; ChatGPT `openai/fileParams` binding the gateway does not model |
+| `projects_list` | added 2026-08-20; enumerates every configured project container |
+| `skills_list` | added 2026-08-20; global + per-project skill catalog with trust |
+| `skills_read` | added 2026-08-20; exact-catalog-id SKILL.md read, trusted tiers only |
`fs_delete` and `apps_power` remain the gateway's highest-risk mapped actions and should keep its human approval policy. The gateway's policy layer supplements, never replaces, MSO's scope checks, path jail, audit trail and per-operation rate limits.
diff --git a/docs/MCP.md b/docs/MCP.md
index 6ae11c75..8b9682ca 100644
--- a/docs/MCP.md
+++ b/docs/MCP.md
@@ -59,16 +59,19 @@ Picked per token, on the consent screen, capped by `OS_MCP_MAX_SCOPE`. The highe
| Scope | Tools |
|---|---|
-| `read` | `fs_list` `fs_read` `fs_search` `fs_usage` `sys_stats` `sys_processes` `apps_list` `apps_logs` `skills_search` `image_generation_status` `screen_capture` `browser_status` |
-| `write` | + `workflow_start` `workflow_cancel` `workflow_finish` `fs_write` `fs_mkdir` `fs_move` `fs_copy` `fs_delete` `apps_power` |
-| `exec` | + `image_generate` `exec_run` `browser_power` |
+| `read` | `fs_list` `fs_read` `fs_search` `fs_usage` `sys_stats` `sys_processes` `apps_list` `apps_logs` `projects_list` `skills_list` `skills_read` `skills_search` `screen_capture` `browser_status` |
+| `write` | + `workflow_start` `workflow_cancel` `workflow_finish` `fs_write` `fs_upload_file` `fs_mkdir` `fs_move` `fs_copy` `fs_delete` `apps_power` |
+| `exec` | + `exec_run` `browser_power` |
Alfa — the in-app assistant — has the same host capabilities under dot.case names,
and `lib/mcp/parity.test.ts` fails if one surface gains a tool the other lacks
without a written reason. `skills_search` maps to Alfa's `skills.search`.
-`screen_capture`, `image_generation_status`, `image_generate`, `workflow_start`, `workflow_cancel` and `workflow_finish` are explicitly MCP-only:
-the external connector needs visual proof and an actor-scoped task boundary, while
-Alfa already runs inside the rendered shell and owns an in-app run boundary. The
+`screen_capture`, `projects_list`, `fs_upload_file`, `workflow_start`, `workflow_cancel` and
+`workflow_finish` are explicitly MCP-only: the external connector needs visual proof,
+an explicit project enumeration and an actor-scoped task boundary, while Alfa already
+runs inside the rendered shell, has the Files window and owns an in-app run boundary.
+`skills_list` and `skills_read` now exist on BOTH surfaces — capability discovery is
+global by design, and withholding it from the connector was scoping nobody chose. The
two catalogs stay separate on purpose (different transport and guard) but may not
drift by accident.
@@ -87,18 +90,77 @@ restarting a daemon does not require handing one over either.
`tools/list` is filtered by the token's scope, and `tools/call` re-checks it — a
client that calls a tool it was never shown still gets refused.
+**The scope ladder is the ONLY thing that narrows the catalog.** An `exec` token sees
+and can call every public tool; `read` and `write` are strict prefixes of it. There is
+no per-project, per-agent, per-workflow or per-client tool filter, and there must not
+be one — which tools EXIST is not a security control here, the ladder plus `lib/host`'s
+path jail and command filter are. Every operational tool carries an OPTIONAL
+`workflow_id`: it correlates steps, it never gates a capability. `lib/mcp/global-tools.test.ts`
+pins all of this, including that a token's visible list matches its callable set exactly.
+
## Toolset version, hash and action refresh
The catalog has a stable server version plus a schema-derived toolset signature. It is returned by public `GET /mcp`, MCP `initialize`, scoped `tools/list`, and the authenticated Settings → MCP endpoint. The signature changes when a name, description, input schema, scope, annotation or per-operation limit changes—not only when the tool count changes.
Settings → MCP shows the current version/hash/count and stores a browser-local acknowledgement when the operator marks ChatGPT refreshed. A later signature change becomes an explicit stale-snapshot warning. This does not mutate ChatGPT remotely; it makes the required refresh visible instead of relying on memory.
-Current catalog: **24 tools**. `image_generation_status` and `image_generate` are the new public names in this release.
+Current catalog: **26 tools** (14 read, 10 write, 2 exec), server `1.5.0` / toolset
+`2026.08.20.3`. `projects_list`, `skills_list` and `skills_read` are the new public
+names in this release; `image_generation_status` and `image_generate` were removed
+(see the migration note below).
## Safe text inspection and overwrite
`fs_read` returns `content`, UTF-8 byte count and SHA-256. For an existing file, pass that digest as `fs_write.expected_sha256`; the write is refused if another process changed the file since inspection. Omitting it preserves create/legacy overwrite behaviour. Workflow memory stores the path, never the content or digest.
+## Global project and skill discovery
+
+MSO drives **all** of the owner's projects, not the one it happens to live in.
+
+`projects_list` enumerates project directories across every configured project
+container — each `OS_FS_READ_ROOTS` entry plus its `projects/` subdirectory, deduped by
+realpath, in configured order. It returns name, absolute path, container root, package
+name/version and Git branch/head read straight off `.git` with no subprocess. Hidden
+directories, symlinks and credential paths are excluded, results are paginated
+(default 50, max 200), and the scan is bounded (12 containers, 400 entries per
+container, 400 projects). The filesystem root `/` is never treated as a container.
+
+`resolveProjectHint` — behind `workflow_start`'s `project` and `fs_search` — searches
+those same containers, deterministically and exact-before-fuzzy: an absolute/`~` path
+wins outright, then an exact directory name or known alias probed container by
+container, then one bounded scan scoring exact package names above substrings. An exact
+name in the second container beats a substring hit in the first.
+
+`skills_list` merges the global roots with the **per-project** roots of every project:
+`.mso/skills`, `.claude/skills`, `.hermes/skills`, `.agents/skills`, `.codex/skills`.
+Each row carries the exact catalog id, trust, source and its project.
+
+**Ids, so nothing shadows anything.** A global skill is addressed by bare name; a
+project skill is `<project>/<name>`. Two projects may both ship `deploy`, and neither
+can displace an operator (`~/.mso/skills`) or official (MSO repo) skill of the same
+name. Within one project, `.mso/skills` outranks the agent-tool roots. Precedence is
+fully deterministic.
+
+**Project trust is earned, never assumed from the path.** A project skill becomes
+`local` only when all three hold: the skill directory realpaths back *inside* its
+project (a `.claude/skills -> /tmp/attacker` symlink is discovered, not followed); the
+directory and its `SKILL.md` are owned by the uid MSO runs as; and `SKILL.md` is a
+regular file, not a symlink. Otherwise it is cataloged `untrusted`. The generic HOME
+agent roots (`~/.claude/skills`, `~/.agents/skills`, `~/.codex/skills`, OpenClaw) keep
+their existing untrusted behaviour — this promotion is for project roots only.
+
+`skills_read` takes the **exact catalog id** and nothing else — no fuzzy resolution, so
+`widget-deploy` will not silently return `widget/widget-deploy`. It returns instructions
+for `official`, hash-`verified`, operator-`local` and ownership-verified project skills.
+An `untrusted` skill returns metadata plus an explicit refusal: review the file, then
+move it into `~/.mso/skills` to promote it. The reader still opens only a realpath'd file
+named exactly `SKILL.md`. Content is capped at 24,000 characters; the project scan is
+bounded to 60 projects, 100 skills per root and 300 project skills per call.
+
+`workflow_start` and `skills_search` search this unified catalog, and every skill hit
+carries its `project` when it has one — so a workflow named against project A still
+finds the relevant skill in project B rather than relearning it.
+
## Semantic skill search and learned workflows
MSO does not need to rediscover the same safe procedure on every conversation.
@@ -188,26 +250,24 @@ is limited to five downloads, sends `Cache-Control: no-store`, and is deleted af
expiry/exhaustion. This provides visual progress without turning a read token into a
general browser or public-file-hosting primitive.
-## Provider-backed image generation
+## Removed: provider-backed image generation
-`image_generation_status` is read-only and reports whether an OpenAI API key is
-available without returning it. `image_generate` is exec-scope because it spends
-provider credits, sends the prompt off-box, and writes binary bytes. Each call is
-exactly one official OpenAI Images API request and produces:
+`image_generation_status` and `image_generate` were removed on 2026-08-20, along with
+`lib/image-generation/`, the `OS_IMAGE_MODEL` / `OS_IMAGE_OUTPUT_ROOT` knobs and the
+Codex provider-side `image_generation` built-in. **A GPT client already carries its own
+image generation**, and offering a second tool for the same job made the model choose
+between them — usually wrong, and the MSO one billed a separate API key. Nothing
+replaces it: ask the client to generate the image with its own capability.
-- a lossless PNG master under `OS_IMAGE_OUTPUT_ROOT` (default `~/generated-images`);
-- a prompt SHA-256 and byte SHA-256;
-- actual provider model and `x-request-id` as the generation run identifier;
-- width, height and alpha status parsed from the returned PNG;
-- a 0600 provenance JSON sidecar that does not contain the raw prompt;
-- a temporary authenticated preview when the image is at most 10 MiB.
+Importing the result is unchanged and deliberately preserved: **`fs_upload_file`** takes
+one ChatGPT conversation/generated file through `openai/fileParams`, downloads the
+temporary OpenAI URL immediately (HTTPS only, `*.oaiusercontent.com` or an OpenAI
+regional `oaisdmnt*.blob.core.windows.net` storage account, redirects re-validated),
+checks type and size, writes inside `OS_FS_WRITE_ROOTS`, and returns bytes plus SHA-256.
-Configure provider OpenAI in Settings → AI or set `OPENAI_API_KEY`. A ChatGPT
-subscription/OAuth login is separate from API billing and is not silently reused.
-Transparent requests automatically use `gpt-image-1.5` unless another compatible
-model is explicitly selected; `gpt-image-2` is refused for transparent output.
-Repository candidates are never written automatically—the generated PNG remains a
-sandbox master until a project-specific validator/post-process promotes it.
+`OS_CODEX_BUILTIN_TOOLS` still exists and still takes an allowlisted list, but its
+default is now EMPTY and `image_generation` is no longer an accepted value — naming it
+is dropped, not honoured.
## What this does and does not protect
@@ -266,7 +326,7 @@ mso mcp activity 100
State-changing calls also land in the append-only security trail
`~/.mso/audit.log`, with `actor=mcp:<id>` matching Settings → MCP and
`mso mcp list`. The audit records `fs.write`, `fs.mkdir`, `fs.move`, `fs.copy`,
-`fs.delete`, `exec.run`, `managed-app.action`, `camoufox.power`,
+`fs.delete`, `fs.upload`, `exec.run`, `managed-app.action`, `camoufox.power`,
`workflow.start`, `workflow.cancel`, `workflow.finish`, and `mcp.denied`. It is intentionally quieter
than the activity stream so security-relevant lines are not buried by reads.
@@ -322,7 +382,8 @@ also carries the **per-operation** limit its route already applies, on the SAME
bucket key — MCP and the browser share one allowance rather than getting one each.
`exec_run` 60/min, fs writes 120/min, fs copy/delete 60/min, `apps_power` and
`browser_power` 12/min per app. MCP-native expensive/stateful operations are
-stricter: `screen_capture` 10/min, `image_generate` 5/min, and workflow-memory writes 30/min.
+stricter: `screen_capture` 10/min, `projects_list` and `skills_list` 30/min,
+`skills_read` 60/min, and workflow-memory writes 30/min.
## Layout
@@ -331,15 +392,20 @@ lib/mcp/pkce.ts S256 verify, base64url, hashing, redirect_uri rules
lib/mcp/scope.ts the read/write/exec ladder + the env kill switch
lib/mcp/store.ts ~/.mso/mcp.json — clients, codes, tokens (hashed)
lib/mcp/tool-kit.ts McpTool, direct image content and run context
-lib/mcp/tools-read.ts bounded reads + skills_search + screen_capture
-lib/mcp/tools-learning.ts one-call bootstrap + start / cancel / finish
-lib/mcp/toolset.ts server/toolset version, schema hash and scoped manifest
-lib/mcp/tools.ts write/exec tools and the assembled catalog
+lib/mcp/tools-read.ts bounded reads + skills_search + screen_capture
+lib/mcp/tools-discovery.ts projects_list / skills_list / skills_read — global discovery
+lib/mcp/tools-learning.ts one-call bootstrap + start / cancel / finish
+lib/mcp/tools-power.ts apps_power + browser_power
+lib/mcp/toolset.ts server/toolset version, schema hash and scoped manifest
+lib/mcp/tools.ts fs write tier and the assembled catalog
lib/mcp/activity.ts workflow-correlated live activity
lib/mcp/dispatch.ts JSON-RPC, scope checks, metadata, activity + recipe capture
-lib/host/projects.ts bounded project resolution, aliases and repo context
+lib/host/projects.ts project resolution across every container, plus aliases
+lib/host/project-roots.ts every configured project container + bounded enumeration
+lib/host/project-meta.ts symlink-refusing package.json / .git readers
lib/host/guarded-write.ts optimistic SHA-256 file overwrite guard
-lib/skills/catalog.ts trusted SKILL.md roots and provenance
+lib/skills/catalog.ts global + per-project SKILL.md roots, ids and provenance
+lib/skills/project-skills.ts per-project roots and their earned-trust checks
lib/skills/semantic.ts local hybrid embedding/search primitives
lib/skills/search.ts unified skill/tool/recipe ranking
lib/skills/memory.ts migrated multi-run exact-id workflow and recipe store
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index bff1559d..677fb37c 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -8,7 +8,76 @@ Running log of what shipped each phase. Newest at top.
> Read those phases as history. **This file is the source of truth for what exists** —
> `ARCHITECTURE.md` is no longer maintained and carries a stale-warning banner.
-## 2026-08-20 — provider-backed MCP image generation (DONE)
+## 2026-08-20 — global project/skill discovery, and image generation removed (DONE)
+
+**Capabilities are global now, and the docs say so.** Two invisible scopings shipped
+together and were both wrong for the same reason: MSO answered "what projects exist"
+and "what skills exist" from `~/projects` and the global skill roots alone. An owner
+who configured three read roots got one of them, and an agent working in project X
+could not see X's own `SKILL.md`. Nobody decided either; they were defaults nobody
+revisited. A capability that silently covers a subset of what the owner configured is
+worse than one that refuses.
+
+Three new `read` MCP tools. `projects_list` enumerates project directories across
+every configured container — each `OS_FS_READ_ROOTS` entry plus its `projects/` child,
+deduped by realpath, in configured order — with name, path, container root, package
+name/version and Git branch/head read straight off `.git` with no subprocess. Hidden
+dirs, symlinks and credential paths are excluded; the scan is bounded (12 containers,
+400 entries each, 400 projects) and paginated (default 50, max 200). `/` is never a
+container. `resolveProjectHint` searches the same containers, exact-before-fuzzy: an
+absolute/`~` path wins outright, then an exact name or alias probed container by
+container, then one bounded scan scoring exact package names above substrings — so an
+exact name in the second container beats a substring hit in the first.
+
+`skills_list` and `skills_read` merge the global roots with the **per-project** roots
+of every project: `.mso/skills`, `.claude/skills`, `.hermes/skills`, `.agents/skills`,
+`.codex/skills`. Skills are now addressed by a catalog **id**: a global skill by bare
+name, a project skill as `<project>/<name>`. Two projects may both ship `deploy` and
+neither can displace an operator or official skill — the collision is impossible rather
+than resolved. `skills_read` takes the exact id and does not fuzzy-resolve into a
+project namespace. Project trust is EARNED, not inherited from the path: `local` only
+after realpath containment inside the project, ownership by MSO's uid, and a regular
+non-symlink `SKILL.md`. Everything else stays `untrusted` — metadata visible,
+instructions withheld until the operator reviews and promotes it into `~/.mso/skills`.
+The generic HOME agent roots keep their untrusted behaviour unchanged. `workflow_start`
+and `skills_search` search the unified catalog and each skill hit carries its project.
+Bounds: 60 projects, 100 skills per root, 300 project skills, 24,000 characters per read.
+
+`skills_list`/`skills_read` therefore exist on BOTH surfaces now, and their old
+`ALFA_ONLY` parity exemption ("stays off a bearer-reached surface") is gone. That was
+the right call for a fuzzy name-resolving reader; it is not for one that takes an exact
+catalog id, returns instructions only for trusted tiers, and still opens nothing but a
+realpath'd file named `SKILL.md`.
+
+**The global-tools invariant is now pinned, not just described.** Alfa already sent
+every tool on every turn; MCP already showed an `exec` token everything. Neither had a
+test that would fail if someone added a per-project filter. `lib/mcp/global-tools.test.ts`
+and a new block in `registry.test.ts` hold both: the exec catalog equals `TOOLS` exactly,
+`read`/`write` are strict prefixes by tier and nothing else, `workflow_id` is optional on
+every operational tool, `HOST_AI_TOOLS` is the same whole-catalog object every turn, and
+`registry.ts` exports nothing that could narrow it. The `read`/`write` opt-down and the
+`exec` consent default are unchanged and covered — the ladder is the security boundary;
+which tools exist is not.
+
+**Image generation is removed end-to-end.** `image_generation_status`, `image_generate`,
+`lib/image-generation/`, `OS_IMAGE_MODEL`, `OS_IMAGE_OUTPUT_ROOT`, the `image.generate`
+audit action and workflow-memory entries, and the Codex provider-side `image_generation`
+built-in are all gone. A GPT client already carries its own image generation; offering a
+second tool for the same job made the model choose between them, usually wrong, and the
+MSO one billed a separate API key. `OS_CODEX_BUILTIN_TOOLS` now defaults to EMPTY and no
+longer accepts `image_generation` — naming it explicitly is dropped, not honoured, and a
+test pins that. **`fs_upload_file` is deliberately preserved**, regional ChatGPT file
+import and `openai/fileParams` binding intact: generating elsewhere and importing here is
+the whole remaining flow. No tool description tells a client to prefer a native or
+provider image tool, and a test greps for that wording.
+
+`lib/mcp/tools.ts` shed `apps_power`/`browser_power` into `tools-power.ts` and the new
+tools live in `tools-discovery.ts`, so every file is back under the 200-line ceiling.
+`lib/host/project-meta.ts` and `project-roots.ts` split the symlink-refusing readers from
+the container enumeration. The MCP server/toolset advance to `1.5.0` / `2026.08.20.3`,
+with **26 tools** (14 read, 10 write, 2 exec).
+
+## 2026-08-20 — provider-backed MCP image generation (SUPERSEDED — removed same day)
MCP now exposes `image_generation_status` (read) and `image_generate` (exec).
Generation uses the official OpenAI Images API rather than the prior procedural
@@ -21,7 +90,7 @@ workflow memory. The output root is write-jailed (`OS_IMAGE_OUTPUT_ROOT`, defaul
authenticated/expiring, and image calls are limited to 5/min. The MCP server/toolset
advance to `1.4.0` / `2026.08.20.1`, with **24 tools**.
-## 2026-08-20 — image generation and full-access defaults (DONE)
+## 2026-08-20 — image generation and full-access defaults (image half SUPERSEDED)
Fresh MSO installs now expose Codex provider-side `image_generation` when
`OS_CODEX_BUILTIN_TOOLS` is absent, matching the owner's expected assistant capability.
diff --git a/frontend/slices/assistant/CONTRACT.md b/frontend/slices/assistant/CONTRACT.md
index 4b76ba98..23e732e8 100644
--- a/frontend/slices/assistant/CONTRACT.md
+++ b/frontend/slices/assistant/CONTRACT.md
@@ -78,12 +78,22 @@ shape, different storage, different lifecycle, and the names do not overlap.
| | |
|---|---|
-| Shape | `{ name, path, description, source, trust, provenance? }` — `lib/skills/catalog.ts` |
-| Source of truth | `GET /api/skills` — explicit operator root → official repo skills → hash-verified bundles → generic discovery roots |
-| Lifecycle | Files on disk; trust is derived from root/provenance, never self-declared by the skill |
-| Written by | MSO, the operator, or discovered agent registries |
-
-The model reaches trusted skills through the `skills.list` and `skills.read` **tools**. `official`, hash-`verified`, and explicit operator `local` skills are executable by default; generic discovered skills are cataloged as `untrusted` but their instructions are not fed directly to the model. `/skill` follows the same trust filter. There is no separate execution path.
+| Shape | `{ id, name, path, description, source, trust, project?, provenance? }` — `lib/skills/catalog-types.ts` |
+| Source of truth | `GET /api/skills` — explicit operator root → official repo skills → hash-verified bundles → generic HOME discovery roots → **per-project roots of every project on the box** |
+| Lifecycle | Files on disk; trust is derived from root/provenance/ownership, never self-declared by the skill |
+| Written by | MSO, the operator, a project checkout, or discovered agent registries |
+
+The model reaches trusted skills through the `skills.list`, `skills.search` and `skills.read` **tools**. `official`, hash-`verified`, explicit operator `local` and ownership-verified project skills are executable by default; generic discovered skills are cataloged as `untrusted` but their instructions are not fed directly to the model. `/skill` follows the same trust filter. There is no separate execution path.
+
+**Discovery is global, and addressed by id.** Skills come from every project across
+every configured project container (each `OS_FS_READ_ROOTS` entry and its `projects/`
+child), from `.mso/skills`, `.claude/skills`, `.hermes/skills`, `.agents/skills` and
+`.codex/skills`. A global skill's id is its bare name; a project skill's is
+`<project>/<name>`, so two projects may ship the same name and neither can shadow an
+operator or official skill. A project skill earns `local` trust only after realpath
+containment inside its project, ownership by MSO's uid, and a regular non-symlink
+`SKILL.md`; the generic HOME agent roots stay untrusted. `skills.read` takes the exact
+id. See [`docs/MCP.md`](../../../docs/MCP.md) and [`skills/README.md`](../../../skills/README.md).
## Agent
@@ -123,7 +133,12 @@ constant is reachable and must not be deleted as dead.
## Decided: tool scoping is deleted, not repaired
-Every agent gets all 18 tools. This is the contract, not a gap.
+Every agent gets **every** tool, on every turn — no per-agent, no per-playbook, and no
+per-project filter. This is the contract, not a gap. `registry.test.ts` pins it: the
+`HOST_AI_TOOLS` array is the whole catalog in catalog order, it is the same object on
+every turn, and `registry.ts` exports nothing that could narrow it. MCP holds the same
+invariant on its own side — an `exec` token sees and can call the entire catalog, and
+the read/write/exec ladder is the only thing that narrows it (`lib/mcp/global-tools.test.ts`).
Four reasons, and the third is the one that settles it:
@@ -141,7 +156,9 @@ Four reasons, and the third is the one that settles it:
4. **It makes an impossible state impossible.** With one tool set, a thread whose
history holds `tool_use` for a tool "the new agent lacks" cannot occur.
-**Done 2026-07-30.** The tool picker, the "Generalist / Curated — by skill" switch,
+**Reaffirmed 2026-08-20** when MCP gained global project/skill discovery: capability
+scoping stayed deleted on both surfaces, and the removed MSO image generation was NOT
+replaced by a per-agent toggle. **Done 2026-07-30.** The tool picker, the "Generalist / Curated — by skill" switch,
the per-agent Skills grant list and every string that counted tools per agent are
gone; `toolsForAgent()` went with them. `agent.allTools` and `agent.skills` remain on
the type because they are persisted and `store-migration.test.ts` covers them — they
@@ -158,8 +175,10 @@ re-discovers them as bugs.
1. **`Skill.starters`** is typed, edited and labelled "shown as quick chips" — and
nothing renders it. (`instructions` IS rendered, as the card body in the library
grid; it just never reaches the model.)
-2. **`/api/skills` is uncached**, `force-dynamic`, ~90 files across 5 roots per
- call.
+2. **`/api/skills` is uncached**, `force-dynamic`, and now walks the global roots PLUS
+ every project's skill roots on each call. Bounded (60 projects, 100 skills per root,
+ 300 project skills), but a wide box pays for it every time; a TTL cache is the
+ obvious next step and was deliberately not added with the discovery change.
3. **The `Skill` → `Playbook` rename has not happened.** The code and the UI still
say "Skill" for the localStorage type.
diff --git a/frontend/slices/assistant/host-tools/catalog-skills.ts b/frontend/slices/assistant/host-tools/catalog-skills.ts
index bdc55fc1..b377f37a 100644
--- a/frontend/slices/assistant/host-tools/catalog-skills.ts
+++ b/frontend/slices/assistant/host-tools/catalog-skills.ts
@@ -10,19 +10,19 @@ export const SKILL_TOOLS: HostTool[] = [
group: "agent",
label: "List skills",
effect: "read",
- description: "List local MSO/OpenClaw/Codex skills available on this VPS. Use before asking to run a specialized skill such as camoufox.",
+ description: "List every trusted skill on this VPS — MSO/OpenClaw/Codex roots plus per-project skill roots across all configured project containers. Use the returned id (a project skill is <project>/<name>) with skills.read.",
parameters: obj({}),
run: async () => {
const data = (await fetch("/api/skills", { cache: "no-store" })
.then((r) => (r.ok ? r.json() : { skills: [], recipes: [] }))
.catch(() => ({ skills: [], recipes: [] }))) as {
- skills?: { name: string; description?: string; trust?: string; source?: string }[];
+ skills?: { id?: string; name: string; description?: string; trust?: string; source?: string; project?: { name: string } }[];
recipes?: { intent: string; attempts: number; successes: number; fastestDurationMs?: number }[];
};
const skills = data.skills ?? [];
const safe = skills.filter((s) => s.trust !== "untrusted");
const blocked = skills.length - safe.length;
- const rows = safe.map((s) => `${s.name} [${s.trust ?? "legacy"}/${s.source ?? "unknown"}]${s.description ? ` — ${s.description}` : ""}`);
+ const rows = safe.map((s) => `${s.id ?? s.name} [${s.trust ?? "legacy"}/${s.source ?? "unknown"}${s.project ? `/project:${s.project.name}` : ""}]${s.description ? ` — ${s.description}` : ""}`);
if (blocked) rows.push(`(${blocked} discovered skill${blocked === 1 ? "" : "s"} hidden because trust=untrusted)`);
for (const r of data.recipes ?? []) {
const rate = r.attempts ? Math.round((r.successes / r.attempts) * 100) : 0;
@@ -63,8 +63,8 @@ export const SKILL_TOOLS: HostTool[] = [
group: "agent",
label: "Read skill",
effect: "read",
- description: "Read one local skill's SKILL.md instructions by exact skill name.",
- parameters: obj({ "name!": str("Exact skill name from skills.list") }),
+ description: "Read one skill's SKILL.md instructions by exact catalog id from skills.list (a project skill is <project>/<name>).",
+ parameters: obj({ "name!": str("Exact catalog id from skills.list") }),
run: async (_api, a) => {
const name = String(a.name ?? "").trim();
if (!name) return "missing skill name";
diff --git a/frontend/slices/assistant/host-tools/registry.test.ts b/frontend/slices/assistant/host-tools/registry.test.ts
index 9e3afd84..64b921a6 100644
--- a/frontend/slices/assistant/host-tools/registry.test.ts
+++ b/frontend/slices/assistant/host-tools/registry.test.ts
@@ -5,7 +5,7 @@ import { describe, expect, it } from "vitest";
// lib/mcp/parity.test.ts.
import { claudeCodeApp, osTerminalApp } from "@/frontend/slices/os-terminal";
import { HOST_TOOLS, SHELL_APPS } from "./catalog";
-import { findHostTool, HOST_AI_TOOLS } from "./registry";
+import { findHostTool, HOST_AI_TOOLS, HOST_SYSTEM } from "./registry";
// Runs in the node env: the catalog + registry pull only the schema helpers and
// type-only imports. The one exception is that barrel, imported for the two
@@ -72,3 +72,37 @@ describe("host-tools registry", () => {
}
});
});
+
+// THE GLOBAL-CAPABILITY INVARIANT for Alfa. CONTRACT.md decided it on 2026-07-30:
+// every agent gets every tool, and the lock is the per-call approval card plus
+// lib/host's path jail — not a shortened list. This block exists because the
+// previous scoping attempt shipped a UI that COUNTED tools per agent while all of
+// them were sent, so the owner believed in containment that did not exist.
+describe("every agent gets every tool, always", () => {
+ it("HOST_AI_TOOLS is the whole catalog, in catalog order", () => {
+ expect(HOST_AI_TOOLS.map((t) => t.name)).toEqual(HOST_TOOLS.map((t) => t.name));
+ });
+
+ it("exposes no per-agent, per-playbook or per-project filter to call it through", async () => {
+ const registry = await import("./registry");
+ // A filter would have to be a function taking an agent/playbook/project. If one
+ // appears here, the contract changed and CONTRACT.md has to change with it.
+ const exported = Object.keys(registry).sort();
+ expect(exported).toEqual(["HOST_AI_TOOLS", "HOST_SYSTEM", "findHostTool"]);
+ expect(typeof registry.HOST_AI_TOOLS).toBe("object");
+ });
+
+ it("sends the same array on every turn — no per-turn narrowing", async () => {
+ const { HOST_AI_TOOLS: again } = await import("./registry");
+ expect(again).toBe(HOST_AI_TOOLS);
+ });
+
+ it("tells the model its skills span ALL projects, not the current one", () => {
+ expect(HOST_SYSTEM).toMatch(/skills across all of the owner's projects/i);
+ });
+
+ it("never points the model at a native or provider image-generation tool", () => {
+ expect(HOST_SYSTEM).not.toMatch(/image/i);
+ expect(HOST_TOOLS.filter((t) => /image/i.test(t.name))).toEqual([]);
+ });
+});
diff --git a/frontend/slices/assistant/host-tools/registry.ts b/frontend/slices/assistant/host-tools/registry.ts
index 349e3223..f240f122 100644
--- a/frontend/slices/assistant/host-tools/registry.ts
+++ b/frontend/slices/assistant/host-tools/registry.ts
@@ -11,6 +11,11 @@ export function findHostTool(name: string): HostTool | undefined {
}
// Anthropic `tools` array derived from the catalog (sent to /api/assistant).
+//
+// EVERY tool, on EVERY turn, for EVERY agent. There is no per-agent, per-playbook or
+// per-project filter here and there must not be one: see CONTRACT.md "tool scoping is
+// deleted, not repaired". The guard is the per-call approval card plus lib/host's
+// path jail, not a shortened list the user cannot see. registry.test.ts pins this.
export const HOST_AI_TOOLS: AiTool[] = HOST_TOOLS.map((t) => ({
name: t.name,
description: t.description,
@@ -26,7 +31,7 @@ export const HOST_SYSTEM = [
"READ tools (fs.*, sys.*, apps.list, skills.*, memory.*) run immediately.",
"Use memory.remember to save lasting facts or preferences the user shares, and memory.forget to remove or correct them when asked — not one-off task details.",
"WRITE tools (fs.write, fs.mkdir, fs.move, fs.copy, fs.delete) and exec.run require the user to APPROVE each call, and may be DENIED.",
- "Specialized local skills such as camoufox can be discovered with skills.list/skills.read; execute their shell steps only through approved exec.run calls.",
+ "Skills across ALL of the owner's projects — not just the current one — are discoverable with skills.list/skills.search/skills.read; execute their shell steps only through approved exec.run calls.",
"If a call is denied, do NOT retry the same call — explain, or propose an alternative and ask.",
"Read/inspect before you mutate. Prefer one dependent call at a time. Confirm concisely when done; no meta-commentary.",
].join(" ");
diff --git a/lib/ai/codex-stream.test.ts b/lib/ai/codex-stream.test.ts
index 1d8a287a..8071bb42 100644
--- a/lib/ai/codex-stream.test.ts
+++ b/lib/ai/codex-stream.test.ts
@@ -197,12 +197,12 @@ describe("reading calls back", () => {
});
describe("provider-executed built-ins", () => {
- it("enables image_generation when OS_CODEX_BUILTIN_TOOLS is absent", async () => {
+ it("declares NO provider built-in when OS_CODEX_BUILTIN_TOOLS is absent", async () => {
vi.unstubAllEnvs();
delete process.env.OS_CODEX_BUILTIN_TOOLS;
const sent = capture(sse({ type: "response.completed", response: { output: [] } }));
await run({ tools: [TOOL] });
- expect((sent().tools ?? []).map((t) => t.type)).toEqual(["function", "image_generation"]);
+ expect((sent().tools ?? []).map((t) => t.type)).toEqual(["function"]);
});
it("accepts an explicit empty value to disable every provider built-in", async () => {
@@ -212,10 +212,20 @@ describe("provider-executed built-ins", () => {
});
it("uses an explicit built-in list by type alone and ignores unknown entries", async () => {
- vi.stubEnv("OS_CODEX_BUILTIN_TOOLS", "image_generation, not_a_tool");
+ vi.stubEnv("OS_CODEX_BUILTIN_TOOLS", "web_search, not_a_tool");
const sent = capture(sse({ type: "response.completed", response: { output: [] } }));
await run({ tools: [TOOL] });
const tools = sent().tools ?? [];
- expect(tools.map((t) => t.type)).toEqual(["function", "image_generation"]);
+ expect(tools.map((t) => t.type)).toEqual(["function", "web_search"]);
+ });
+
+ // MSO removed image generation everywhere. A GPT client already has its own, and
+ // a second same-purpose tool is a choice the model gets wrong. The allowlist must
+ // not quietly accept it back through the env knob.
+ it("refuses image_generation even when the operator names it explicitly", async () => {
+ vi.stubEnv("OS_CODEX_BUILTIN_TOOLS", "image_generation");
+ const sent = capture(sse({ type: "response.completed", response: { output: [] } }));
+ await run({ tools: [TOOL] });
+ expect((sent().tools ?? []).map((t) => t.type)).toEqual(["function"]);
});
});
diff --git a/lib/ai/codex-stream.ts b/lib/ai/codex-stream.ts
index 32742aa0..82fc1acd 100644
--- a/lib/ai/codex-stream.ts
+++ b/lib/ai/codex-stream.ts
@@ -22,15 +22,18 @@ import type { OaMsg, OaTool } from "./openai-stream";
// chat-only shortcut looked reasonable at the time.
/** Provider-EXECUTED tools: declared by type alone, no schema, the provider runs
- * them and streams the result back. `image_generation` is the one worth having —
- * it is why "Codex can't do tools" was visibly false to anyone who had used it.
- * Kept as an allowlist rather than pass-through: an unknown type is a 400. */
+ * them and streams the result back. Kept as an allowlist rather than pass-through:
+ * an unknown type is a 400.
+ *
+ * `image_generation` is deliberately ABSENT. MSO no longer generates images on any
+ * surface: a GPT client already carries its own image generation, and declaring a
+ * second one made the model pick between two tools that do the same thing. Adding
+ * it back means re-adding the capability, not flipping a flag. */
const BUILTIN_TOOL_TYPES = new Set([
"web_search",
"web_search_preview",
"file_search",
"code_interpreter",
- "image_generation",
"computer_use_preview",
"local_shell",
]);
@@ -39,11 +42,11 @@ type ResponsesTool =
| { type: "function"; name: string; description: string; strict: boolean; parameters: Record<string, unknown> }
| { type: string };
-/** Provider-run built-ins available to Codex. `image_generation` is enabled when
- * the variable is absent; an explicit empty `OS_CODEX_BUILTIN_TOOLS=` disables all
- * built-ins, while a comma/space-separated value replaces the default. */
+/** Provider-run built-ins available to Codex. NONE are enabled by default — the
+ * owner opts in per deployment with a comma/space-separated `OS_CODEX_BUILTIN_TOOLS`
+ * drawn from the allowlist above. Unknown entries are dropped rather than sent. */
function builtinTools(): ResponsesTool[] {
- return (process.env.OS_CODEX_BUILTIN_TOOLS ?? "image_generation")
+ return (process.env.OS_CODEX_BUILTIN_TOOLS ?? "")
.split(/[\s,]+/)
.filter((t) => BUILTIN_TOOL_TYPES.has(t))
.map((type) => ({ type }));
diff --git a/lib/host/audit.ts b/lib/host/audit.ts
index 0811bad4..ce6aaf7c 100644
--- a/lib/host/audit.ts
+++ b/lib/host/audit.ts
@@ -26,7 +26,6 @@ export type AuditAction =
| "sys.update"
| "managed-app.action"
| "camoufox.power"
- | "image.generate"
| "workflow.start"
| "workflow.cancel"
| "workflow.finish"
diff --git a/lib/host/index.ts b/lib/host/index.ts
index ce5a2d13..1083deee 100644
--- a/lib/host/index.ts
+++ b/lib/host/index.ts
@@ -11,6 +11,8 @@ export { runCommand } from "./exec";
export { sha256Text, utf8Bytes } from "./hash";
export { writeFileGuarded } from "./guarded-write";
export { resolveProjectHint, inspectProject } from "./projects";
+export { listProjects, listProjectDirs, projectRoots, PROJECT_LIMITS } from "./project-roots";
+export type { ProjectRow, ListProjectsResult } from "./project-roots";
export { normalizeProjectKey, projectAliasesFor, projectAliasTarget } from "./project-aliases";
export type { ProjectResolution } from "./projects";
export { openPty, attachPty, writePty, resizePty, closePty, hasPty } from "./pty";
diff --git a/lib/host/paths.ts b/lib/host/paths.ts
index 4dd369de..1b6d9560 100644
--- a/lib/host/paths.ts
+++ b/lib/host/paths.ts
@@ -115,7 +115,10 @@ export function isAppSecret(real: string): boolean {
return path.dirname(real) === APP_DIR && base.startsWith(".env") && base !== ".env.example";
}
-function isCredentialPath(real: string): boolean {
+/** Exported for the project/skill enumerators: they walk directory TREES the
+ * per-path resolvers never see, and must drop a credential directory themselves
+ * rather than discover it one `resolveReadable` too late. */
+export function isCredentialPath(real: string): boolean {
const store = path.join(homeDir(), ".mso");
if (real === store || isUnderRoot(real, store)) return true;
if (isSensitivePath(real)) return true;
diff --git a/lib/host/project-meta.ts b/lib/host/project-meta.ts
new file mode 100644
index 00000000..ff462f68
--- /dev/null
+++ b/lib/host/project-meta.ts
@@ -0,0 +1,85 @@
+// Bounded, side-effect-free metadata about ONE project directory. Split out of
+// projects.ts so multi-root resolution and the projects_list enumeration can share
+// exactly the same readers — two copies would be two chances to forget the symlink
+// refusal below.
+//
+// Everything here refuses a symlink. A project's `package.json` or `.git/HEAD`
+// pointing somewhere else is not a project fact, it is a redirect, and following
+// one turns a bounded read into an arbitrary one.
+import { promises as fs } from "fs";
+import path from "path";
+import { runCommand } from "./exec";
+
+export type PackageMeta = { name?: string; version?: string; scripts: string[] };
+export type GitMeta = {
+ available: boolean;
+ branch?: string;
+ clean?: boolean;
+ changes?: string[];
+ head?: { sha: string; subject?: string; date?: string };
+ statusChecked: boolean;
+ error?: string;
+};
+
+export async function readRegularText(file: string): Promise<string> {
+ const stat = await fs.lstat(file).catch(() => null);
+ if (!stat?.isFile() || stat.isSymbolicLink()) return "";
+ return fs.readFile(file, "utf8").catch(() => "");
+}
+
+export async function packageMeta(dir: string): Promise<PackageMeta> {
+ try {
+ const raw = await readRegularText(path.join(dir, "package.json"));
+ if (!raw) return { scripts: [] };
+ const parsed = JSON.parse(raw) as { name?: unknown; version?: unknown; scripts?: unknown };
+ return {
+ name: typeof parsed.name === "string" ? parsed.name : undefined,
+ version: typeof parsed.version === "string" ? parsed.version : undefined,
+ scripts: parsed.scripts && typeof parsed.scripts === "object" ? Object.keys(parsed.scripts) : [],
+ };
+ } catch {
+ return { scripts: [] };
+ }
+}
+
+/** Git context read straight off `.git`, with NO subprocess — safe to run across
+ * every project in an enumeration, where spawning one `git status` per row would
+ * not be. */
+export async function boundedGitMeta(dir: string): Promise<GitMeta> {
+ const gitDir = path.join(dir, ".git");
+ const gitStat = await fs.lstat(gitDir).catch(() => null);
+ if (!gitStat?.isDirectory() || gitStat.isSymbolicLink()) return { available: false, statusChecked: false };
+ const head = await readRegularText(path.join(gitDir, "HEAD"));
+ if (!head) return { available: false, statusChecked: false };
+ const candidateRef = head.trim().startsWith("ref: ") ? head.trim().slice(5) : undefined;
+ const ref = candidateRef && /^refs\/(?:heads|remotes)\/[a-z0-9._\/-]+$/i.test(candidateRef) && !candidateRef.includes("..")
+ ? candidateRef
+ : undefined;
+ const branch = ref?.replace(/^refs\/heads\//, "");
+ let sha = ref ? (await readRegularText(path.join(gitDir, ref))).trim() : head.trim();
+ if (!sha && ref) {
+ const packed = await readRegularText(path.join(gitDir, "packed-refs"));
+ sha = packed.split("\n").find((line) => line.endsWith(` ${ref}`))?.split(" ")[0] ?? "";
+ }
+ return { available: true, branch, statusChecked: false, ...(sha ? { head: { sha } } : {}) };
+}
+
+/** The exec-scope variant: one subprocess, working tree status included. */
+export async function fullGitMeta(dir: string): Promise<GitMeta> {
+ const marker = "__MSO_HEAD__";
+ const result = await runCommand(`git status --short --branch && printf '\n${marker}\n' && git log -1 --format='%H%n%s%n%aI'`, dir);
+ if (result.code !== 0)
+ return { available: false, statusChecked: true, error: (result.stderr || result.stdout).trim().slice(0, 220) };
+ const [statusPart, headPart = ""] = result.stdout.split(`\n${marker}\n`);
+ const statusLines = statusPart.split("\n").filter(Boolean);
+ const changes = statusLines.slice(1, 81);
+ const [sha = "", subject = "", date = ""] = headPart.trim().split("\n");
+ return {
+ available: true,
+ branch: statusLines[0]?.replace(/^##\s*/, ""),
+ clean: changes.length === 0,
+ changes,
+ statusChecked: true,
+ head: { sha, subject, date },
+ };
+}
diff --git a/lib/host/project-roots.test.ts b/lib/host/project-roots.test.ts
new file mode 100644
index 00000000..1e4d50f7
--- /dev/null
+++ b/lib/host/project-roots.test.ts
@@ -0,0 +1,97 @@
+import { afterAll, describe, expect, it } from "vitest";
+import { promises as fs } from "fs";
+import os from "os";
+import path from "path";
+
+// Two SEPARATE containers, plus a `projects/` child of the first. The point of the
+// whole file: an owner who configured more than one read root must see every one of
+// them, because the old behaviour looked at `~/projects` and nothing else.
+const base = await fs.mkdtemp(path.join(os.tmpdir(), "mso-roots-"));
+const alpha = path.join(base, "alpha");
+const beta = path.join(base, "beta");
+const nested = path.join(alpha, "projects");
+await fs.mkdir(nested, { recursive: true });
+await fs.mkdir(beta, { recursive: true });
+
+await fs.mkdir(path.join(alpha, "apex"));
+await fs.writeFile(path.join(alpha, "apex", "package.json"), JSON.stringify({ name: "@acme/apex", version: "2.0.0" }));
+await fs.mkdir(path.join(nested, "inner"));
+await fs.mkdir(path.join(beta, "zulu"));
+await fs.mkdir(path.join(beta, ".hidden"));
+await fs.mkdir(path.join(base, "outside"));
+await fs.symlink(path.join(base, "outside"), path.join(beta, "linked"));
+
+const previous = process.env.OS_FS_READ_ROOTS;
+process.env.OS_FS_READ_ROOTS = `${alpha}:${beta}`;
+const { listProjects, projectRoots, resolveProjectHint } = await import("./index");
+
+describe("project containers span every configured read root", () => {
+ afterAll(async () => {
+ if (previous === undefined) delete process.env.OS_FS_READ_ROOTS;
+ else process.env.OS_FS_READ_ROOTS = previous;
+ await fs.rm(base, { recursive: true, force: true });
+ });
+
+ it("treats each read root and its projects/ child as a container, in configured order", async () => {
+ await expect(projectRoots()).resolves.toEqual([
+ await fs.realpath(alpha),
+ await fs.realpath(nested),
+ await fs.realpath(beta),
+ ]);
+ });
+
+ it("enumerates projects from ALL containers, not only the first", async () => {
+ const { projects, roots, total } = await listProjects();
+ expect(roots).toHaveLength(3);
+ expect(projects.map((p) => p.name)).toEqual(["apex", "inner", "zulu"]);
+ expect(total).toBe(3);
+ });
+
+ it("does not list a container as a project of its own parent", async () => {
+ const { projects } = await listProjects();
+ // `alpha/projects` is a CONTAINER, so it must not also appear as a project
+ // named "projects" sitting inside alpha.
+ expect(projects.map((p) => p.name)).not.toContain("projects");
+ });
+
+ it("excludes hidden directories and symlinks", async () => {
+ const { projects } = await listProjects();
+ expect(projects.map((p) => p.name)).not.toContain(".hidden");
+ expect(projects.map((p) => p.name)).not.toContain("linked");
+ });
+
+ it("reports package and container metadata for the returned page", async () => {
+ const { projects } = await listProjects({ query: "apex" });
+ expect(projects).toEqual([expect.objectContaining({
+ name: "apex", packageName: "@acme/apex", packageVersion: "2.0.0", root: await fs.realpath(alpha),
+ })]);
+ });
+
+ it("paginates deterministically without losing the total", async () => {
+ const first = await listProjects({ limit: 2, offset: 0 });
+ const second = await listProjects({ limit: 2, offset: 2 });
+ expect(first.projects.map((p) => p.name)).toEqual(["apex", "inner"]);
+ expect(second.projects.map((p) => p.name)).toEqual(["zulu"]);
+ expect(second.total).toBe(3);
+ });
+
+ it("resolves a project living in a non-first container by exact name", async () => {
+ await expect(resolveProjectHint("zulu")).resolves.toMatchObject({
+ name: "zulu", path: path.join(beta, "zulu"), matchedBy: "name",
+ });
+ });
+
+ it("prefers an exact name in a later container over a fuzzy hit in an earlier one", async () => {
+ // "apexish" substring-matches `apex` in the FIRST container. An exact directory
+ // in the second must still win, or resolution depends on root order.
+ await fs.mkdir(path.join(beta, "apexish"));
+ await expect(resolveProjectHint("apexish")).resolves.toMatchObject({
+ name: "apexish", matchedBy: "name", root: await fs.realpath(beta),
+ });
+ await fs.rm(path.join(beta, "apexish"), { recursive: true, force: true });
+ });
+
+ it("resolves an exact package name from any container", async () => {
+ await expect(resolveProjectHint("@acme/apex")).resolves.toMatchObject({ name: "apex", matchedBy: "package" });
+ });
+});
diff --git a/lib/host/project-roots.ts b/lib/host/project-roots.ts
new file mode 100644
index 00000000..26d08092
--- /dev/null
+++ b/lib/host/project-roots.ts
@@ -0,0 +1,129 @@
+// EVERY configured project container, not just ~/projects.
+//
+// MSO used to hard-code `~/projects` as "where projects live". That was invisible
+// scoping: an owner who set OS_FS_READ_ROOTS to two or three checkout areas still
+// had project resolution, skill discovery and the MCP bootstrap looking at exactly
+// one of them, and nothing said so. A capability that silently covers a subset of
+// what the owner configured is worse than one that refuses.
+//
+// A container is a directory that HOLDS projects. Every read root is one, plus its
+// `projects/` subdirectory when it has one (the default `~` + `~/projects` pair is
+// this case). The filesystem root is deliberately NOT a container: "/" as a read
+// root means browse-anywhere, not "every top-level system directory is a project".
+import { promises as fs } from "fs";
+import path from "path";
+import { isCredentialPath, readRootList } from "./paths";
+import { boundedGitMeta, packageMeta } from "./project-meta";
+
+export const PROJECT_LIMITS = {
+ /** Containers scanned per call. */
+ maxRoots: 12,
+ /** Directory entries read per container before the listing is truncated. */
+ maxEntriesPerRoot: 400,
+ /** Projects enumerated in total, across all containers. */
+ maxProjects: 400,
+ defaultPageSize: 50,
+ maxPageSize: 200,
+} as const;
+
+export type ProjectRow = {
+ name: string;
+ path: string;
+ root: string;
+ packageName?: string;
+ packageVersion?: string;
+ git?: { branch?: string; head?: string };
+};
+
+async function realDir(p: string): Promise<string | null> {
+ const real = await fs.realpath(p).catch(() => null);
+ if (!real) return null;
+ const stat = await fs.stat(real).catch(() => null);
+ return stat?.isDirectory() ? real : null;
+}
+
+/**
+ * Deterministic: configured read-root order, each root followed by its `projects/`
+ * child, deduped by realpath. Order is the contract — two calls on an unchanged box
+ * must enumerate identically, or pagination lies.
+ */
+export async function projectRoots(): Promise<string[]> {
+ const out: string[] = [];
+ const seen = new Set<string>();
+ for (const configured of readRootList()) {
+ for (const candidate of [configured, path.join(configured, "projects")]) {
+ const real = await realDir(candidate);
+ if (!real || real === "/" || seen.has(real) || isCredentialPath(real)) continue;
+ seen.add(real);
+ out.push(real);
+ if (out.length >= PROJECT_LIMITS.maxRoots) return out;
+ }
+ }
+ return out;
+}
+
+/** A project directory: real, owner-visible, not hidden, not a symlink, not a
+ * credential path, and not a container in its own right (`~/projects` under `~`). */
+async function projectDirsIn(root: string, containers: Set<string>): Promise<string[]> {
+ const entries = (await fs.readdir(root, { withFileTypes: true }).catch(() => []))
+ // isDirectory() is false for a symlink, so a link out of the container is
+ // dropped here rather than realpath-checked later.
+ .filter((entry) => entry.isDirectory() && !entry.name.startsWith("."))
+ .sort((a, b) => a.name.localeCompare(b.name))
+ .slice(0, PROJECT_LIMITS.maxEntriesPerRoot);
+ const out: string[] = [];
+ for (const entry of entries) {
+ const full = path.join(root, entry.name);
+ if (containers.has(full) || isCredentialPath(full)) continue;
+ out.push(full);
+ }
+ return out;
+}
+
+/** Every project directory across every container, in root-then-name order. */
+export async function listProjectDirs(): Promise<{ roots: string[]; dirs: Array<{ root: string; dir: string }>; truncated: boolean }> {
+ const roots = await projectRoots();
+ const containers = new Set(roots);
+ const dirs: Array<{ root: string; dir: string }> = [];
+ let truncated = false;
+ for (const root of roots) {
+ for (const dir of await projectDirsIn(root, containers)) {
+ if (dirs.length >= PROJECT_LIMITS.maxProjects) { truncated = true; break; }
+ dirs.push({ root, dir });
+ }
+ if (truncated) break;
+ }
+ return { roots, dirs, truncated };
+}
+
+export type ListProjectsResult = {
+ roots: string[];
+ total: number;
+ offset: number;
+ limit: number;
+ truncated: boolean;
+ projects: ProjectRow[];
+};
+
+/** Bounded, paginated enumeration. Metadata is read only for the returned PAGE —
+ * `total` counts directories, so a wide box does not pay for 400 package reads. */
+export async function listProjects(options: { query?: string; limit?: number; offset?: number } = {}): Promise<ListProjectsResult> {
+ const { roots, dirs, truncated } = await listProjectDirs();
+ const query = options.query?.trim().toLowerCase();
+ const matched = query ? dirs.filter(({ dir }) => path.basename(dir).toLowerCase().includes(query)) : dirs;
+ const limit = Math.min(Math.max(Math.round(options.limit ?? PROJECT_LIMITS.defaultPageSize), 1), PROJECT_LIMITS.maxPageSize);
+ const offset = Math.max(Math.round(options.offset ?? 0), 0);
+ const page = matched.slice(offset, offset + limit);
+ const projects = await Promise.all(page.map(async ({ root, dir }) => {
+ const [pkg, git] = await Promise.all([packageMeta(dir), boundedGitMeta(dir)]);
+ return {
+ name: path.basename(dir),
+ path: dir,
+ root,
+ ...(pkg.name ? { packageName: pkg.name } : {}),
+ ...(pkg.version ? { packageVersion: pkg.version } : {}),
+ ...(git.available ? { git: { branch: git.branch, head: git.head?.sha?.slice(0, 12) } } : {}),
+ };
+ }));
+ return { roots, total: matched.length, offset, limit, truncated, projects };
+}
diff --git a/lib/host/projects.ts b/lib/host/projects.ts
index 80250e55..86a5906d 100644
--- a/lib/host/projects.ts
+++ b/lib/host/projects.ts
@@ -1,131 +1,72 @@
import { promises as fs } from "fs";
import path from "path";
-import { runCommand } from "./exec";
import { normalizeProjectKey, projectAliasesFor, projectAliasTarget } from "./project-aliases";
+import { boundedGitMeta, fullGitMeta, packageMeta } from "./project-meta";
import { resolveReadable } from "./paths";
+import { listProjectDirs, projectRoots } from "./project-roots";
export type ProjectResolution = {
hint: string;
name: string;
path: string;
+ root?: string;
packageName?: string;
aliases: string[];
matchedBy: "path" | "name" | "alias" | "package" | "fuzzy";
};
-type PackageMeta = { name?: string; version?: string; scripts: string[] };
-type GitMeta = {
- available: boolean;
- branch?: string;
- clean?: boolean;
- changes?: string[];
- head?: { sha: string; subject?: string; date?: string };
- statusChecked: boolean;
- error?: string;
-};
-
-async function readRegularText(file: string): Promise<string> {
- const stat = await fs.lstat(file).catch(() => null);
- if (!stat?.isFile() || stat.isSymbolicLink()) return "";
- return fs.readFile(file, "utf8").catch(() => "");
-}
-
-async function packageMeta(dir: string): Promise<PackageMeta> {
- try {
- const raw = await readRegularText(path.join(dir, "package.json"));
- if (!raw) return { scripts: [] };
- const parsed = JSON.parse(raw) as {
- name?: unknown; version?: unknown; scripts?: unknown;
- };
- return {
- name: typeof parsed.name === "string" ? parsed.name : undefined,
- version: typeof parsed.version === "string" ? parsed.version : undefined,
- scripts: parsed.scripts && typeof parsed.scripts === "object" ? Object.keys(parsed.scripts) : [],
- };
- } catch {
- return { scripts: [] };
- }
+async function resolvedDir(p: string): Promise<string | null> {
+ const resolved = await resolveReadable(p).catch(() => null);
+ if (!resolved) return null;
+ return (await fs.stat(resolved).catch(() => null))?.isDirectory() ? resolved : null;
}
-async function boundedGitMeta(dir: string): Promise<GitMeta> {
- const gitDir = path.join(dir, ".git");
- const gitStat = await fs.lstat(gitDir).catch(() => null);
- if (!gitStat?.isDirectory() || gitStat.isSymbolicLink()) return { available: false, statusChecked: false };
- const head = await readRegularText(path.join(gitDir, "HEAD"));
- if (!head) return { available: false, statusChecked: false };
- const candidateRef = head.trim().startsWith("ref: ") ? head.trim().slice(5) : undefined;
- const ref = candidateRef && /^refs\/(?:heads|remotes)\/[a-z0-9._\/-]+$/i.test(candidateRef) && !candidateRef.includes("..")
- ? candidateRef
- : undefined;
- const branch = ref?.replace(/^refs\/heads\//, "");
- let sha = ref ? (await readRegularText(path.join(gitDir, ref))).trim() : head.trim();
- if (!sha && ref) {
- const packed = await readRegularText(path.join(gitDir, "packed-refs"));
- sha = packed.split("\n").find((line) => line.endsWith(` ${ref}`))?.split(" ")[0] ?? "";
- }
- return { available: true, branch, statusChecked: false, ...(sha ? { head: { sha } } : {}) };
+async function resolutionFor(dir: string, hint: string, matchedBy: ProjectResolution["matchedBy"], root?: string): Promise<ProjectResolution> {
+ const name = path.basename(dir);
+ const meta = await packageMeta(dir);
+ return { hint, name, path: dir, ...(root ? { root } : {}), packageName: meta.name, aliases: projectAliasesFor(name), matchedBy };
}
-async function fullGitMeta(dir: string): Promise<GitMeta> {
- const marker = "__MSO_HEAD__";
- const result = await runCommand(`git status --short --branch && printf '\n${marker}\n' && git log -1 --format='%H%n%s%n%aI'`, dir);
- if (result.code !== 0)
- return { available: false, statusChecked: true, error: (result.stderr || result.stdout).trim().slice(0, 220) };
- const [statusPart, headPart = ""] = result.stdout.split(`\n${marker}\n`);
- const statusLines = statusPart.split("\n").filter(Boolean);
- const changes = statusLines.slice(1, 81);
- const [sha = "", subject = "", date = ""] = headPart.trim().split("\n");
- return {
- available: true,
- branch: statusLines[0]?.replace(/^##\s*/, ""),
- clean: changes.length === 0,
- changes,
- statusChecked: true,
- head: { sha, subject, date },
- };
-}
-
-export async function resolveProjectHint(hint: string, rootHint = "~/projects"): Promise<ProjectResolution | null> {
+/**
+ * Resolve a project hint across EVERY configured container, not just `~/projects`.
+ *
+ * Deterministic order, exact before fuzzy: an absolute/`~` path wins outright; then
+ * an exact directory name or known alias, probed container by container in
+ * configured order; then one bounded scan that scores exact package names above
+ * substring matches. Scanning first would let a fuzzy hit in the first container
+ * beat an exact directory in the second, which is the kind of answer nobody can
+ * reproduce.
+ */
+export async function resolveProjectHint(hint: string, rootHint?: string): Promise<ProjectResolution | null> {
const raw = hint.trim();
if (!raw) return null;
const pathHint = raw.startsWith("projects/") ? `~/${raw}` : raw;
if (/^(?:~\/|\/|\.\.?\/)/.test(pathHint)) {
- const resolved = await resolveReadable(pathHint).catch(() => null);
- if (resolved && (await fs.stat(resolved).catch(() => null))?.isDirectory()) {
- const meta = await packageMeta(resolved);
- return { hint: raw, name: path.basename(resolved), path: resolved, packageName: meta.name, aliases: projectAliasesFor(path.basename(resolved)), matchedBy: "path" };
- }
+ const resolved = await resolvedDir(pathHint);
+ if (resolved) return resolutionFor(resolved, raw, "path");
}
- const root = await resolveReadable(rootHint);
+ const roots = rootHint ? [await resolveReadable(rootHint).catch(() => null)].filter((r): r is string => !!r) : await projectRoots();
const query = normalizeProjectKey(raw);
const aliasTarget = projectAliasTarget(raw);
// Known aliases and exact directory names are the common path. Resolve them in
- // one bounded stat/read instead of scanning and parsing every project package.
+ // one bounded stat per container instead of scanning and parsing every package.
const directName = aliasTarget ?? (/^[a-z0-9._-]+$/i.test(raw) ? raw : undefined);
if (directName) {
- const candidate = await resolveReadable(path.join(root, directName)).catch(() => null);
- if (candidate && (await fs.stat(candidate).catch(() => null))?.isDirectory()) {
- const meta = await packageMeta(candidate);
- const name = path.basename(candidate);
- return {
- hint: raw,
- name,
- path: candidate,
- packageName: meta.name,
- aliases: projectAliasesFor(name),
- matchedBy: aliasTarget ? "alias" : "name",
- };
+ for (const root of roots) {
+ const candidate = await resolvedDir(path.join(root, directName));
+ if (candidate) return resolutionFor(candidate, raw, aliasTarget ? "alias" : "name", root);
}
}
- const entries = (await fs.readdir(root, { withFileTypes: true }))
- .filter((entry) => entry.isDirectory() && !entry.name.startsWith(".")).slice(0, 300);
- const candidates = await Promise.all(entries.map(async (entry) => {
- const dir = path.join(root, entry.name);
+ const { dirs } = rootHint
+ ? { dirs: (await listProjectDirs()).dirs.filter(({ root }) => roots.includes(root)) }
+ : await listProjectDirs();
+ const candidates = await Promise.all(dirs.map(async ({ root, dir }) => {
+ const name = path.basename(dir);
const meta = await packageMeta(dir);
- const nameKey = normalizeProjectKey(entry.name);
+ const nameKey = normalizeProjectKey(name);
const packageKey = normalizeProjectKey(meta.name ?? "");
let score = 0;
let matchedBy: ProjectResolution["matchedBy"] = "fuzzy";
@@ -134,13 +75,14 @@ export async function resolveProjectHint(hint: string, rootHint = "~/projects"):
else if (packageKey && packageKey === query) { score = 94; matchedBy = "package"; }
else if (nameKey.includes(query) || query.includes(nameKey)) score = 65;
else if (packageKey && (packageKey.includes(query) || query.includes(packageKey))) score = 60;
- return { entry, dir, meta, score, matchedBy };
+ return { name, dir, root, meta, score, matchedBy };
}));
- const best = candidates.sort((a, b) => b.score - a.score || a.entry.name.localeCompare(b.entry.name))[0];
+ // Ties break on name then path, so the same box always answers the same way.
+ const best = candidates.sort((a, b) => b.score - a.score || a.name.localeCompare(b.name) || a.dir.localeCompare(b.dir))[0];
if (!best || best.score < 60) return null;
return {
- hint: raw, name: best.entry.name, path: best.dir, packageName: best.meta.name,
- aliases: projectAliasesFor(best.entry.name), matchedBy: best.matchedBy,
+ hint: raw, name: best.name, path: best.dir, root: best.root, packageName: best.meta.name,
+ aliases: projectAliasesFor(best.name), matchedBy: best.matchedBy,
};
}
diff --git a/lib/image-generation/openai.test.ts b/lib/image-generation/openai.test.ts
deleted file mode 100644
index 9510900d..00000000
--- a/lib/image-generation/openai.test.ts
+++ /dev/null
@@ -1,137 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { promises as fs } from "fs";
-import os from "os";
-import path from "path";
-
-const state = vi.hoisted(() => ({ key: "sk-test" }));
-vi.mock("@/lib/config/store", () => ({
- hostCredentialStore: () => ({ getKey: async () => state.key }),
-}));
-
-const {
- generateOpenAiImage,
- imageGenerationStatus,
- shouldReturnDirectImage,
-} = await import("./openai");
-
-let root = "";
-const realFetch = globalThis.fetch;
-
-function fakePng(width = 1, height = 1, colorType = 6): Buffer {
- const out = Buffer.alloc(33);
- Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]).copy(out, 0);
- out.writeUInt32BE(13, 8);
- out.write("IHDR", 12, "ascii");
- out.writeUInt32BE(width, 16);
- out.writeUInt32BE(height, 20);
- out[24] = 8;
- out[25] = colorType;
- return out;
-}
-
-beforeEach(async () => {
- root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-image-generation-"));
- process.env.OS_FS_WRITE_ROOTS = root;
- process.env.OS_IMAGE_OUTPUT_ROOT = path.join(root, "images");
- process.env.OS_IMAGE_MODEL = "gpt-image-2";
- state.key = "sk-test";
-});
-
-afterEach(async () => {
- globalThis.fetch = realFetch;
- delete process.env.OS_FS_WRITE_ROOTS;
- delete process.env.OS_IMAGE_OUTPUT_ROOT;
- delete process.env.OS_IMAGE_MODEL;
- await fs.rm(root, { recursive: true, force: true });
-});
-
-describe("OpenAI image generation bridge", () => {
- it("reports readiness without exposing the key", async () => {
- const status = await imageGenerationStatus();
- expect(status).toMatchObject({ ready: true, provider: "openai", credential: "configured" });
- expect(JSON.stringify(status)).not.toContain("sk-test");
- });
-
- it("persists one PNG master and prompt-free provenance with provider request id", async () => {
- const png = fakePng();
- let sent: Record<string, unknown> | undefined;
- globalThis.fetch = vi.fn(async (_url, init) => {
- sent = JSON.parse(String(init?.body));
- return new Response(JSON.stringify({
- created: 1_787_161_600,
- data: [{ b64_json: png.toString("base64") }],
- usage: { total_tokens: 123 },
- }), { status: 200, headers: { "content-type": "application/json", "x-request-id": "req_test_123" } });
- });
-
- const result = await generateOpenAiImage({
- prompt: "private studio prompt",
- project: "antinrml-game",
- filenameStem: "zone-house-empty",
- size: "auto",
- quality: "high",
- background: "opaque",
- });
-
- expect(sent).toMatchObject({ model: "gpt-image-2", output_format: "png", n: 1 });
- expect(result.summary).toMatchObject({
- provider: "openai",
- generationRunId: "req_test_123",
- width: 1,
- height: 1,
- lossless: true,
- candidateEligible: true,
- });
- expect(await fs.readFile(result.summary.masterPath)).toEqual(png);
- const provenance = await fs.readFile(result.summary.provenancePath, "utf8");
- expect(provenance).toContain('"promptSha256"');
- expect(provenance).toContain('"generationRunId": "req_test_123"');
- expect(provenance).not.toContain("private studio prompt");
- });
-
- it("uses gpt-image-1.5 automatically for transparent output", async () => {
- const png = fakePng();
- let sent: Record<string, unknown> | undefined;
- globalThis.fetch = vi.fn(async (_url, init) => {
- sent = JSON.parse(String(init?.body));
- return new Response(JSON.stringify({ data: [{ b64_json: png.toString("base64") }] }), {
- status: 200,
- headers: { "x-request-id": "req_transparent" },
- });
- });
- await generateOpenAiImage({ prompt: "one prop", size: "auto", background: "transparent" });
- expect(sent).toMatchObject({ model: "gpt-image-1.5", background: "transparent" });
- });
-
- it("refuses an explicit transparent gpt-image-2 request before spending", async () => {
- globalThis.fetch = vi.fn();
- await expect(generateOpenAiImage({
- prompt: "one prop",
- model: "gpt-image-2",
- background: "transparent",
- })).rejects.toThrow(/does not support transparent/);
- expect(globalThis.fetch).not.toHaveBeenCalled();
- });
-
- it("fails clearly when the OpenAI API key is absent", async () => {
- state.key = "";
- await expect(generateOpenAiImage({ prompt: "x" })).rejects.toThrow(/not configured/);
- });
-
- it("keeps an output sandbox-only when provider request id is missing", async () => {
- const png = fakePng();
- globalThis.fetch = vi.fn(async () => new Response(
- JSON.stringify({ data: [{ b64_json: png.toString("base64") }] }),
- { status: 200 },
- ));
- const result = await generateOpenAiImage({ prompt: "x", size: "auto" });
- expect(result.summary.generationRunId).toBeNull();
- expect(result.summary.candidateEligible).toBe(false);
- expect(result.summary.findings).toContain("provider request id missing");
- });
-
- it("bounds direct image responses", () => {
- expect(shouldReturnDirectImage(1)).toBe(true);
- expect(shouldReturnDirectImage(9 * 1024 * 1024)).toBe(false);
- });
-});
diff --git a/lib/image-generation/openai.ts b/lib/image-generation/openai.ts
deleted file mode 100644
index 2c2df190..00000000
--- a/lib/image-generation/openai.ts
+++ /dev/null
@@ -1,402 +0,0 @@
-import { createHash, randomUUID } from "crypto";
-import { promises as fs } from "fs";
-import os from "os";
-import path from "path";
-import { hostCredentialStore } from "@/lib/config/store";
-import { createTempShare, tempShareUrl } from "@/lib/host/temp-share";
-import { isUnderRoot, resolveWriteRoots, safeWritePath } from "@/lib/host/paths";
-
-const OPENAI_IMAGES_ENDPOINT = "https://api.openai.com/v1/images/generations";
-const DEFAULT_MODEL = "gpt-image-2" as const;
-const TRANSPARENT_MODEL = "gpt-image-1.5" as const;
-const DEFAULT_OUTPUT_ROOT = path.join(os.homedir(), "generated-images");
-const MAX_PROMPT_CHARS = 32_000;
-const MAX_PROVIDER_BYTES = 64 * 1024 * 1024;
-const TEMP_SHARE_MAX_BYTES = 10 * 1024 * 1024;
-const DIRECT_IMAGE_MAX_BYTES = 8 * 1024 * 1024;
-
-export const OPENAI_IMAGE_MODELS = [
- "gpt-image-2",
- "gpt-image-1.5",
- "gpt-image-1",
- "gpt-image-1-mini",
-] as const;
-export type OpenAiImageModel = (typeof OPENAI_IMAGE_MODELS)[number];
-
-export const OPENAI_IMAGE_SIZES = ["auto", "1024x1024", "1024x1536", "1536x1024"] as const;
-export type OpenAiImageSize = (typeof OPENAI_IMAGE_SIZES)[number];
-
-export const OPENAI_IMAGE_QUALITIES = ["auto", "low", "medium", "high"] as const;
-export type OpenAiImageQuality = (typeof OPENAI_IMAGE_QUALITIES)[number];
-
-export const OPENAI_IMAGE_BACKGROUNDS = ["auto", "opaque", "transparent"] as const;
-export type OpenAiImageBackground = (typeof OPENAI_IMAGE_BACKGROUNDS)[number];
-
-export interface GenerateOpenAiImageInput {
- prompt: string;
- project?: string;
- filenameStem?: string;
- model?: OpenAiImageModel;
- size?: OpenAiImageSize;
- quality?: OpenAiImageQuality;
- background?: OpenAiImageBackground;
-}
-
-export interface GeneratedImageSummary {
- generationMethod: "image-generation";
- provider: "openai";
- model: OpenAiImageModel;
- generationRunId: string | null;
- generationRunIdKind: "provider-request-id" | null;
- localRunId: string;
- promptSha256: string;
- masterPath: string;
- provenancePath: string;
- width: number;
- height: number;
- format: "png";
- mimeType: "image/png";
- lossless: true;
- alphaStatus: "present" | "absent";
- bytes: number;
- sha256: string;
- candidateEligible: boolean;
- findings: string[];
- previewUrl: string | null;
- downloadUrl: string | null;
- createdAt: string;
-}
-
-export interface GeneratedImageResult {
- summary: GeneratedImageSummary;
- data: Buffer;
-}
-
-function configuredOutputRoot(): string {
- const raw = process.env.OS_IMAGE_OUTPUT_ROOT?.trim();
- if (!raw) return DEFAULT_OUTPUT_ROOT;
- if (raw === "~") return os.homedir();
- if (raw.startsWith("~/")) return path.join(os.homedir(), raw.slice(2));
- return path.resolve(raw);
-}
-
-function configuredModel(): OpenAiImageModel {
- const raw = process.env.OS_IMAGE_MODEL?.trim();
- return isOneOf(raw, OPENAI_IMAGE_MODELS) ? raw : DEFAULT_MODEL;
-}
-
-function isOneOf<T extends readonly string[]>(value: unknown, values: T): value is T[number] {
- return typeof value === "string" && (values as readonly string[]).includes(value);
-}
-
-function assertOneOf<T extends readonly string[]>(
- value: unknown,
- values: T,
- field: string,
- fallback: T[number],
-): T[number] {
- if (value == null || value === "") return fallback;
- if (!isOneOf(value, values)) throw new Error(`${field} must be one of: ${values.join(", ")}`);
- return value;
-}
-
-function cleanSegment(value: string | undefined, fallback: string, max: number): string {
- const normalized = (value ?? fallback)
- .normalize("NFKD")
- .replace(/[^a-zA-Z0-9._-]+/g, "-")
- .replace(/^[._-]+|[._-]+$/g, "")
- .slice(0, max);
- return normalized || fallback;
-}
-
-function sha256(data: Uint8Array | string): string {
- return createHash("sha256").update(data).digest("hex");
-}
-
-function redactProviderError(raw: string, prompt: string): string {
- let message = raw;
- try {
- const parsed = JSON.parse(raw) as { error?: { message?: string; code?: string; type?: string } };
- message = parsed.error?.message ?? parsed.error?.code ?? parsed.error?.type ?? raw;
- } catch {
- // Keep the raw provider text when it was not JSON.
- }
- if (prompt) message = message.split(prompt).join("[prompt]");
- return message
- .replace(/\b(?:sk|pk)_[a-z0-9_-]{8,}\b/gi, "[redacted]")
- .replace(/\b(?:sk-proj|sk-live)-[a-z0-9_-]{8,}\b/gi, "[redacted]")
- .slice(0, 500);
-}
-
-function parsePngMetadata(data: Buffer): { width: number; height: number; hasAlpha: boolean } {
- const signature = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
- if (data.length < 33 || !data.subarray(0, 8).equals(signature)) {
- throw new Error("OpenAI returned bytes that are not a PNG image");
- }
- if (data.subarray(12, 16).toString("ascii") !== "IHDR") {
- throw new Error("OpenAI PNG is missing the IHDR header");
- }
- const width = data.readUInt32BE(16);
- const height = data.readUInt32BE(20);
- const colorType = data[25] ?? 0;
- let hasTransparencyChunk = false;
- let offset = 8;
- while (offset + 12 <= data.length) {
- const length = data.readUInt32BE(offset);
- const type = data.subarray(offset + 4, offset + 8).toString("ascii");
- const next = offset + 12 + length;
- if (next > data.length) break;
- if (type === "tRNS") hasTransparencyChunk = true;
- if (type === "IEND") break;
- offset = next;
- }
- return { width, height, hasAlpha: colorType === 4 || colorType === 6 || hasTransparencyChunk };
-}
-
-function expectedDimensions(size: OpenAiImageSize): { width: number; height: number } | null {
- if (size === "auto") return null;
- const [width, height] = size.split("x").map(Number);
- return { width, height };
-}
-
-async function ensureOutputRoot(): Promise<string> {
- const lexical = await safeWritePath(configuredOutputRoot(), false);
- await fs.mkdir(lexical, { recursive: true, mode: 0o700 });
- const real = await fs.realpath(lexical);
- const roots = await resolveWriteRoots();
- if (!roots.some((root) => isUnderRoot(real, root))) {
- throw new Error("OS_IMAGE_OUTPUT_ROOT resolves outside writable roots");
- }
- await fs.chmod(real, 0o700).catch(() => undefined);
- return real;
-}
-
-async function makeJobDirectory(root: string, project: string, day: string): Promise<string> {
- const dir = path.join(root, project, day);
- await fs.mkdir(dir, { recursive: true, mode: 0o700 });
- const real = await fs.realpath(dir);
- if (!isUnderRoot(real, root)) throw new Error("Image output directory escaped its sandbox root");
- await fs.chmod(real, 0o700).catch(() => undefined);
- return real;
-}
-
-async function writeExclusive(file: string, data: Buffer | string): Promise<void> {
- await fs.writeFile(file, data, { flag: "wx", mode: 0o600 });
-}
-
-function selectedModel(explicit: OpenAiImageModel | undefined, background: OpenAiImageBackground): OpenAiImageModel {
- const base = explicit ?? configuredModel();
- if (!isOneOf(base, OPENAI_IMAGE_MODELS)) throw new Error(`Unsupported OpenAI image model: ${base}`);
- if (background === "transparent" && base === "gpt-image-2") {
- if (explicit) throw new Error("gpt-image-2 does not support transparent backgrounds; use gpt-image-1.5 or gpt-image-1");
- return TRANSPARENT_MODEL;
- }
- return base;
-}
-
-export async function imageGenerationStatus(): Promise<Record<string, unknown>> {
- const key = await hostCredentialStore().getKey(undefined, "openai");
- return {
- ready: Boolean(key),
- provider: "openai",
- endpoint: OPENAI_IMAGES_ENDPOINT,
- defaultModel: configuredModel(),
- transparentModel: TRANSPARENT_MODEL,
- outputRoot: configuredOutputRoot(),
- outputFormat: "png",
- losslessMaster: true,
- supportedModels: [...OPENAI_IMAGE_MODELS],
- supportedSizes: [...OPENAI_IMAGE_SIZES],
- supportedQualities: [...OPENAI_IMAGE_QUALITIES],
- supportedBackgrounds: [...OPENAI_IMAGE_BACKGROUNDS],
- credential: key ? "configured" : "missing",
- setup: key
- ? "ready"
- : "Add an OpenAI API key in MSO Settings → AI (provider OpenAI) or set OPENAI_API_KEY. ChatGPT OAuth/Plus is not an OpenAI API key.",
- };
-}
-
-export async function generateOpenAiImage(input: GenerateOpenAiImageInput): Promise<GeneratedImageResult> {
- const prompt = input.prompt?.trim() ?? "";
- if (!prompt) throw new Error("prompt must be a non-empty string");
- if (prompt.length > MAX_PROMPT_CHARS) throw new Error(`prompt exceeds ${MAX_PROMPT_CHARS} characters`);
-
- const key = await hostCredentialStore().getKey(undefined, "openai");
- if (!key) {
- throw new Error(
- "OpenAI image generation is not configured. Add an OpenAI API key in MSO Settings → AI (provider OpenAI) or set OPENAI_API_KEY. ChatGPT OAuth/Plus is separate from API billing.",
- );
- }
-
- const size = assertOneOf(input.size, OPENAI_IMAGE_SIZES, "size", "1024x1024");
- const quality = assertOneOf(input.quality, OPENAI_IMAGE_QUALITIES, "quality", "high");
- const background = assertOneOf(input.background, OPENAI_IMAGE_BACKGROUNDS, "background", "auto");
- const model = selectedModel(input.model, background);
- const localRunId = randomUUID();
- const promptSha256 = sha256(prompt);
-
- const controller = new AbortController();
- const timeout = setTimeout(() => controller.abort(), 300_000);
- timeout.unref?.();
- let response: Response;
- try {
- response = await fetch(OPENAI_IMAGES_ENDPOINT, {
- method: "POST",
- headers: {
- authorization: `Bearer ${key}`,
- "content-type": "application/json",
- "x-client-request-id": localRunId,
- },
- body: JSON.stringify({
- model,
- prompt,
- n: 1,
- size,
- quality,
- background,
- output_format: "png",
- }),
- signal: controller.signal,
- });
- } catch (error) {
- if ((error as Error).name === "AbortError") throw new Error("OpenAI image generation timed out after 300 seconds");
- throw error;
- } finally {
- clearTimeout(timeout);
- }
-
- const raw = await response.text();
- if (!response.ok) throw new Error(`OpenAI Images API HTTP ${response.status}: ${redactProviderError(raw, prompt)}`);
-
- let payload: {
- created?: number;
- data?: Array<{ b64_json?: string }>;
- usage?: unknown;
- };
- try {
- payload = JSON.parse(raw) as typeof payload;
- } catch {
- throw new Error("OpenAI Images API returned invalid JSON");
- }
- const encoded = payload.data?.[0]?.b64_json;
- if (!encoded) throw new Error("OpenAI Images API returned no base64 image bytes");
- const data = Buffer.from(encoded, "base64");
- if (!data.length || data.length > MAX_PROVIDER_BYTES) {
- throw new Error(`OpenAI image bytes must be between 1 and ${MAX_PROVIDER_BYTES} bytes`);
- }
-
- const png = parsePngMetadata(data);
- const expected = expectedDimensions(size);
- const findings: string[] = [];
- const requestId = response.headers.get("x-request-id") ?? response.headers.get("openai-request-id");
- if (!requestId) findings.push("provider request id missing");
- if (expected && (expected.width !== png.width || expected.height !== png.height)) {
- findings.push(`provider returned ${png.width}x${png.height}, expected ${expected.width}x${expected.height}`);
- }
- if (background === "transparent" && !png.hasAlpha) findings.push("transparent background requested but PNG has no alpha channel");
-
- const root = await ensureOutputRoot();
- const project = cleanSegment(input.project, "general", 48);
- const stem = cleanSegment(input.filenameStem, "generated-image", 64);
- const createdAt = new Date().toISOString();
- const day = createdAt.slice(0, 10);
- const stamp = createdAt.replace(/[:.]/g, "-");
- const jobDir = await makeJobDirectory(root, project, day);
- const base = `${stamp}-${localRunId.slice(0, 8)}-${stem}`;
- const masterPath = path.join(jobDir, `${base}.png`);
- const provenancePath = path.join(jobDir, `${base}.provenance.json`);
- const bytesSha256 = sha256(data);
- const candidateEligible = findings.length === 0;
-
- const provenance = {
- schemaVersion: 1,
- generationMethod: "image-generation",
- provider: "openai",
- model,
- generationRunId: requestId,
- generationRunIdKind: requestId ? "provider-request-id" : null,
- localRunId,
- promptSha256,
- referenceInputs: [],
- request: { size, quality, background, outputFormat: "png", n: 1 },
- providerCreatedAt: payload.created ? new Date(payload.created * 1000).toISOString() : null,
- usage: payload.usage ?? null,
- generatedMaster: {
- sandboxOnly: true,
- path: masterPath,
- width: png.width,
- height: png.height,
- format: "png",
- mimeType: "image/png",
- lossless: true,
- alphaStatus: png.hasAlpha ? "present" : "absent",
- bytes: data.length,
- sha256: bytesSha256,
- },
- convertedFromLegacyAsset: false,
- rasterizedFromSvg: false,
- tracedExistingArtwork: false,
- candidateEligible,
- findings,
- createdAt,
- };
-
- try {
- await writeExclusive(masterPath, data);
- await writeExclusive(provenancePath, JSON.stringify(provenance, null, 2) + "\n");
- } catch (error) {
- await fs.rm(masterPath, { force: true }).catch(() => undefined);
- await fs.rm(provenancePath, { force: true }).catch(() => undefined);
- throw error;
- }
-
- let previewUrl: string | null = null;
- let downloadUrl: string | null = null;
- if (data.length <= TEMP_SHARE_MAX_BYTES) {
- try {
- const share = await createTempShare({
- data,
- filename: path.basename(masterPath),
- mimeType: "image/png",
- ttlMs: 30 * 60_000,
- maxDownloads: 5,
- });
- previewUrl = tempShareUrl(share.id);
- downloadUrl = tempShareUrl(share.id, true);
- } catch {
- // The durable sandbox path remains the source of truth when preview creation fails.
- }
- }
-
- return {
- data,
- summary: {
- generationMethod: "image-generation",
- provider: "openai",
- model,
- generationRunId: requestId,
- generationRunIdKind: requestId ? "provider-request-id" : null,
- localRunId,
- promptSha256,
- masterPath,
- provenancePath,
- width: png.width,
- height: png.height,
- format: "png",
- mimeType: "image/png",
- lossless: true,
- alphaStatus: png.hasAlpha ? "present" : "absent",
- bytes: data.length,
- sha256: bytesSha256,
- candidateEligible,
- findings,
- previewUrl,
- downloadUrl,
- createdAt,
- },
- };
-}
-
-export function shouldReturnDirectImage(bytes: number): boolean {
- return bytes > 0 && bytes <= DIRECT_IMAGE_MAX_BYTES;
-}
diff --git a/lib/mcp/dispatch.test.ts b/lib/mcp/dispatch.test.ts
index a67254ca..d7cf767f 100644
--- a/lib/mcp/dispatch.test.ts
+++ b/lib/mcp/dispatch.test.ts
@@ -44,7 +44,7 @@ describe("protocol", () => {
it("publishes server and toolset metadata so action drift is visible", async () => {
const r = await dispatch({ id: 1, method: "initialize" }, "exec");
const result = r.result as { serverInfo: { version: string }; _meta: { toolset: { toolCount: number; hash: string } } };
- expect(result.serverInfo.version).toBe("1.4.1");
+ expect(result.serverInfo.version).toBe("1.5.0");
expect(result._meta.toolset.toolCount).toBe(TOOLS.length);
expect(result._meta.toolset.hash).toMatch(/^[a-f0-9]{16}$/);
});
@@ -85,7 +85,9 @@ describe("tools/list is scope-filtered", () => {
expect(n).toContain("fs_list");
expect(n).toContain("sys_stats");
expect(n).toContain("skills_search");
- expect(n).toContain("image_generation_status");
+ expect(n).toContain("projects_list");
+ expect(n).toContain("skills_list");
+ expect(n).toContain("skills_read");
expect(n).not.toContain("workflow_start");
expect(n).not.toContain("fs_write");
expect(n).not.toContain("exec_run");
@@ -100,7 +102,6 @@ describe("tools/list is scope-filtered", () => {
expect(n).toContain("workflow_finish");
expect(n).not.toContain("exec_run");
expect(n).not.toContain("browser_power");
- expect(n).not.toContain("image_generate");
});
it("shows an exec token the whole catalog", async () => {
@@ -227,7 +228,7 @@ describe("catalog hygiene", () => {
});
it("the irreversible tools carry destructiveHint so clients keep prompting", () => {
- for (const name of ["fs_delete", "exec_run", "browser_power", "image_generate"]) {
+ for (const name of ["fs_delete", "exec_run", "browser_power"]) {
expect(TOOLS.find((t) => t.name === name)?.annotations?.destructiveHint, name).toBe(true);
}
});
diff --git a/lib/mcp/global-tools.test.ts b/lib/mcp/global-tools.test.ts
new file mode 100644
index 00000000..d5ed6fd2
--- /dev/null
+++ b/lib/mcp/global-tools.test.ts
@@ -0,0 +1,142 @@
+import { describe, expect, it, vi } from "vitest";
+vi.mock("server-only", () => ({}));
+
+const { TOOLS } = await import("./tools");
+const { dispatch } = await import("./dispatch");
+const { allows, clampScope, defaultConsentScope, maxScope, parseScope, SCOPES } = await import("./scope");
+const { toolsetInfo } = await import("./toolset");
+
+// THE GLOBAL-CAPABILITY INVARIANT.
+//
+// MSO must never scope its tool catalog to one project, one agent or one playbook.
+// Which tools EXIST is not a security control here — the scope ladder, the path jail
+// and the approval card are. A silently shortened catalog just makes the assistant
+// look broken while the owner believes it is contained.
+//
+// What IS a control, and must survive: the read < write < exec ladder. An operator
+// who opts a deployment down to `read` gets fewer tools because they asked for fewer,
+// not because MSO decided a project needed less.
+
+const names = async (scope: "read" | "write" | "exec") => {
+ const r = await dispatch({ id: 1, method: "tools/list" }, scope);
+ return (r.result as { tools: { name: string }[] }).tools.map((t) => t.name);
+};
+
+describe("an exec token sees the entire public catalog", () => {
+ it("lists every tool, with nothing filtered out", async () => {
+ const listed = await names("exec");
+ expect(listed.sort()).toEqual(TOOLS.map((t) => t.name).sort());
+ });
+
+ it("can CALL every listed tool — nothing is listed-but-refused at exec scope", async () => {
+ // Not executing them (they touch the host); asserting the dispatcher's scope gate
+ // admits each one. A name that lists but cannot be called is the drift that made
+ // "ChatGPT says it has no such tool" a recurring bug report.
+ for (const tool of TOOLS) expect(allows("exec", tool.scope), tool.name).toBe(true);
+ });
+
+ it("reports the same count in the toolset signature clients diff against", async () => {
+ const r = await dispatch({ id: 1, method: "tools/list" }, "exec");
+ const meta = (r.result as { _meta: { toolset: { toolCount: number; names: string[]; hash: string } } })._meta;
+ expect(meta.toolset.toolCount).toBe(TOOLS.length);
+ expect(meta.toolset.names).toEqual([...TOOLS.map((t) => t.name)].sort());
+ expect(toolsetInfo(TOOLS, "exec").hash).toBe(meta.toolset.hash);
+ });
+});
+
+describe("the scope ladder is the ONLY thing that narrows the catalog", () => {
+ it("read and write are strict prefixes of exec, by tier and nothing else", async () => {
+ const [read, write, exec] = await Promise.all([names("read"), names("write"), names("exec")]);
+ expect(read).toEqual(TOOLS.filter((t) => t.scope === "read").map((t) => t.name));
+ expect(write).toEqual(TOOLS.filter((t) => allows("write", t.scope)).map((t) => t.name));
+ expect(exec).toEqual(TOOLS.map((t) => t.name));
+ expect(read.every((n) => write.includes(n))).toBe(true);
+ expect(write.every((n) => exec.includes(n))).toBe(true);
+ });
+
+ it("keeps the read/write opt-down available to an operator", () => {
+ vi.stubEnv("OS_MCP_MAX_SCOPE", "read");
+ expect(maxScope()).toBe("read");
+ expect(clampScope("exec")).toBe("read");
+ vi.stubEnv("OS_MCP_MAX_SCOPE", "write");
+ expect(clampScope("exec")).toBe("write");
+ vi.stubEnv("OS_MCP_MAX_SCOPE", "nonsense");
+ expect(maxScope(), "a malformed ceiling must fail closed, never open").toBe("write");
+ vi.unstubAllEnvs();
+ });
+
+ it("still defaults consent to exec on a deployment that set no ceiling", () => {
+ vi.stubEnv("OS_MCP_MAX_SCOPE", "");
+ expect(maxScope()).toBe("exec");
+ expect(defaultConsentScope(maxScope())).toBe("exec");
+ expect(parseScope(undefined), "an absent request is still least-privilege").toBe("read");
+ vi.unstubAllEnvs();
+ });
+
+ it("has no scope outside the three-tier ladder", () => {
+ expect([...SCOPES]).toEqual(["read", "write", "exec"]);
+ for (const tool of TOOLS) expect(SCOPES, tool.name).toContain(tool.scope);
+ });
+});
+
+describe("no per-project or per-agent tool filter exists", () => {
+ it("exposes an identical catalog regardless of the project a workflow names", async () => {
+ // The catalog is a module-level constant with no project input. If someone adds
+ // one, `visibleTools` stops being a pure function of scope and this breaks.
+ const first = await names("exec");
+ const second = await names("exec");
+ expect(first).toEqual(second);
+ expect(TOOLS.every((t) => typeof t.run === "function")).toBe(true);
+ });
+
+ it("advertises workflow_id as CONTEXT, never as a capability filter", () => {
+ // Every operational tool carries an optional workflow_id. It correlates steps;
+ // it must not be required, or a client without a workflow would lose the tool.
+ for (const tool of TOOLS) {
+ if (["skills_search", "workflow_start", "workflow_cancel", "workflow_finish"].includes(tool.name)) continue;
+ expect(Object.keys(tool.inputSchema.properties), tool.name).toContain("workflow_id");
+ expect(tool.inputSchema.required ?? [], tool.name).not.toContain("workflow_id");
+ }
+ });
+});
+
+describe("image generation is gone from every surface", () => {
+ it("exposes no image-generation tool at any scope", async () => {
+ const exec = await names("exec");
+ expect(exec.filter((n) => /image_gener/i.test(n))).toEqual([]);
+ expect(TOOLS.filter((t) => /image_gener/i.test(t.name))).toEqual([]);
+ });
+
+ it("does not advertise image generation in a description either", () => {
+ // A description that says "generate an image" is a tool call the model will try.
+ const offenders = TOOLS.filter((t) => /generate[sd]? (?:an? )?(?:new )?(?:raster |png )?image/i.test(t.description));
+ expect(offenders.map((t) => t.name)).toEqual([]);
+ });
+
+ it("never tells the client to prefer a native or provider image tool", () => {
+ const wording = /(native|provider|built-?in).{0,40}image (generation|tool)/i;
+ expect(TOOLS.filter((t) => wording.test(t.description)).map((t) => t.name)).toEqual([]);
+ });
+});
+
+describe("file import survives the image-generation removal", () => {
+ it("keeps fs_upload_file with its ChatGPT file-parameter binding", () => {
+ const upload = TOOLS.find((t) => t.name === "fs_upload_file");
+ expect(upload).toBeDefined();
+ expect(upload!.scope).toBe("write");
+ expect(upload!.meta).toEqual({ "openai/fileParams": ["file"] });
+ expect(upload!.inputSchema.required).toEqual(["file", "dest"]);
+ expect(upload!.limit).toMatchObject({ key: "fs.upload", max: 20 });
+ });
+
+ it("is reachable by a write token, so importing a ChatGPT file needs no shell", async () => {
+ expect(await names("write")).toContain("fs_upload_file");
+ });
+});
+
+describe("global discovery is part of the public catalog", () => {
+ it("ships projects_list, skills_list and skills_read at read scope", async () => {
+ const read = await names("read");
+ for (const name of ["projects_list", "skills_list", "skills_read", "skills_search"]) expect(read).toContain(name);
+ });
+});
diff --git a/lib/mcp/parity.test.ts b/lib/mcp/parity.test.ts
index 9eec35b2..6edc3294 100644
--- a/lib/mcp/parity.test.ts
+++ b/lib/mcp/parity.test.ts
@@ -28,16 +28,13 @@ const capability = (name: string) => name.replace(/[._]/g, ".");
* reason. If a reason stops being true, delete the line and add the tool. */
const ALFA_ONLY: Record<string, string> = {
"app.open": "openWindow is browser store state; an MCP client has no window to open",
- "skills.list": "the skill catalog is the assistant's own prompt furniture, not host control",
- "skills.read": "same — and /api/skills reads outside the fs jail, so it stays off a bearer-reached surface",
"memory.remember": "writes into the owner's Alfa recall, which an MCP client does not share",
"memory.forget": "same store; an MCP client has its own memory",
};
const MCP_ONLY: Record<string, string> = {
"screen.capture": "external MCP clients need visual proof of the rendered OS; in-shell Alfa already runs inside that browser UI",
- "image.generation.status": "provider readiness is exposed to external asset agents; Alfa currently has no image-generation output renderer",
- "image.generate": "the external asset agent needs provider bytes, durable sandbox paths and provenance; Alfa currently cannot render or persist provider image output",
+ "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",
"fs.upload.file": "external ChatGPT connectors need openai/fileParams to move conversation-generated files onto the VPS; in-shell Alfa already has direct host filesystem access",
"workflow.start": "the external connector needs an actor-scoped task boundary; Alfa already owns an in-app conversation/run boundary",
"workflow.cancel": "same actor-scoped boundary; external runs need explicit recovery from an interrupted task",
@@ -102,7 +99,11 @@ describe("MCP rate limits mirror the routes", () => {
// MCP clients and is expensive enough to deserve a much smaller bucket.
"screen.capture": 10,
"workflow.memory": 30,
- "image.generate": 5,
+ // Global discovery reads: no HTTP route mirrors them, and each one walks
+ // every configured container, so they get their own small buckets.
+ "projects.list": 30,
+ "skills.list": 30,
+ "skills.read": 60,
};
for (const t of TOOLS) {
if (!t.limit) continue;
diff --git a/lib/mcp/tools-discovery.test.ts b/lib/mcp/tools-discovery.test.ts
new file mode 100644
index 00000000..2d3f7b6d
--- /dev/null
+++ b/lib/mcp/tools-discovery.test.ts
@@ -0,0 +1,122 @@
+import { afterAll, describe, expect, it, vi } from "vitest";
+vi.mock("server-only", () => ({}));
+import { promises as fs } from "fs";
+import os from "os";
+import path from "path";
+
+// One temp container holding two projects. OS_FS_READ_ROOTS is pointed at it so the
+// project half of the catalog is deterministic; the GLOBAL half still comes from the
+// real repo (`claude-skills/`), which is exactly what these tools are supposed to
+// merge, so assertions below check containment rather than exact equality.
+const workspace = await fs.mkdtemp(path.join(os.tmpdir(), "mso-discovery-"));
+const widget = path.join(workspace, "widget");
+const gadget = path.join(workspace, "gadget");
+await fs.mkdir(path.join(widget, ".claude/skills/widget-deploy"), { recursive: true });
+await fs.writeFile(
+ path.join(widget, ".claude/skills/widget-deploy/SKILL.md"),
+ "---\nname: widget-deploy\ndescription: Ship the widget service.\n---\n\n# Widget deploy\n\nstep one\n",
+);
+await fs.writeFile(path.join(widget, "package.json"), JSON.stringify({ name: "widget", version: "0.1.0" }));
+// A project skill whose SKILL.md is a symlink: discoverable, but never trusted.
+await fs.mkdir(path.join(gadget, ".codex/skills/gadget-wild"), { recursive: true });
+await fs.writeFile(path.join(gadget, "SKILL.md"), "---\nname: gadget-wild\ndescription: Unverified.\n---\n\n# wild\n");
+await fs.symlink(path.join(gadget, "SKILL.md"), path.join(gadget, ".codex/skills/gadget-wild/SKILL.md"));
+
+const previous = process.env.OS_FS_READ_ROOTS;
+process.env.OS_FS_READ_ROOTS = workspace;
+const { DISCOVERY_TOOLS } = await import("./tools-discovery");
+
+const tool = (name: string) => {
+ const found = DISCOVERY_TOOLS.find((t) => t.name === name);
+ if (!found) throw new Error(`missing ${name}`);
+ return found;
+};
+const run = (name: string, args: Record<string, unknown> = {}) =>
+ tool(name).run(args, { scope: "read" as const });
+
+type SkillRow = { id: string; trust: string; instructionsReadable: boolean; project?: { name: string } };
+
+afterAll(async () => {
+ if (previous === undefined) delete process.env.OS_FS_READ_ROOTS;
+ else process.env.OS_FS_READ_ROOTS = previous;
+ await fs.rm(workspace, { recursive: true, force: true });
+});
+
+describe("projects_list", () => {
+ it("is a read tool with a read-only annotation", () => {
+ expect(tool("projects_list").scope).toBe("read");
+ expect(tool("projects_list").annotations?.readOnlyHint).toBe(true);
+ });
+
+ it("enumerates every project in the configured container with bounded metadata", async () => {
+ const result = await run("projects_list") as { total: number; projects: Array<{ name: string; packageName?: string }> };
+ expect(result.projects.map((p) => p.name)).toEqual(["gadget", "widget"]);
+ expect(result.projects.find((p) => p.name === "widget")?.packageName).toBe("widget");
+ expect(result.total).toBe(2);
+ });
+
+ it("filters and paginates", async () => {
+ const result = await run("projects_list", { query: "wid", limit: 1 }) as { total: number; limit: number; projects: Array<{ name: string }> };
+ expect(result).toMatchObject({ total: 1, limit: 1 });
+ expect(result.projects.map((p) => p.name)).toEqual(["widget"]);
+ });
+});
+
+describe("skills_list spans global and project roots", () => {
+ it("returns official repo skills AND per-project skills in one catalog", async () => {
+ const { skills } = await run("skills_list", { limit: 200 }) as { skills: SkillRow[] };
+ const ids = skills.map((s) => s.id);
+ expect(ids).toContain("mso"); // official, from this repo's claude-skills/
+ expect(ids).toContain("widget/widget-deploy");
+ expect(skills.find((s) => s.id === "widget/widget-deploy")).toMatchObject({
+ trust: "local", instructionsReadable: true, project: { name: "widget" },
+ });
+ });
+
+ it("marks a project skill with a symlinked SKILL.md untrusted and unreadable", async () => {
+ const { skills } = await run("skills_list", { limit: 200 }) as { skills: SkillRow[] };
+ expect(skills.find((s) => s.id === "gadget/gadget-wild")).toMatchObject({
+ trust: "untrusted", instructionsReadable: false,
+ });
+ });
+
+ it("filters by project and by trust", async () => {
+ const byProject = await run("skills_list", { project: "widget" }) as { skills: SkillRow[] };
+ expect(byProject.skills.map((s) => s.id)).toEqual(["widget/widget-deploy"]);
+ const official = await run("skills_list", { trust: "official", limit: 200 }) as { skills: SkillRow[] };
+ expect(official.skills.every((s) => s.trust === "official")).toBe(true);
+ expect(official.skills.some((s) => s.project)).toBe(false);
+ });
+});
+
+describe("skills_read reads the exact catalog id only", () => {
+ it("returns instructions for a trusted project skill", async () => {
+ const result = await run("skills_read", { name: "widget/widget-deploy" }) as { content: string; project: { name: string }; trust: string };
+ expect(result.trust).toBe("local");
+ expect(result.project.name).toBe("widget");
+ expect(result.content).toContain("# Widget deploy");
+ });
+
+ it("returns instructions for an official global skill", async () => {
+ const result = await run("skills_read", { name: "mso" }) as { content: string; trust: string };
+ expect(result.trust).toBe("official");
+ expect(result.content.length).toBeGreaterThan(0);
+ });
+
+ it("withholds instructions for an untrusted skill but still reports metadata", async () => {
+ const result = await run("skills_read", { name: "gadget/gadget-wild" }) as {
+ instructionsWithheld: boolean; reason: string; content?: string; trust: string;
+ };
+ expect(result).toMatchObject({ instructionsWithheld: true, trust: "untrusted" });
+ expect(result.content).toBeUndefined();
+ expect(result.reason).toContain("~/.mso/skills");
+ });
+
+ it("refuses the bare name of a project skill — the namespaced id is the address", async () => {
+ await expect(run("skills_read", { name: "widget-deploy" })).rejects.toThrow(/unknown skill id/);
+ });
+
+ it("refuses an unknown id rather than guessing", async () => {
+ await expect(run("skills_read", { name: "does-not-exist" })).rejects.toThrow(/skills_list/);
+ });
+});
diff --git a/lib/mcp/tools-discovery.ts b/lib/mcp/tools-discovery.ts
new file mode 100644
index 00000000..35e06d6f
--- /dev/null
+++ b/lib/mcp/tools-discovery.ts
@@ -0,0 +1,117 @@
+import { listProjects, PROJECT_LIMITS } from "@/lib/host";
+import { catalogSkills, findSkill, readSkillFile, skillIsExecutableByDefault } from "@/lib/skills/catalog";
+import { type McpTool, str, opt, S, READ_ONLY } from "./tool-kit";
+
+// GLOBAL discovery: every project container the owner configured, and every skill
+// root inside them. MSO used to answer both questions from `~/projects` and the
+// global skill roots alone, which quietly told a connected client that a
+// multi-project box had one project and no project skills. All three tools are
+// `read` — enumerating what exists changes nothing, and a read token is exactly the
+// grant an agent should need to plan its work.
+
+const SKILL_CONTENT_LIMIT = 24_000;
+const SKILL_PAGE_MAX = 200;
+
+const page = (a: Record<string, unknown>, max: number, fallback: number) => ({
+ limit: Math.min(Math.max(Math.round(typeof a.limit === "number" ? a.limit : fallback), 1), max),
+ offset: Math.max(Math.round(typeof a.offset === "number" ? a.offset : 0), 0),
+});
+
+export const DISCOVERY_TOOLS: McpTool[] = [
+ {
+ name: "projects_list",
+ description:
+ "Enumerate the owner's projects across EVERY configured project container (each OS_FS_READ_ROOTS entry and its projects/ subdirectory), not just ~/projects. " +
+ "Returns name, absolute path, its container root, package name/version and bounded Git branch/head read straight off .git with no shell. " +
+ "USE THIS FIRST when the user names a project you have not located — it is one call, needs no shell scope, and is the input to workflow_start's project hint. " +
+ "Hidden directories, symlinks and credential paths are excluded; results are paginated.",
+ scope: "read",
+ annotations: READ_ONLY,
+ limit: { key: "projects.list", max: 30, windowMs: 60_000 },
+ inputSchema: S({
+ query: { type: "string", description: "Optional case-insensitive substring matched against the directory name." },
+ limit: { type: "number", minimum: 1, maximum: PROJECT_LIMITS.maxPageSize, description: `Page size. Default ${PROJECT_LIMITS.defaultPageSize}.` },
+ offset: { type: "number", minimum: 0, description: "Page offset into the deterministic root-then-name ordering. Default 0." },
+ }),
+ run: (a) => listProjects({ query: opt(a, "query"), ...page(a, PROJECT_LIMITS.maxPageSize, PROJECT_LIMITS.defaultPageSize) }),
+ },
+ {
+ name: "skills_list",
+ description:
+ "List every SKILL.md MSO can see: the global roots (operator ~/.mso/skills, official MSO skills, hash-verified bundles, generic agent registries) AND the per-project roots " +
+ "(.mso/skills, .claude/skills, .hermes/skills, .agents/skills, .codex/skills) of every project across every configured container. " +
+ "Each row carries the exact catalog id to pass to skills_read — a project skill is addressed as <project>/<name>, so two projects may ship the same skill name — plus trust, source and its project. " +
+ "Trust is earned, not assumed: a project skill is only `local` after realpath containment, owner uid and a regular non-symlink SKILL.md.",
+ scope: "read",
+ annotations: READ_ONLY,
+ limit: { key: "skills.list", max: 30, windowMs: 60_000 },
+ inputSchema: S({
+ project: { type: "string", description: "Optional project name or absolute path; keeps only skills belonging to that project." },
+ trust: { type: "string", enum: ["official", "verified", "local", "untrusted"], description: "Optional exact trust filter." },
+ query: { type: "string", description: "Optional case-insensitive substring matched against id and description." },
+ limit: { type: "number", minimum: 1, maximum: SKILL_PAGE_MAX, description: "Page size. Default 100." },
+ offset: { type: "number", minimum: 0, description: "Page offset into the id-sorted catalog. Default 0." },
+ }),
+ run: async (a) => {
+ const project = opt(a, "project");
+ const trust = opt(a, "trust");
+ const query = opt(a, "query")?.toLowerCase();
+ const all = await catalogSkills();
+ const matched = all.filter((skill) => {
+ if (project && skill.project?.name !== project && skill.project?.path !== project) return false;
+ if (trust && skill.trust !== trust) return false;
+ if (query && !`${skill.id} ${skill.description}`.toLowerCase().includes(query)) return false;
+ return true;
+ });
+ const { limit, offset } = page(a, SKILL_PAGE_MAX, 100);
+ return {
+ total: matched.length,
+ offset,
+ limit,
+ skills: matched.slice(offset, offset + limit).map((skill) => ({
+ id: skill.id,
+ name: skill.name,
+ description: skill.description,
+ source: skill.source,
+ trust: skill.trust,
+ instructionsReadable: skillIsExecutableByDefault(skill),
+ ...(skill.project ? { project: skill.project } : {}),
+ ...(skill.provenance ? { provenance: skill.provenance } : {}),
+ })),
+ };
+ },
+ },
+ {
+ name: "skills_read",
+ description:
+ "Read one skill's SKILL.md by its EXACT catalog id from skills_list or skills_search (a project skill is <project>/<name>). " +
+ "Instructions are returned for official, hash-verified, operator-local and ownership-verified project skills. " +
+ "An untrusted skill returns metadata only — inspect it as a file and move it into ~/.mso/skills after review to promote it. " +
+ "The reader opens only a realpath'd file named SKILL.md, so a link pointing elsewhere is refused rather than followed.",
+ scope: "read",
+ annotations: READ_ONLY,
+ limit: { key: "skills.read", max: 60, windowMs: 60_000 },
+ inputSchema: S({
+ name: { type: "string", description: "Exact catalog id from skills_list. Fuzzy names are not resolved here." },
+ }, ["name"]),
+ run: async (a) => {
+ const id = str(a, "name");
+ const skill = findSkill(await catalogSkills(), id);
+ if (!skill) throw new Error(`unknown skill id "${id}" — call skills_list for the exact ids`);
+ const meta = {
+ id: skill.id, name: skill.name, description: skill.description, source: skill.source, trust: skill.trust,
+ ...(skill.project ? { project: skill.project } : {}),
+ };
+ if (!skillIsExecutableByDefault(skill)) {
+ return {
+ ...meta,
+ instructionsWithheld: true,
+ reason: `trust=${skill.trust}: MSO does not feed unreviewed skill instructions to a model. Read ${skill.path} as a file, then move the reviewed skill into ~/.mso/skills to promote it.`,
+ };
+ }
+ const content = await readSkillFile(skill.path);
+ if (content === null) throw new Error(`skill "${id}" no longer has a readable SKILL.md`);
+ return { ...meta, content: content.slice(0, SKILL_CONTENT_LIMIT), truncated: content.length > SKILL_CONTENT_LIMIT };
+ },
+ },
+];
diff --git a/lib/mcp/tools-learning.test.ts b/lib/mcp/tools-learning.test.ts
index 76234185..1d6fcb5f 100644
--- a/lib/mcp/tools-learning.test.ts
+++ b/lib/mcp/tools-learning.test.ts
@@ -11,6 +11,16 @@ await fs.mkdir(project);
await fs.writeFile(path.join(project, "package.json"), JSON.stringify({
name: "mso", version: "9.9.9", scripts: { test: "vitest", build: "next build" },
}));
+// A skill living inside a DIFFERENT project than the one the workflow names. The
+// bootstrap search must still find it: capability discovery is global, and an agent
+// that can only see the current project's skills relearns what the box already knows.
+const sibling = path.join(dir, "orchard");
+await fs.mkdir(path.join(sibling, ".claude/skills/orchard-harvest"), { recursive: true });
+await fs.writeFile(
+ path.join(sibling, ".claude/skills/orchard-harvest/SKILL.md"),
+ "---\nname: orchard-harvest\ndescription: Harvest and verify the orchard dataset export.\n---\n\n# Orchard harvest\n",
+);
+
const previous = {
read: process.env.OS_FS_READ_ROOTS,
write: process.env.OS_FS_WRITE_ROOTS,
@@ -76,6 +86,22 @@ describe("workflow_start bootstrap", () => {
]));
});
+ it("searches skills from EVERY project, not just the one the workflow names", async () => {
+ const start = LEARNING_TOOLS.find((tool) => tool.name === "workflow_start")!;
+ const result = await start.run({
+ intent: "harvest and verify the orchard dataset export",
+ project, // deliberately the OTHER project
+ }, { actor: "mcp:global-skills", scope: "write" as const }) as {
+ search: { hits: Array<{ kind: string; id: string; name: string; trust?: string; project?: { name: string } }> };
+ };
+ expect(result.search.hits).toEqual(expect.arrayContaining([
+ expect.objectContaining({
+ kind: "skill", id: "orchard/orchard-harvest", name: "orchard-harvest",
+ trust: "local", project: { name: "orchard", path: sibling },
+ }),
+ ]));
+ });
+
it("supports parallel conversations and exposes explicit cancel/finish ids", async () => {
const start = LEARNING_TOOLS.find((tool) => tool.name === "workflow_start")!;
const cancel = LEARNING_TOOLS.find((tool) => tool.name === "workflow_cancel")!;
diff --git a/lib/mcp/tools-power.ts b/lib/mcp/tools-power.ts
new file mode 100644
index 00000000..9c4078f3
--- /dev/null
+++ b/lib/mcp/tools-power.ts
@@ -0,0 +1,56 @@
+import { setCamoufoxEnabled } from "@/lib/camoufox/service";
+import { performManagedAppAction } from "@/lib/managed-apps/manager";
+import { isManagedAppId } from "@/lib/managed-apps/catalog";
+import { MANAGED_APP_ACTIONS, type ManagedAppAction } from "@/lib/managed-apps/types";
+import { type McpTool, str, S } from "./tool-kit";
+
+// Powering long-lived host state on and off: managed daemons and the Camoufox
+// session. Split from tools.ts, which is the fs write tier plus the catalog
+// assembly — both files stay readable and under the 200-line ceiling.
+export const POWER_TOOLS: McpTool[] = [
+ {
+ name: "apps_power",
+ limit: { key: "managed-app", max: 12, windowMs: 60_000, keyArg: "id" },
+ audit: { action: "managed-app.action" as const, targetArg: "id" },
+ description:
+ "Start, stop, restart or back up a managed application on the VPS. Bounded to the known apps and " +
+ "those four verbs — restarting a daemon should not require handing over a shell, so this sits at " +
+ "write scope rather than exec. Check apps_list or apps_logs first.",
+ scope: "write",
+ annotations: { destructiveHint: true },
+ // The verb list is READ from MANAGED_APP_ACTIONS, never retyped. It was retyped,
+ // and `backup` — a real action with a real route, taken automatically before
+ // every update — was missing from the enum AND from the guard below, so an MCP
+ // client could not take one and was told the tool only did three things.
+ inputSchema: S({
+ id: { type: "string", description: "Managed app id from apps_list." },
+ action: { type: "string", enum: [...MANAGED_APP_ACTIONS], description: MANAGED_APP_ACTIONS.join(" | ") },
+ }, ["id", "action"]),
+ run: (a) => {
+ const id = str(a, "id");
+ const action = str(a, "action");
+ if (!isManagedAppId(id)) throw new Error(`unknown managed application "${id}" — call apps_list for valid ids`);
+ if (!(MANAGED_APP_ACTIONS as readonly string[]).includes(action))
+ throw new Error(`action must be one of ${MANAGED_APP_ACTIONS.join(", ")}`);
+ // `{ app }`, matching POST /api/v1/managed-apps/[id]. Same capability, same
+ // envelope — a client that learned the shape from the CLI or the route must
+ // not have to learn a second one here.
+ return performManagedAppAction(id, action as ManagedAppAction).then((app) => ({ app }));
+ },
+ },
+ {
+ name: "browser_power",
+ limit: { key: "camoufox", max: 12, windowMs: 60_000 },
+ audit: { action: "camoufox.power" as const, targetArg: "on" },
+ description:
+ "Start or stop the Camoufox browser session on the VPS. Starting boots a real Firefox on a headless " +
+ "X display; the session self-terminates after 2h. Stop it when done — it holds a live logged-in profile.",
+ scope: "exec",
+ annotations: { destructiveHint: true },
+ inputSchema: S({ on: { type: "boolean", description: "true = start, false = stop." } }, ["on"]),
+ run: async (a) => {
+ const s = await setCamoufoxEnabled(a.on === true);
+ return { installed: s.installed, running: s.running, autostart: s.enabled };
+ },
+ },
+];
diff --git a/lib/mcp/tools-read.ts b/lib/mcp/tools-read.ts
index f350d1e6..7e120ae3 100644
--- a/lib/mcp/tools-read.ts
+++ b/lib/mcp/tools-read.ts
@@ -2,7 +2,6 @@ import { listDir, readFile, searchFs, usage, stats, processes, captureMsoScreen,
import { camoufoxStatus } from "@/lib/camoufox/service";
import { listManagedApps, getManagedAppLogs } from "@/lib/managed-apps/manager";
import { searchSkillMemory } from "@/lib/skills/search";
-import { imageGenerationStatus } from "@/lib/image-generation/openai";
import { isManagedAppId } from "@/lib/managed-apps/catalog";
import { type McpTool, str, opt, S, PATH_P, READ_ONLY, mcpDirect } from "./tool-kit";
@@ -127,16 +126,6 @@ export const READ_TOOLS: McpTool[] = [
});
},
},
- {
- name: "image_generation_status",
- description:
- "Check whether the official OpenAI Images API is configured, which model/output root will be used, and which sizes/background modes are available. " +
- "This never generates an image, spends credits, or exposes the API key.",
- scope: "read",
- annotations: READ_ONLY,
- inputSchema: S({}),
- run: () => imageGenerationStatus(),
- },
{
name: "screen_capture",
description:
diff --git a/lib/mcp/tools.ts b/lib/mcp/tools.ts
index 3a560bde..427c93d9 100644
--- a/lib/mcp/tools.ts
+++ b/lib/mcp/tools.ts
@@ -1,24 +1,10 @@
import { writeFileGuarded, makeDir, remove, move, copy, runCommand } from "@/lib/host";
-import { setCamoufoxEnabled } from "@/lib/camoufox/service";
-import { performManagedAppAction } from "@/lib/managed-apps/manager";
-import { isManagedAppId } from "@/lib/managed-apps/catalog";
-import { MANAGED_APP_ACTIONS, type ManagedAppAction } from "@/lib/managed-apps/types";
-import { type McpTool, str, opt, S, PATH_P, mcpDirect } from "./tool-kit";
+import { type McpTool, str, opt, S, PATH_P } from "./tool-kit";
import { importOpenAiProvidedFile } from "./openai-file-upload";
-import {
- generateOpenAiImage,
- OPENAI_IMAGE_BACKGROUNDS,
- OPENAI_IMAGE_MODELS,
- OPENAI_IMAGE_QUALITIES,
- OPENAI_IMAGE_SIZES,
- shouldReturnDirectImage,
- type OpenAiImageBackground,
- type OpenAiImageModel,
- type OpenAiImageQuality,
- type OpenAiImageSize,
-} from "@/lib/image-generation/openai";
import { READ_TOOLS } from "./tools-read";
+import { DISCOVERY_TOOLS } from "./tools-discovery";
import { LEARNING_TOOLS } from "./tools-learning";
+import { POWER_TOOLS } from "./tools-power";
// The write and exec tiers. Each carries an `audit` descriptor — the dispatcher,
// not the tool, writes the trail, because these call lib/host directly and so
@@ -120,73 +106,6 @@ const MUTATE_TOOLS: McpTool[] = [
run: async (a) => { await remove(str(a, "path")); return { ok: true, path: a.path }; },
},
- {
- name: "apps_power",
- limit: { key: "managed-app", max: 12, windowMs: 60_000, keyArg: "id" },
- audit: { action: "managed-app.action" as const, targetArg: "id" },
- description:
- "Start, stop, restart or back up a managed application on the VPS. Bounded to the known apps and " +
- "those four verbs — restarting a daemon should not require handing over a shell, so this sits at " +
- "write scope rather than exec. Check apps_list or apps_logs first.",
- scope: "write",
- annotations: { destructiveHint: true },
- // The verb list is READ from MANAGED_APP_ACTIONS, never retyped. It was retyped,
- // and `backup` — a real action with a real route, taken automatically before
- // every update — was missing from the enum AND from the guard below, so an MCP
- // client could not take one and was told the tool only did three things.
- inputSchema: S({
- id: { type: "string", description: "Managed app id from apps_list." },
- action: { type: "string", enum: [...MANAGED_APP_ACTIONS], description: MANAGED_APP_ACTIONS.join(" | ") },
- }, ["id", "action"]),
- run: (a) => {
- const id = str(a, "id");
- const action = str(a, "action");
- if (!isManagedAppId(id)) throw new Error(`unknown managed application "${id}" — call apps_list for valid ids`);
- if (!(MANAGED_APP_ACTIONS as readonly string[]).includes(action))
- throw new Error(`action must be one of ${MANAGED_APP_ACTIONS.join(", ")}`);
- // `{ app }`, matching POST /api/v1/managed-apps/[id]. Same capability, same
- // envelope — a client that learned the shape from the CLI or the route must
- // not have to learn a second one here.
- return performManagedAppAction(id, action as ManagedAppAction).then((app) => ({ app }));
- },
- },
- {
- name: "image_generate",
- limit: { key: "image.generate", max: 5, windowMs: 60_000 },
- audit: { action: "image.generate" as const, targetArg: "project" },
- description:
- "Generate exactly one genuinely new raster image through the official OpenAI Images API. " +
- "The provider response is saved as a lossless PNG sandbox master under OS_IMAGE_OUTPUT_ROOT and accompanied by prompt SHA-256, byte SHA-256, dimensions, alpha status, provider/model/request id, and a provenance sidecar. " +
- "This is a billed external operation and requires an OpenAI API key configured in MSO Settings → AI or OPENAI_API_KEY.",
- scope: "exec",
- annotations: { destructiveHint: true, openWorldHint: true },
- inputSchema: S({
- prompt: { type: "string", description: "Complete image-generation prompt. It is sent to OpenAI but never stored in MCP activity or workflow memory." },
- project: { type: "string", description: "Safe project slug used only to organize the sandbox output directory. Default general." },
- filename_stem: { type: "string", description: "Safe filename stem. A timestamp and random run id are always added." },
- model: { type: "string", enum: [...OPENAI_IMAGE_MODELS], description: "OpenAI image model. Default OS_IMAGE_MODEL or gpt-image-2. Transparent requests default to gpt-image-1.5." },
- size: { type: "string", enum: [...OPENAI_IMAGE_SIZES], description: "Requested output size. Default 1024x1024." },
- quality: { type: "string", enum: [...OPENAI_IMAGE_QUALITIES], description: "Provider quality. Default high." },
- background: { type: "string", enum: [...OPENAI_IMAGE_BACKGROUNDS], description: "auto, opaque, or transparent. gpt-image-2 does not support transparent output." },
- }, ["prompt"]),
- run: async (a) => {
- const result = await generateOpenAiImage({
- prompt: str(a, "prompt"),
- project: opt(a, "project"),
- filenameStem: opt(a, "filename_stem"),
- model: opt(a, "model") as OpenAiImageModel | undefined,
- size: opt(a, "size") as OpenAiImageSize | undefined,
- quality: opt(a, "quality") as OpenAiImageQuality | undefined,
- background: opt(a, "background") as OpenAiImageBackground | undefined,
- });
- const content: Array<{ type: "image"; data: string; mimeType: string } | { type: "text"; text: string }> = [];
- if (shouldReturnDirectImage(result.data.byteLength)) {
- content.push({ type: "image", data: result.data.toString("base64"), mimeType: "image/png" });
- }
- content.push({ type: "text", text: JSON.stringify(result.summary, null, 2) });
- return mcpDirect(content);
- },
- },
{
name: "exec_run",
limit: { key: "exec", max: 60, windowMs: 60_000 },
@@ -216,21 +135,6 @@ const MUTATE_TOOLS: McpTool[] = [
}, ["command"]),
run: (a) => runCommand(str(a, "command"), opt(a, "cwd")),
},
- {
- name: "browser_power",
- limit: { key: "camoufox", max: 12, windowMs: 60_000 },
- audit: { action: "camoufox.power" as const, targetArg: "on" },
- description:
- "Start or stop the Camoufox browser session on the VPS. Starting boots a real Firefox on a headless " +
- "X display; the session self-terminates after 2h. Stop it when done — it holds a live logged-in profile.",
- scope: "exec",
- annotations: { destructiveHint: true },
- inputSchema: S({ on: { type: "boolean", description: "true = start, false = stop." } }, ["on"]),
- run: async (a) => {
- const s = await setCamoufoxEnabled(a.on === true);
- return { installed: s.installed, running: s.running, autostart: s.enabled };
- },
- },
];
const WORKFLOW_CONTEXT_EXEMPT = new Set(["skills_search", "workflow_start", "workflow_cancel", "workflow_finish"]);
@@ -249,6 +153,6 @@ const withWorkflowContext = (tool: McpTool): McpTool => WORKFLOW_CONTEXT_EXEMPT.
},
});
-export const TOOLS: McpTool[] = [...READ_TOOLS, ...LEARNING_TOOLS, ...MUTATE_TOOLS].map(withWorkflowContext);
+export const TOOLS: McpTool[] = [...READ_TOOLS, ...DISCOVERY_TOOLS, ...LEARNING_TOOLS, ...MUTATE_TOOLS, ...POWER_TOOLS].map(withWorkflowContext);
export const TOOLS_BY_NAME = new Map(TOOLS.map((t) => [t.name, t]));
export type { McpTool } from "./tool-kit";
diff --git a/lib/mcp/toolset.ts b/lib/mcp/toolset.ts
index f92a86c5..46b699c3 100644
--- a/lib/mcp/toolset.ts
+++ b/lib/mcp/toolset.ts
@@ -2,9 +2,9 @@ import { createHash } from "crypto";
import type { Scope } from "./scope";
import type { McpTool } from "./tool-kit";
-export const MCP_SERVER_VERSION = "1.4.1";
-export const MCP_TOOLSET_VERSION = "2026.08.20.2";
-export const MCP_TOOLSET_CHANGED_AT = "2026-08-19T21:24:00Z";
+export const MCP_SERVER_VERSION = "1.5.0";
+export const MCP_TOOLSET_VERSION = "2026.08.20.3";
+export const MCP_TOOLSET_CHANGED_AT = "2026-08-20T12:00:00Z";
export type McpToolsetInfo = {
serverVersion: string;
diff --git a/lib/skills/catalog-types.ts b/lib/skills/catalog-types.ts
new file mode 100644
index 00000000..9f0bbbba
--- /dev/null
+++ b/lib/skills/catalog-types.ts
@@ -0,0 +1,29 @@
+// The catalog's shared vocabulary. Split from catalog.ts so per-project discovery
+// can depend on the types without an import cycle back through the scanner.
+
+export const SKILL_FILE = "SKILL.md";
+
+export type SkillTrust = "official" | "verified" | "local" | "untrusted";
+export type SkillSource = "mso" | "bundled" | "operator" | "claude" | "agents" | "codex" | "openclaw" | "project";
+
+export type SkillInfo = {
+ /** The exact catalog id, and the ONLY key `skills_read` accepts. Global skills are
+ * addressed by bare name; a project skill is `<project>/<name>`, so two projects
+ * may ship `deploy` without either one shadowing the other — or an official skill. */
+ id: string;
+ name: string;
+ path: string;
+ description: string;
+ source: SkillSource;
+ trust: SkillTrust;
+ /** Present only for a skill discovered inside a project checkout. */
+ project?: { name: string; path: string };
+ provenance?: {
+ registry?: string;
+ owner?: string;
+ version?: string;
+ sha256?: string;
+ };
+};
+
+export const skillIsExecutableByDefault = (skill: Pick<SkillInfo, "trust">): boolean => skill.trust !== "untrusted";
diff --git a/lib/skills/catalog.test.ts b/lib/skills/catalog.test.ts
index 082c9149..b4202fa6 100644
--- a/lib/skills/catalog.test.ts
+++ b/lib/skills/catalog.test.ts
@@ -24,12 +24,16 @@ async function skill(dir: string, name: string, description: string) {
return { target, md };
}
+// `projectDirs: []` keeps these cases about GLOBAL root precedence. Without it the
+// catalog also walks the real box's project containers, and the assertions would
+// depend on which projects happen to be checked out on the machine running them.
+// Per-project discovery has its own file: project-skills.test.ts.
describe("skill catalog trust and precedence", () => {
it("finds official repo skills without ~/.claude symlinks", async () => {
const app = await temp();
const home = await temp();
await skill(path.join(app, "claude-skills"), "mso", "official");
- const rows = await catalogSkills({ appDir: app, homeDir: home });
+ const rows = await catalogSkills({ appDir: app, homeDir: home, projectDirs: [] });
expect(rows).toMatchObject([{ name: "mso", source: "mso", trust: "official", description: "official" }]);
});
@@ -38,7 +42,7 @@ describe("skill catalog trust and precedence", () => {
const home = await temp();
await skill(path.join(app, "claude-skills"), "mso", "official");
await skill(path.join(home, ".claude/skills"), "mso", "host override");
- const [row] = await catalogSkills({ appDir: app, homeDir: home });
+ const [row] = await catalogSkills({ appDir: app, homeDir: home, projectDirs: [] });
expect(row).toMatchObject({ name: "mso", source: "mso", trust: "official", description: "official" });
});
@@ -47,7 +51,7 @@ describe("skill catalog trust and precedence", () => {
const home = await temp();
await skill(path.join(app, "claude-skills"), "mso", "official");
await skill(path.join(home, ".mso/skills"), "mso", "operator override");
- const [row] = await catalogSkills({ appDir: app, homeDir: home });
+ const [row] = await catalogSkills({ appDir: app, homeDir: home, projectDirs: [] });
expect(row).toMatchObject({ name: "mso", source: "operator", trust: "local", description: "operator override" });
});
@@ -58,11 +62,11 @@ describe("skill catalog trust and precedence", () => {
await mkdir(path.join(target, ".clawhub"), { recursive: true });
const sha256 = createHash("sha256").update(md).digest("hex");
await writeFile(path.join(target, ".clawhub/origin.json"), JSON.stringify({ registry: "https://clawhub.ai", ownerHandle: "alice", installedVersion: "1.2.3", skillFile: { sha256 } }));
- let [row] = await catalogSkills({ appDir: app, homeDir: home });
+ let [row] = await catalogSkills({ appDir: app, homeDir: home, projectDirs: [] });
expect(row).toMatchObject({ trust: "verified", provenance: { owner: "alice", version: "1.2.3", sha256 } });
await writeFile(path.join(target, "SKILL.md"), md + "tampered\n");
- [row] = await catalogSkills({ appDir: app, homeDir: home });
+ [row] = await catalogSkills({ appDir: app, homeDir: home, projectDirs: [] });
expect(row.trust).toBe("untrusted");
});
diff --git a/lib/skills/catalog.ts b/lib/skills/catalog.ts
index 2130877f..4fa5ab39 100644
--- a/lib/skills/catalog.ts
+++ b/lib/skills/catalog.ts
@@ -2,25 +2,11 @@ import { createHash } from "crypto";
import { promises as fs } from "fs";
import os from "os";
import path from "path";
+import { SKILL_FILE, skillIsExecutableByDefault, type SkillInfo, type SkillSource, type SkillTrust } from "./catalog-types";
+import { PROJECT_SKILL_LIMITS, projectSkillRoots, projectSkillTrust, type ProjectRef } from "./project-skills";
-export const SKILL_FILE = "SKILL.md";
-
-export type SkillTrust = "official" | "verified" | "local" | "untrusted";
-export type SkillSource = "mso" | "bundled" | "operator" | "claude" | "agents" | "codex" | "openclaw";
-
-export type SkillInfo = {
- name: string;
- path: string;
- description: string;
- source: SkillSource;
- trust: SkillTrust;
- provenance?: {
- registry?: string;
- owner?: string;
- version?: string;
- sha256?: string;
- };
-};
+export { SKILL_FILE, skillIsExecutableByDefault };
+export type { SkillInfo, SkillSource, SkillTrust };
type RootSpec = {
path: string;
@@ -28,9 +14,16 @@ type RootSpec = {
trust: SkillTrust;
priority: number;
verifyClawHub?: boolean;
+ project?: ProjectRef;
};
-type CatalogOptions = { appDir?: string; homeDir?: string };
+type CatalogOptions = {
+ appDir?: string;
+ homeDir?: string;
+ /** Project directories to scan for per-project skill roots. Defaults to every
+ * project across every configured container; pass `[]` to catalog global roots only. */
+ projectDirs?: Array<{ dir: string }>;
+};
/**
* Root priority is a security boundary, not just display order.
@@ -40,6 +33,10 @@ type CatalogOptions = { appDir?: string; homeDir?: string };
* so installing a same-named OpenClaw/Claude/Codex skill cannot silently replace
* MSO's own instructions. Bundled third-party skills are verified by their ClawHub
* SKILL.md hash. Generic discovered roots are visible but untrusted.
+ *
+ * Per-project roots sit BELOW all of these (priority 56–60, see project-skills.ts)
+ * and are addressed by a `<project>/<name>` id, so a project skill can neither
+ * outrank nor collide with an operator or official one.
*/
export function skillRoots(appDir = process.cwd(), homeDir = os.homedir()): RootSpec[] {
return [
@@ -110,42 +107,67 @@ async function verifiedBundledSkill(dir: string, md: string): Promise<Pick<Skill
};
}
-export async function catalogSkills(options: CatalogOptions = {}): Promise<SkillInfo[]> {
- const appDir = options.appDir ?? process.cwd();
- const homeDir = options.homeDir ?? os.homedir();
- const chosen = new Map<string, { skill: SkillInfo; priority: number }>();
+async function scanRoot(spec: RootSpec, budget: { left: number }): Promise<Array<{ skill: SkillInfo; priority: number }>> {
+ const entries = await fs.readdir(spec.path, { withFileTypes: true }).catch(() => []);
+ const found: Array<{ skill: SkillInfo; priority: number }> = [];
+ const limit = spec.project ? PROJECT_SKILL_LIMITS.maxSkillsPerRoot : entries.length;
+ for (const entry of entries.slice().sort((a, b) => a.name.localeCompare(b.name))) {
+ if (found.length >= limit || (spec.project && budget.left <= 0)) break;
+ if (!(await isSkillDir(spec.path, entry))) continue;
+ const dir = path.join(spec.path, entry.name);
+ const file = path.join(dir, SKILL_FILE);
+ const md = await readSkillFile(file);
+ if (!md) continue;
+
+ let trust = spec.trust;
+ let provenance: SkillInfo["provenance"];
+ if (spec.verifyClawHub) {
+ const verified = await verifiedBundledSkill(dir, md);
+ trust = verified.trust;
+ provenance = verified.provenance;
+ } else if (spec.project) {
+ // Path alone grants nothing: containment, ownership and SKILL.md shape decide.
+ trust = await projectSkillTrust(dir, spec.project.path);
+ budget.left -= 1;
+ }
- for (const spec of skillRoots(appDir, homeDir)) {
- const entries = await fs.readdir(spec.path, { withFileTypes: true }).catch(() => []);
- for (const entry of entries) {
- if (!(await isSkillDir(spec.path, entry))) continue;
- const dir = path.join(spec.path, entry.name);
- const file = path.join(dir, SKILL_FILE);
- const md = await readSkillFile(file);
- if (!md) continue;
-
- let trust = spec.trust;
- let provenance: SkillInfo["provenance"];
- if (spec.verifyClawHub) {
- const verified = await verifiedBundledSkill(dir, md);
- trust = verified.trust;
- provenance = verified.provenance;
- }
-
- const candidate: SkillInfo = {
+ found.push({
+ priority: spec.priority,
+ skill: {
+ id: spec.project ? `${spec.project.name}/${entry.name}` : entry.name,
name: entry.name,
path: file,
description: skillDescription(md),
source: spec.source,
trust,
+ ...(spec.project ? { project: spec.project } : {}),
...(provenance ? { provenance } : {}),
- };
- const current = chosen.get(candidate.name);
- if (!current || spec.priority > current.priority) chosen.set(candidate.name, { skill: candidate, priority: spec.priority });
+ },
+ });
+ }
+ return found;
+}
+
+export async function catalogSkills(options: CatalogOptions = {}): Promise<SkillInfo[]> {
+ const appDir = options.appDir ?? process.cwd();
+ const homeDir = options.homeDir ?? os.homedir();
+ const projectRoots = (await projectSkillRoots(options.projectDirs))
+ .map((root): RootSpec => ({ path: root.path, source: "project", trust: "untrusted", priority: root.priority, project: root.project }));
+ const chosen = new Map<string, { skill: SkillInfo; priority: number }>();
+ const budget = { left: PROJECT_SKILL_LIMITS.maxProjectSkills };
+
+ for (const spec of [...skillRoots(appDir, homeDir), ...projectRoots]) {
+ for (const candidate of await scanRoot(spec, budget)) {
+ const current = chosen.get(candidate.skill.id);
+ if (!current || candidate.priority > current.priority) chosen.set(candidate.skill.id, candidate);
}
}
- return [...chosen.values()].map(({ skill }) => skill).sort((a, b) => a.name.localeCompare(b.name));
+ return [...chosen.values()].map(({ skill }) => skill).sort((a, b) => a.id.localeCompare(b.id));
}
-export const skillIsExecutableByDefault = (skill: Pick<SkillInfo, "trust">): boolean => skill.trust !== "untrusted";
+/** Resolve a catalog id. Falls back to the bare `name` so pre-id callers and the
+ * `mso skills read <name>` CLI keep working for global skills. */
+export function findSkill(skills: SkillInfo[], idOrName: string): SkillInfo | undefined {
+ return skills.find((s) => s.id === idOrName) ?? skills.find((s) => s.name === idOrName && !s.project);
+}
diff --git a/lib/skills/memory.ts b/lib/skills/memory.ts
index a6185fee..1558d099 100644
--- a/lib/skills/memory.ts
+++ b/lib/skills/memory.ts
@@ -206,8 +206,10 @@ const SAFE_TOOL_ARGS: Record<string, readonly string[]> = {
fs_search: ["query", "root"],
fs_usage: ["path"],
apps_logs: ["id"],
+ projects_list: ["query", "limit", "offset"],
+ skills_list: ["project", "trust", "limit", "offset"],
+ skills_read: ["name"],
screen_capture: ["shell", "width", "height"],
- image_generate: ["project", "filename_stem", "model", "size", "quality", "background"],
fs_write: ["path"], // content is intentionally impossible to persist
fs_mkdir: ["path"],
fs_move: ["from", "to"],
@@ -246,7 +248,7 @@ function enrichBestSteps(best: WorkflowStep[], current: WorkflowStep[]): Workflo
const MAX_RECIPE_STEPS = 24;
const IMPORTANT_RECIPE_TOOLS = new Set([
"fs_write", "fs_mkdir", "fs_move", "fs_copy", "fs_delete",
- "apps_power", "browser_power", "exec_run", "screen_capture", "image_generate",
+ "apps_power", "browser_power", "exec_run", "screen_capture",
]);
/** Keep the recipe replayable without teaching the next run to repeat every
diff --git a/lib/skills/project-skills.test.ts b/lib/skills/project-skills.test.ts
new file mode 100644
index 00000000..6d730020
--- /dev/null
+++ b/lib/skills/project-skills.test.ts
@@ -0,0 +1,132 @@
+import { afterEach, describe, expect, it } from "vitest";
+import { mkdir, mkdtemp, rm, symlink, writeFile } from "fs/promises";
+import os from "os";
+import path from "path";
+import { catalogSkills } from "./catalog";
+import { PROJECT_SKILL_DIRS, projectSkillTrust } from "./project-skills";
+
+const temps: string[] = [];
+async function temp() {
+ const dir = await mkdtemp(path.join(os.tmpdir(), "mso-project-skills-"));
+ temps.push(dir);
+ return dir;
+}
+afterEach(async () => {
+ await Promise.all(temps.splice(0).map((d) => rm(d, { recursive: true, force: true })));
+});
+
+async function skill(root: string, name: string, description: string) {
+ const dir = path.join(root, name);
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, "SKILL.md"), `---\nname: ${name}\ndescription: ${description}\n---\n\n# ${name}\n`);
+ return dir;
+}
+
+/** Catalog with an explicit project list, so the box's real checkouts never leak in. */
+const catalog = (app: string, home: string, dirs: string[]) =>
+ catalogSkills({ appDir: app, homeDir: home, projectDirs: dirs.map((dir) => ({ dir })) });
+
+describe("per-project skill discovery", () => {
+ it("catalogs skills from every supported project root, in every project", async () => {
+ const app = await temp();
+ const home = await temp();
+ const workspace = await temp();
+ const one = path.join(workspace, "one");
+ const two = path.join(workspace, "two");
+ await skill(path.join(one, ".claude/skills"), "ship", "project one ship");
+ await skill(path.join(two, ".codex/skills"), "audit", "project two audit");
+
+ const rows = await catalog(app, home, [one, two]);
+ expect(rows.map((r) => `${r.id}:${r.trust}`)).toEqual(["one/ship:local", "two/audit:local"]);
+ expect(rows[0]).toMatchObject({ name: "ship", source: "project", project: { name: "one", path: one } });
+ });
+
+ it("keeps two projects' same-named skills as distinct catalog ids", async () => {
+ const app = await temp();
+ const home = await temp();
+ const workspace = await temp();
+ const one = path.join(workspace, "one");
+ const two = path.join(workspace, "two");
+ await skill(path.join(one, ".claude/skills"), "deploy", "one deploy");
+ await skill(path.join(two, ".claude/skills"), "deploy", "two deploy");
+
+ const rows = await catalog(app, home, [one, two]);
+ expect(rows.map((r) => r.id)).toEqual(["one/deploy", "two/deploy"]);
+ expect(rows.map((r) => r.description)).toEqual(["one deploy", "two deploy"]);
+ });
+
+ it("never lets a project skill shadow an operator or official skill of the same name", async () => {
+ const app = await temp();
+ const home = await temp();
+ const workspace = await temp();
+ const proj = path.join(workspace, "one");
+ await skill(path.join(app, "claude-skills"), "mso", "official");
+ await skill(path.join(home, ".mso/skills"), "ops", "operator");
+ await skill(path.join(proj, ".claude/skills"), "mso", "project impostor");
+ await skill(path.join(proj, ".claude/skills"), "ops", "project impostor");
+
+ const rows = await catalog(app, home, [proj]);
+ expect(rows.find((r) => r.id === "mso")).toMatchObject({ source: "mso", trust: "official", description: "official" });
+ expect(rows.find((r) => r.id === "ops")).toMatchObject({ source: "operator", trust: "local", description: "operator" });
+ // The project copies remain visible, but only under their own namespaced ids.
+ expect(rows.map((r) => r.id).sort()).toEqual(["mso", "one/mso", "one/ops", "ops"]);
+ });
+
+ it("ranks the explicit .mso/skills root above the agent-tool roots within one project", async () => {
+ const app = await temp();
+ const home = await temp();
+ const workspace = await temp();
+ const proj = path.join(workspace, "one");
+ await skill(path.join(proj, ".claude/skills"), "release", "claude copy");
+ await skill(path.join(proj, ".mso/skills"), "release", "explicit mso copy");
+
+ const rows = await catalog(app, home, [proj]);
+ expect(rows).toEqual([expect.objectContaining({ id: "one/release", description: "explicit mso copy" })]);
+ });
+
+ it("lists every documented project skill root", () => {
+ expect([...PROJECT_SKILL_DIRS]).toEqual([".mso/skills", ".claude/skills", ".hermes/skills", ".agents/skills", ".codex/skills"]);
+ });
+});
+
+describe("project skill trust is earned, not assumed", () => {
+ it("refuses a skill directory that realpaths outside its project", async () => {
+ const workspace = await temp();
+ const outside = await temp();
+ const proj = path.join(workspace, "one");
+ await mkdir(path.join(proj, ".claude"), { recursive: true });
+ const evil = await skill(outside, "escape", "outside the project");
+ await symlink(outside, path.join(proj, ".claude/skills"));
+
+ await expect(projectSkillTrust(evil, proj)).resolves.toBe("untrusted");
+ const rows = await catalog(await temp(), await temp(), [proj]);
+ expect(rows).toEqual([expect.objectContaining({ id: "one/escape", trust: "untrusted", source: "project" })]);
+ });
+
+ it("refuses a SKILL.md that is a symlink rather than a regular file", async () => {
+ const workspace = await temp();
+ const proj = path.join(workspace, "one");
+ const dir = path.join(proj, ".claude/skills/linked");
+ await mkdir(dir, { recursive: true });
+ const real = path.join(proj, "real.md");
+ await writeFile(real, "---\nname: linked\ndescription: linked\n---\n");
+ await symlink(real, path.join(dir, "SKILL.md"));
+
+ await expect(projectSkillTrust(dir, proj)).resolves.toBe("untrusted");
+ });
+
+ it("trusts a contained, owner-owned, regular-file skill", async () => {
+ const workspace = await temp();
+ const proj = path.join(workspace, "one");
+ const dir = await skill(path.join(proj, ".hermes/skills"), "patrol", "hermes patrol");
+ await expect(projectSkillTrust(dir, proj)).resolves.toBe("local");
+ });
+
+ it("keeps the generic HOME agent roots untrusted even though project roots are promoted", async () => {
+ const app = await temp();
+ const home = await temp();
+ await skill(path.join(home, ".claude/skills"), "wander", "discovered in home");
+ const rows = await catalog(app, home, []);
+ expect(rows).toEqual([expect.objectContaining({ id: "wander", source: "claude", trust: "untrusted" })]);
+ });
+});
diff --git a/lib/skills/project-skills.ts b/lib/skills/project-skills.ts
new file mode 100644
index 00000000..381c3721
--- /dev/null
+++ b/lib/skills/project-skills.ts
@@ -0,0 +1,97 @@
+// Per-PROJECT skill roots, across every configured project container.
+//
+// A skill that lives with the repository it automates is the normal case, and MSO
+// was blind to all of them: only global roots (~/.mso/skills, the MSO repo, ~/.claude
+// and friends) were cataloged, so an agent working in project X could not see X's own
+// SKILL.md. That is capability scoping nobody chose.
+//
+// Trust is EARNED per directory, never assumed from the path. A project skill reaches
+// `local` only when all three hold:
+// 1. containment — the skill directory realpaths back inside the project directory,
+// so a `.claude/skills -> /tmp/attacker` symlink is discovered, not followed;
+// 2. ownership — the skill directory and its SKILL.md belong to the uid MSO runs
+// as, so a world-writable drop-in cannot become executable instructions;
+// 3. shape — SKILL.md is a regular file, not a symlink to somewhere else.
+// Anything else is cataloged as `untrusted`: visible for inspection, instructions
+// withheld. The generic HOME agent roots (~/.claude/skills, …) keep their existing
+// untrusted behaviour — this promotion is for project-scoped roots only.
+import { promises as fs } from "fs";
+import path from "path";
+import { listProjectDirs } from "@/lib/host/project-roots";
+import { SKILL_FILE, type SkillTrust } from "./catalog-types";
+
+/** Where a project may keep skills. `.mso/skills` is the explicit MSO root — the
+ * per-project counterpart of `~/.mso/skills` — and therefore ranks above the
+ * agent-tool conventions that follow it. */
+export const PROJECT_SKILL_DIRS = [
+ ".mso/skills",
+ ".claude/skills",
+ ".hermes/skills",
+ ".agents/skills",
+ ".codex/skills",
+] as const;
+
+export const PROJECT_SKILL_LIMITS = {
+ /** Projects scanned for skills per catalog call. */
+ maxProjects: 60,
+ /** Skill directories taken from one project root. */
+ maxSkillsPerRoot: 100,
+ /** Project skills cataloged in total. */
+ maxProjectSkills: 300,
+} as const;
+
+export type ProjectRef = { name: string; path: string };
+export type ProjectSkillRoot = { path: string; project: ProjectRef; priority: number };
+
+function currentUid(): number | undefined {
+ return typeof process.getuid === "function" ? process.getuid() : undefined;
+}
+
+async function ownedByUs(target: string): Promise<boolean> {
+ const uid = currentUid();
+ if (uid === undefined) return true; // no uid concept (Windows); containment + shape still apply
+ const stat = await fs.lstat(target).catch(() => null);
+ return !!stat && stat.uid === uid;
+}
+
+function contains(parent: string, child: string): boolean {
+ const rel = path.relative(parent, child);
+ return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
+}
+
+/**
+ * The trust decision for ONE project skill directory. Exported so the catalog and
+ * its tests exercise the same three checks rather than a reimplementation.
+ */
+export async function projectSkillTrust(skillDir: string, projectPath: string): Promise<SkillTrust> {
+ const projectReal = await fs.realpath(projectPath).catch(() => null);
+ const dirReal = await fs.realpath(skillDir).catch(() => null);
+ if (!projectReal || !dirReal || !contains(projectReal, dirReal)) return "untrusted";
+ const file = path.join(dirReal, SKILL_FILE);
+ const stat = await fs.lstat(file).catch(() => null);
+ if (!stat?.isFile() || stat.isSymbolicLink()) return "untrusted";
+ if (!(await ownedByUs(dirReal)) || !(await ownedByUs(file))) return "untrusted";
+ return "local";
+}
+
+/**
+ * Every per-project skill root on the box, in deterministic order: project order
+ * from `listProjectDirs()` (configured container order, then name), then
+ * `PROJECT_SKILL_DIRS` order. `priority` ranks a project skill BELOW every global
+ * root, so a project can never shadow an operator or official skill.
+ */
+export async function projectSkillRoots(projectDirs?: Array<{ dir: string }>): Promise<ProjectSkillRoot[]> {
+ const dirs = (projectDirs ?? (await listProjectDirs()).dirs).slice(0, PROJECT_SKILL_LIMITS.maxProjects);
+ const out: ProjectSkillRoot[] = [];
+ for (const { dir } of dirs) {
+ const project: ProjectRef = { name: path.basename(dir), path: dir };
+ for (const [index, sub] of PROJECT_SKILL_DIRS.entries()) {
+ const root = path.join(dir, sub);
+ const stat = await fs.lstat(root).catch(() => null);
+ if (!stat?.isDirectory() && !stat?.isSymbolicLink()) continue;
+ if (!(await fs.stat(root).catch(() => null))?.isDirectory()) continue;
+ out.push({ path: root, project, priority: 60 - index });
+ }
+ }
+ return out;
+}
diff --git a/lib/skills/search.ts b/lib/skills/search.ts
index b00d10d3..7ca01013 100644
--- a/lib/skills/search.ts
+++ b/lib/skills/search.ts
@@ -13,6 +13,8 @@ export type SkillSearchHit = {
kind: "recipe" | "skill" | "tool";
id: string;
name: string;
+ /** Set when the hit is a skill that lives inside a project checkout. */
+ project?: { name: string; path: string };
score: number;
description: string;
source?: string;
@@ -31,6 +33,8 @@ export type SkillSearchOptions = {
toolDocs?: SkillSearchToolDoc[];
appDir?: string;
homeDir?: string;
+ /** Forwarded to catalogSkills; `[]` restricts the search to global roots. */
+ projectDirs?: Array<{ dir: string }>;
};
function skillQuality(skill: SkillInfo): number {
@@ -86,15 +90,16 @@ export async function searchSkillMemory(query: string, options: SkillSearchOptio
});
}
- const skills = await catalogSkills({ appDir: options.appDir, homeDir: options.homeDir });
+ const skills = await catalogSkills({ appDir: options.appDir, homeDir: options.homeDir, projectDirs: options.projectDirs });
for (const skill of skills) {
if (!options.includeUntrusted && skill.trust === "untrusted") continue;
const content = skill.trust === "untrusted" ? "" : (await readSkillFile(skill.path))?.slice(0, 18_000) ?? "";
- const text = `${skill.name}\n${skill.description}\n${content}`;
+ const text = `${skill.id}\n${skill.name}\n${skill.project?.name ?? ""}\n${skill.description}\n${content}`;
hits.push({
kind: "skill",
- id: skill.name,
+ id: skill.id,
name: skill.name,
+ ...(skill.project ? { project: skill.project } : {}),
score: Math.max(0, Math.min(1, hybridSemanticScore(q, text) + skillQuality(skill))),
description: skill.description,
source: skill.source,
diff --git a/skills/README.md b/skills/README.md
index 681be486..856937b3 100644
--- a/skills/README.md
+++ b/skills/README.md
@@ -1,21 +1,46 @@
# MSO skill catalog
-MSO exposes markdown playbooks from several roots, but discovery is **not** the same as trust.
+MSO exposes markdown playbooks from several roots — **global roots and the per-project roots of every project on the box** — but discovery is **not** the same as trust.
## Trust and precedence
-Highest precedence wins when two roots contain the same skill name:
+Highest precedence wins when two roots contain the same catalog id:
1. `~/.mso/skills` — **local** operator override. This is the only host root that may intentionally replace an MSO skill.
2. `<MSO_ROOT>/claude-skills` — **official** MSO skills. These are always cataloged directly from the repo; Claude does not need to be installed and no symlink is required.
3. `<MSO_ROOT>/skills` — bundled third-party skills. A ClawHub skill is **verified** only while its current `SKILL.md` SHA-256 matches `.clawhub/origin.json`; otherwise it is **untrusted**.
-4. Generic discovery roots (`~/.claude/skills`, `~/.agents/skills`, `~/.codex/skills`, OpenClaw roots) — **untrusted** by default and cannot shadow the three roots above.
+4. Generic HOME discovery roots (`~/.claude/skills`, `~/.agents/skills`, `~/.codex/skills`, OpenClaw roots) — **untrusted** by default and cannot shadow the three roots above.
+5. **Per-project roots**, inside every project across every configured container: `.mso/skills`, then `.claude/skills`, `.hermes/skills`, `.agents/skills`, `.codex/skills`. Ranked below every global root.
The assistant lists/loads only `official`, `verified`, and `local` instructions by default. Untrusted skills remain visible in the catalog for inspection, but their instructions are not fed directly to the model. Review one as a normal file, then copy/move the approved skill into `~/.mso/skills` if you intentionally want to trust it.
+## Ids: a project skill cannot shadow anything
+
+A global skill is addressed by its bare **name**. A project skill is `<project>/<name>`.
+So two projects may both ship `deploy`, and neither can displace the operator or
+official skill of the same name — the collision is impossible rather than resolved.
+`skills_read` / `skills.read` accept the **exact id only**; they do not fuzzy-resolve
+`deploy` into `widget/deploy`.
+
+## Project skills earn `local` trust; they do not inherit it
+
+Living in a project grants nothing by itself. A project skill is promoted to `local`
+only when all three hold:
+
+1. **Containment** — the skill directory realpaths back inside its project, so a
+ `.claude/skills -> /tmp/attacker` symlink is *discovered*, not followed.
+2. **Ownership** — the skill directory and its `SKILL.md` belong to the uid MSO runs as.
+3. **Shape** — `SKILL.md` is a regular file, not a symlink to somewhere else.
+
+Anything else is cataloged `untrusted`. The generic HOME agent roots keep their existing
+untrusted behaviour; this promotion applies to project-scoped roots only.
+
+Scans are bounded: 60 projects, 100 skills per root, 300 project skills and 24,000
+characters of instructions per read.
+
## Contract
-Each skill is a directory containing `SKILL.md` with YAML frontmatter (`name`, `description`). MSO returns catalog metadata including `source`, `trust`, and verified provenance when available.
+Each skill is a directory containing `SKILL.md` with YAML frontmatter (`name`, `description`). MSO returns catalog metadata including `id`, `source`, `trust`, its `project` when it has one, and verified provenance when available.
Skill roots are intentionally read outside the normal filesystem jail, because agent skill registries may live outside `OS_FS_READ_ROOTS`. The reader therefore opens only a file named exactly `SKILL.md` after `realpath`; a symlink such as `SKILL.md -> ~/.ssh/config` is refused. Root trust/precedence handles the remaining instruction-supply-chain risk.
@@ -25,8 +50,11 @@ Skill roots are intentionally read outside the normal filesystem jail, because a
## Semantic search and learned recipes
-The catalog is indexed together with the live MCP tool schemas and successful
-workflow recipes. `skills_search` / `skills.search` and `GET /api/skills?q=...` use
+The catalog — global roots and every project's roots together — is indexed with the
+live MCP tool schemas and successful workflow recipes, and each skill hit carries its
+project. `workflow_start` searches the same unified catalog, so a workflow named against
+one project still finds the relevant skill in another.
+`skills_search` / `skills.search` and `GET /api/skills?q=...` use
the local `mso-local-hybrid-v1` encoder, so searches work across English, Indonesian
and minor typos without a cloud embedding API. Untrusted skill instructions remain
excluded by default.