Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Replace skill projection with an explicit skill tool and per-turn skill directories (#1432)

Regan Bell98ac521ec044
diff --git a/docs/skill-registry.md b/docs/skill-registry.md
index 17e5c7149..0efaaa8ec 100644
--- a/docs/skill-registry.md
+++ b/docs/skill-registry.md
@@ -71,19 +71,17 @@ commit.
The skills are governed store records, visible and auditable on the admin Skills page, rather than
ungoverned files on each box.
-## Reading published skills
-
-The skill index advertises `skill://<name>/SKILL.md` for the agent's `read` tool.
-These read-only references resolve the currently visible, screened published skill
-without creating or waking a sandbox. Relative manifest files can be read at
-`skill://<name>/<relative-path>`. Unavailable skills and invalid paths return no file.
-
-Shell commands still use `skills/<name>/...`. Filesystem reads and commands referencing a
-skill materialize its assets when needed, including pack files under the path named
-in the skill body. Ordinary filesystem reads and writes
-retain their existing behavior, including local edits; they are distinct from the
-published source. Publish changes through the skill API to update that source.
-
-Command detection uses literal skill paths. Before executing a command that constructs
-its asset paths dynamically, read the needed file at its `skills/...` filesystem path
-to materialize it.
+## Loading published skills
+
+The skill index lists each visible skill. The agent's `skill` tool resolves the currently
+visible, screened published skill and returns its SKILL.md, or a relative manifest file
+named by `path`, without creating or waking a sandbox. Unavailable skills and invalid
+paths return no file.
+
+When a skill ships supporting files or pack bundles, the same call lays them into the
+turn's private directory under `.agent-turn/<conversation>/skills/<name>/` (packs under
+`.packs/<id>/` beside it) and reports that path; the body's own `skills/<name>/` references
+are rewritten to it. That directory is wiped when the turn ends and before the next one
+starts, so nothing reconciles, locks, or sweeps: plain commands and filesystem reads never
+wait on skill synchronization, and revoked or archived content cannot outlive the turn
+that loaded it. Publish changes through the skill API to update the source.
diff --git a/plugins/onboarding/skills/onboarding/SKILL.md b/plugins/onboarding/skills/onboarding/SKILL.md
index 6368a20b3..d5c840e44 100644
--- a/plugins/onboarding/skills/onboarding/SKILL.md
+++ b/plugins/onboarding/skills/onboarding/SKILL.md
@@ -75,7 +75,7 @@ form, never into chat.
### Personal connections
Check the live credential inventory first. When an authorized Composio credential is available,
-read `skill://composio/SKILL.md`, discover available apps, and use its consent flow for the
+load the composio skill with the skill tool, discover available apps, and use its consent flow for the
user's choices. Reuse their connected accounts after checking identity and permissions;
a project key is not proof that a personal account is connected. Do not ask them to
create OAuth apps for connections this source already provides. Do not infer that Composio is unavailable from an empty direct OAuth list
diff --git a/plugins/web-ui/src/activity-presentation.ts b/plugins/web-ui/src/activity-presentation.ts
index 3b1c6c551..65cd91c4e 100644
--- a/plugins/web-ui/src/activity-presentation.ts
+++ b/plugins/web-ui/src/activity-presentation.ts
@@ -3,7 +3,7 @@ import type { WorkBlock } from "./core-bridge.ts";
export type ActivityCategory = "read" | "search" | "execute" | "other";
-export function compactPath(path: string): string {
+function compactPath(path: string): string {
const parts = path.replace(/\/$/, "").split("/");
return parts.at(-1) === "SKILL.md" ? parts.slice(-2).join("/") : parts.at(-1) || path;
}
@@ -31,6 +31,10 @@ export function activityDescription(
} {
const tool = toolCategory({ ...result, ...call });
if (tool === "read") return { category: "read", target: compactPath(call.path ?? result.path ?? "") };
+ if (tool === "skill") {
+ const name = call.name ?? result.name ?? "";
+ return { category: "read", target: `${name}/${compactPath(call.path ?? result.path ?? "SKILL.md")}` };
+ }
if (tool !== "execute") return { category: "other", target: "" };
const command = call.command ?? "";
const words = shellWords(command);
diff --git a/plugins/web-ui/src/chat.ts b/plugins/web-ui/src/chat.ts
index 49db3f83b..6384c9b03 100644
--- a/plugins/web-ui/src/chat.ts
+++ b/plugins/web-ui/src/chat.ts
@@ -2489,6 +2489,7 @@ export function createChatSurface(
const TOOL_META: Record<string, { icon: IconNode; active: string; done: string; attempted: string }> = {
execute: { icon: Terminal, active: "Running command", done: "Ran command", attempted: "Tried command" },
read: { icon: BookOpen, active: "Reading file", done: "Read file", attempted: "Tried reading file" },
+ skill: { icon: BookOpen, active: "Loading skill", done: "Loaded skill", attempted: "Tried loading skill" },
write: { icon: Pencil, active: "Writing file", done: "Wrote file", attempted: "Tried writing file" },
publish: { icon: Rocket, active: "Publishing", done: "Published", attempted: "Tried publishing" },
recall: { icon: Brain, active: "Searching memory", done: "Searched memory", attempted: "Tried searching memory" },
@@ -2562,6 +2563,8 @@ export function createChatSurface(
return call.command ? firstLine(call.command) : "";
case "read":
return call.path ?? result.path ?? "";
+ case "skill":
+ return `${call.name ?? result.name ?? ""}/${call.path ?? result.path ?? "SKILL.md"}`;
case "write": {
const path = call.path ?? result.path ?? "";
const bytes = result.bytes ?? call.bytes;
diff --git a/plugins/web-ui/test/activity-presentation.test.ts b/plugins/web-ui/test/activity-presentation.test.ts
index 7529c48c7..eb7af3090 100644
--- a/plugins/web-ui/test/activity-presentation.test.ts
+++ b/plugins/web-ui/test/activity-presentation.test.ts
@@ -5,7 +5,6 @@ import {
activityGroupSummary,
activityGroups,
activityLabel,
- compactPath,
thinkingPresentation,
sessionPresentation,
} from "../src/activity-presentation.ts";
@@ -42,7 +41,14 @@ test("simple shell reads and searches get semantic labels, compound commands sta
);
assert.equal(activityLabel(row("sed -n '1,120p' src/main.ts"), "complete"), "main.ts");
assert.equal(activityLabel(row("rg --files src"), "complete"), "Searched for files in src");
- assert.equal(compactPath("skill://publish/SKILL.md"), "publish/SKILL.md");
+ assert.deepEqual(activityDescription({ tool: "skill", name: "publish" }), {
+ category: "read",
+ target: "publish/SKILL.md",
+ });
+ assert.deepEqual(activityDescription({ tool: "skill", name: "publish", path: "templates/x.md" }), {
+ category: "read",
+ target: "publish/x.md",
+ });
});
test("status labels never report missing or failed results as successful", () => {
diff --git a/scripts/skills-materialize-smoke.ts b/scripts/skills-materialize-smoke.ts
index 18aefe677..e714d04d8 100644
--- a/scripts/skills-materialize-smoke.ts
+++ b/scripts/skills-materialize-smoke.ts
@@ -5,7 +5,7 @@ import { createSpritesSandbox } from "../src/sandbox/sprites-sandbox.ts";
import { createLocalWorkspaceStore } from "../src/workspace/workspace-store.ts";
import { scopeId } from "../src/types.ts";
import { loadConfig } from "../src/config.ts";
-import { reconcileSkillIndex, materializeSkillTree } from "../src/skills/materialize.ts";
+import { materializeSkillTree } from "../src/skills/materialize.ts";
import { computeBundleHash, type SkillBundle } from "../src/skills/skill-bundle-store.ts";
import type { SkillFile, SkillResolution } from "../src/skills/skill-store.ts";
@@ -38,21 +38,10 @@ try {
{ path: "scripts/render.py", content: "print('render')\n" },
{ path: "references/catalog.md", content: "# big catalog\n" },
]);
- const light = res("plain-skill", "# Plain\njust instructions");
-
- console.log("reconcileSkillIndex (ownership only) …");
- await reconcileSkillIndex(sb, h, [heavy, light]);
- assert((await sb.readFile(h, "skills/popular-web-designs/SKILL.md")) === null, "heavy body stays in core");
- assert((await sb.readFile(h, "skills/plain-skill/SKILL.md")) === null, "unused body stays in core");
- assert(
- (await sb.readFile(h, "skills/popular-web-designs/scripts/render.py")) === null,
- "asset NOT laid by index (lazy)",
- );
- console.log(" ok: no skill content copied");
console.log("materializeSkillTree (lazy, assets + bundle, one tar) …");
const b = bundle("pack1", [{ path: "lib/cite.mjs", content: "export const cite = 1\n" }]);
- await materializeSkillTree(sb, h, heavy, [b]);
+ await materializeSkillTree(sb, h, "skills", heavy, [b]);
assert(
(await sb.readFile(h, "skills/popular-web-designs/scripts/render.py"))?.includes("render"),
"asset laid lazily",
@@ -65,37 +54,8 @@ try {
(await sb.readFile(h, "skills/.packs/pack1/lib/cite.mjs"))?.includes("cite"),
"pack bundle overlaid at repo-relative path",
);
- assert((await sb.readFile(h, "skills/popular-web-designs/.tree")) !== null, "tree marker written");
console.log(" ok: assets + bundle landed via tar");
- const before = await sb.readFile(h, "skills/popular-web-designs/.tree");
- await materializeSkillTree(
- sb,
- h,
- res("popular-web-designs", "# Popular web designs\nthe entry point", [
- { path: "scripts/render.py", content: "print('render')\n" },
- { path: "references/catalog.md", content: "# big catalog\n" },
- ]),
- [bundle("pack1", [{ path: "lib/cite.mjs", content: "export const cite = 1\n" }])],
- );
- assert((await sb.readFile(h, "skills/popular-web-designs/.tree")) === before, "unchanged tree → same marker (skip)");
- console.log(" ok: unchanged tree skipped");
-
- console.log("re-lay with references/ removed …");
- await materializeSkillTree(
- sb,
- h,
- res("popular-web-designs", "# Popular web designs\nthe entry point", [
- { path: "scripts/render.py", content: "print('render v2')\n" },
- ]),
- );
- assert(
- (await sb.readFile(h, "skills/popular-web-designs/scripts/render.py"))?.includes("v2"),
- "changed asset re-laid",
- );
- assert((await sb.readFile(h, "skills/popular-web-designs/references/catalog.md")) === null, "removed asset cleared");
- console.log(" ok: removed asset gone, changed asset updated");
-
console.log("\nALL SKILLS MATERIALIZE SMOKE CHECKS PASSED");
} finally {
console.log("destroying smoke sprite …");
diff --git a/skills-seed/cloud-cli/SKILL.md b/skills-seed/cloud-cli/SKILL.md
index 0d507f3c3..4447f3d42 100644
--- a/skills-seed/cloud-cli/SKILL.md
+++ b/skills-seed/cloud-cli/SKILL.md
@@ -26,7 +26,7 @@ If it is missing, say so and pick a path rather than failing halfway:
provider's own installer, into the workspace or `$HOME`, not a system path. Say that you
installed it; it lasts as long as the machine's disk.
- **Use the provider's HTTP API** with a credential you already have (a keychain entry, or
- a shared org credential by proxy — see `skill://use-shared-credential/SKILL.md`).
+ a shared org credential by proxy — see the `use-shared-credential` skill).
- **Ask the operator** to add the CLI to the sandbox image if this will recur. That is the
durable fix; a per-turn install is not.
@@ -61,7 +61,7 @@ The platform recognizes these as device-flow logins and runs them as **durable p
sessions**: the command prints the verification URL and one-time code immediately and keeps
polling across turns — it does not block your turn or die at teardown. Give the user the URL
and the code, tell them to approve and then say "done". See
-`skill://interactive-login/SKILL.md` for how to drive that from the background tool.
+the `interactive-login` skill for how to drive that from the background tool.
On the next turn, run the same login command again (or any provider command): if approval
landed, the platform reports you are already authenticated and the token is cached; if it is
diff --git a/skills-seed/connect-apps/SKILL.md b/skills-seed/connect-apps/SKILL.md
index 6b89345be..9e4f86659 100644
--- a/skills-seed/connect-apps/SKILL.md
+++ b/skills-seed/connect-apps/SKILL.md
@@ -6,7 +6,7 @@ description: Connect an administrator-enabled SaaS app for a user with a one-tim
## Connecting SaaS apps
Check the live credential inventory first. When an authorized Composio credential is
-available, read `skill://composio/SKILL.md` and use its discovery and consent flow instead
+available, load the `composio` skill and use its discovery and consent flow instead
of the direct OAuth flow below. An empty direct OAuth list or a native
`oauth_not_configured` error does not describe Composio availability. Preserve explicit
app restrictions and account permissions; never switch credentials to evade a denial.
diff --git a/skills-seed/github-gitlab/SKILL.md b/skills-seed/github-gitlab/SKILL.md
index eaf3c44dc..dcac128fa 100644
--- a/skills-seed/github-gitlab/SKILL.md
+++ b/skills-seed/github-gitlab/SKILL.md
@@ -23,7 +23,7 @@ a write, ask. Do not infer permission from a login merely being present on the c
provider account (for example, `gh api user --jq .login`) and the Git transport's auth
configuration; a CLI API identity alone does not prove which account Git will use.
- **Shared org credential:** if listed in the prompt, select its slug and use the
- core-hosted smart HTTP remote in `skill://use-shared-credential/SKILL.md`. This uses
+ core-hosted smart HTTP remote in the `use-shared-credential` skill. This uses
the configured shared account, even when a personal OAuth connector is live.
Its name is an admin label, not a verified upstream username.
- **Connected app:** use only advertised capabilities. API access does not by itself
diff --git a/skills-seed/google-workspace/SKILL.md b/skills-seed/google-workspace/SKILL.md
index 8edb63855..27d377184 100644
--- a/skills-seed/google-workspace/SKILL.md
+++ b/skills-seed/google-workspace/SKILL.md
@@ -25,8 +25,8 @@ flow.
## Gmail
-For the `email-voice-profile` task, the direct OAuth corpus helper is
-`python3 skills/email-voice-profile/scripts/fetch_sent.py --limit 300`.
+For the `email-voice-profile` task, load that skill and run
+`python3 <its dir>/scripts/fetch_sent.py --limit 300` from the directory it reports.
Use the bundled helper for every Gmail operation — it owns MIME construction, encoding,
and reply threading so you only ever handle plain text:
diff --git a/skills-seed/popular-web-designs/SKILL.md b/skills-seed/popular-web-designs/SKILL.md
index 4bd99c497..f47289b1e 100644
--- a/skills-seed/popular-web-designs/SKILL.md
+++ b/skills-seed/popular-web-designs/SKILL.md
@@ -12,8 +12,8 @@ system, shadows, responsive behavior, and practical agent prompts with exact CSS
## Default look comes first
This skill is for when the user wants a page styled after **a specific known brand**. If they
-have not named one, use your deployment's house-style skill (a `*-design` skill under
-`skills/`, when installed) instead of picking from this catalog.
+have not named one, use your deployment's house-style skill (a `*-design` skill in the
+Skills index, when installed) instead of picking from this catalog.
## Related design skills
@@ -28,9 +28,9 @@ have not named one, use your deployment's house-style skill (a `*-design` skill
## How to Use
1. Pick a design from the catalog below
-2. Read it: `read skills/popular-web-designs/templates/<site>.md`
+2. Read it: `skill({ name: "popular-web-designs", path: "templates/<site>.md" })`
3. Use the design tokens and component specs when generating HTML
-4. Build with `write`, then serve the result with the `publish` skill (`skill://publish/SKILL.md`)
+4. Build with `write`, then serve the result with the `publish` skill
Each template includes an **Implementation Notes** block at the top with:
diff --git a/skills-seed/publish/SKILL.md b/skills-seed/publish/SKILL.md
index b4fc55a9f..6cc400822 100644
--- a/skills-seed/publish/SKILL.md
+++ b/skills-seed/publish/SKILL.md
@@ -22,12 +22,12 @@ Anything browsable you publish should look designed, not defaulted. Before you b
UI, load the design skills and apply your organization's **house style** unless the user
asked for a different look:
-- **The deployment's house-style skill** — if a `*-design` skill is installed (list
- `skills/`), it carries the org's look as ready-to-paste CSS and design tokens. Start
+- **The deployment's house-style skill** — if the Skills index lists a `*-design` skill,
+ it carries the org's look as ready-to-paste CSS and design tokens. Start
there for the look.
-- **`skill://taste-skill/SKILL.md`** — the design _process_: reading the brief, layout,
+- **`taste-skill`** — the design _process_: reading the brief, layout,
hierarchy, verifying the result, avoiding generic AI-design slop.
-- **`skill://popular-web-designs/SKILL.md`** — when the user wants a specific visual
+- **`popular-web-designs`** — when the user wants a specific visual
reference (Stripe, Linear, Vercel…).
This is about the page a person sees — skip it for an internal-only API or a script with
diff --git a/skills-seed/send/SKILL.md b/skills-seed/send/SKILL.md
index 724be8764..a5ca8c24a 100644
--- a/skills-seed/send/SKILL.md
+++ b/skills-seed/send/SKILL.md
@@ -21,11 +21,12 @@ any issues that come up, and merge once CI is **fully** green.
GitLab. Detect from the remote.
3. **Wait for CI in one blocking process, with bounded transport retries.**
- Read the `github-gitlab` skill. For GitHub, capture the PR's full head SHA and
- use its bundled helper, not bare `gh pr checks --watch`:
+ Load the `github-gitlab` skill; it reports the directory holding its scripts. For
+ GitHub, capture the PR's full head SHA and use its bundled helper, not bare
+ `gh pr checks --watch`:
```bash
- node skills/github-gitlab/scripts/watch-ci.mjs --repo OWNER/REPO --pr NUMBER --head REVIEWED_HEAD_SHA
+ node <github-gitlab dir>/scripts/watch-ci.mjs --repo OWNER/REPO --pr NUMBER --head REVIEWED_HEAD_SHA
```
Run this in the background with authorized credentials and subscribe to completion.
diff --git a/skills-seed/taste-skill/SKILL.md b/skills-seed/taste-skill/SKILL.md
index 594d35f4d..44a95739a 100644
--- a/skills-seed/taste-skill/SKILL.md
+++ b/skills-seed/taste-skill/SKILL.md
@@ -12,12 +12,12 @@ process; the anti-slop playbook in `references/tasteskill.md` carries the visual
## House style comes first
Unless the user asks for a different look, the default visual system is your
-organization's **house style**: if the deployment installs a `*-design` skill (list
-`skills/`), read it and apply its tokens — color, type, spacing, components. Depart from
+organization's **house style**: if the Skills index lists a `*-design` skill, load it
+and apply its tokens — color, type, spacing, components. Depart from
it only when the user names a different brand or asks for a one-off exploration.
If the user wants a _known brand's_ look (Stripe, Linear, Vercel, Notion…), read
-`skill://popular-web-designs/SKILL.md` for the visual vocabulary and let this skill drive
+the `popular-web-designs` skill for the visual vocabulary and let this skill drive
the process.
## The playbook
@@ -36,7 +36,7 @@ anything externally facing or high-fidelity. Two adjustments for this runtime:
You have a real computer, not a hosted design canvas. Build the artifact as files in your
workspace, verify it locally, and when it should outlive the turn ship it with the
-`publish` skill (`skill://publish/SKILL.md`).
+`publish` skill.
- **`write` / `read` / `execute`** — author files, install deps, run build steps.
- **`background`** — run a dev server (`PORT=8080 node server.js`) so you can look at it.
diff --git a/src/api/agent-api-catalog.ts b/src/api/agent-api-catalog.ts
index 2ac1e3a8b..d8369b126 100644
--- a/src/api/agent-api-catalog.ts
+++ b/src/api/agent-api-catalog.ts
@@ -682,7 +682,7 @@ const FAMILIES: AgentApiFamily[] = [
((m === "PUT" || m === "DELETE") && p.startsWith("/v1/skills/")) ||
(m === "POST" && /^\/v1\/skills\/[^/]+\/restore$/.test(p)),
guidance:
- "Save a skill when you've worked out a repeatable procedure worth keeping (a checklist, a multi-step flow, a house style) — it is advertised for reading at skill://<name>/SKILL.md on future turns. The skill homes in THIS conversation's scope: in a 1:1 DM it's yours alone; in a private channel or group DM it's owned by that room and every member can edit or delete it (the audit trail records who changed what); a public channel stays owner-only. Write the `body` as a plain-step recipe addressed to your future self; edit or delete it as it goes stale.",
+ "Save a skill when you've worked out a repeatable procedure worth keeping (a checklist, a multi-step flow, a house style) — it is advertised in the skill index and loaded with the skill tool on future turns. The skill homes in THIS conversation's scope: in a 1:1 DM it's yours alone; in a private channel or group DM it's owned by that room and every member can edit or delete it (the audit trail records who changed what); a public channel stays owner-only. Write the `body` as a plain-step recipe addressed to your future self; edit or delete it as it goes stale.",
routes: [
{
method: "POST",
diff --git a/src/core/orchestrator.ts b/src/core/orchestrator.ts
index 192370815..4fa949505 100644
--- a/src/core/orchestrator.ts
+++ b/src/core/orchestrator.ts
@@ -110,7 +110,7 @@ import { createPerTurnStrategy } from "../memory/strategies/per-turn.ts";
import { DEFAULT_MEMORY_POLICY } from "../memory/policy.ts";
import { createMemoryMap } from "../persistence/durable-map.ts";
import { collectBlob, createMemoryBlobTransferStore } from "../persistence/blob-transfer.ts";
-import { createSkillMaterializer, skillsIndex, SKILLS_DIR } from "../skills/materialize.ts";
+import { skillsIndex } from "../skills/materialize.ts";
import {
resolveOnboardingStatus,
onboardingSkillVisible,
@@ -264,7 +264,6 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
);
}
const leaseKeepaliveMs = Math.floor(deps.sessions.leaseTtlMs / 3);
- const skillMaterializer = createSkillMaterializer(deps.advisoryLock);
const pending = deps.approvals ?? createMemoryMap<PendingApprovalRecord>();
const transcripts = createTranscriptSource(deps.sessions);
const approvalGrants = deps.approvalGrants ?? createMemoryMap<CommandApprovalGrant>();
@@ -1702,8 +1701,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
provisionScratch,
provisionResource,
provisionOwnerAuth,
- ensureSkillTree,
- readSkill,
+ useSkill,
provisionForReach,
reclaimBox,
provisionPending,
@@ -1731,9 +1729,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
credentialCutoverServices,
quarantinedServices,
cutoverModeOf,
- visibleSkills,
visibleSkillsForTurn,
- skillMaterializer,
emitGapWork,
perf,
});
@@ -2169,7 +2165,6 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
const snapshotExcludeDirs = [
...resolution.layers.filter((l) => l.mode === "ro" && l.mountPath).map((l) => l.mountPath),
TURN_FILES_DIR,
- SKILLS_DIR,
];
const spine: SpineState = {
@@ -2309,8 +2304,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
...(provisionOwnerAuth ? { provisionOwnerAuth } : {}),
...(ownerAuthCommand ? { ownerAuthCommand } : {}),
...(scopedCommand ? { scopedCommand } : {}),
- ensureSkillTree,
- readSkill,
+ useSkill,
...(reachAvailable
? {
reach: {
@@ -2867,15 +2861,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
const sessionUsedTools = visibleHistory.some(
(e) =>
e.type === "tool_call" &&
- !(
- e.payload !== null &&
- typeof e.payload === "object" &&
- "tool" in e.payload &&
- e.payload.tool === "read" &&
- "path" in e.payload &&
- typeof e.payload.path === "string" &&
- e.payload.path.startsWith("skill://")
- ),
+ !(e.payload !== null && typeof e.payload === "object" && "tool" in e.payload && e.payload.tool === "skill"),
);
if (
!strictReadOnly &&
diff --git a/src/core/orchestrator/sandboxes.ts b/src/core/orchestrator/sandboxes.ts
index 2cea5fb37..5b9a11495 100644
--- a/src/core/orchestrator/sandboxes.ts
+++ b/src/core/orchestrator/sandboxes.ts
@@ -11,11 +11,17 @@ import {
import type { DeviceFlowCutoverMode } from "../../credentials/device-flow-cutover.ts";
import { expandServiceAliases } from "../../credentials/resident-paths.ts";
import { shq } from "../../util/shell.ts";
-import { createSkillMaterializer, renderSkillBody, safeSkillDirName } from "../../skills/materialize.ts";
+import {
+ materializeSkillTree as laySkillTree,
+ packRoot,
+ rehomeSkillPaths,
+ renderSkillBody,
+ skillDir,
+ SKILLS_DIR,
+} from "../../skills/materialize.ts";
import { safeSkillFilePath, type SkillResolution } from "../../skills/skill-store.ts";
import { isSafeSkillName } from "../../skills/skill-name.ts";
-import { isSkillMaterializationControlPath } from "../../skills/materialization-paths.ts";
-import type { ReadResult } from "../../tools/primitives.ts";
+import type { SkillResult } from "../../tools/primitives.ts";
import { TURN_FILES_DIR } from "../attachments.ts";
import { errMessage, swallow, swallowAs } from "../../util/errors.ts";
import { sleep } from "../../util/async.ts";
@@ -47,9 +53,7 @@ export interface TurnSandboxContext {
credentialCutoverServices: string[];
quarantinedServices: string[];
cutoverModeOf: (service: string) => DeviceFlowCutoverMode;
- visibleSkills: SkillResolution[];
visibleSkillsForTurn: () => Promise<SkillResolution[]>;
- skillMaterializer: ReturnType<typeof createSkillMaterializer>;
emitGapWork: (phase: GapPhase, start: number, end: number) => void;
perf: { credsMs: number };
}
@@ -78,9 +82,7 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {
credentialCutoverServices,
quarantinedServices,
cutoverModeOf,
- visibleSkills,
visibleSkillsForTurn,
- skillMaterializer,
emitGapWork,
perf,
} = ctx;
@@ -308,51 +310,19 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {
emit("proc_reconcile", procReconcileStart, Date.now());
}
}
- if (deps.skills) await skillMaterializer.reconcileIndex(deps.sandbox, handle, visibleSkills, visibleSkillsForTurn);
box.handle = handle;
return handle;
};
- const readSkill = async (path: string): Promise<ReadResult> => {
- const missing = { content: null, sourceScopeId: null };
- const match = /^skill:\/\/([^/]+)\/(.+)$/.exec(path);
- if (!match || !isSafeSkillName(match[1]!)) return missing;
- const [, name, file] = match;
- try {
- if (safeSkillFilePath(file!) !== file || isSkillMaterializationControlPath(`skills/${name}/${file}`))
- return missing;
- } catch {
- return missing;
- }
- const resolution = (await visibleSkillsForTurn()).find((r) => r.skill?.manifest.name === name);
- if (!resolution?.skill) return missing;
- const content =
- file === "SKILL.md"
- ? renderSkillBody(resolution)
- : resolution.skill.manifest.files?.find((f) => f.path === file)?.content;
- if (content === undefined) return missing;
- if (deps.skills)
- void deps.skills.recordUse(resolution.skill.id).catch((e) => swallow("orchestrator: skill recordUse", e));
- return { content, sourceScopeId: resolution.skill.scopeId };
- };
+ const skillsRoot = `${turnFilesDir}/${SKILLS_DIR}`;
const laidTrees = new Set<string>();
const materializeSkillTree = async (handle: SandboxHandle, r: SkillResolution, sandboxId?: string): Promise<void> => {
- const skillDir = safeSkillDirName(r.skill!.manifest.name);
- const treeKey = `${sandboxId ?? "default"}:${skillDir}`;
+ const treeKey = `${sandboxId ?? "default"}:${skillDir(skillsRoot, r)}`;
if (laidTrees.has(treeKey)) return;
const start = Date.now();
try {
- await skillMaterializer.materializeTree(deps.sandbox, handle, r, [], async () => {
- const latest = (await visibleSkillsForTurn()).find(
- (candidate) => candidate.skill && safeSkillDirName(candidate.skill.manifest.name) === skillDir,
- );
- if (!latest) return null;
- const bundles =
- latest.screenedBundles ?? (deps.skillBundles ? await loadActiveBundles(deps.skillBundles, [latest]) : []);
- return { resolution: latest, bundles };
- });
+ const bundles = r.screenedBundles ?? (deps.skillBundles ? await loadActiveBundles(deps.skillBundles, [r]) : []);
+ await laySkillTree(deps.sandbox, handle, skillsRoot, r, bundles);
laidTrees.add(treeKey);
- if (r.skill && deps.skills)
- void deps.skills.recordUse(r.skill.id).catch((e) => swallow("orchestrator: skill recordUse", e));
} catch (err) {
deps.errors?.record(
{
@@ -364,23 +334,45 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {
},
err,
);
+ throw err;
} finally {
emitGapWork("skills_materialize", start, Date.now());
}
};
- const ensureSkillTree = async (skillDir: string, sandboxId?: string): Promise<void> => {
- const current = await visibleSkillsForTurn();
- const requested = current.filter(
- (r) =>
- r.skill &&
- (skillDir.startsWith(".packs/")
- ? r.skill.pack?.packId === skillDir.slice(".packs/".length)
- : r.skill.manifest.name === skillDir),
- );
- const handle = sandboxId ? await provisionResource(sandboxId) : await provision();
- for (const r of requested) {
- await materializeSkillTree(handle, r, sandboxId);
+ const useSkill = async (name: string, file: string, sandboxId?: string): Promise<SkillResult> => {
+ const missing = { content: null, sourceScopeId: null };
+ if (!isSafeSkillName(name)) return missing;
+ try {
+ if (safeSkillFilePath(file) !== file) return missing;
+ } catch {
+ return missing;
}
+ const resolution = (await visibleSkillsForTurn()).find((r) => r.skill?.manifest.name === name);
+ if (!resolution?.skill) return missing;
+ const shipsFiles = (resolution.skill.manifest.files?.length ?? 0) > 0 || resolution.skill.pack !== undefined;
+ const asset = resolution.skill.manifest.files?.find((f) => {
+ try {
+ return safeSkillFilePath(f.path) === file;
+ } catch {
+ return false;
+ }
+ })?.content;
+ let content: string | undefined;
+ if (file === "SKILL.md") content = renderSkillBody(resolution, shipsFiles ? skillsRoot : undefined);
+ else if (asset !== undefined) content = rehomeSkillPaths(resolution, asset, skillsRoot);
+ if (content === undefined) return missing;
+ if (deps.skills)
+ void deps.skills.recordUse(resolution.skill.id).catch((e) => swallow("orchestrator: skill recordUse", e));
+ if (!shipsFiles) return { content, sourceScopeId: resolution.skill.scopeId };
+ const handle = sandboxId ? await provisionResource(sandboxId) : await provision();
+ await materializeSkillTree(handle, resolution, sandboxId);
+ const pack = packRoot(skillsRoot, resolution);
+ return {
+ content,
+ sourceScopeId: resolution.skill.scopeId,
+ dir: skillDir(skillsRoot, resolution),
+ ...(pack ? { packDir: pack } : {}),
+ };
};
const provisionResource = (id: string): Promise<SandboxHandle> => {
const existing = resourceHandles.get(id);
@@ -401,8 +393,6 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {
resourcePendingHandles.set(id, handle);
await prepareCredentials(handle, emitGapWork);
await prepareTurnFiles(handle);
- if (deps.skills)
- await skillMaterializer.reconcileIndex(deps.sandbox, handle, visibleSkills, visibleSkillsForTurn);
resourceHandles.set(id, handle);
resourcePendingHandles.delete(id);
return handle;
@@ -698,8 +688,7 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {
provisionScratch,
provisionResource,
provisionOwnerAuth,
- ensureSkillTree,
- readSkill,
+ useSkill,
provisionForReach,
reclaimBox,
provisionPending: () => provisionInFlight !== null,
diff --git a/src/harness/agent-tools.ts b/src/harness/agent-tools.ts
index dab0363d5..04f8e52d6 100644
--- a/src/harness/agent-tools.ts
+++ b/src/harness/agent-tools.ts
@@ -975,13 +975,66 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):
},
});
+ const skill = defineTool({
+ name: "skill",
+ label: "skill",
+ description:
+ "Load a skill from the Skills index before relying on it. Returns its SKILL.md instructions (or the relative file named by `path`) straight from the published source, without starting a sandbox. When the skill ships scripts or supporting files, this call also syncs them into a directory that lives for this turn and reports it; run and read them there with execute and read, in this turn.",
+ parameters: Type.Object({
+ name: Type.String({ description: "Skill name exactly as listed in the Skills index." }),
+ path: Type.Optional(
+ Type.String({ description: "Relative file within the skill to return instead of SKILL.md." }),
+ ),
+ ...(opts?.sandboxResources
+ ? {
+ sandbox_id: Type.Optional(
+ Type.String({ description: "Sync the skill's files into this sandbox instead of the default." }),
+ ),
+ }
+ : {}),
+ }),
+ async execute(callId, params) {
+ const tc = ref.current;
+ if (!tc) return text("[error] no active tool context");
+ const p = params as { name: string; path?: string; sandbox_id?: string };
+ await recordCall(callId, { tool: "skill", name: p.name, ...(p.path ? { path: p.path } : {}) });
+ const signal = ref.abortSignal;
+ signal?.throwIfAborted();
+ const { content, sourceScopeId, dir, packDir } = await tc.skill(p.name, {
+ ...(p.path ? { path: p.path } : {}),
+ ...(p.sandbox_id ? { sandboxId: p.sandbox_id } : {}),
+ ...(signal ? { signal } : {}),
+ });
+ signal?.throwIfAborted();
+ const onSandbox = p.sandbox_id
+ ? ` on sandbox ${p.sandbox_id}; reach them with execute using that sandbox_id`
+ : "";
+ const where = dir
+ ? `[skill files synced to ${dir}/${packDir ? `; pack files at ${packDir}/` : ""}${onSandbox}]\n\n`
+ : "";
+ return recordResult(
+ callId,
+ {
+ tool: "skill",
+ name: p.name,
+ ...(p.path ? { path: p.path } : {}),
+ found: content !== null,
+ ...(content !== null ? { bytes: content.length, sourceScopeId } : {}),
+ ...(dir ? { dir } : {}),
+ },
+ text(content === null ? `[no such skill file: ${p.name}/${p.path ?? "SKILL.md"}]` : `${where}${content}`),
+ content === null,
+ sourceScopeId,
+ );
+ },
+ });
+
const read = defineTool({
name: "read",
label: "read",
- description:
- "Read published skill sources at skill://<name>/<path> without a sandbox, or workspace files (scope, then global). Returns contents.",
+ description: "Read a file from the workspace (scope, then global). Returns its contents.",
parameters: Type.Object({
- path: Type.String({ description: "Published skill URI or relative path within the workspace." }),
+ path: Type.String({ description: "Relative path within the workspace." }),
}),
async execute(callId, params) {
const tc = ref.current;
@@ -3847,6 +3900,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):
const tools = [
...(!opts?.sandboxResources ? [execute] : []),
...(credentialExecServices.length ? [credentialExec] : []),
+ skill,
read,
write,
publish,
diff --git a/src/harness/mock-harness.ts b/src/harness/mock-harness.ts
index 78be710aa..000830ffd 100644
--- a/src/harness/mock-harness.ts
+++ b/src/harness/mock-harness.ts
@@ -31,6 +31,8 @@ const READ_ONLY_BLOCKED_PREFIXES = [
"!screened-run ",
"!double-exec ",
"!read ",
+ "!skill ",
+ "!skill-run ",
"!write ",
"!attach ",
"!writeattach ",
@@ -553,6 +555,39 @@ export function createMockHarness(): Harness {
const added = await turn.tools.memoryRemember([fact]);
usedTool = true;
reply = added === null ? "(memory unavailable)" : `remembered ${added}`;
+ } else if (command0.startsWith("!skill-run ")) {
+ const rest = command0.slice(11).trim();
+ const sp = rest.indexOf(" ");
+ const name = sp === -1 ? rest : rest.slice(0, sp);
+ const r = await turn.tools.skill(name);
+ usedTool = true;
+ if (r.content == null) reply = `(no skill file: ${name}/SKILL.md)`;
+ else {
+ const command = rest
+ .slice(sp + 1)
+ .split("{dir}")
+ .join(r.dir ?? "");
+ const ran = await turn.tools.execute(command);
+ reply = (ran.stdout || ran.stderr).trim();
+ }
+ } else if (command0.startsWith("!skill ")) {
+ const [name, path] = command0.slice(7).trim().split(/\s+/);
+ const r = await turn.tools.skill(name!, path ? { path } : undefined);
+ await turn.emit({
+ type: "tool_result",
+ payload: { tool: "skill", name, found: r.content != null, ...(r.dir ? { dir: r.dir } : {}) },
+ scopeLabel: classifyScopeLabel({
+ type: "tool_result",
+ sessionScopeId: turn.scopeLabel,
+ orgScopeId: turn.orgScopeId,
+ sourceScopeId: r.sourceScopeId,
+ }),
+ });
+ usedTool = true;
+ reply =
+ r.content == null
+ ? `(no skill file: ${name}/${path ?? "SKILL.md"})`
+ : `${r.dir ? `${r.dir}\n` : ""}${r.content}`;
} else if (command0.startsWith("!write ")) {
const rest = command0.slice(7);
const sp = rest.indexOf(" ");
diff --git a/src/onboarding/onboarding.ts b/src/onboarding/onboarding.ts
index 316261435..3355e7b64 100644
--- a/src/onboarding/onboarding.ts
+++ b/src/onboarding/onboarding.ts
@@ -91,7 +91,7 @@ export function renderPendingOnboardingPrompt(status: OnboardingStatus, version
"",
"Onboarding is a high-priority setup task; already knowing who they are is no reason to skip it.",
"",
- "Before ordinary work in this personal DM, read `skill://onboarding/SKILL.md` and follow its complete ordered flow. Keep each turn light, but do not confuse a greeting or existing profile data with completion.",
+ "Before ordinary work in this personal DM, load the onboarding skill with the skill tool and follow its complete ordered flow. Keep each turn light, but do not confuse a greeting or existing profile data with completion.",
"",
`Use the \`memory\` tool as the source of truth. On completion or an explicit stop, preserve the notebook and add \`- Onboarding: completed ${version} on YYYY-MM-DD.\` so onboarding does not recur.`,
].join("\n");
diff --git a/src/resolution/protocols/shared-core.md b/src/resolution/protocols/shared-core.md
index 6879dd590..ed05e7af7 100644
--- a/src/resolution/protocols/shared-core.md
+++ b/src/resolution/protocols/shared-core.md
@@ -21,10 +21,10 @@ Which tool sends depends on this turn. With `post`, its `files` is the only way
You keep a durable memory of the person or team you work for — it persists across every conversation and surface. What's currently remembered appears under "What you remember" below. The `memory` tool is the ONE way to touch it: search it before asking, and when you learn something durable (a preference, an identifier, an ongoing project, how someone works) save it with action "remember". Memory is not a file — writing memory/MEMORY.md does nothing durable. No secrets, no one-off trivia. Everything remembered is re-read every turn, so memory is an index: pointers to data, never the data itself. Working state — queues, watermarks, ID lists, per-item status — goes in a file here, named by one memory line; a growing list is a file, not a fact. Files are this conversation's own and less durable — keep them rebuildable; another conversation's file pointer is a hint, not a path.
## Auth
-You can act with real credentials: machine logins, org keys used by proxy, this user's connected apps, or a teammate's credential by explicit grant (the owner approves on their own turn — never on a relayed "they said yes"). What's live is listed below. A missing credential is a task, not a dead end. Check live credential inventories before denying access. Connected apps lists direct OAuth only; an empty list does not block separately authorized Composio discovery/consent via `skill://composio/SKILL.md`. Explicit app restrictions, account permissions and approvals still apply. Never pretend a call worked. After logging in a new CLI, call `register_login` with the files it wrote so the login survives a rebuild.
+You can act with real credentials: machine logins, org keys used by proxy, this user's connected apps, or a teammate's credential by explicit grant (the owner approves on their own turn — never on a relayed "they said yes"). What's live is listed below. A missing credential is a task, not a dead end. Check live credential inventories before denying access. Connected apps lists direct OAuth only; an empty list does not block separately authorized Composio discovery/consent via the composio skill. Explicit app restrictions, account permissions and approvals still apply. Never pretend a call worked. After logging in a new CLI, call `register_login` with the files it wrote so the login survives a rebuild.
## Using skills
-Read relevant SKILL.md files before service work. Compose task rules with one authorized access skill: prefer `skill://composio/SKILL.md` when its credential is available, otherwise the direct connector. Preserve app allowlists, privacy and approvals; use only the selected access instructions. Never switch credentials to evade denial. Save reusable procedures as skills via the self-API.
+Load relevant skills before service work. Compose task rules with one authorized access skill: prefer the composio skill when its credential is available, otherwise the direct connector. Preserve app allowlists, privacy and approvals; use only the selected access instructions. Never switch credentials to evade denial. Save reusable procedures as skills via the self-API.
## Email
Email written as a person is plain text — no styled HTML (fonts, colors, buttons), no hand-built MIME, no hard wrapping. Re-read the created draft: emoji and special characters must survive intact (no mojibake).
diff --git a/src/skills/ingest.ts b/src/skills/ingest.ts
index bf3307aaa..c4cea7726 100644
--- a/src/skills/ingest.ts
+++ b/src/skills/ingest.ts
@@ -3,13 +3,7 @@ import { upsertSeedSkill, type UpsertOutcome } from "./seed.ts";
import { safeSkillFilePath, type SkillFile, type SkillManifest, type SkillStore } from "./skill-store.ts";
import type { SkillPack } from "./skill-pack-store.ts";
import type { ScopeId } from "../types.ts";
-import {
- skillRecordPaths,
- bundleFilePaths,
- detectPathCollisions,
- materializationControlPathCollisions,
- SkillPackCollisionError,
-} from "./skill-collision.ts";
+import { skillRecordPaths, bundleFilePaths, detectPathCollisions, SkillPackCollisionError } from "./skill-collision.ts";
export interface RepoFile {
path: string;
@@ -248,8 +242,6 @@ export async function importPack(
const incomingSkillPaths = toWrite.flatMap((w) => skillRecordPaths(w.manifest.name, w.manifest.files));
const incomingBundlePaths = bundleFilePaths(ctx.bundleFiles ?? []);
- const controlCollisions = materializationControlPathCollisions(incomingBundlePaths);
- if (controlCollisions.length) throw new SkillPackCollisionError(controlCollisions);
if (ctx.claimedPaths) {
const incoming = [...incomingSkillPaths, ...incomingBundlePaths];
const collisions = detectPathCollisions(incoming, ctx.claimedPaths);
diff --git a/src/skills/materialization-paths.ts b/src/skills/materialization-paths.ts
deleted file mode 100644
index 41dc1f0b3..000000000
--- a/src/skills/materialization-paths.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-export const SKILLS_DIR = "skills";
-export const SKILLS_INDEX_MARKER = `${SKILLS_DIR}/.index`;
-export const SKILL_TREE_MARKER = ".tree";
-
-export function isSkillMaterializationControlPath(path: string): boolean {
- if (path === SKILLS_INDEX_MARKER || path.startsWith(`${SKILLS_INDEX_MARKER}/`)) return true;
- const parts = path.split("/");
- return parts.length >= 3 && parts[0] === SKILLS_DIR && parts[2] === SKILL_TREE_MARKER;
-}
diff --git a/src/skills/materialize.ts b/src/skills/materialize.ts
index d4cba9709..52c3ee56f 100644
--- a/src/skills/materialize.ts
+++ b/src/skills/materialize.ts
@@ -1,88 +1,34 @@
import { CapabilityUnsupportedError, type Sandbox, type SandboxHandle } from "../sandbox/sandbox.ts";
-import { createHash } from "node:crypto";
import { safeSkillFilePath, type SkillFile, type SkillResolution } from "./skill-store.ts";
import type { SkillBundle } from "./skill-bundle-store.ts";
import { swallow } from "../util/errors.ts";
-import { assertSafeSkillName, isSafeSkillName } from "./skill-name.ts";
-import { createKeyedQueue } from "../util/async.ts";
-import type { AdvisoryLock } from "../persistence/advisory-lock.ts";
+import { assertSafeSkillName } from "./skill-name.ts";
import type { ScopeId } from "../types.ts";
-import {
- isSkillMaterializationControlPath,
- SKILLS_DIR,
- SKILLS_INDEX_MARKER as INDEX_MARKER,
- SKILL_TREE_MARKER as TREE_MARKER,
-} from "./materialization-paths.ts";
-const SKILL_PACKS_DIR = `${SKILLS_DIR}/.packs`;
-export { SKILLS_DIR } from "./materialization-paths.ts";
-
-export interface SkillMaterializer {
- reconcileIndex(
- sandbox: Sandbox,
- handle: SandboxHandle,
- resolved: SkillResolution[],
- current?: () => Promise<SkillResolution[]>,
- ): Promise<void>;
- materializeTree(
- sandbox: Sandbox,
- handle: SandboxHandle,
- resolution: SkillResolution,
- bundles?: SkillBundle[],
- current?: () => Promise<{ resolution: SkillResolution; bundles: SkillBundle[] } | null>,
- ): Promise<void>;
-}
-
-function materializationKey(handle: SandboxHandle): string {
- const sandboxId = createHash("sha256").update(handle.id).update("\0").update(handle.rootDir).digest("hex");
- return `skills:projection:${sandboxId}`;
-}
+export const SKILLS_DIR = "skills";
export function safeSkillDirName(name: string): string {
return assertSafeSkillName(name);
}
-function indexHash(resolved: SkillResolution[]): string {
- const h = createHash("sha256");
- const entries = resolved
- .filter((r) => r.skill)
- .map((r) => `${r.skill!.manifest.name}\0${r.skill!.scopeId}\0${r.skill!.id}`)
- .sort();
- for (const e of entries) {
- h.update(e);
- h.update("\n");
- }
- return h.digest("hex");
+export function skillDir(root: string, resolution: SkillResolution): string {
+ return `${root}/${safeSkillDirName(resolution.skill!.manifest.name)}`;
}
-function treeHash(resolution: SkillResolution, bundles: SkillBundle[]): string {
- const m = resolution.skill!.manifest;
- const files = [...(m.files ?? [])]
- .map((f) => `${f.path}\0${f.content}\0${f.executable === true ? "1" : "0"}`)
- .sort()
- .join("\0");
- const folded = [...bundles]
- .map((b) => b.hash)
- .sort()
- .join("\0");
- return createHash("sha256")
- .update(renderSkillBody(resolution))
- .update("\0")
- .update(files)
- .update("\0")
- .update(folded)
- .digest("hex");
+export function packRoot(root: string, resolution: SkillResolution): string | null {
+ return resolution.skill?.pack ? `${root}/.packs/${safeSkillDirName(resolution.skill.pack.packId)}` : null;
}
-function packRoot(resolution: SkillResolution): string | null {
- return resolution.skill?.pack ? `${SKILL_PACKS_DIR}/${safeSkillDirName(resolution.skill.pack.packId)}` : null;
+export function rehomeSkillPaths(resolution: SkillResolution, text: string, root: string): string {
+ const name = safeSkillDirName(resolution.skill!.manifest.name);
+ return text.split(`${SKILLS_DIR}/${name}/`).join(`${root}/${name}/`);
}
-export function renderSkillBody(resolution: SkillResolution): string {
- const body = resolution.skill!.manifest.body;
- const root = packRoot(resolution);
- return root
- ? `${body}\n\n## Pack files\nResolve repository-relative shared-file paths against \`${root}/\`; pack files never overwrite the workspace root.`
+export function renderSkillBody(resolution: SkillResolution, root = SKILLS_DIR): string {
+ const body = rehomeSkillPaths(resolution, resolution.skill!.manifest.body, root);
+ const pack = packRoot(root, resolution);
+ return pack
+ ? `${body}\n\n## Pack files\nResolve repository-relative shared-file paths against \`${pack}/\`; pack files never overwrite the workspace root.`
: body;
}
@@ -91,114 +37,46 @@ interface LayEntry {
content: string;
}
-interface IndexMarkerState {
- version: 2;
- hash: string;
- names: string[];
- identities?: Record<string, string>;
- legacyExternalPathsPreserved?: true;
-}
-
-interface TreeMarkerState {
- version: 2;
- hash: string;
- skillPaths: string[];
- bundlePaths: string[];
-}
-
-function parsedMarker(raw: string | null): Record<string, unknown> | null {
- if (!raw?.startsWith("{")) return null;
- try {
- const parsed = JSON.parse(raw) as Record<string, unknown>;
- return parsed.version === 2 && typeof parsed.hash === "string" ? parsed : null;
- } catch {
- return null;
- }
-}
-
-function indexMarkerState(raw: string | null): IndexMarkerState | null {
- const parsed = parsedMarker(raw);
- if (
- !parsed ||
- !Array.isArray(parsed.names) ||
- !parsed.names.every((name) => typeof name === "string" && isSafeSkillName(name))
- )
- return null;
- return parsed as unknown as IndexMarkerState;
-}
-
-function isSafeMaterializedPath(path: unknown): path is string {
- if (typeof path !== "string") return false;
- try {
- return safeSkillFilePath(path) === path;
- } catch {
- return false;
- }
-}
-
-function treeMarkerState(raw: string | null, dir: string): TreeMarkerState | null {
- const parsed = parsedMarker(raw);
- if (!parsed || !Array.isArray(parsed.skillPaths) || !Array.isArray(parsed.bundlePaths)) return null;
- if (
- !parsed.skillPaths.every(
- (path) => isSafeMaterializedPath(path) && path.startsWith(`${dir}/`) && !isSkillMaterializationControlPath(path),
- )
- )
- return null;
- if (!parsed.bundlePaths.every((path) => isSafeMaterializedPath(path) && !isSkillMaterializationControlPath(path)))
- return null;
- return parsed as unknown as TreeMarkerState;
-}
-
-function samePaths(a: string[], b: string[]): boolean {
- return a.length === b.length && a.every((path, index) => path === b[index]);
-}
-
-async function readMarker(
- sandbox: Sandbox,
- handle: SandboxHandle,
- path: string,
+function entriesUnder(
+ dir: string,
+ files: SkillFile[],
label: string,
-): Promise<string | null> {
- try {
- return await sandbox.readFile(handle, path);
- } catch (error) {
- swallow(label, error);
- return null;
- }
-}
-
-function guardedSkillPaths(dir: string, files: SkillFile[] | undefined): string[] {
- const paths = [`${dir}/SKILL.md`];
- for (const file of files ?? []) {
+ content: (f: SkillFile) => string = (f) => f.content,
+ skip: (rel: string) => boolean = () => false,
+): LayEntry[] {
+ const entries: LayEntry[] = [];
+ for (const f of files) {
try {
- const path = `${dir}/${safeSkillFilePath(file.path)}`;
- if (!isSkillMaterializationControlPath(path)) paths.push(path);
- } catch (error) {
- swallow(`skills: bad asset path ${file.path}`, error);
- }
- }
- return [...new Set(paths)].sort();
-}
-
-function guardedBundlePaths(bundles: SkillBundle[]): string[] {
- const paths: string[] = [];
- for (const bundle of bundles) {
- const root = `${SKILL_PACKS_DIR}/${safeSkillDirName(bundle.packId)}`;
- for (const file of bundle.files) {
- try {
- const path = `${root}/${safeSkillFilePath(file.path)}`;
- if (!isSkillMaterializationControlPath(path)) paths.push(path);
- } catch (error) {
- swallow(`skills: bad bundle path ${file.path}`, error);
- }
+ const rel = safeSkillFilePath(f.path);
+ if (!skip(rel)) entries.push({ path: `${dir}/${rel}`, content: content(f) });
+ } catch (e) {
+ swallow(`skills: bad ${label} path ${f.path}`, e);
}
}
- return [...new Set(paths)].sort();
+ return entries;
}
-async function layFiles(sandbox: Sandbox, handle: SandboxHandle, entries: LayEntry[]): Promise<void> {
- if (!entries.length) return;
+export async function materializeSkillTree(
+ sandbox: Sandbox,
+ handle: SandboxHandle,
+ root: string,
+ resolution: SkillResolution,
+ bundles: SkillBundle[] = [],
+): Promise<void> {
+ if (!resolution.skill) return;
+ const dir = skillDir(root, resolution);
+ const entries: LayEntry[] = [
+ { path: `${dir}/SKILL.md`, content: renderSkillBody(resolution, root) },
+ ...entriesUnder(
+ dir,
+ resolution.skill.manifest.files ?? [],
+ "asset",
+ (f) => rehomeSkillPaths(resolution, f.content, root),
+ (rel) => rel === "SKILL.md",
+ ),
+ ];
+ for (const b of bundles)
+ entries.push(...entriesUnder(`${root}/.packs/${safeSkillDirName(b.packId)}`, b.files, "bundle"));
if (sandbox.importFiles) {
try {
await sandbox.importFiles(
@@ -213,197 +91,6 @@ async function layFiles(sandbox: Sandbox, handle: SandboxHandle, entries: LayEnt
for (const e of entries) await sandbox.writeFile(handle, e.path, e.content);
}
-async function reconcileSkillIndexUnlocked(
- sandbox: Sandbox,
- handle: SandboxHandle,
- resolved: SkillResolution[],
-): Promise<void> {
- const want = indexHash(resolved);
- const names = resolved.flatMap((r) => (r.skill ? [safeSkillDirName(r.skill.manifest.name)] : [])).sort();
- const identities = Object.fromEntries(
- resolved.flatMap((r) =>
- r.skill ? [[safeSkillDirName(r.skill.manifest.name), JSON.stringify([r.skill.scopeId, r.skill.id])]] : [],
- ),
- );
- const raw = await readMarker(sandbox, handle, INDEX_MARKER, "skills: index probe");
- const prev = indexMarkerState(raw);
- if (prev?.hash === want && samePaths(prev.names, names)) return;
- const legacyExternalPathsPreserved = prev?.legacyExternalPathsPreserved === true || Boolean(raw && !prev);
-
- if (raw && !prev) {
- await sandbox.removeDir(handle, SKILLS_DIR);
- } else if (prev) {
- const unchangedNames = new Set(names.filter((name) => prev.identities?.[name] === identities[name]));
- const activeBundlePaths = new Set<string>();
- for (const name of unchangedNames) {
- const currentRaw = await readMarker(
- sandbox,
- handle,
- `${SKILLS_DIR}/${name}/${TREE_MARKER}`,
- `skills: tree probe ${name}`,
- );
- const current = treeMarkerState(currentRaw, `${SKILLS_DIR}/${name}`);
- for (const path of current?.bundlePaths ?? []) activeBundlePaths.add(path);
- }
- for (const name of prev.names) {
- if (unchangedNames.has(name)) continue;
- const dir = `${SKILLS_DIR}/${name}`;
- const staleRaw = await readMarker(sandbox, handle, `${dir}/${TREE_MARKER}`, `skills: tree probe ${name}`);
- const stale = treeMarkerState(staleRaw, dir);
- const paths = new Set([`${dir}/SKILL.md`, ...(stale?.skillPaths ?? []), ...(stale?.bundlePaths ?? [])]);
- for (const path of paths) {
- if (!activeBundlePaths.has(path)) await sandbox.removeDir(handle, path);
- }
- const protectsDirectory = [...activeBundlePaths].some((path) => path.startsWith(`${dir}/`));
- if (protectsDirectory) await sandbox.removeDir(handle, `${dir}/${TREE_MARKER}`);
- else await sandbox.removeDir(handle, dir);
- }
- }
-
- const entries: LayEntry[] = [];
- entries.push({
- path: INDEX_MARKER,
- content: JSON.stringify({
- version: 2,
- hash: want,
- names,
- identities,
- ...(legacyExternalPathsPreserved ? { legacyExternalPathsPreserved: true as const } : {}),
- } satisfies IndexMarkerState),
- });
- await layFiles(sandbox, handle, entries);
-}
-
-async function materializeSkillTreeUnlocked(
- sandbox: Sandbox,
- handle: SandboxHandle,
- resolution: SkillResolution,
- bundles: SkillBundle[] = [],
-): Promise<void> {
- if (!resolution.skill) return;
- const m = resolution.skill.manifest;
- const files = m.files ?? [];
-
- const dir = `${SKILLS_DIR}/${safeSkillDirName(m.name)}`;
- const marker = `${dir}/${TREE_MARKER}`;
- const want = treeHash(resolution, bundles);
- const skillPaths = guardedSkillPaths(dir, files);
- const bundlePaths = guardedBundlePaths(bundles);
- const raw = await readMarker(sandbox, handle, marker, "skills: tree probe");
- const prev = treeMarkerState(raw, dir);
- if (prev?.hash === want && samePaths(prev.skillPaths, skillPaths) && samePaths(prev.bundlePaths, bundlePaths)) return;
-
- if (raw === want) {
- await sandbox.writeFile(
- handle,
- marker,
- JSON.stringify({ version: 2, hash: want, skillPaths, bundlePaths } satisfies TreeMarkerState),
- );
- return;
- }
-
- const otherBundlePaths = new Set<string>();
- const indexRaw = await readMarker(sandbox, handle, INDEX_MARKER, "skills: index probe");
- const index = indexMarkerState(indexRaw);
- for (const name of index?.names ?? []) {
- if (name === safeSkillDirName(m.name)) continue;
- const otherRaw = await readMarker(
- sandbox,
- handle,
- `${SKILLS_DIR}/${name}/${TREE_MARKER}`,
- `skills: tree probe ${name}`,
- );
- const other = treeMarkerState(otherRaw, `${SKILLS_DIR}/${name}`);
- for (const path of other?.bundlePaths ?? []) otherBundlePaths.add(path);
- }
-
- if (prev) {
- const currentSkillPaths = new Set(skillPaths);
- const currentBundlePaths = new Set(bundlePaths);
- for (const path of prev.skillPaths) {
- if (!currentSkillPaths.has(path) && !otherBundlePaths.has(path)) await sandbox.removeDir(handle, path);
- }
- for (const path of prev.bundlePaths) {
- if (!currentBundlePaths.has(path) && !otherBundlePaths.has(path)) await sandbox.removeDir(handle, path);
- }
- } else if (![...otherBundlePaths].some((path) => path.startsWith(`${dir}/`))) {
- await sandbox.removeDir(handle, dir);
- }
-
- const entries: LayEntry[] = [{ path: `${dir}/SKILL.md`, content: renderSkillBody(resolution) }];
- for (const f of files) {
- let rel: string;
- try {
- rel = safeSkillFilePath(f.path);
- } catch (e) {
- swallow(`skills: bad asset path ${f.path}`, e);
- continue;
- }
- const path = `${dir}/${rel}`;
- if (!isSkillMaterializationControlPath(path)) entries.push({ path, content: f.content });
- }
- for (const b of bundles) {
- const root = `${SKILL_PACKS_DIR}/${safeSkillDirName(b.packId)}`;
- for (const f of b.files) {
- let rel: string;
- try {
- rel = safeSkillFilePath(f.path);
- } catch (e) {
- swallow(`skills: bad bundle path ${f.path}`, e);
- continue;
- }
- const path = `${root}/${rel}`;
- if (!isSkillMaterializationControlPath(path)) entries.push({ path, content: f.content });
- }
- }
- entries.push({
- path: marker,
- content: JSON.stringify({ version: 2, hash: want, skillPaths, bundlePaths } satisfies TreeMarkerState),
- });
- await layFiles(sandbox, handle, entries);
-}
-
-export function createSkillMaterializer(advisoryLock?: AdvisoryLock): SkillMaterializer {
- const queue = createKeyedQueue<string>();
- const locked = <T>(handle: SandboxHandle, fn: () => Promise<T>): Promise<T> => {
- const key = materializationKey(handle);
- return queue(key, () => advisoryLock?.withLock(key, fn) ?? fn());
- };
- return {
- reconcileIndex(sandbox, handle, resolved, current) {
- return locked(handle, async () => {
- const latest = current ? await current() : resolved;
- await reconcileSkillIndexUnlocked(sandbox, handle, latest);
- });
- },
- materializeTree(sandbox, handle, resolution, bundles = [], current) {
- return locked(handle, async () => {
- const latest = current ? await current() : { resolution, bundles };
- if (latest) await materializeSkillTreeUnlocked(sandbox, handle, latest.resolution, latest.bundles);
- });
- },
- };
-}
-
-const localMaterializer = createSkillMaterializer();
-
-export function reconcileSkillIndex(
- sandbox: Sandbox,
- handle: SandboxHandle,
- resolved: SkillResolution[],
-): Promise<void> {
- return localMaterializer.reconcileIndex(sandbox, handle, resolved);
-}
-
-export function materializeSkillTree(
- sandbox: Sandbox,
- handle: SandboxHandle,
- resolution: SkillResolution,
- bundles: SkillBundle[] = [],
-): Promise<void> {
- return localMaterializer.materializeTree(sandbox, handle, resolution, bundles);
-}
-
export function skillsIndex(resolved: SkillResolution[], provenanceScopes: readonly ScopeId[] = []): string {
const provenance = new Set(provenanceScopes);
const items = resolved
@@ -419,11 +106,11 @@ export function skillsIndex(resolved: SkillResolution[], provenanceScopes: reado
const m = r.skill!.manifest;
const shadow = r.shadowed.length ? " (shadows a broader-scope skill of the same name)" : "";
const source = provenance.has(r.skill!.scopeId) ? ` [from ${r.skill!.scopeId}]` : "";
- return `- **${m.name}**${source} — ${m.description}${shadow} → read \`skill://${safeSkillDirName(m.name)}/SKILL.md\``;
+ return `- **${m.name}**${source} — ${m.description}${shadow}`;
});
return [
"## Skills",
- "Read published skills with the read tool at skill://<name>/SKILL.md; this does not start a sandbox. Read relative skill files at skill://<name>/<path>. These are read-only published sources, not filesystem paths. Execute scripts and access working copies under skills/<name>/ in the sandbox; ordinary filesystem reads preserve local edits.",
+ "Load a skill with the skill tool before relying on it: skill({ name }) returns its instructions without starting a sandbox. When a skill ships scripts or supporting files, the same call syncs them into a directory that lives for this turn and names it; run and read them there.",
...lines,
].join("\n");
}
diff --git a/src/skills/skill-collision.ts b/src/skills/skill-collision.ts
index 8a90af498..fed588091 100644
--- a/src/skills/skill-collision.ts
+++ b/src/skills/skill-collision.ts
@@ -1,5 +1,4 @@
-import { safeSkillDirName } from "./materialize.ts";
-import { isSkillMaterializationControlPath, SKILLS_DIR, SKILL_TREE_MARKER } from "./materialization-paths.ts";
+import { safeSkillDirName, SKILLS_DIR } from "./materialize.ts";
import { safeSkillFilePath, type SkillFile } from "./skill-store.ts";
import { isSafeSkillName } from "./skill-name.ts";
@@ -7,26 +6,17 @@ export const SKILL_MATERIALIZATION_LOCK = "skills:materialization";
export function skillRecordPaths(name: string, files: SkillFile[] | undefined): string[] {
const dir = `${SKILLS_DIR}/${safeSkillDirName(name)}`;
- const out = [`${dir}/SKILL.md`, `${dir}/${SKILL_TREE_MARKER}`];
+ const out = [`${dir}/SKILL.md`];
for (const f of files ?? []) {
- let rel: string;
try {
- rel = safeSkillFilePath(f.path);
+ out.push(`${dir}/${safeSkillFilePath(f.path)}`);
} catch {
continue;
}
- const path = `${dir}/${rel}`;
- if (!isSkillMaterializationControlPath(path)) out.push(path);
}
return out;
}
-export function materializationControlPathCollisions(paths: string[]): PathCollision[] {
- return paths
- .filter(isSkillMaterializationControlPath)
- .map((path) => ({ path, owner: "core skill materialization metadata" }));
-}
-
export function persistedSkillRecordPaths(name: string, files: SkillFile[] | undefined): string[] {
return isSafeSkillName(name) ? skillRecordPaths(name, files) : [];
}
diff --git a/src/tools/primitives.ts b/src/tools/primitives.ts
index 0689bec3b..0e1a63a71 100644
--- a/src/tools/primitives.ts
+++ b/src/tools/primitives.ts
@@ -77,20 +77,6 @@ import type { CapabilityClaims } from "../auth/capability-token.ts";
import type { VisibleCron } from "../api/app.ts";
import { createPlaygroundArtifact, type PlaygroundArtifact } from "../playgrounds/playground.ts";
-const SKILL_FILE_RE = /^(?:\.\/)?skills\/(\.packs\/[^/]+|[^/]+)\/.+$/;
-function skillTreeDirFor(path: string): string | null {
- const m = SKILL_FILE_RE.exec(path);
- return m ? m[1]! : null;
-}
-
-const SKILL_DIR_IN_COMMAND_RE =
- /(?:^|[\s'"=(&|;])(?:\.\/)?skills\/(\.packs\/[^/\s'"&|;)]+|[^/\s'"&|;)]+)(?=[/\s'"&|;)]|$)/g;
-function skillTreeDirsInCommand(command: string): string[] {
- const dirs = new Set<string>();
- for (const m of command.matchAll(SKILL_DIR_IN_COMMAND_RE)) dirs.add(m[1]!);
- return [...dirs];
-}
-
export interface PublishInput {
dir?: string;
entrypoint?: string;
@@ -145,12 +131,19 @@ export class CommandDenied extends Error {
}
}
-export interface ReadResult {
+interface ReadResult {
content: string | null;
sourceScopeId: ScopeId | null;
shared?: true;
}
+export interface SkillResult {
+ content: string | null;
+ sourceScopeId: ScopeId | null;
+ dir?: string;
+ packDir?: string;
+}
+
export interface ShareDirective {
scope: ScopeId | "org";
permission?: Permission;
@@ -216,6 +209,7 @@ export interface ToolContext extends SurfaceToolDeps {
restartComputer(sandboxId?: string): Promise<void>;
migrateComputer(to: string): Promise<{ from: string; to: string }>;
read(path: string, signal?: AbortSignal): Promise<ReadResult>;
+ skill(name: string, opts?: { path?: string; sandboxId?: string; signal?: AbortSignal }): Promise<SkillResult>;
write(path: string, data?: string, share?: ShareDirective[]): Promise<WriteResult>;
publish(input: PublishInput): Promise<PublishResult>;
createPlayground(input: { title: string; html: string }): Promise<PlaygroundArtifact>;
@@ -435,8 +429,7 @@ export interface ToolContextDeps {
provisionOwnerAuth?: () => Promise<SandboxHandle>;
ownerAuthCommand?: (command: string) => string;
scopedCommand?: (command: string) => string;
- readSkill?: (path: string) => Promise<ReadResult>;
- ensureSkillTree?: (skillDir: string, sandboxId?: string) => Promise<void>;
+ useSkill?: (name: string, path: string, sandboxId?: string) => Promise<SkillResult>;
reach?: {
resolveChannel(query: string): Promise<ReachResolution>;
provisionFor(scopeId: ScopeId): Promise<SandboxHandle>;
@@ -786,11 +779,6 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {
...(execOpts?.signal ? { signal: execOpts.signal } : {}),
}
: undefined;
- const local = !scratch && !ownerAuth && reached === undefined && !execOpts?.sandboxId;
- if ((local || execOpts?.sandboxId) && deps.ensureSkillTree) {
- for (const skillDir of skillTreeDirsInCommand(command))
- await deps.ensureSkillTree(skillDir, execOpts?.sandboxId);
- }
return once(async () => {
if (reached) {
deps.auditLog?.record({
@@ -816,8 +804,6 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {
async read(path: string, signal?: AbortSignal): Promise<ReadResult> {
signal?.throwIfAborted();
- if (path.startsWith("skill://"))
- return deps.readSkill ? withAbort(() => deps.readSkill!(path), signal) : { content: null, sourceScopeId: null };
if (path === MEMORY_FILE && deps.memory && deps.memoryScopeId) {
if (!deps.memoryAccess?.read.includes(deps.memoryScopeId)) {
throw new Error("memory recall is not enabled for this conversation; use the `memory` tool when enabled");
@@ -858,8 +844,6 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {
};
}
if (path.startsWith("shared/open-")) return { content: null, sourceScopeId: null };
- const skillDir = skillTreeDirFor(path);
- if (skillDir && deps.ensureSkillTree) await deps.ensureSkillTree(skillDir);
signal?.throwIfAborted();
const handle = await deps.provision();
return timed("file_op", async () => {
@@ -884,9 +868,23 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {
);
},
+ async skill(
+ name: string,
+ opts?: { path?: string; sandboxId?: string; signal?: AbortSignal },
+ ): Promise<SkillResult> {
+ opts?.signal?.throwIfAborted();
+ if (!deps.useSkill) return { content: null, sourceScopeId: null };
+ if (opts?.sandboxId) {
+ if (!deps.sandboxResources || !deps.provisionResource)
+ throw new Error("named sandboxes are not available here");
+ const record = await deps.sandboxResources.get(opts.sandboxId);
+ if (!record) throw new Error(`unknown sandbox ${opts.sandboxId}`);
+ if (record.ownerScopeId !== writableScopeId) throw new Error("load skills from the sandbox's owning scope");
+ }
+ return withAbort(() => deps.useSkill!(name, opts?.path ?? "SKILL.md", opts?.sandboxId), opts?.signal);
+ },
+
async write(path: string, data?: string, share?: ShareDirective[]): Promise<WriteResult> {
- if (path.startsWith("skill://"))
- throw new Error("Published skill sources are read-only; edit skills through the skill API.");
const wantShare = share !== undefined && share.length > 0;
if (data === undefined && !wantShare) {
throw new Error("write needs `data` to save content, `share` to grant access, or both");
@@ -1160,9 +1158,6 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {
if (decision === "require_approval" && !deps.authorizeCommand(command, approvalKey)) {
throw new NeedsApproval(command, reason ?? "requires approval", "approval", matched, approvalKey);
}
- if (deps.ensureSkillTree) {
- for (const skillDir of skillTreeDirsInCommand(command)) await deps.ensureSkillTree(skillDir, opts?.sandboxId);
- }
return once(
() =>
deps.backgroundBroker!.start(
diff --git a/test/agent-tools.test.ts b/test/agent-tools.test.ts
index 993f89903..3fb5b8b1c 100644
--- a/test/agent-tools.test.ts
+++ b/test/agent-tools.test.ts
@@ -27,6 +27,9 @@ function fakeToolContext(sink?: { lastExecOpts?: Parameters<ToolContext["execute
async computerStatus() {
return { machine: "healthy", guestResponsive: true };
},
+ async skill() {
+ return { content: null, sourceScopeId: null };
+ },
async read(path) {
return path === "a.txt"
? { content: "data", sourceScopeId: "personal:U1" }
@@ -378,7 +381,7 @@ test("each agent tool emits a tool_call then a tool_result", async () => {
},
scopeLabel: "personal:U1",
};
- const [execute, read, write] = createAgentTools(ref);
+ const [execute, , read, write] = createAgentTools(ref);
await call(execute, { command: "echo hi" });
await call(read, { path: "a.txt" });
@@ -1498,7 +1501,7 @@ test("a cross-scope read's tool_result keeps the SOURCE scope label so the audie
scopeLabel: "channel:C1",
orgScopeId: "org:default-org",
};
- const [execute, read] = createAgentTools(ref);
+ const [execute, , read] = createAgentTools(ref);
await call(read, { path: "a.txt" });
await call(read, { path: "missing.txt" });
@@ -1563,7 +1566,7 @@ test("a cross-scope result's classified label is recorded by callId for the tape
scopeLabel: "channel:C1",
orgScopeId: "org:acme",
};
- const [execute, read] = createAgentTools(ref);
+ const [execute, , read] = createAgentTools(ref);
await callWith(read, "call-private", { path: "a.txt" });
await callWith(read, "call-missing", { path: "missing.txt" });
@@ -1583,7 +1586,7 @@ test("tool entries carry the call id + faithful model-facing result (WAL replay
},
scopeLabel: "personal:U1",
};
- const [execute, read, , , memory] = createAgentTools(ref);
+ const [execute, , read, , , memory] = createAgentTools(ref);
await callWith(execute, "call-exec", { command: "echo hi" });
await callWith(read, "call-read", { path: "a.txt" });
@@ -1750,7 +1753,7 @@ test("not-found read and denied command record isError + the faithful error text
},
scopeLabel: "org:default-org",
};
- const [execute, read] = createAgentTools(ref);
+ const [execute, , read] = createAgentTools(ref);
await callWith(execute, "c1", { command: "rm -rf /" });
await callWith(read, "c2", { path: "missing.txt" });
@@ -1780,7 +1783,7 @@ test("a denied command still emits a tool_result (denied), and a missing read re
},
scopeLabel: "org:default-org",
};
- const [execute, read] = createAgentTools(ref);
+ const [execute, , read] = createAgentTools(ref);
await call(execute, { command: "rm -rf /" });
await call(read, { path: "missing.txt" });
@@ -1905,7 +1908,7 @@ test("publish reply states owner + resolved audience in human terms (ADR 0003 D7
});
const org = textOf(
- await call(createAgentTools({ current: withAudience({ kind: "org", orgId: "acme" }) })[3], {
+ await call(createAgentTools({ current: withAudience({ kind: "org", orgId: "acme" }) })[4], {
entrypoint: "x",
name: "site",
}),
@@ -1914,7 +1917,7 @@ test("publish reply states owner + resolved audience in human terms (ADR 0003 D7
assert.match(org, /anyone at acme/);
const members = textOf(
- await call(createAgentTools({ current: withAudience({ kind: "members", channelRef: "C1", memberCount: 3 }) })[3], {
+ await call(createAgentTools({ current: withAudience({ kind: "members", channelRef: "C1", memberCount: 3 }) })[4], {
entrypoint: "x",
name: "site",
}),
@@ -1922,7 +1925,7 @@ test("publish reply states owner + resolved audience in human terms (ADR 0003 D7
assert.match(members, /reachable by the 3 people currently in #C1/);
const owner = textOf(
- await call(createAgentTools({ current: withAudience({ kind: "owner" }) })[3], { entrypoint: "x", name: "site" }),
+ await call(createAgentTools({ current: withAudience({ kind: "owner" }) })[4], { entrypoint: "x", name: "site" }),
);
assert.match(owner, /owner-only/);
@@ -1933,7 +1936,7 @@ test("publish reply states owner + resolved audience in human terms (ADR 0003 D7
kind: "owner",
note: "couldn't enumerate the channel's members to auto-share — share manually",
}),
- })[3],
+ })[4],
{ entrypoint: "x", name: "site" },
),
);
@@ -1954,7 +1957,7 @@ test("publish reply: the reply never carries a capability token, even from a sta
} as never;
},
};
- const out = textOf(await call(createAgentTools({ current: stale })[3], { entrypoint: "x", name: "site" }));
+ const out = textOf(await call(createAgentTools({ current: stale })[4], { entrypoint: "x", name: "site" }));
assert.match(out, /https:\/\/site\.apps\.example\.com\//, "the bare URL is in the reply");
assert.doesNotMatch(out, /access=/, "no capability token in the reply");
assert.doesNotMatch(out, /anyone with this link/, "reach is described by the audience, never a bearer claim");
diff --git a/test/deployment-skill.test.ts b/test/deployment-skill.test.ts
index 8c1bc56cf..fe2294ea8 100644
--- a/test/deployment-skill.test.ts
+++ b/test/deployment-skill.test.ts
@@ -108,7 +108,7 @@ test("connector onboarding is governed by the live admin-configured list", () =>
assert.doesNotMatch(skill, /Slack and Google first|Slack, Google, Notion, Linear, and GitHub/);
}
for (const skill of [onboarding, connectApps]) {
- assert.match(skill, /skill:\/\/composio\/SKILL\.md/);
+ assert.match(skill, /composio`? skill/);
assert.match(skill, /never switch credentials to evade a denial/i);
assert.doesNotMatch(skill, /If it says none are enabled, skip|offer none when that list is/);
}
diff --git a/test/ingest.test.ts b/test/ingest.test.ts
index 72ab6d9cd..cd1a9a573 100644
--- a/test/ingest.test.ts
+++ b/test/ingest.test.ts
@@ -140,29 +140,3 @@ test("a shared bundle cannot clobber a skill record in another scope", async ()
);
assert.equal((await store.list()).length, 0);
});
-
-test("a shared bundle cannot write core materialization markers", async () => {
- const store = createSkillStore();
- const packs = createSkillPackStore();
- const pack = await packs.create({
- kind: "git",
- url: "u",
- ref: "abc1234",
- syncMode: "pinned",
- trustTier: "third-party",
- targetScopeId: scopeId("org", "acme"),
- subset: "all",
- createdBy: "u1",
- });
-
- await assert.rejects(
- importPack(repo(), store, {
- pack,
- selected: "all",
- nativeNames: new Set(),
- bundleFiles: [{ path: "skills/company-directory/.tree", content: "forged" }],
- }),
- /skills\/company-directory\/\.tree \(owned by core skill materialization metadata\)/,
- );
- assert.equal((await store.list()).length, 0);
-});
diff --git a/test/onboarding.test.ts b/test/onboarding.test.ts
index c0647ff25..e44308ac8 100644
--- a/test/onboarding.test.ts
+++ b/test/onboarding.test.ts
@@ -80,7 +80,7 @@ test("a new personal DM gets the high-priority pending onboarding prompt", async
assert.match(sys.reply ?? "", /## Pending Onboarding/);
assert.match(sys.reply ?? "", /high-priority setup task/);
assert.match(sys.reply ?? "", /no reason to skip it/);
- assert.match(sys.reply ?? "", /skill:\/\/onboarding\/SKILL\.md/);
+ assert.match(sys.reply ?? "", /load the onboarding skill with the skill tool/);
});
test("completed or dismissed onboarding markers suppress the pending prompt", async () => {
diff --git a/test/prompt-modes.test.ts b/test/prompt-modes.test.ts
index 3637f6059..2045991fb 100644
--- a/test/prompt-modes.test.ts
+++ b/test/prompt-modes.test.ts
@@ -288,7 +288,7 @@ test("shared-core platform guidance reaches both the DM and the spine prompt", a
assert.match(prompt, /## Auth/);
assert.match(prompt, /## Using skills/);
assert.match(prompt, /Compose task rules with one authorized access skill/);
- assert.match(prompt, /prefer `skill:\/\/composio\/SKILL.md`/);
+ assert.match(prompt, /prefer the composio skill/);
assert.match(prompt, /Never switch credentials to evade denial/);
assert.doesNotMatch(prompt, /## Scheduling & self-configuration/);
}
diff --git a/test/sharing-context-e2e.test.ts b/test/sharing-context-e2e.test.ts
index efb7af843..479b2cc21 100644
--- a/test/sharing-context-e2e.test.ts
+++ b/test/sharing-context-e2e.test.ts
@@ -122,55 +122,34 @@ test("sharing e2e: skill lazy assets execute, update, and disappear from the sam
const b = await fixture(t);
const s = await b.skill("personal:U1", "carried-helper", "VERSION_ONE");
assert.match(await b.turn("!sysprompt", true), /carried-helper/);
- assert.match(await b.turn("!read skills/carried-helper/SKILL.md", true), /scripts\/value.py/);
- assert.equal(await b.turn("!run python3 skills/carried-helper/scripts/value.py", true), "VERSION_ONE");
+ assert.equal(await b.turn("!skill-run carried-helper python3 {dir}/scripts/value.py", true), "VERSION_ONE");
await b.skills.update(s.id, {
...s.manifest,
files: [{ path: "scripts/value.py", content: "print('VERSION_TWO')\n" }],
});
await b.skills.review(s.id, "U1", []);
await b.skills.publish(s.id);
- await b.turn("!read skills/carried-helper/SKILL.md", true);
- assert.equal(await b.turn("!run python3 skills/carried-helper/scripts/value.py", true), "VERSION_TWO");
+ await assert.equal(await b.turn("!skill-run carried-helper python3 {dir}/scripts/value.py", true), "VERSION_TWO");
await b.config.setSharingPosture("personal:U1", "isolated");
assert.doesNotMatch(await b.turn("!sysprompt", true), /carried-helper/);
- assert.match(await b.turn("!read skills/carried-helper/SKILL.md", true), /no file/);
- assert.equal(
- await b.turn(
- "!run python3 -c \"import os; print('STALE' if os.path.exists('skills/carried-helper/scripts/value.py') else 'CLEAN')\"",
- true,
- ),
- "CLEAN",
- );
+ assert.match(await b.turn("!skill carried-helper", true), /no skill file/);
+ assert.equal(await b.turn("!run sh -c \"find . -name value.py | wc -l | tr -d ' '\"", true), "0");
await b.config.clearSharingPosture("personal:U1");
- await b.turn("!read skills/carried-helper/SKILL.md", true);
- assert.equal(await b.turn("!run python3 skills/carried-helper/scripts/value.py", true), "VERSION_TWO");
+ await assert.equal(await b.turn("!skill-run carried-helper python3 {dir}/scripts/value.py", true), "VERSION_TWO");
await b.skills.archive(s.id);
- assert.match(await b.turn("!read skills/carried-helper/SKILL.md", true), /no file/);
- assert.equal(
- await b.turn(
- "!run python3 -c \"import os; print('STALE' if os.path.exists('skills/carried-helper/scripts/value.py') else 'CLEAN')\"",
- true,
- ),
- "CLEAN",
- );
+ assert.match(await b.turn("!skill carried-helper", true), /no skill file/);
+ assert.equal(await b.turn("!run sh -c \"find . -name value.py | wc -l | tr -d ' '\"", true), "0");
});
test("sharing e2e: room skills are removed from an existing DM computer after membership revocation", async (t) => {
const b = await fixture(t);
await b.skill("channel:C1", "room-helper", "ROOM_HELPER");
await b.turn("hello", true);
- await b.turn("!read skills/room-helper/SKILL.md");
- assert.equal(await b.turn("!run python3 skills/room-helper/scripts/value.py"), "ROOM_HELPER");
+ await assert.equal(await b.turn("!skill-run room-helper python3 {dir}/scripts/value.py"), "ROOM_HELPER");
assert.doesNotMatch(await b.turn("!sysprompt", false, "U4"), /room-helper/);
await b.remove("U1");
- assert.match(await b.turn("!read skills/room-helper/SKILL.md"), /no file/);
- assert.equal(
- await b.turn(
- "!run python3 -c \"import os; print('STALE' if os.path.exists('skills/room-helper/scripts/value.py') else 'CLEAN')\"",
- ),
- "CLEAN",
- );
+ assert.match(await b.turn("!skill room-helper"), /no skill file/);
+ assert.equal(await b.turn("!run sh -c \"find . -name value.py | wc -l | tr -d ' '\""), "0");
});
test("sharing e2e: Isolated preserves local skills and explicit grants without implicit carry", async (t) => {
@@ -189,28 +168,20 @@ test("sharing e2e: Isolated preserves local skills and explicit grants without i
"U2",
);
assert.match(await b.turn("!sysprompt"), /personal-helper/);
- await b.turn("!read skills/explicit-helper/SKILL.md");
- assert.equal(await b.turn("!run python3 skills/explicit-helper/scripts/value.py"), "EXPLICIT");
+ await assert.equal(await b.turn("!skill-run explicit-helper python3 {dir}/scripts/value.py"), "EXPLICIT");
assert.doesNotMatch(await b.turn("!sysprompt", true), /personal-helper|explicit-helper/);
await b.acl.revoke("personal:U2", `skill:${s.id}`, "personal:U1", "U2", "U2");
- assert.match(await b.turn("!read skills/explicit-helper/SKILL.md"), /no file/);
- assert.equal(
- await b.turn(
- "!run python3 -c \"import os; print('STALE' if os.path.exists('skills/explicit-helper/scripts/value.py') else 'CLEAN')\"",
- ),
- "CLEAN",
- );
+ assert.match(await b.turn("!skill explicit-helper"), /no skill file/);
+ assert.equal(await b.turn("!run sh -c \"find . -name value.py | wc -l | tr -d ' '\""), "0");
});
test("sharing e2e: local skill name wins, then exposes the carried fallback when archived", async (t) => {
const b = await fixture(t);
await b.skill("personal:U1", "duplicate-helper", "CARRIED");
const local = await b.skill("channel:C1", "duplicate-helper", "LOCAL");
- await b.turn("!read skills/duplicate-helper/SKILL.md", true);
- assert.equal(await b.turn("!run python3 skills/duplicate-helper/scripts/value.py", true), "LOCAL");
+ await assert.equal(await b.turn("!skill-run duplicate-helper python3 {dir}/scripts/value.py", true), "LOCAL");
await b.skills.archive(local.id);
- await b.turn("!read skills/duplicate-helper/SKILL.md", true);
- assert.equal(await b.turn("!run python3 skills/duplicate-helper/scripts/value.py", true), "CARRIED");
+ await assert.equal(await b.turn("!skill-run duplicate-helper python3 {dir}/scripts/value.py", true), "CARRIED");
});
test("sharing e2e: writes and memory capture remain local while reading carried context", async (t) => {
@@ -282,14 +253,8 @@ test("sharing e2e: unavailable connector skills cannot be read or executed", asy
const b = await fixture(t);
await b.skill("personal:U1", "google-workspace", "UNCONFIGURED_CONNECTOR");
assert.doesNotMatch(await b.turn("!sysprompt", true), /\*\*google-workspace\*\*/);
- assert.match(await b.turn("!read skills/google-workspace/SKILL.md", true), /no file/);
- assert.equal(
- await b.turn(
- "!run python3 -c \"import os; print(os.path.exists('skills/google-workspace/scripts/value.py'))\"",
- true,
- ),
- "False",
- );
+ assert.match(await b.turn("!skill google-workspace", true), /no skill file/);
+ assert.equal(await b.turn("!run sh -c \"find . -name value.py | wc -l | tr -d ' '\"", true), "0");
});
for (const memoryRecall of ["off", "writable"] as const) {
@@ -301,9 +266,8 @@ for (const memoryRecall of ["off", "writable"] as const) {
assert.doesNotMatch(await b.turn("!sysprompt", true), /NO_CARRIED_MEMORY/);
assert.doesNotMatch(await b.turn("!memorysearch NO_CARRIED_MEMORY", true), /NO_CARRIED_MEMORY/);
assert.equal(await b.turn("!read shared/open-personal-U1/notes.txt", true), "FILE_WITH_MEMORY_RESTRICTED");
- await b.turn("!read skills/independent-helper/SKILL.md", true);
assert.equal(
- await b.turn("!run python3 skills/independent-helper/scripts/value.py", true),
+ await b.turn("!skill-run independent-helper python3 {dir}/scripts/value.py", true),
"SKILL_WITH_MEMORY_RESTRICTED",
);
});
@@ -312,39 +276,23 @@ for (const memoryRecall of ["off", "writable"] as const) {
test("sharing e2e: switching the speaker removes the previous speaker's skill before execute", async (t) => {
const b = await fixture(t);
await b.skill("personal:U1", "speaker-helper", "SPEAKER_ONE");
- await b.turn("!read skills/speaker-helper/SKILL.md", true);
- assert.equal(await b.turn("!run python3 skills/speaker-helper/scripts/value.py", true), "SPEAKER_ONE");
- assert.equal(
- await b.turn(
- "!run python3 -c \"import os; print(os.path.exists('skills/speaker-helper/scripts/value.py'))\"",
- true,
- "U2",
- ),
- "False",
- );
- await b.turn("!read skills/speaker-helper/SKILL.md", true);
- assert.equal(await b.turn("!run python3 skills/speaker-helper/scripts/value.py", true), "SPEAKER_ONE");
+ await assert.equal(await b.turn("!skill-run speaker-helper python3 {dir}/scripts/value.py", true), "SPEAKER_ONE");
+ assert.equal(await b.turn("!run sh -c \"find . -name value.py | wc -l | tr -d ' '\"", true, "U2"), "0");
+ await assert.equal(await b.turn("!skill-run speaker-helper python3 {dir}/scripts/value.py", true), "SPEAKER_ONE");
});
test("sharing e2e: a newly blocked skill asset removes previously materialized content", async (t) => {
const b = await fixture(t);
const s = await b.skill("personal:U1", "screened-helper", "OLD_SAFE_ASSET");
- await b.turn("!read skills/screened-helper/SKILL.md", true);
- assert.equal(await b.turn("!run python3 skills/screened-helper/scripts/value.py", true), "OLD_SAFE_ASSET");
+ await assert.equal(await b.turn("!skill-run screened-helper python3 {dir}/scripts/value.py", true), "OLD_SAFE_ASSET");
await b.skills.update(s.id, {
...s.manifest,
files: [{ path: "scripts/value.py", content: "# !security-risk\nprint('UNSCREENED_NEW_ASSET')\n" }],
});
await b.skills.review(s.id, "U1", []);
await b.skills.publish(s.id);
- assert.equal(
- await b.turn(
- "!run python3 -c \"import os; print(os.path.exists('skills/screened-helper/scripts/value.py'))\"",
- true,
- ),
- "False",
- );
- assert.match(await b.turn("!read skills/screened-helper/SKILL.md", true), /no file/);
+ assert.equal(await b.turn("!run sh -c \"find . -name value.py | wc -l | tr -d ' '\"", true), "0");
+ assert.match(await b.turn("!skill screened-helper", true), /no skill file/);
assert.ok((await b.auditLog.events()).some((e) => e.action === "sharing.skill_screen_blocked"));
});
@@ -388,8 +336,10 @@ test("sharing e2e: complete notebooks retain provenance without truncating late
test("sharing e2e: screening off preserves carried skills without model calls", async (t) => {
const b = await fixture(t, { securityScreenBackend: "off" });
await b.skill("personal:U1", "unscreened-helper", "SHARED_SKILL_OK");
- await b.turn("!read skills/unscreened-helper/SKILL.md", true);
- assert.equal(await b.turn("!run python3 skills/unscreened-helper/scripts/value.py", true), "SHARED_SKILL_OK");
+ await assert.equal(
+ await b.turn("!skill-run unscreened-helper python3 {dir}/scripts/value.py", true),
+ "SHARED_SKILL_OK",
+ );
assert.equal(b.modelGateway.audit().filter((rec) => rec.model === "mock-security").length, 0);
});
diff --git a/test/skill-collision.test.ts b/test/skill-collision.test.ts
index ff891d8bb..f63f9ebdf 100644
--- a/test/skill-collision.test.ts
+++ b/test/skill-collision.test.ts
@@ -4,35 +4,18 @@ import {
skillRecordPaths,
persistedSkillRecordPaths,
detectPathCollisions,
- materializationControlPathCollisions,
SkillPackCollisionError,
} from "../src/skills/skill-collision.ts";
test("skillRecordPaths mirrors materialize's validated skills/<name>/ layout", () => {
assert.deepEqual(
skillRecordPaths("My-Skill", [{ path: "scripts/x.py", content: "" }]).sort(),
- ["skills/My-Skill/.tree", "skills/My-Skill/SKILL.md", "skills/My-Skill/scripts/x.py"],
+ ["skills/My-Skill/SKILL.md", "skills/My-Skill/scripts/x.py"],
"files land under the validated name (same as materialize)",
);
assert.throws(() => skillRecordPaths("My Skill", []), /skill name must/);
});
-test("materialization marker paths are reserved from shared bundles", () => {
- assert.deepEqual(
- materializationControlPathCollisions([
- "lib/ok.mjs",
- "skills/.index",
- "skills/alpha/.tree",
- "skills/alpha/.tree/child",
- ]),
- [
- { path: "skills/.index", owner: "core skill materialization metadata" },
- { path: "skills/alpha/.tree", owner: "core skill materialization metadata" },
- { path: "skills/alpha/.tree/child", owner: "core skill materialization metadata" },
- ],
- );
-});
-
test("persistedSkillRecordPaths quarantines a legacy unsafe name without inventing a path", () => {
assert.deepEqual(persistedSkillRecordPaths("My Skill", [{ path: "asset.txt", content: "x" }]), []);
assert.throws(() => skillRecordPaths("My Skill", []), /skill name must/);
diff --git a/test/skill-tool.test.ts b/test/skill-tool.test.ts
new file mode 100644
index 000000000..fdcb68c95
--- /dev/null
+++ b/test/skill-tool.test.ts
@@ -0,0 +1,97 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { createToolContext, type SkillResult } from "../src/tools/primitives.ts";
+import type { Sandbox, SandboxHandle } from "../src/sandbox/sandbox.ts";
+import { scopeId } from "../src/types.ts";
+
+function ctx(useSkill: (name: string, path: string, sandboxId?: string) => Promise<SkillResult>) {
+ const calls: string[] = [];
+ const sandbox = {
+ readFile: async (_h: SandboxHandle, _p: string) => null,
+ run: async (_h: SandboxHandle, command: string) => {
+ calls.push(command);
+ return { stdout: "ran", stderr: "", code: 0, timedOut: false };
+ },
+ } as unknown as Sandbox;
+ const backgroundBroker = {
+ start: async (_h: SandboxHandle, command: string) => {
+ calls.push(command);
+ return { processId: "p1", output: "ran", cursor: 0, status: { state: "exited", exitCode: 0 }, reattached: false };
+ },
+ };
+ const tc = createToolContext({
+ sandbox,
+ provision: async () => ({ id: "h", rootDir: "/workspace" }) as SandboxHandle,
+ useSkill,
+ backgroundBroker: backgroundBroker as never,
+ layers: [{ scopeId: scopeId("personal", "U1"), mountPath: "", mode: "rw" }],
+ commandPolicy: () => ({ mode: "denylist", rules: [] }),
+ authorizeCommand: () => false,
+ grantedHandles: [],
+ workspace: {} as never,
+ deploy: {} as never,
+ acl: {} as never,
+ createdBy: "U1",
+ });
+ return { tc, calls };
+}
+
+test("skill loads SKILL.md by default and passes the requested path through", async () => {
+ const seen: Array<[string, string, string | undefined]> = [];
+ const { tc } = ctx(async (name, path, sandboxId) => {
+ seen.push([name, path, sandboxId]);
+ return { content: `${name}:${path}`, sourceScopeId: scopeId("personal", "U1") };
+ });
+ assert.equal((await tc.skill("send")).content, "send:SKILL.md");
+ assert.equal((await tc.skill("send", { path: "references/notes.md" })).content, "send:references/notes.md");
+ assert.deepEqual(seen, [
+ ["send", "SKILL.md", undefined],
+ ["send", "references/notes.md", undefined],
+ ]);
+});
+
+test("skill reports the synced directory when the skill ships files", async () => {
+ const { tc } = ctx(async () => ({
+ content: "BODY",
+ sourceScopeId: scopeId("personal", "U1"),
+ dir: "skills/google-workspace",
+ packDir: "skills/.packs/workspace",
+ }));
+ const r = await tc.skill("google-workspace");
+ assert.equal(r.dir, "skills/google-workspace");
+ assert.equal(r.packDir, "skills/.packs/workspace");
+});
+
+test("execute, read, write and background never trigger skill synchronization", async () => {
+ let loads = 0;
+ const { tc, calls } = ctx(async () => {
+ loads++;
+ return { content: "BODY", sourceScopeId: scopeId("personal", "U1") };
+ });
+ await tc.execute("cd skills/google-workspace && python scripts/gmail.py");
+ await tc.read("skills/google-workspace/SKILL.md");
+ await tc.backgroundStart("sh skills/.packs/selected/job.sh");
+ assert.equal(loads, 0);
+ assert.equal(calls.length, 2);
+});
+
+test("skill without a materializer reports no file", async () => {
+ const { tc } = createToolContextWithout();
+ assert.deepEqual(await tc.skill("send"), { content: null, sourceScopeId: null });
+});
+
+function createToolContextWithout() {
+ const tc = createToolContext({
+ sandbox: {} as unknown as Sandbox,
+ provision: async () => ({ id: "h", rootDir: "/workspace" }) as SandboxHandle,
+ layers: [{ scopeId: scopeId("personal", "U1"), mountPath: "", mode: "rw" }],
+ commandPolicy: () => ({ mode: "denylist", rules: [] }),
+ authorizeCommand: () => false,
+ grantedHandles: [],
+ workspace: {} as never,
+ deploy: {} as never,
+ acl: {} as never,
+ createdBy: "U1",
+ });
+ return { tc };
+}
diff --git a/test/skills-callable.test.ts b/test/skills-callable.test.ts
index 5b14bee5e..7713a2135 100644
--- a/test/skills-callable.test.ts
+++ b/test/skills-callable.test.ts
@@ -35,7 +35,7 @@ async function publishPersonalSkill(skills: ReturnType<typeof buildApp>["skills"
return sk;
}
-test("a published personal skill is advertised + materialized in the owner's DM", async () => {
+test("a published personal skill is advertised and loads in the owner's DM", async () => {
const { app, skills } = freshApp();
await publishPersonalSkill(skills);
@@ -52,7 +52,7 @@ test("a published personal skill is advertised + materialized in the owner's DM"
surface: "test",
actor,
conversation: { kind: "dm", threadRef: "dm:U1:t2" },
- text: "!read skills/make-digest/SKILL.md",
+ text: "!skill make-digest",
} as TurnRequest);
assert.match(read.reply ?? "", /Step 1: gather/);
});
@@ -69,7 +69,7 @@ test("a channel session does NOT see a personal skill (scope boundary)", async (
assert.doesNotMatch(sys.reply ?? "", /make-digest/);
});
-test("ordinary sandbox work reconciles ownership without copying skill contents", async () => {
+test("ordinary sandbox work never touches the skills tree", async () => {
const { app, skills, sandbox } = freshApp();
await publishPersonalSkill(skills);
const touched: string[] = [];
@@ -94,20 +94,38 @@ test("ordinary sandbox work reconciles ownership without copying skill contents"
conversation: { kind: "dm", threadRef: "dm:U1:no-sync" },
text: "!read missing.txt",
} as TurnRequest);
- assert.deepEqual(touched, ["skills/.index", "skills/.index"]);
+ assert.deepEqual(touched, []);
});
-test("ordinary sandbox reads remove archived skill files before access", async () => {
+async function publishFileSkill(skills: ReturnType<typeof buildApp>["skills"], name: string) {
+ const sk = await skills.create({
+ scopeId: scopeId("personal", "U1"),
+ manifest: {
+ name,
+ description: `${name} ships a script`,
+ requiredCapabilities: [],
+ body: "run the script",
+ files: [{ path: "scripts/run.sh", content: `printf ${name}` }],
+ },
+ createdBy: "U1",
+ });
+ await skills.review(sk.id, "reviewer-1", []);
+ await skills.publish(sk.id);
+ return sk;
+}
+
+test("skill files live only for the turn that loaded them", async () => {
const { app, skills } = freshApp();
- const skill = await publishPersonalSkill(skills);
+ const first = await publishFileSkill(skills, "helper");
const request = {
surface: "test",
actor,
conversation: { kind: "dm", threadRef: "dm:U1:archive" },
};
- const before = await app.turn({ ...request, text: "!read skills/make-digest/SKILL.md" } as TurnRequest);
- assert.match(before.reply ?? "", /Step 1: gather/);
- await skills.archive(skill.id);
- const after = await app.turn({ ...request, text: "!read ././skills/make-digest/SKILL.md" } as TurnRequest);
- assert.doesNotMatch(after.reply ?? "", /Step 1: gather/);
+ const ran = await app.turn({ ...request, text: "!skill-run helper cat {dir}/scripts/run.sh" } as TurnRequest);
+ assert.equal(ran.reply, "printf helper");
+ const next = await app.turn({ ...request, text: "!run find . -name run.sh | wc -l | tr -d ' '" } as TurnRequest);
+ assert.equal(next.reply, "0");
+ await skills.archive(first.id);
+ assert.match((await app.turn({ ...request, text: "!skill helper" } as TurnRequest)).reply ?? "", /no skill file/);
});
diff --git a/test/skills-lazy-read-seam.test.ts b/test/skills-lazy-read-seam.test.ts
deleted file mode 100644
index b2eef6f69..000000000
--- a/test/skills-lazy-read-seam.test.ts
+++ /dev/null
@@ -1,113 +0,0 @@
-import { test } from "node:test";
-import assert from "node:assert/strict";
-import { createToolContext } from "../src/tools/primitives.ts";
-import type { Sandbox, SandboxHandle } from "../src/sandbox/sandbox.ts";
-import { scopeId } from "../src/types.ts";
-
-function ctx(onEnsure: (dir: string) => void) {
- const materialized = new Set<string>();
- const runCommand = (command: string) => {
- const wants = /(?:^|[\s'"=(&|;])(?:\.\/)?skills\/([^/\s'"&|;)]+)/.exec(command)?.[1];
- const present = !wants || materialized.has(wants);
- return present
- ? { stdout: "ran", stderr: "", code: 0, timedOut: false }
- : { stdout: "", stderr: `ModuleNotFoundError: skills/${wants} assets missing`, code: 1, timedOut: false };
- };
- const sandbox = {
- readFile: async (_h: SandboxHandle, _p: string) => null,
- run: async (_h: SandboxHandle, command: string) => runCommand(command),
- } as unknown as Sandbox;
- const backgroundBroker = {
- start: async (_h: SandboxHandle, command: string) => {
- const r = runCommand(command);
- return {
- processId: "p1",
- output: r.stdout || r.stderr,
- cursor: 0,
- status: { state: "exited", exitCode: r.code },
- reattached: false,
- };
- },
- };
- return createToolContext({
- sandbox,
- provision: async () => ({ id: "h", rootDir: "/workspace" }) as SandboxHandle,
- ensureSkillTree: async (dir: string) => {
- materialized.add(dir);
- onEnsure(dir);
- },
- backgroundBroker: backgroundBroker as never,
- layers: [{ scopeId: scopeId("personal", "U1"), mountPath: "", mode: "rw" }],
- commandPolicy: () => ({ mode: "denylist", rules: [] }),
- authorizeCommand: () => false,
- grantedHandles: [],
- workspace: {} as never,
- deploy: {} as never,
- acl: {} as never,
- createdBy: "U1",
- });
-}
-
-test("reading skills/<name>/SKILL.md triggers lazy materialization of that skill", async () => {
- const seen: string[] = [];
- const tc = ctx((d) => seen.push(d));
- await tc.read("skills/popular-web-designs/SKILL.md");
- assert.deepEqual(seen, ["popular-web-designs"]);
-});
-
-test("a leading ./ on the SKILL.md path still triggers materialization", async () => {
- const seen: string[] = [];
- const tc = ctx((d) => seen.push(d));
- await tc.read("./skills/taste-skill/SKILL.md");
- assert.deepEqual(seen, ["taste-skill"]);
-});
-
-test("reading assets inside skill directories materializes their trees", async () => {
- const seen: string[] = [];
- const tc = ctx((d) => seen.push(d));
- await tc.read("skills/popular-web-designs/scripts/render.py");
- await tc.read("skills/foo/references/notes.md");
- await tc.read("reports/report.md");
- assert.deepEqual(seen, ["popular-web-designs", "foo"]);
-});
-
-test("executing a skill's script on a cold box (no prior SKILL.md read) materializes its tree first", async () => {
- const seen: string[] = [];
- const tc = ctx((d) => seen.push(d));
- const r = await tc.execute("cd skills/google-workspace && python scripts/gmail.py");
- assert.deepEqual(seen, ["google-workspace"], "execute materialized the referenced skill tree");
- assert.equal(r.code, 0, "the command ran cleanly because the assets were laid before it ran");
-});
-
-test("executing a script by path under a skill dir also materializes that skill", async () => {
- const seen: string[] = [];
- const tc = ctx((d) => seen.push(d));
- const r = await tc.execute("python skills/email-voice-profile/scripts/fetch_sent.py");
- assert.deepEqual(seen, ["email-voice-profile"]);
- assert.equal(r.code, 0);
-});
-
-test("an execute that references no skill dir does NOT materialize anything", async () => {
- const seen: string[] = [];
- const tc = ctx((d) => seen.push(d));
- await tc.execute("echo hello && ls skills");
- assert.deepEqual(seen, [], "no skill dir referenced ⇒ no lazy trigger");
-});
-
-test("a background job that runs a skill's script materializes its tree first too", async () => {
- const seen: string[] = [];
- const tc = ctx((d) => seen.push(d));
- const r = await tc.backgroundStart("cd skills/google-workspace && python scripts/gmail.py");
- assert.deepEqual(seen, ["google-workspace"], "background materialized the referenced skill tree");
- assert.equal(r.status.state, "exited");
- assert.equal(r.output, "ran", "the job ran cleanly because the assets were laid before it started");
-});
-
-test("pack file access selects only the named pack", async () => {
- const seen: string[] = [];
- const tc = ctx((dir) => seen.push(dir));
- await tc.read("skills/.packs/selected/reference.txt");
- await tc.execute("python skills/.packs/selected/script.py");
- await tc.backgroundStart("sh skills/.packs/selected/job.sh");
- assert.deepEqual(seen, [".packs/selected", ".packs/selected", ".packs/selected"]);
-});
diff --git a/test/skills-materialize.test.ts b/test/skills-materialize.test.ts
index e28a15224..99abbc1d6 100644
--- a/test/skills-materialize.test.ts
+++ b/test/skills-materialize.test.ts
@@ -2,16 +2,11 @@ import { test } from "node:test";
import assert from "node:assert/strict";
import { CapabilityUnsupportedError, type Sandbox, type SandboxHandle } from "../src/sandbox/sandbox.ts";
import type { SkillFile, SkillResolution } from "../src/skills/skill-store.ts";
-import {
- createSkillMaterializer,
- reconcileSkillIndex,
- materializeSkillTree,
- safeSkillDirName,
-} from "../src/skills/materialize.ts";
+import { materializeSkillTree, renderSkillBody, safeSkillDirName } from "../src/skills/materialize.ts";
import { computeBundleHash, type SkillBundle } from "../src/skills/skill-bundle-store.ts";
-import { createMemoryAdvisoryLock } from "../src/persistence/advisory-lock.ts";
const handle: SandboxHandle = { id: "h", rootDir: "/workspace" };
+const root = ".agent-turn/t1/skills";
function res(name: string, body: string, files: SkillFile[] = [], packId?: string): SkillResolution {
return {
@@ -29,439 +24,68 @@ function bundle(packId: string, files: SkillFile[]): SkillBundle {
function fakeSandbox() {
const files = new Map<string, string>();
- const calls = { reads: 0, writes: 0, removes: 0 };
const sandbox = {
- async readFile(_h: SandboxHandle, rel: string) {
- calls.reads++;
- return files.has(rel) ? files.get(rel)! : null;
- },
async writeFile(_h: SandboxHandle, rel: string, data: string) {
- calls.writes++;
files.set(rel, data);
},
- async removeDir(_h: SandboxHandle, rel: string) {
- calls.removes++;
- for (const k of files.keys()) if (k === rel || k.startsWith(`${rel}/`)) files.delete(k);
- },
} as unknown as Sandbox;
- return { sandbox, files, calls };
+ return { sandbox, files };
}
test("materialized skill directory names are validated and never lossy", () => {
- assert.equal(safeSkillDirName("foo-bar_v1.2"), "foo-bar_v1.2");
- assert.throws(() => safeSkillDirName("foo/bar"), /skill name must/);
- assert.throws(() => safeSkillDirName(".."), /skill name must/);
-});
-
-test("reconcileSkillIndex records ownership without copying any skill content", async () => {
- const { sandbox, files, calls } = fakeSandbox();
- await reconcileSkillIndex(sandbox, handle, [res("alpha", "A"), res("beta", "B")]);
-
- assert.equal(files.has("skills/alpha/SKILL.md"), false);
- assert.equal(files.has("skills/beta/SKILL.md"), false);
- assert.ok(files.has("skills/.index"), "an index marker is written");
- assert.equal(calls.writes, 1);
-});
-
-test("reconcileSkillIndex does NOT lay a skill's asset tree (that's lazy)", async () => {
- const { sandbox, files } = fakeSandbox();
- await reconcileSkillIndex(sandbox, handle, [
- res("gamma", "G", [{ path: "scripts/hello.py", content: "print('hi')" }]),
- ]);
-
- assert.equal(files.has("skills/gamma/SKILL.md"), false);
- assert.equal(files.has("skills/gamma/scripts/hello.py"), false, "the asset is NOT laid until first read");
-});
-
-test("reconcileSkillIndex SKIPS when the body set is unchanged (order-independent)", async () => {
- const { sandbox, calls } = fakeSandbox();
- await reconcileSkillIndex(sandbox, handle, [res("alpha", "A"), res("beta", "B")]);
- const writes = calls.writes;
-
- await reconcileSkillIndex(sandbox, handle, [res("beta", "B"), res("alpha", "A")]);
- assert.equal(calls.writes, writes, "no rewrite on a matching body set");
-});
-
-test("reconcileSkillIndex ignores body changes until that skill is invoked", async () => {
- const { sandbox, files, calls } = fakeSandbox();
- await reconcileSkillIndex(sandbox, handle, [res("alpha", "A")]);
- const writes = calls.writes;
- await reconcileSkillIndex(sandbox, handle, [res("alpha", "A2")]);
- assert.equal(calls.writes, writes);
- assert.equal(files.has("skills/alpha/SKILL.md"), false);
-});
-
-test("reconcileSkillIndex does NOT re-lay when only an asset changes (asset is not in the index hash)", async () => {
- const { sandbox, calls } = fakeSandbox();
- await reconcileSkillIndex(sandbox, handle, [res("gamma", "G", [{ path: "s.py", content: "v1" }])]);
- const writes = calls.writes;
- await reconcileSkillIndex(sandbox, handle, [res("gamma", "G", [{ path: "s.py", content: "v2" }])]);
- assert.equal(calls.writes, writes, "asset-only change doesn't touch the eager index");
-});
-
-test("reconcileSkillIndex removes an archived skill's materialized tree", async () => {
- const { sandbox, files, calls } = fakeSandbox();
- const alpha = res("alpha", "A", [{ path: "asset.txt", content: "asset" }]);
- await reconcileSkillIndex(sandbox, handle, [alpha]);
- await materializeSkillTree(sandbox, handle, alpha, [bundle("p", [{ path: "lib/alpha.mjs", content: "shared" }])]);
-
- await reconcileSkillIndex(sandbox, handle, []);
- assert.equal(files.has("skills/alpha/SKILL.md"), false);
- assert.equal(files.has("skills/alpha/asset.txt"), false);
- assert.equal(files.has("lib/alpha.mjs"), false);
-
- const removes = calls.removes;
- await reconcileSkillIndex(sandbox, handle, []);
- assert.equal(calls.removes, removes, "the reconciled marker makes the next pass idempotent");
-});
-
-test("reconcileSkillIndex migrates a legacy hash marker without retaining old skill paths", async () => {
- const { sandbox, files } = fakeSandbox();
- const alpha = res("alpha", "A");
- await reconcileSkillIndex(sandbox, handle, [alpha]);
- const state = JSON.parse(files.get("skills/.index")!) as { hash: string };
- files.set("skills/.index", state.hash);
- files.set("skills/removed/SKILL.md", "removed");
- files.set("skills/removed/asset.txt", "stale");
-
- await reconcileSkillIndex(sandbox, handle, [alpha]);
- assert.equal(files.has("skills/removed/SKILL.md"), false);
- assert.equal(files.has("skills/removed/asset.txt"), false);
- assert.equal(files.has("skills/alpha/SKILL.md"), false);
- const migrated = JSON.parse(files.get("skills/.index")!);
- assert.equal(migrated.version, 2);
- assert.equal(migrated.legacyExternalPathsPreserved, true);
-});
-
-test("legacy migration cleans the managed skills namespace but preserves unknown external files", async () => {
- const { sandbox, files } = fakeSandbox();
- const alpha = res("alpha", "A");
- const currentBundle = bundle("p", [{ path: "lib/current.mjs", content: "current" }]);
- await reconcileSkillIndex(sandbox, handle, [alpha]);
- await materializeSkillTree(sandbox, handle, alpha, [currentBundle]);
- const index = JSON.parse(files.get("skills/.index")!) as { hash: string };
- files.set("skills/.index", index.hash);
- files.set("skills/removed/stale.txt", "provably managed");
- files.set("skills/.packs/p/lib/current.mjs", "stale known content");
- files.set("lib/unknown-pre-v1.mjs", "ownership unknowable");
-
- await reconcileSkillIndex(sandbox, handle, [alpha]);
- await materializeSkillTree(sandbox, handle, alpha, [currentBundle]);
- assert.equal(files.has("skills/removed/stale.txt"), false);
- assert.equal(
- files.get("skills/.packs/p/lib/current.mjs"),
- "current",
- "the current bundle proves ownership and is reconciled",
- );
- assert.equal(files.get("lib/unknown-pre-v1.mjs"), "ownership unknowable");
- assert.equal(JSON.parse(files.get("skills/.index")!).legacyExternalPathsPreserved, true);
-
- await reconcileSkillIndex(sandbox, handle, [res("alpha", "A2")]);
- assert.equal(
- JSON.parse(files.get("skills/.index")!).legacyExternalPathsPreserved,
- true,
- "the incomplete legacy inventory is never silently declared complete",
- );
+ assert.equal(safeSkillDirName("popular-web-designs"), "popular-web-designs");
+ assert.throws(() => safeSkillDirName("../evil"));
+ assert.throws(() => safeSkillDirName("a/b"));
});
-test("materializeSkillTree lays the asset tree + a per-skill marker", async () => {
+test("materializeSkillTree lays SKILL.md and assets under the turn root", async () => {
const { sandbox, files } = fakeSandbox();
await materializeSkillTree(
sandbox,
handle,
+ root,
res("gamma", "G", [
{ path: "scripts/hello.py", content: "print('hi')", executable: true },
{ path: "references/notes.md", content: "# notes" },
]),
);
-
- assert.equal(files.get("skills/gamma/SKILL.md"), "G", "SKILL.md is re-laid as part of the tree");
- assert.equal(files.get("skills/gamma/scripts/hello.py"), "print('hi')");
- assert.equal(files.get("skills/gamma/references/notes.md"), "# notes");
- assert.ok(files.has("skills/gamma/.tree"), "a per-skill tree marker is written");
-});
-
-test("materializeSkillTree records and skips a clean body-only tree", async () => {
- const { sandbox, files, calls } = fakeSandbox();
- await materializeSkillTree(sandbox, handle, res("alpha", "A"));
- assert.equal(files.get("skills/alpha/SKILL.md"), "A");
- assert.equal(files.has("skills/alpha/.tree"), true);
- const writes = calls.writes;
- await materializeSkillTree(sandbox, handle, res("alpha", "A"));
- assert.equal(calls.writes, writes);
+ assert.equal(files.get(`${root}/gamma/SKILL.md`), "G");
+ assert.equal(files.get(`${root}/gamma/scripts/hello.py`), "print('hi')");
+ assert.equal(files.get(`${root}/gamma/references/notes.md`), "# notes");
});
-test("materializeSkillTree SKIPS when the tree is unchanged", async () => {
- const { sandbox, calls } = fakeSandbox();
- const skill = res("gamma", "G", [{ path: "s.py", content: "v1" }]);
- await materializeSkillTree(sandbox, handle, skill);
- const writes = calls.writes;
- await materializeSkillTree(sandbox, handle, res("gamma", "G", [{ path: "s.py", content: "v1" }]));
- assert.equal(calls.writes, writes, "no rewrite when the tree is identical");
+test("renderSkillBody rewrites the skill's own skills/<name>/ paths to the turn root", () => {
+ const r = res("gamma", "Run python3 skills/gamma/scripts/hello.py, not skills/other/x.py");
+ assert.equal(renderSkillBody(r, root), `Run python3 ${root}/gamma/scripts/hello.py, not skills/other/x.py`);
+ assert.equal(renderSkillBody(r), "Run python3 skills/gamma/scripts/hello.py, not skills/other/x.py");
});
-test("materializeSkillTree re-lays when an asset changes, and clears a removed asset", async () => {
- const { sandbox, files, calls } = fakeSandbox();
+test("unsafe asset paths are skipped rather than escaping the skill directory", async () => {
+ const { sandbox, files } = fakeSandbox();
await materializeSkillTree(
sandbox,
handle,
+ root,
res("gamma", "G", [
- { path: "a.py", content: "A" },
- { path: "b.py", content: "B" },
+ { path: "../escape.txt", content: "nope" },
+ { path: "ok.txt", content: "yes" },
]),
);
- const writes = calls.writes;
-
- await materializeSkillTree(sandbox, handle, res("gamma", "G", [{ path: "a.py", content: "A2" }]));
- assert.ok(calls.writes > writes, "a changed tree re-lays");
- assert.equal(files.get("skills/gamma/a.py"), "A2");
- assert.equal(files.has("skills/gamma/b.py"), false, "a removed asset is cleared (dir cleared before re-lay)");
-});
-
-test("materializeSkillTree migrates a legacy hash marker by clearing stale pre-upgrade assets", async () => {
- const { sandbox, files } = fakeSandbox();
- const before = res("gamma", "G", [{ path: "old.py", content: "old" }]);
- await materializeSkillTree(sandbox, handle, before);
- const state = JSON.parse(files.get("skills/gamma/.tree")!) as { hash: string };
- files.set("skills/gamma/.tree", state.hash);
- files.set("skills/gamma/untracked.py", "stale");
-
- await materializeSkillTree(sandbox, handle, res("gamma", "G2", [{ path: "new.py", content: "new" }]));
- assert.equal(files.has("skills/gamma/old.py"), false);
- assert.equal(files.has("skills/gamma/untracked.py"), false);
- assert.equal(files.get("skills/gamma/new.py"), "new");
- assert.equal(JSON.parse(files.get("skills/gamma/.tree")!).version, 2);
-});
-
-test("materializeSkillTree clears stale assets when its marker was deleted", async () => {
- const { sandbox, files } = fakeSandbox();
- await materializeSkillTree(sandbox, handle, res("gamma", "G", [{ path: "old.py", content: "old" }]));
- files.delete("skills/gamma/.tree");
-
- await materializeSkillTree(sandbox, handle, res("gamma", "G", [{ path: "new.py", content: "new" }]));
- assert.equal(files.has("skills/gamma/old.py"), false);
- assert.equal(files.get("skills/gamma/new.py"), "new");
-});
-
-test("materializeSkillTree clears stale assets after marker deletion when the skill becomes body-only", async () => {
- const { sandbox, files } = fakeSandbox();
- await materializeSkillTree(sandbox, handle, res("gamma", "G", [{ path: "old.py", content: "old" }]));
- files.delete("skills/gamma/.tree");
-
- await materializeSkillTree(sandbox, handle, res("gamma", "G"));
- assert.equal(files.has("skills/gamma/old.py"), false);
- assert.equal(files.get("skills/gamma/SKILL.md"), "G");
- assert.equal(files.has("skills/gamma/.tree"), true);
-});
-
-test("materializeSkillTree SKIPS when only file ordering differs", async () => {
- const { sandbox, calls } = fakeSandbox();
- const a: SkillFile = { path: "a.py", content: "A" };
- const b: SkillFile = { path: "b.py", content: "B" };
- await materializeSkillTree(sandbox, handle, res("gamma", "G", [a, b]));
- const writes = calls.writes;
- await materializeSkillTree(sandbox, handle, res("gamma", "G", [b, a]));
- assert.equal(calls.writes, writes, "reordered files are the same set — no rewrite");
-});
-
-test("materialization serializes concurrent mutations for the same sandbox handle", async () => {
- const { sandbox, files, calls } = fakeSandbox();
- await materializeSkillTree(sandbox, handle, res("gamma", "G", [{ path: "s.py", content: "v1" }]));
- const originalWrite = sandbox.writeFile.bind(sandbox);
- let entered!: () => void;
- let release!: () => void;
- const blocked = new Promise<void>((resolve) => {
- entered = resolve;
- });
- const unblocked = new Promise<void>((resolve) => {
- release = resolve;
- });
- sandbox.writeFile = async (h, path, data) => {
- if (path === "skills/gamma/s.py" && data === "v2") {
- entered();
- await unblocked;
- }
- await originalWrite(h, path, data);
- };
-
- const second = materializeSkillTree(sandbox, handle, res("gamma", "G", [{ path: "s.py", content: "v2" }]));
- await blocked;
- const readsWhileBlocked = calls.reads;
- const third = materializeSkillTree(sandbox, handle, res("gamma", "G", [{ path: "s.py", content: "v3" }]));
- await new Promise<void>((resolve) => setImmediate(resolve));
- assert.equal(
- calls.reads,
- readsWhileBlocked,
- "the later mutation has not probed stale state while the first is in flight",
- );
- release();
- await Promise.all([second, third]);
- assert.equal(files.get("skills/gamma/s.py"), "v3", "invocation order determines the final tree");
-});
-
-test("fleet lock serializes materializers from separate process instances", async () => {
- const { sandbox, files, calls } = fakeSandbox();
- const fleetLock = createMemoryAdvisoryLock();
- const instanceA = createSkillMaterializer(fleetLock);
- const instanceB = createSkillMaterializer(fleetLock);
- await instanceA.materializeTree(sandbox, handle, res("gamma", "G", [{ path: "s.py", content: "v1" }]));
-
- const originalWrite = sandbox.writeFile.bind(sandbox);
- let entered!: () => void;
- let release!: () => void;
- const blocked = new Promise<void>((resolve) => {
- entered = resolve;
- });
- const unblocked = new Promise<void>((resolve) => {
- release = resolve;
- });
- sandbox.writeFile = async (h, path, data) => {
- if (path === "skills/gamma/s.py" && data === "v2") {
- entered();
- await unblocked;
- }
- await originalWrite(h, path, data);
- };
-
- const oldLay = instanceA.materializeTree(sandbox, handle, res("gamma", "G", [{ path: "s.py", content: "v2" }]));
- await blocked;
- const readsWhileBlocked = calls.reads;
- const newLay = instanceB.materializeTree(sandbox, handle, res("gamma", "G", [{ path: "s.py", content: "v3" }]));
- await new Promise<void>((resolve) => setImmediate(resolve));
- assert.equal(
- calls.reads,
- readsWhileBlocked,
- "the second process cannot probe while the first process mutates the projection",
- );
-
- release();
- await Promise.all([oldLay, newLay]);
- assert.equal(files.get("skills/gamma/s.py"), "v3");
-});
-
-test("fresh reconciliation prevents an older turn from regressing a newer projection", async () => {
- const { sandbox, files, calls } = fakeSandbox();
- const fleetLock = createMemoryAdvisoryLock();
- const newerTurn = createSkillMaterializer(fleetLock);
- const olderTurn = createSkillMaterializer(fleetLock);
- const current = res("gamma", "G3", [{ path: "s.py", content: "v3" }]);
-
- await newerTurn.reconcileIndex(sandbox, handle, [current], async () => [current]);
- await newerTurn.materializeTree(sandbox, handle, current, [], async () => ({ resolution: current, bundles: [] }));
- const removes = calls.removes;
-
- await olderTurn.reconcileIndex(sandbox, handle, [], async () => [current]);
- await olderTurn.materializeTree(
- sandbox,
- handle,
- res("gamma", "G2", [{ path: "s.py", content: "v2" }]),
- [],
- async () => ({ resolution: current, bundles: [] }),
- );
-
- assert.equal(files.get("skills/gamma/SKILL.md"), "G3");
- assert.equal(files.get("skills/gamma/s.py"), "v3");
- assert.equal(calls.removes, removes, "the stale empty index does not delete the current skill tree");
+ assert.deepEqual([...files.keys()].sort(), [`${root}/gamma/SKILL.md`, `${root}/gamma/ok.txt`]);
});
test("materializeSkillTree confines a pack's shared bundle below its pack root", async () => {
const { sandbox, files } = fakeSandbox();
- await materializeSkillTree(sandbox, handle, res("gmail", "G", [], "s1"), [
+ await materializeSkillTree(sandbox, handle, root, res("gmail", "G", [], "s1"), [
bundle("s1", [
{ path: "lib/cite.mjs", content: "cite" },
{ path: "skills/conventions/quality.md", content: "q" },
]),
]);
- assert.match(files.get("skills/gmail/SKILL.md") ?? "", /skills\/\.packs\/s1/);
- assert.equal(files.get("skills/.packs/s1/lib/cite.mjs"), "cite");
- assert.equal(files.get("skills/.packs/s1/skills/conventions/quality.md"), "q");
- assert.equal(files.get("lib/cite.mjs"), undefined, "pack bytes never overwrite the workspace root");
-});
-
-test("materializeSkillTree never lays bundle content over core marker paths", async () => {
- const { sandbox, files } = fakeSandbox();
- const alpha = res("alpha", "A");
- const beta = res("beta", "B");
- await reconcileSkillIndex(sandbox, handle, [alpha, beta]);
- files.set("keep.txt", "valuable");
- const forged = JSON.stringify({
- version: 1,
- hash: "forged",
- skillPaths: ["skills/alpha/SKILL.md"],
- bundlePaths: ["keep.txt"],
- });
-
- await materializeSkillTree(sandbox, handle, beta, [
- bundle("evil", [
- { path: "skills/.index", content: forged },
- { path: "skills/alpha/.tree", content: forged },
- ]),
- ]);
- await materializeSkillTree(sandbox, handle, alpha);
-
- assert.equal(files.get("keep.txt"), "valuable");
- assert.notEqual(files.get("skills/.index"), forged);
- assert.notEqual(files.get("skills/alpha/.tree"), forged);
-});
-
-test("materializeSkillTree never trusts a pre-hardening JSON delete manifest", async () => {
- const { sandbox, files } = fakeSandbox();
- const alpha = res("alpha", "A");
- await reconcileSkillIndex(sandbox, handle, [alpha]);
- files.set("keep.txt", "valuable");
- files.set(
- "skills/alpha/.tree",
- JSON.stringify({
- version: 1,
- hash: "forged",
- skillPaths: ["skills/alpha/SKILL.md"],
- bundlePaths: ["keep.txt"],
- }),
- );
-
- await materializeSkillTree(sandbox, handle, alpha);
-
- assert.equal(files.get("keep.txt"), "valuable");
- assert.equal(JSON.parse(files.get("skills/alpha/.tree")!).version, 2);
-});
-
-test("materializeSkillTree re-lays when only a shared bundle file changes", async () => {
- const { sandbox, files, calls } = fakeSandbox();
- await materializeSkillTree(sandbox, handle, res("gmail", "G"), [
- bundle("s1", [{ path: "lib/cite.mjs", content: "v1" }]),
- ]);
- const writes = calls.writes;
- await materializeSkillTree(sandbox, handle, res("gmail", "G"), [
- bundle("s1", [{ path: "lib/cite.mjs", content: "v2" }]),
- ]);
- assert.ok(calls.writes > writes, "a changed shared file busts the tree key even when no asset changed");
- assert.equal(files.get("skills/.packs/s1/lib/cite.mjs"), "v2");
-});
-
-test("materializeSkillTree removes stale bundle paths but preserves another current owner's paths", async () => {
- const { sandbox, files } = fakeSandbox();
- const alpha = res("alpha", "A");
- const beta = res("beta", "B");
- await reconcileSkillIndex(sandbox, handle, [alpha, beta]);
- await materializeSkillTree(sandbox, handle, beta, [
- bundle("shared-pack", [{ path: "lib/shared.mjs", content: "shared" }]),
- ]);
- await materializeSkillTree(sandbox, handle, alpha, [
- bundle("shared-pack", [
- { path: "lib/shared.mjs", content: "shared" },
- { path: "lib/stale.mjs", content: "stale" },
- ]),
- ]);
-
- await materializeSkillTree(sandbox, handle, alpha);
- assert.equal(
- files.get("skills/.packs/shared-pack/lib/shared.mjs"),
- "shared",
- "a current owner's claim protects the shared path",
- );
- assert.equal(files.has("skills/.packs/shared-pack/lib/stale.mjs"), false, "an unclaimed old bundle path is removed");
- assert.equal(files.get("skills/alpha/SKILL.md"), "A");
- assert.equal(files.has("skills/alpha/.tree"), true, "the clean body-only projection remains idempotent");
+ assert.match(files.get(`${root}/gmail/SKILL.md`) ?? "", new RegExp(`${root}/\\.packs/s1`));
+ assert.equal(files.get(`${root}/.packs/s1/lib/cite.mjs`), "cite");
+ assert.equal(files.get(`${root}/.packs/s1/skills/conventions/quality.md`), "q");
+ assert.equal(files.get("lib/cite.mjs"), undefined);
});
test("a router-advertised importFiles the handle's backend refuses falls back to per-file writes", async () => {
@@ -472,16 +96,17 @@ test("a router-advertised importFiles the handle's backend refuses falls back to
await materializeSkillTree(
sandbox,
handle,
+ root,
res("delta", "D", [
{ path: "a.py", content: "A" },
{ path: "b.py", content: "B" },
]),
);
- assert.equal(files.get("skills/delta/a.py"), "A");
- assert.equal(files.get("skills/delta/b.py"), "B");
+ assert.equal(files.get(`${root}/delta/a.py`), "A");
+ assert.equal(files.get(`${root}/delta/b.py`), "B");
});
-test("materializeSkillTree uses importFiles (one batch) when the backend offers it", async () => {
+test("materializeSkillTree uses importFiles in one batch when the backend offers it", async () => {
const { sandbox, files } = fakeSandbox();
let batches = 0;
(sandbox as unknown as { importFiles: Sandbox["importFiles"] }).importFiles = async (_h, entries) => {
@@ -491,40 +116,35 @@ test("materializeSkillTree uses importFiles (one batch) when the backend offers
await materializeSkillTree(
sandbox,
handle,
+ root,
res("gamma", "G", [
{ path: "a.py", content: "A" },
{ path: "b.py", content: "B" },
]),
);
- assert.equal(batches, 1, "the whole tree is laid in a single round-trip");
- assert.equal(files.get("skills/gamma/a.py"), "A");
- assert.equal(files.get("skills/gamma/b.py"), "B");
+ assert.equal(batches, 1);
+ assert.equal(files.get(`${root}/gamma/a.py`), "A");
});
-test("reconciling a same-named skill source removes prior private assets before invocation", async () => {
- const { sandbox, files, calls } = fakeSandbox();
- const privateSkill = res(
- "deploy",
- "Same instructions",
- [{ path: "private.txt", content: "PRIVATE_ASSET" }],
- "private-pack",
+test("text assets get the same path rewrite as the body and cannot shadow SKILL.md", async () => {
+ const { sandbox, files } = fakeSandbox();
+ await materializeSkillTree(
+ sandbox,
+ handle,
+ root,
+ res("gamma", "G", [
+ { path: "references/how.md", content: "see skills/gamma/scripts/run.sh" },
+ { path: "SKILL.md", content: "forged" },
+ ]),
);
- Object.assign(privateSkill.skill!, { id: "private", scopeId: "personal:U1" });
- const orgSkill = res("deploy", "Same instructions");
- Object.assign(orgSkill.skill!, { id: "public", scopeId: "org:acme" });
- await reconcileSkillIndex(sandbox, handle, [privateSkill]);
- await materializeSkillTree(sandbox, handle, privateSkill, [
- bundle("private-pack", [{ path: "private-lib.txt", content: "PRIVATE_PACK" }]),
+ assert.equal(files.get(`${root}/gamma/references/how.md`), `see ${root}/gamma/scripts/run.sh`);
+ assert.equal(files.get(`${root}/gamma/SKILL.md`), "G");
+});
+
+test("a pack bundle may ship a root SKILL.md of its own", async () => {
+ const { sandbox, files } = fakeSandbox();
+ await materializeSkillTree(sandbox, handle, root, res("gmail", "G", [], "s1"), [
+ bundle("s1", [{ path: "SKILL.md", content: "pack readme" }]),
]);
- assert.ok([...files.values()].some((body) => body.includes("PRIVATE_ASSET")));
- assert.ok([...files.values()].some((body) => body.includes("PRIVATE_PACK")));
- await reconcileSkillIndex(sandbox, handle, [orgSkill]);
- assert.equal(files.has("skills/deploy/SKILL.md"), false);
- assert.equal(
- [...files.values()].some((body) => body.includes("PRIVATE_ASSET") || body.includes("PRIVATE_PACK")),
- false,
- );
- const writes = calls.writes;
- await reconcileSkillIndex(sandbox, handle, [orgSkill]);
- assert.equal(calls.writes, writes);
+ assert.equal(files.get(`${root}/.packs/s1/SKILL.md`), "pack readme");
});
diff --git a/test/skills-seed.test.ts b/test/skills-seed.test.ts
index eba6e787f..ac9b0f261 100644
--- a/test/skills-seed.test.ts
+++ b/test/skills-seed.test.ts
@@ -199,7 +199,7 @@ test("a fresh app advertises and materializes only admin-enabled connector skill
surface: "test",
actor,
conversation: { kind: "dm", threadRef: "dm:U1:seeded-skills-read" },
- text: "!read skills/google-workspace/SKILL.md",
+ text: "!skill google-workspace",
} as TurnRequest);
assert.match(read.reply ?? "", /Google Workspace/);
assert.match(read.reply ?? "", /VAULT_TOKEN_GMAIL_GOOGLEAPIS_COM/);
@@ -209,7 +209,7 @@ test("a fresh app advertises and materializes only admin-enabled connector skill
surface: "test",
actor,
conversation: { kind: "dm", threadRef: "dm:U1:seeded-drive-read" },
- text: "!read skills/google-drive-sheets/SKILL.md",
+ text: "!skill google-drive-sheets",
} as TurnRequest);
assert.match(drive.reply ?? "", /Google Drive \/ Docs \/ Sheets \/ Slides/);
assert.match(drive.reply ?? "", /sheets\.googleapis\.com/);
@@ -254,7 +254,7 @@ test("a bundled skill round-trips seed → store → materialize, assets land be
const { sandbox, files } = fakeSandbox();
const handle: SandboxHandle = { id: "h", rootDir: "/workspace" };
const resolved = await skills.resolve("tooled", [org]);
- await materializeSkillTree(sandbox, handle, resolved);
+ await materializeSkillTree(sandbox, handle, "skills", resolved);
assert.equal(files.get("skills/tooled/SKILL.md"), tooled.manifest.body);
assert.equal(files.get("skills/tooled/scripts/hello.py"), "print('hi')\n");
assert.equal(files.get("skills/tooled/references/notes.md"), "# notes\n");
diff --git a/test/skills-source-read.test.ts b/test/skills-source-read.test.ts
index 9cd33f5e2..90c7a847d 100644
--- a/test/skills-source-read.test.ts
+++ b/test/skills-source-read.test.ts
@@ -29,13 +29,13 @@ async function fixture(t: TestContext) {
assert.equal(result.status, "ok", JSON.stringify(result));
return result.reply ?? "";
};
- const publish = async (scopeId: string, body: string, packId?: string) => {
+ const publish = async (scopeId: string, body: string, packId?: string, name = "source-helper") => {
const skill = await built.skills.create({
scopeId,
createdBy: "U1",
- ...(packId ? { pack: { packId, commit: "c", upstreamName: "source-helper" } } : {}),
+ ...(packId ? { pack: { packId, commit: "c", upstreamName: name } } : {}),
manifest: {
- name: "source-helper",
+ name,
description: "source test",
body,
requiredCapabilities: [],
@@ -52,29 +52,47 @@ async function fixture(t: TestContext) {
test("published skill sources and assets read without a sandbox, respecting scope and archive", async (t) => {
const b = await fixture(t);
const skill = await b.publish("personal:U1", "PUBLISHED_BODY");
- assert.match(await b.turn("!sysprompt"), /skill:\/\/source-helper\/SKILL.md/);
- assert.equal(await b.turn("!read skill://source-helper/SKILL.md"), "PUBLISHED_BODY");
- assert.equal(await b.turn("!read skill://source-helper/references/example.txt"), "PUBLISHED_ASSET");
- assert.match(await b.turn("!read skill://source-helper/SKILL.md", "U2"), /no file/);
+ assert.match(await b.turn("!sysprompt"), /\*\*source-helper\*\*/);
+ assert.match(
+ await b.turn("!skill source-helper"),
+ /^\.agent-turn\/\w+\/[\w-]+\/skills\/source-helper\nPUBLISHED_BODY$/,
+ );
+ assert.match(await b.turn("!skill source-helper references/example.txt"), /\nPUBLISHED_ASSET$/);
+ assert.equal(await b.turn("!skill-run source-helper cat {dir}/references/example.txt"), "PUBLISHED_ASSET");
+ assert.match(await b.turn("!skill source-helper", "U2"), /no skill file/);
await b.skills.archive(skill.id);
- assert.match(await b.turn("!read skill://source-helper/SKILL.md"), /no file/);
- assert.equal(b.provisions(), 0);
+ assert.match(await b.turn("!skill source-helper"), /no skill file/);
+ assert.equal(b.provisions(), 3);
+});
+
+test("a body-only skill loads without any sandbox work", async (t) => {
+ const b = await fixture(t);
+ const skill = await b.skills.create({
+ scopeId: "personal:U1",
+ createdBy: "U1",
+ manifest: { name: "notes-only", description: "text only", body: "JUST_TEXT", requiredCapabilities: [] },
+ });
+ await b.skills.review(skill.id, "reviewer", []);
+ await b.skills.publish(skill.id);
+ assert.equal(await b.turn("!skill notes-only"), "JUST_TEXT");
+ assert.equal(await b.turn("!run echo hi"), "hi");
+ assert.equal(b.provisions(), 1);
});
-test("published skill reads reject invalid and control paths without provisioning", async (t) => {
+test("published skill loads reject invalid and control paths without provisioning", async (t) => {
const b = await fixture(t);
await b.publish("personal:U1", "PUBLISHED_BODY");
- for (const path of [
- "skill://missing/SKILL.md",
- "skill://source-helper/../SKILL.md",
- "skill://source-helper/.tree",
- "skill://../SKILL.md",
- "skill://source-helper//SKILL.md",
- "skill://source-helper/./SKILL.md",
- "skill://source-helper/references/../../secret",
- "skill://source-helper/%2e%2e/secret",
+ for (const [name, path] of [
+ ["missing", "SKILL.md"],
+ ["source-helper", "../SKILL.md"],
+ ["source-helper", ".tree"],
+ ["..", "SKILL.md"],
+ ["source-helper", "/SKILL.md"],
+ ["source-helper", "./SKILL.md"],
+ ["source-helper", "references/../../secret"],
+ ["source-helper", "%2e%2e/secret"],
])
- assert.match(await b.turn(`!read ${path}`), /no file/, path);
+ assert.match(await b.turn(`!skill ${name} ${path}`), /no skill file/, `${name}/${path}`);
assert.equal(b.provisions(), 0);
});
@@ -82,19 +100,16 @@ test("published source follows scope shadowing and preserves sandbox-authored wo
const b = await fixture(t);
await b.publish("org:default-org", "ORG_BODY");
const personal = await b.publish("personal:U1", "PERSONAL_BODY");
- assert.equal(await b.turn("!read skill://source-helper/SKILL.md"), "PERSONAL_BODY");
- assert.equal(b.provisions(), 0);
- await b.turn("!read skills/source-helper/SKILL.md");
+ assert.match(await b.turn("!skill source-helper"), /\nPERSONAL_BODY$/);
await b.turn("!write skills/source-helper/SKILL.md LOCAL_EDIT");
- assert.equal(await b.turn("!read skill://source-helper/SKILL.md"), "PERSONAL_BODY");
+ assert.match(await b.turn("!skill source-helper"), /\nPERSONAL_BODY$/);
assert.equal(await b.turn("!read skills/source-helper/SKILL.md"), "LOCAL_EDIT");
await b.skills.archive(personal.id);
- assert.equal(await b.turn("!read skill://source-helper/SKILL.md"), "ORG_BODY");
+ assert.match(await b.turn("!skill source-helper"), /\nORG_BODY$/);
});
-test("a source-only read avoids sandbox work and a subsequent asset request materializes the current revision", async () => {
+test("a body read avoids sandbox work and a file request materializes that skill under the turn directory", async () => {
const { createTurnSandboxes } = await import("../src/core/orchestrator/sandboxes.ts");
- const { createSkillMaterializer } = await import("../src/skills/materialize.ts");
type TurnSandboxContext = import("../src/core/orchestrator/sandboxes.ts").TurnSandboxContext;
type SkillResolution = import("../src/skills/skill-store.ts").SkillResolution;
const files = new Map<string, string>();
@@ -116,6 +131,7 @@ test("a source-only read avoids sandbox work and a subsequent asset request mate
unrelated.skill!.id = "other";
unrelated.skill!.manifest.name = "unrelated";
unrelated.skill!.pack = { packId: "other-pack", commit: "c", upstreamName: "unrelated" };
+ const visible = [resolution, unrelated];
const handle = { id: "box", rootDir: "/workspace" };
const turn = createTurnSandboxes({
deps: {
@@ -146,26 +162,31 @@ test("a source-only read avoids sandbox work and a subsequent asset request mate
connectorEnv: {},
ownerEnvCredentialIds: [],
credentialCutoverServices: [],
- visibleSkills: [resolution, unrelated],
- visibleSkillsForTurn: async () => [resolution, unrelated],
- skillMaterializer: createSkillMaterializer(),
+ visibleSkillsForTurn: async () => visible,
emitGapWork: () => {},
perf: { credsMs: 0 },
} as unknown as TurnSandboxContext);
- assert.equal((await turn.readSkill("skill://source-helper/SKILL.md")).content, "BODY");
- assert.equal(provisions, 0);
+ const bodyOnly = structuredClone(unrelated);
+ bodyOnly.skill!.id = "body-only";
+ bodyOnly.skill!.manifest.name = "body-only";
+ bodyOnly.skill!.manifest.files = [];
+ delete bodyOnly.skill!.pack;
+ visible.push(bodyOnly);
+ assert.deepEqual(await turn.useSkill("body-only", "SKILL.md"), { content: "BODY", sourceScopeId: "personal:U1" });
+ await turn.provision();
+ assert.equal(provisions, 1);
assert.equal(files.size, 0);
resolution = structuredClone(resolution);
resolution.skill!.manifest.files![0]!.content = "v2";
- assert.equal((await turn.readSkill("skill://source-helper/references/example.txt")).content, "v2");
- await turn.provision();
- assert.deepEqual([...files.keys()], ["skills/.index"]);
- await turn.ensureSkillTree("source-helper");
+ visible[0] = resolution;
+ const loaded = await turn.useSkill("source-helper", "references/example.txt");
+ assert.equal(loaded.content, "v2");
+ assert.equal(loaded.dir, "turn/s/t/skills/source-helper");
assert.equal(provisions, 1);
- assert.equal(files.get("skills/source-helper/references/example.txt"), "v2");
- files.set("skills/source-helper/references/example.txt", "local edit");
- await turn.provision();
- assert.equal(files.get("skills/source-helper/references/example.txt"), "local edit");
+ assert.equal(files.get("turn/s/t/skills/source-helper/references/example.txt"), "v2");
+ files.set("turn/s/t/skills/source-helper/references/example.txt", "local edit");
+ await turn.useSkill("source-helper", "SKILL.md");
+ assert.equal(files.get("turn/s/t/skills/source-helper/references/example.txt"), "local edit");
resolution.skill!.pack = { packId: "pack", commit: "c", upstreamName: "source-helper" };
resolution.screenedBundles = [
{ packId: "pack", commit: "c", hash: "pack-hash", files: [{ path: "lib.txt", content: "PACK_RESOURCE" }] },
@@ -173,25 +194,26 @@ test("a source-only read avoids sandbox work and a subsequent asset request mate
const beforeResource = new Map(files);
await turn.provisionResource("resource-1");
assert.deepEqual(files, beforeResource);
- await turn.ensureSkillTree(".packs/pack", "resource-1");
+ const onResource = await turn.useSkill("source-helper", "SKILL.md", "resource-1");
+ assert.equal(onResource.packDir, "turn/s/t/skills/.packs/pack");
assert.deepEqual(sandboxIds, [undefined, "resource-1"]);
- assert.equal(files.get("skills/.packs/pack/lib.txt"), "PACK_RESOURCE");
+ assert.equal(files.get("turn/s/t/skills/.packs/pack/lib.txt"), "PACK_RESOURCE");
assert.equal(
- [...files.keys()].some((path) => path.startsWith("skills/unrelated/")),
+ [...files.keys()].some((path) => path.includes("/unrelated/")),
false,
);
});
-test("pack assets remain readable and executable on later turns after source-only reads", async (t) => {
+test("pack assets run from the turn directory and vanish with it", async (t) => {
const { computeBundleHash } = await import("../src/skills/skill-bundle-store.ts");
const b = await fixture(t);
const skill = await b.publish("personal:U1", "PACK_BODY", "source-pack");
const files = [{ path: "example.sh", content: "printf PACK_ASSET" }];
await b.skillBundles.put({ packId: "source-pack", commit: "c", files, hash: computeBundleHash(files) });
- assert.match(await b.turn("!read skill://source-helper/SKILL.md"), /skills\/\.packs\/source-pack/);
- assert.equal(b.provisions(), 0);
- assert.equal(await b.turn("!run sh skills/.packs/source-pack/example.sh"), "PACK_ASSET");
- assert.equal(await b.turn("!read skills/.packs/source-pack/example.sh"), "printf PACK_ASSET");
+ assert.match(await b.turn("!skill source-helper"), /skills\/\.packs\/source-pack/);
+ assert.equal(b.provisions(), 1);
+ assert.equal(await b.turn("!skill-run source-helper sh {dir}/../.packs/source-pack/example.sh"), "PACK_ASSET");
+ assert.equal(await b.turn("!run find . -name example.sh | wc -l | tr -d ' '"), "0");
await b.skills.archive(skill.id);
- assert.match(await b.turn("!read skills/.packs/source-pack/example.sh"), /no file/);
+ assert.match(await b.turn("!skill source-helper"), /no skill file/);
});
diff --git a/test/system-prompt-order.test.ts b/test/system-prompt-order.test.ts
index 78398a99d..eb31ce5f3 100644
--- a/test/system-prompt-order.test.ts
+++ b/test/system-prompt-order.test.ts
@@ -793,7 +793,7 @@ for (const location of [
audience: [actor],
publishMembers: [actor],
},
- text: "!read skills/carried-method/SKILL.md",
+ text: "!skill carried-method",
});
assert.equal(read.status, "ok", read.reason);
assert.doesNotMatch(read.reply ?? "", /!security-risk|!security-screen-unavailable/);
@@ -810,11 +810,10 @@ for (const location of [
audience: [actor],
publishMembers: [actor],
},
- text: "!read skills/local-method/SKILL.md",
+ text: "!skill local-method",
});
assert.equal(localRead.status, "ok", localRead.reason);
assert.match(localRead.reply ?? "", /Do useful work/);
- assert.ok(disk.has("skills/local-method/SKILL.md"));
assert.equal(disk.has("skills/carried-method/SKILL.md"), false);
});
}