Something went wrong. Try again.
This repository has no description
Something went wrong. Try again.
JavaScript
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490import assert from "node:assert/strict";import { createHash } from "node:crypto";import { test } from "node:test";import { setTimeout as sleep } from "node:timers/promises";import { build } from "esbuild";import { Miniflare, convertV4MiniflareOptions } from "miniflare";
const files = [ { path: "references/guide.md", content: "# PRIVATE RESOURCE\nRead this markdown 🦊.", mimeType: "text/markdown", kind: "reference", }, { path: "resources/data.json", content: JSON.stringify({ unicode: "雪🦊", escaped: '\u0001"\\\n' }), mimeType: "application/json", kind: "file", }, { path: "resources/table.csv", content: 'name,value\n"雪",42\n', mimeType: "text/csv", kind: "file", }, { path: "resources/page.txt", content: '<script>fetch("https://must-not-run.example/html")</script>', mimeType: "text/plain", kind: "file", }, { path: "resources/large.txt", content: "\u0001🦊\n".repeat(15_000), mimeType: "text/plain", kind: "file", }, { path: "assets/picture.png", content: Buffer.alloc(60_000, 7).toString("base64"), encoding: "base64", mimeType: "image/png", kind: "asset", }, { path: "scripts/check.js", content: 'fetch("https://must-not-run.example/script"); throw new Error("EXECUTED RESOURCE");', mimeType: "text/javascript", kind: "script", },];const envelope = (name, version = "1.0.0") => ({ formatVersion: 1, files: [ { path: "SKILL.md", content: `---\nname: ${name}\ndescription: Metadata for ${name}\nmetadata:\n version: "${version}"\n---\nRead resources only when necessary.`, }, ...files.map(({ path, content, encoding }) => ({ path, content, ...(encoding ? { encoding } : {}), })), ],});const selection = (skill, enabled) => ({ source: skill.origin.kind === "bundled" ? "bundled" : "installed", name: skill.name, fingerprint: skill.fingerprint, revision: skill.revision, enabled,});const outputs = (snapshot, name = "read_skill_resource") => snapshot.messages .flatMap((message) => message.parts) .filter((part) => part.type === `tool-${name}` || part.toolName === name) .map((part) => part.output) .filter((output) => output !== undefined);const unavailable = { ok: false, error: "Skill resource unavailable" };const hash = (value) => createHash("sha256").update(value).digest("hex");async function until(read, predicate, label, signal) { const deadline = Date.now() + 10_000; do { signal.throwIfAborted(); const value = await read(); if (predicate(value)) return value; await sleep(10, undefined, { signal }); } while (Date.now() < deadline); assert.fail(`Timed out: ${label}`);}
test( "native Skill resources stay lazy, bounded, inert and tied to current authority", { timeout: 90_000 }, async (t) => { const bundle = await build({ entryPoints: ["tests/fixtures/skill-activation-worker.ts"], alias: { path: "node:path", crypto: "node:crypto", async_hooks: "node:async_hooks", }, target: "es2022", keepNames: true, bundle: true, write: false, format: "esm", platform: "neutral", conditions: ["workerd", "worker", "browser"], mainFields: ["module", "main"], external: ["cloudflare:*", "node:*"], }); let foreignRequests = 0; const worker = new Miniflare( convertV4MiniflareOptions({ modules: true, script: bundle.outputFiles[0].text, compatibilityDate: "2026-09-04", compatibilityFlags: ["nodejs_compat"], durableObjects: { MODEL: { className: "PersonalAgent", useSQLite: true }, }, r2Buckets: ["ATTACHMENTS"], outboundService: () => { foreignRequests++; return new Response("Unexpected external request", { status: 503 }); }, }), ); const requests = new AbortController(); const signal = AbortSignal.any([t.signal, requests.signal]); let disposal; const cleanup = () => { requests.abort(); return (disposal ??= (async () => { let timer; try { await Promise.race([ worker.dispose(), new Promise((_, reject) => { timer = setTimeout( () => reject(new Error("Skill fixture disposal timed out")), 15_000, ); }), ]); } finally { clearTimeout(timer); } })()); }; t.after(cleanup, { timeout: 16_000 }); const poll = (read, predicate, label) => until(read, predicate, label, signal); const pending = new Map(); const call = async (action, value, name = "conversation") => { const response = await worker.dispatchFetch("https://fixture.example/", { method: "POST", signal, body: JSON.stringify({ action, value, name }), }); assert.equal(response.status, 200); const result = await response.json(); assert.ok(!result?.fixtureError, JSON.stringify(result)); return result; }; const list = () => call("list"); const skill = async (name) => (await list()).find((item) => item.name === name); const toggle = async (item, enabled) => { const result = await call("toggle", selection(item, enabled)); assert.equal(result.ok, true, JSON.stringify(result)); return skill(item.name); }; const submit = (name, resources = [], extra = {}) => call("submit", { resources, ...extra }, name); const start = (name, resources, extra = {}) => { const work = submit(name, resources, extra); pending.set(name, work); }; const finish = async (name) => { const result = await pending.get(name); pending.delete(name); return result; }; const resource = (name, path = files[0].path) => ({ name, path }); const assertActivity = (snapshot, original, path, status) => { const activity = snapshot.activities.find( (item) => item.toolName === "read_skill_resource", ); assert.equal(activity.status, status); assert.equal(activity.capability.fingerprint, original.fingerprint); assert.equal(activity.capability.version, original.version); assert.equal(activity.capability.name, `${original.name}/${path}`); assert.deepEqual(activity.capability.source, { kind: "skill", id: `installed:${original.name}`, name: original.name, }); const diagnostic = snapshot.diagnostics.events.find( (event) => event.kind === "tool" && event.status === status && event.details.tool === "read_skill_resource", ); assert.ok(diagnostic, JSON.stringify(snapshot.diagnostics)); assert.equal( diagnostic.details.capabilityId, hash(activity.capability.id), ); assert.equal( diagnostic.details.capabilityFingerprint, hash(original.fingerprint), ); assert.equal( diagnostic.details.capabilitySourceId, hash(`installed:${original.name}`), ); assert.equal(diagnostic.details.capabilitySourceKind, "skill"); assert.ok( !JSON.stringify(snapshot.diagnostics).includes("PRIVATE RESOURCE"), ); assert.ok(!JSON.stringify(snapshot.diagnostics).includes(original.name)); return activity; }; const assertFailed = (snapshot, original) => { assert.deepEqual(outputs(snapshot), [unavailable]); assertActivity(snapshot, original, files[0].path, "failed"); assert.ok( !JSON.stringify(snapshot.messages).includes("PRIVATE RESOURCE"), ); assert.ok(!JSON.stringify(snapshot).includes("Fixture private")); }; try { for (const item of await list()) await toggle(item, false); for (const name of ["resource-guide", "other-guide"]) { const installed = await call("install", { envelope: envelope(name) }); await toggle(installed, true); } const original = await skill("resource-guide"); const before = (await call("metrics")).reads; const metadata = await submit("lazy"); assert.equal((await call("metrics")).reads, before); assert.ok(!metadata.observed[0].prompt.includes("PRIVATE RESOURCE")); const activated = await submit("inventory", [], { names: [original.name], }); assert.equal( (await call("metrics")).reads, before + 1, "activation loads one package, not every listed resource", ); const inventory = outputs(activated, "activate_skill")[0]; assert.match(inventory, /name="resource-guide"/); assert.match(inventory, /version="1.0.0"/); for (const file of files) assert.ok(inventory.includes(file.path), file.path); assert.ok(!inventory.includes("PRIVATE RESOURCE")); assert.equal( activated.observed[0].prompt.split("CURRENT OWNER INSTRUCTIONS:") .length - 1, 1, );
const combined = await submit( "activate-then-read", [resource(original.name)], { names: [original.name] }, ); assert.equal(outputs(combined, "activate_skill").length, 1); assert.equal(outputs(combined)[0].content, files[0].content); assert.ok(combined.observed.at(-1).prompt.includes("PRIVATE RESOURCE")); assert.ok( combined.observed .at(-1) .prompt.includes("Read resources only when necessary."), );
let firstId; for (const file of files) { const snapshot = await submit(`read-${file.path}`, [ resource(original.name, file.path), ]); const [output] = outputs(snapshot); assert.equal(output.ok, true, JSON.stringify(output)); assert.deepEqual(output.skill, { source: "installed", name: original.name, version: original.version, fingerprint: original.fingerprint, }); assert.equal(output.path, file.path); assert.equal(output.kind, file.kind); assert.equal(output.encoding, file.encoding ?? "text"); assert.equal(output.mimeType, file.mimeType); assert.match(output.id, /^[a-f0-9]{64}$/); assert.ok(Buffer.byteLength(JSON.stringify(output)) <= 65_536); const large = file.path === "resources/large.txt" || file.encoding === "base64"; assert.equal(output.truncated, large); if (large) { assert.ok( output.content.length > 0 && output.content.length < file.content.length, ); assert.ok(file.content.startsWith(output.content)); assert.equal(output.content.isWellFormed(), true); if (file.encoding === "base64") { assert.equal(output.content.length % 4, 0); const decoded = Buffer.from(output.content, "base64"); assert.deepEqual(decoded, Buffer.alloc(decoded.length, 7)); assert.equal(decoded.toString("base64"), output.content); } } else assert.equal(output.content, file.content); const activity = assertActivity( snapshot, original, file.path, "succeeded", ); assert.equal(activity.capability.id, output.id); if (file === files[0]) firstId = output.id; } const repeated = outputs( await submit("repeat", [resource(original.name)]), )[0]; assert.equal(repeated.id, firstId); const other = outputs( await submit("other-source", [resource("other-guide")]), )[0]; assert.notEqual( other.id, firstId, "same relative path remains qualified by source", ); assert.equal(other.skill.name, "other-guide");
// Changing false to true saves one JSON byte. A result that exceeds the // limit by exactly one byte must still remove content before claiming it. const boundaryContent = "x".repeat( 65_537 - Buffer.byteLength(JSON.stringify({ ...other, content: "" })), ); assert.equal( Buffer.byteLength( JSON.stringify({ ...other, content: boundaryContent }), ), 65_537, ); const boundaryPackage = envelope("other-guide"); boundaryPackage.files.find( (file) => file.path === files[0].path, ).content = boundaryContent; const boundaryInstalled = await call("install", { envelope: boundaryPackage, revision: (await skill("other-guide")).revision, }); await toggle(boundaryInstalled, true); const boundaryOutput = outputs( await submit("one-byte-boundary", [resource("other-guide")]), )[0]; assert.equal(boundaryOutput.ok, true); assert.ok(Buffer.byteLength(JSON.stringify(boundaryOutput)) <= 65_536); assert.equal(boundaryOutput.truncated, true); assert.ok( boundaryOutput.content.length < boundaryContent.length, "truncated must mean resource content was actually removed", ); assert.ok(boundaryContent.startsWith(boundaryOutput.content));
for (const path of [ "../SKILL.md", "/references/guide.md", "references/../SKILL.md", "references\\guide.md", "references/%2e%2e/guide.md", ]) { const reads = (await call("metrics")).reads; assert.deepEqual( outputs( await submit(`invalid-${path}`, [resource(original.name, path)]), ), [unavailable], ); assert.equal( (await call("metrics")).reads, reads, "invalid path rejected before R2", ); } const reads = (await call("metrics")).reads; assert.deepEqual( outputs(await submit("unknown-skill", [resource("unknown-guide")])), [unavailable], ); assert.equal((await call("metrics")).reads, reads); assert.deepEqual( outputs( await submit("unknown-file", [ resource(original.name, "resources/missing.txt"), ]), ), [unavailable], );
start("stale-before-input", [resource(original.name)], { hold: true }); const raw = await poll( () => call("snapshot", undefined, "stale-before-input"), (value) => value.holding && value.activities.some( (item) => item.toolName === "read_skill_resource", ), "native raw input start", ); assert.equal(raw.activities[0].capability, undefined); const beforeStale = (await call("metrics")).reads; await toggle(original, false); await call("release", undefined, "stale-before-input"); assertFailed(await finish("stale-before-input"), original); assert.equal((await call("metrics")).reads, beforeStale);
for (const race of ["disable", "replace", "remove"]) { const current = await toggle(await skill(original.name), true); await call("fault", { holdRead: true }); const name = `${race}-during-resource-read`; start(name, [resource(current.name)]); await poll( () => call("metrics"), (value) => value.waitingRead, "real R2 read held across authority mutation", ); if (race === "disable") await toggle(current, false); else if (race === "replace") await call("install", { envelope: envelope(current.name, "2.0.0"), revision: current.revision, }); else await call("remove", { name: current.name, revision: current.revision, }); await call("fault", { holdRead: false }); assertFailed(await finish(name), current); } const reinstalled = await call("install", { envelope: envelope(original.name, "3.0.0"), }); const current = await toggle(reinstalled, true); await call("fault", { failRead: true }); const failure = await submit("storage-failure", [resource(current.name)]); assertFailed(failure, current); await call("fault", { failRead: false }); const recovery = await submit("storage-failure", [ resource(current.name), ]); assert.equal(recovery.instanceId, failure.instanceId); assert.equal(outputs(recovery).at(-1).content, files[0].content); assert.equal( outputs(recovery).at(-1).id, firstId, "version changes keep the resource address stable", ); assert.equal(outputs(recovery).at(-1).skill.version, "3.0.0"); assert.notEqual( outputs(recovery).at(-1).skill.fingerprint, original.fingerprint, ); assert.equal( foreignRequests, 0, "resource reads and script text never make foreign requests", ); } finally { if (!t.signal.aborted) await Promise.allSettled([ call("fault", { holdRead: false }), ...[...pending.keys()].map((name) => call("release", undefined, name), ), ]); const settled = Promise.allSettled(pending.values()); await cleanup(); await settled; } },);