@buildanagent/harness 0.0.0-stage → 0.1.0-alpha.28
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +54 -0
- package/LICENSE-APACHE +202 -0
- package/LICENSE-MIT +21 -0
- package/README.md +716 -2
- package/dist/ablation.d.ts +2 -0
- package/dist/ablation.js +3 -0
- package/dist/ablation.js.map +1 -0
- package/dist/completion/check.d.ts +64 -0
- package/dist/completion/check.js +152 -0
- package/dist/completion/check.js.map +1 -0
- package/dist/completion/checks.d.ts +45 -0
- package/dist/completion/checks.js +173 -0
- package/dist/completion/checks.js.map +1 -0
- package/dist/completion/flags.d.ts +25 -0
- package/dist/completion/flags.js +87 -0
- package/dist/completion/flags.js.map +1 -0
- package/dist/completion/index.d.ts +8 -0
- package/dist/completion/index.js +9 -0
- package/dist/completion/index.js.map +1 -0
- package/dist/completion/snapshot.d.ts +33 -0
- package/dist/completion/snapshot.js +83 -0
- package/dist/completion/snapshot.js.map +1 -0
- package/dist/context/cap.d.ts +32 -0
- package/dist/context/cap.js +50 -0
- package/dist/context/cap.js.map +1 -0
- package/dist/context/estimate.d.ts +18 -0
- package/dist/context/estimate.js +20 -0
- package/dist/context/estimate.js.map +1 -0
- package/dist/context/file-spill.d.ts +5 -0
- package/dist/context/file-spill.js +25 -0
- package/dist/context/file-spill.js.map +1 -0
- package/dist/context/index.d.ts +10 -0
- package/dist/context/index.js +10 -0
- package/dist/context/index.js.map +1 -0
- package/dist/context/mask.d.ts +27 -0
- package/dist/context/mask.js +71 -0
- package/dist/context/mask.js.map +1 -0
- package/dist/context/mid-turn.d.ts +40 -0
- package/dist/context/mid-turn.js +82 -0
- package/dist/context/mid-turn.js.map +1 -0
- package/dist/context/policy.d.ts +9 -0
- package/dist/context/policy.js +140 -0
- package/dist/context/policy.js.map +1 -0
- package/dist/context/spill-ledger.d.ts +25 -0
- package/dist/context/spill-ledger.js +54 -0
- package/dist/context/spill-ledger.js.map +1 -0
- package/dist/context/spill.d.ts +6 -0
- package/dist/context/spill.js +14 -0
- package/dist/context/spill.js.map +1 -0
- package/dist/context/summarize.d.ts +53 -0
- package/dist/context/summarize.js +204 -0
- package/dist/context/summarize.js.map +1 -0
- package/dist/context/summary-template.d.ts +29 -0
- package/dist/context/summary-template.js +69 -0
- package/dist/context/summary-template.js.map +1 -0
- package/dist/context/types.d.ts +150 -0
- package/dist/context/types.js +2 -0
- package/dist/context/types.js.map +1 -0
- package/dist/context/write-cap.d.ts +19 -0
- package/dist/context/write-cap.js +41 -0
- package/dist/context/write-cap.js.map +1 -0
- package/dist/create-harness.d.ts +7 -0
- package/dist/create-harness.js +21 -0
- package/dist/create-harness.js.map +1 -0
- package/dist/credentials/addresses.d.ts +14 -0
- package/dist/credentials/addresses.js +144 -0
- package/dist/credentials/addresses.js.map +1 -0
- package/dist/credentials/allowlist.d.ts +34 -0
- package/dist/credentials/allowlist.js +77 -0
- package/dist/credentials/allowlist.js.map +1 -0
- package/dist/credentials/egress-proxy.d.ts +70 -0
- package/dist/credentials/egress-proxy.js +482 -0
- package/dist/credentials/egress-proxy.js.map +1 -0
- package/dist/credentials/index.d.ts +9 -0
- package/dist/credentials/index.js +10 -0
- package/dist/credentials/index.js.map +1 -0
- package/dist/credentials/scrub.d.ts +16 -0
- package/dist/credentials/scrub.js +93 -0
- package/dist/credentials/scrub.js.map +1 -0
- package/dist/errors.d.ts +56 -0
- package/dist/errors.js +63 -0
- package/dist/errors.js.map +1 -0
- package/dist/extensions/compose.d.ts +27 -0
- package/dist/extensions/compose.js +83 -0
- package/dist/extensions/compose.js.map +1 -0
- package/dist/extensions/context-files-node.d.ts +28 -0
- package/dist/extensions/context-files-node.js +74 -0
- package/dist/extensions/context-files-node.js.map +1 -0
- package/dist/extensions/context-files.d.ts +68 -0
- package/dist/extensions/context-files.js +214 -0
- package/dist/extensions/context-files.js.map +1 -0
- package/dist/extensions/digest.d.ts +6 -0
- package/dist/extensions/digest.js +68 -0
- package/dist/extensions/digest.js.map +1 -0
- package/dist/extensions/index.d.ts +10 -0
- package/dist/extensions/index.js +10 -0
- package/dist/extensions/index.js.map +1 -0
- package/dist/extensions/load.d.ts +42 -0
- package/dist/extensions/load.js +211 -0
- package/dist/extensions/load.js.map +1 -0
- package/dist/extensions/lock.d.ts +8 -0
- package/dist/extensions/lock.js +95 -0
- package/dist/extensions/lock.js.map +1 -0
- package/dist/extensions/node.d.ts +10 -0
- package/dist/extensions/node.js +11 -0
- package/dist/extensions/node.js.map +1 -0
- package/dist/extensions/project-dirs.d.ts +24 -0
- package/dist/extensions/project-dirs.js +97 -0
- package/dist/extensions/project-dirs.js.map +1 -0
- package/dist/extensions/skills-node.d.ts +34 -0
- package/dist/extensions/skills-node.js +123 -0
- package/dist/extensions/skills-node.js.map +1 -0
- package/dist/extensions/skills.d.ts +51 -0
- package/dist/extensions/skills.js +175 -0
- package/dist/extensions/skills.js.map +1 -0
- package/dist/extensions/trust-file.d.ts +3 -0
- package/dist/extensions/trust-file.js +62 -0
- package/dist/extensions/trust-file.js.map +1 -0
- package/dist/extensions/trust-store-node.d.ts +10 -0
- package/dist/extensions/trust-store-node.js +33 -0
- package/dist/extensions/trust-store-node.js.map +1 -0
- package/dist/extensions/types.d.ts +42 -0
- package/dist/extensions/types.js +2 -0
- package/dist/extensions/types.js.map +1 -0
- package/dist/harness.d.ts +156 -0
- package/dist/harness.js +2 -0
- package/dist/harness.js.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -0
- package/dist/mcp/connection.d.ts +22 -0
- package/dist/mcp/connection.js +267 -0
- package/dist/mcp/connection.js.map +1 -0
- package/dist/mcp/content.d.ts +27 -0
- package/dist/mcp/content.js +177 -0
- package/dist/mcp/content.js.map +1 -0
- package/dist/mcp/errors.d.ts +19 -0
- package/dist/mcp/errors.js +21 -0
- package/dist/mcp/errors.js.map +1 -0
- package/dist/mcp/index.d.ts +10 -0
- package/dist/mcp/index.js +10 -0
- package/dist/mcp/index.js.map +1 -0
- package/dist/mcp/manager.d.ts +7 -0
- package/dist/mcp/manager.js +173 -0
- package/dist/mcp/manager.js.map +1 -0
- package/dist/mcp/record.d.ts +7 -0
- package/dist/mcp/record.js +20 -0
- package/dist/mcp/record.js.map +1 -0
- package/dist/mcp/stdio.d.ts +39 -0
- package/dist/mcp/stdio.js +382 -0
- package/dist/mcp/stdio.js.map +1 -0
- package/dist/mcp/types.d.ts +172 -0
- package/dist/mcp/types.js +2 -0
- package/dist/mcp/types.js.map +1 -0
- package/dist/memory/index.d.ts +2 -0
- package/dist/memory/index.js +3 -0
- package/dist/memory/index.js.map +1 -0
- package/dist/permissions/default-rules.d.ts +7 -0
- package/dist/permissions/default-rules.js +42 -0
- package/dist/permissions/default-rules.js.map +1 -0
- package/dist/permissions/errors.d.ts +11 -0
- package/dist/permissions/errors.js +14 -0
- package/dist/permissions/errors.js.map +1 -0
- package/dist/permissions/index.d.ts +9 -0
- package/dist/permissions/index.js +9 -0
- package/dist/permissions/index.js.map +1 -0
- package/dist/permissions/match.d.ts +33 -0
- package/dist/permissions/match.js +287 -0
- package/dist/permissions/match.js.map +1 -0
- package/dist/permissions/pipeline.d.ts +9 -0
- package/dist/permissions/pipeline.js +235 -0
- package/dist/permissions/pipeline.js.map +1 -0
- package/dist/permissions/rules.d.ts +22 -0
- package/dist/permissions/rules.js +74 -0
- package/dist/permissions/rules.js.map +1 -0
- package/dist/permissions/shadow.d.ts +5 -0
- package/dist/permissions/shadow.js +22 -0
- package/dist/permissions/shadow.js.map +1 -0
- package/dist/permissions/types.d.ts +104 -0
- package/dist/permissions/types.js +2 -0
- package/dist/permissions/types.js.map +1 -0
- package/dist/sandbox/base.d.ts +35 -0
- package/dist/sandbox/base.js +60 -0
- package/dist/sandbox/base.js.map +1 -0
- package/dist/sandbox/docker/index.d.ts +35 -0
- package/dist/sandbox/docker/index.js +448 -0
- package/dist/sandbox/docker/index.js.map +1 -0
- package/dist/sandbox/errors.d.ts +16 -0
- package/dist/sandbox/errors.js +22 -0
- package/dist/sandbox/errors.js.map +1 -0
- package/dist/sandbox/host-files.d.ts +63 -0
- package/dist/sandbox/host-files.js +248 -0
- package/dist/sandbox/host-files.js.map +1 -0
- package/dist/sandbox/index.d.ts +8 -0
- package/dist/sandbox/index.js +8 -0
- package/dist/sandbox/index.js.map +1 -0
- package/dist/sandbox/none.d.ts +17 -0
- package/dist/sandbox/none.js +108 -0
- package/dist/sandbox/none.js.map +1 -0
- package/dist/sandbox/process.d.ts +61 -0
- package/dist/sandbox/process.js +253 -0
- package/dist/sandbox/process.js.map +1 -0
- package/dist/sandbox/spawn-env.d.ts +20 -0
- package/dist/sandbox/spawn-env.js +128 -0
- package/dist/sandbox/spawn-env.js.map +1 -0
- package/dist/sandbox/srt/index.d.ts +35 -0
- package/dist/sandbox/srt/index.js +264 -0
- package/dist/sandbox/srt/index.js.map +1 -0
- package/dist/sandbox/srt/settings.d.ts +48 -0
- package/dist/sandbox/srt/settings.js +31 -0
- package/dist/sandbox/srt/settings.js.map +1 -0
- package/dist/sandbox/types.d.ts +88 -0
- package/dist/sandbox/types.js +6 -0
- package/dist/sandbox/types.js.map +1 -0
- package/dist/server/answers.d.ts +16 -0
- package/dist/server/answers.js +43 -0
- package/dist/server/answers.js.map +1 -0
- package/dist/server/connection.d.ts +99 -0
- package/dist/server/connection.js +309 -0
- package/dist/server/connection.js.map +1 -0
- package/dist/server/dispatcher.d.ts +86 -0
- package/dist/server/dispatcher.js +800 -0
- package/dist/server/dispatcher.js.map +1 -0
- package/dist/server/index.d.ts +13 -0
- package/dist/server/index.js +12 -0
- package/dist/server/index.js.map +1 -0
- package/dist/server/local-transport.d.ts +44 -0
- package/dist/server/local-transport.js +103 -0
- package/dist/server/local-transport.js.map +1 -0
- package/dist/server/outbox.d.ts +31 -0
- package/dist/server/outbox.js +130 -0
- package/dist/server/outbox.js.map +1 -0
- package/dist/server/params.d.ts +25 -0
- package/dist/server/params.js +112 -0
- package/dist/server/params.js.map +1 -0
- package/dist/server/protocol.schema.json +2448 -0
- package/dist/server/rpc-session.d.ts +43 -0
- package/dist/server/rpc-session.js +167 -0
- package/dist/server/rpc-session.js.map +1 -0
- package/dist/server/stdio-streams.d.ts +67 -0
- package/dist/server/stdio-streams.js +218 -0
- package/dist/server/stdio-streams.js.map +1 -0
- package/dist/server/stdio.d.ts +59 -0
- package/dist/server/stdio.js +189 -0
- package/dist/server/stdio.js.map +1 -0
- package/dist/server/websocket.d.ts +106 -0
- package/dist/server/websocket.js +327 -0
- package/dist/server/websocket.js.map +1 -0
- package/dist/session/approvals.d.ts +81 -0
- package/dist/session/approvals.js +217 -0
- package/dist/session/approvals.js.map +1 -0
- package/dist/session/code-call-log.d.ts +42 -0
- package/dist/session/code-call-log.js +63 -0
- package/dist/session/code-call-log.js.map +1 -0
- package/dist/session/code-call-result.d.ts +19 -0
- package/dist/session/code-call-result.js +95 -0
- package/dist/session/code-call-result.js.map +1 -0
- package/dist/session/code-call.d.ts +49 -0
- package/dist/session/code-call.js +345 -0
- package/dist/session/code-call.js.map +1 -0
- package/dist/session/effect-scope.d.ts +11 -0
- package/dist/session/effect-scope.js +10 -0
- package/dist/session/effect-scope.js.map +1 -0
- package/dist/session/errors.d.ts +19 -0
- package/dist/session/errors.js +27 -0
- package/dist/session/errors.js.map +1 -0
- package/dist/session/file-index.d.ts +8 -0
- package/dist/session/file-index.js +70 -0
- package/dist/session/file-index.js.map +1 -0
- package/dist/session/file-key-store.d.ts +16 -0
- package/dist/session/file-key-store.js +169 -0
- package/dist/session/file-key-store.js.map +1 -0
- package/dist/session/file-lock.d.ts +52 -0
- package/dist/session/file-lock.js +324 -0
- package/dist/session/file-lock.js.map +1 -0
- package/dist/session/index.d.ts +22 -0
- package/dist/session/index.js +20 -0
- package/dist/session/index.js.map +1 -0
- package/dist/session/jsonl-store.d.ts +37 -0
- package/dist/session/jsonl-store.js +386 -0
- package/dist/session/jsonl-store.js.map +1 -0
- package/dist/session/jsonl.d.ts +9 -0
- package/dist/session/jsonl.js +10 -0
- package/dist/session/jsonl.js.map +1 -0
- package/dist/session/lock.d.ts +19 -0
- package/dist/session/lock.js +2 -0
- package/dist/session/lock.js.map +1 -0
- package/dist/session/memory-store.d.ts +12 -0
- package/dist/session/memory-store.js +60 -0
- package/dist/session/memory-store.js.map +1 -0
- package/dist/session/migrate.d.ts +41 -0
- package/dist/session/migrate.js +86 -0
- package/dist/session/migrate.js.map +1 -0
- package/dist/session/pointer.d.ts +15 -0
- package/dist/session/pointer.js +22 -0
- package/dist/session/pointer.js.map +1 -0
- package/dist/session/rebuild.d.ts +53 -0
- package/dist/session/rebuild.js +230 -0
- package/dist/session/rebuild.js.map +1 -0
- package/dist/session/resume.d.ts +26 -0
- package/dist/session/resume.js +128 -0
- package/dist/session/resume.js.map +1 -0
- package/dist/session/retention.d.ts +97 -0
- package/dist/session/retention.js +702 -0
- package/dist/session/retention.js.map +1 -0
- package/dist/session/runner.d.ts +156 -0
- package/dist/session/runner.js +656 -0
- package/dist/session/runner.js.map +1 -0
- package/dist/session/scheduler.d.ts +47 -0
- package/dist/session/scheduler.js +85 -0
- package/dist/session/scheduler.js.map +1 -0
- package/dist/session/secret-key-store.d.ts +47 -0
- package/dist/session/secret-key-store.js +79 -0
- package/dist/session/secret-key-store.js.map +1 -0
- package/dist/session/session.d.ts +106 -0
- package/dist/session/session.js +353 -0
- package/dist/session/session.js.map +1 -0
- package/dist/session/sticky.d.ts +48 -0
- package/dist/session/sticky.js +232 -0
- package/dist/session/sticky.js.map +1 -0
- package/dist/session/store.d.ts +108 -0
- package/dist/session/store.js +163 -0
- package/dist/session/store.js.map +1 -0
- package/dist/telemetry/index.d.ts +2 -0
- package/dist/telemetry/index.js +3 -0
- package/dist/telemetry/index.js.map +1 -0
- package/dist/testing/fake-sandbox.d.ts +34 -0
- package/dist/testing/fake-sandbox.js +221 -0
- package/dist/testing/fake-sandbox.js.map +1 -0
- package/dist/testing/index.d.ts +10 -0
- package/dist/testing/index.js +11 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/testing/key-store-conformance.d.ts +22 -0
- package/dist/testing/key-store-conformance.js +97 -0
- package/dist/testing/key-store-conformance.js.map +1 -0
- package/dist/testing/run-cases.d.ts +21 -0
- package/dist/testing/run-cases.js +20 -0
- package/dist/testing/run-cases.js.map +1 -0
- package/dist/testing/sandbox-conformance.d.ts +64 -0
- package/dist/testing/sandbox-conformance.js +361 -0
- package/dist/testing/sandbox-conformance.js.map +1 -0
- package/dist/testing/scheduler-conformance.d.ts +32 -0
- package/dist/testing/scheduler-conformance.js +72 -0
- package/dist/testing/scheduler-conformance.js.map +1 -0
- package/dist/testing/store-conformance.d.ts +21 -0
- package/dist/testing/store-conformance.js +320 -0
- package/dist/testing/store-conformance.js.map +1 -0
- package/dist/tools/errors.d.ts +13 -0
- package/dist/tools/errors.js +17 -0
- package/dist/tools/errors.js.map +1 -0
- package/dist/tools/index.d.ts +8 -0
- package/dist/tools/index.js +8 -0
- package/dist/tools/index.js.map +1 -0
- package/dist/tools/registry.d.ts +3 -0
- package/dist/tools/registry.js +234 -0
- package/dist/tools/registry.js.map +1 -0
- package/dist/tools/tool-search.d.ts +30 -0
- package/dist/tools/tool-search.js +118 -0
- package/dist/tools/tool-search.js.map +1 -0
- package/dist/tools/types.d.ts +106 -0
- package/dist/tools/types.js +2 -0
- package/dist/tools/types.js.map +1 -0
- package/llms.txt +435 -0
- package/package.json +118 -3
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Loading the extensions a project supplies. A project's extensions live in `.agents/extensions/<folder>/`, each with an
|
|
3
|
+
* `index.mjs` or `index.js` whose default export is an `Extension`, or a function returning one. They load only when the
|
|
4
|
+
* project is trusted and the run is not headless, and only when every folder's hash matches the lock file. Trust gates
|
|
5
|
+
* loading, not execution: an extension that loads runs with the harness's own permissions. Node-only.
|
|
6
|
+
*/
|
|
7
|
+
import { access, lstat, readdir, realpath } from "node:fs/promises";
|
|
8
|
+
import { join, resolve } from "node:path";
|
|
9
|
+
import { pathToFileURL } from "node:url";
|
|
10
|
+
import { HarnessError } from "../errors.js";
|
|
11
|
+
import { hashExtensionDir, readLock, writeLock } from "./lock.js";
|
|
12
|
+
/** The path with symlinks resolved, so a symlinked root and its target are one project to the trust store. */
|
|
13
|
+
export async function canonicalPath(path) {
|
|
14
|
+
try {
|
|
15
|
+
return await realpath(resolve(path));
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
return resolve(path);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Whether the trust store trusts the project at `root`, asked about its real path only. A link that the store trusted
|
|
23
|
+
* can be pointed at another folder later, so the spelling the caller wrote is never what is trusted: the folder it
|
|
24
|
+
* resolves to now is. Every loader asks through this, so the extensions and the skills of a project are trusted alike.
|
|
25
|
+
*/
|
|
26
|
+
export async function projectTrusted(trust, root) {
|
|
27
|
+
return trust.isTrusted(await canonicalPath(root));
|
|
28
|
+
}
|
|
29
|
+
const places = async (root, options) => ({
|
|
30
|
+
// The folder is canonical, so a relative or symlinked spelling of it is one folder to the import-cache check.
|
|
31
|
+
dir: await canonicalPath(options.extensionsDir ?? join(root, ".agents", "extensions")),
|
|
32
|
+
lock: options.lockFile ?? join(root, ".agents", "extensions.lock.json"),
|
|
33
|
+
});
|
|
34
|
+
/** Whether `path` exists, without following a link or reading it. */
|
|
35
|
+
async function exists(path) {
|
|
36
|
+
try {
|
|
37
|
+
await lstat(path);
|
|
38
|
+
return true;
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/** The extension folders under `dir`, by name; none when the folder does not exist. */
|
|
45
|
+
async function folders(dir) {
|
|
46
|
+
try {
|
|
47
|
+
const entries = await readdir(dir, { withFileTypes: true });
|
|
48
|
+
// A linked folder is not hashed as the folder it points at, so it cannot be pinned.
|
|
49
|
+
const linked = entries.find((entry) => entry.isSymbolicLink());
|
|
50
|
+
if (linked !== undefined) {
|
|
51
|
+
throw new HarnessError("invalid_extension", `${join(dir, linked.name)} is a link, which an extension folder may not be`);
|
|
52
|
+
}
|
|
53
|
+
return entries
|
|
54
|
+
.filter((entry) => entry.isDirectory())
|
|
55
|
+
.map((entry) => entry.name)
|
|
56
|
+
.sort();
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
const code = error.code;
|
|
60
|
+
if (code === "ENOENT" || code === "ENOTDIR")
|
|
61
|
+
return [];
|
|
62
|
+
throw error;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
async function entryFile(dir) {
|
|
66
|
+
for (const name of ["index.mjs", "index.js"]) {
|
|
67
|
+
try {
|
|
68
|
+
await access(join(dir, name));
|
|
69
|
+
return join(dir, name);
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
// try the next name
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
throw new HarnessError("invalid_extension", `the extension folder ${dir} has no index.mjs or index.js`);
|
|
76
|
+
}
|
|
77
|
+
// The hash each folder had when this process first imported it. Node caches modules for the life of the process, so a
|
|
78
|
+
// folder that changed since then would run its old code while the log recorded the new hash.
|
|
79
|
+
const importedHashes = new Map();
|
|
80
|
+
/** Refuses a folder this process has imported with other files, before any folder of the project is imported. */
|
|
81
|
+
function refuseChanged(folder, hash) {
|
|
82
|
+
const before = importedHashes.get(folder);
|
|
83
|
+
if (before !== undefined && before !== hash) {
|
|
84
|
+
throw new HarnessError("extension_hash_mismatch", `the extension in ${folder} changed after this process loaded it; restart the process to load the new files`);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
const isFunction = (value) => typeof value === "function";
|
|
88
|
+
const badShape = (dir, why) => new HarnessError("invalid_extension", `the extension in ${dir} ${why}`);
|
|
89
|
+
/** Throws unless `interceptors` is an object whose hooks are functions, apart from the `onFailure` setting. */
|
|
90
|
+
function checkInterceptors(interceptors, dir) {
|
|
91
|
+
if (interceptors === undefined)
|
|
92
|
+
return;
|
|
93
|
+
if (typeof interceptors !== "object" || interceptors === null) {
|
|
94
|
+
throw badShape(dir, "has interceptors that are not an object");
|
|
95
|
+
}
|
|
96
|
+
for (const [name, hook] of Object.entries(interceptors)) {
|
|
97
|
+
if (name !== "onFailure" && !isFunction(hook))
|
|
98
|
+
throw badShape(dir, `has an interceptor "${name}" that is not a function`);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
/** Throws unless `observers` is a list of functions and `tools` a list of `{ name, definition }`. */
|
|
102
|
+
function checkLists(observers, tools, dir) {
|
|
103
|
+
if (observers !== undefined && !(Array.isArray(observers) && observers.every(isFunction))) {
|
|
104
|
+
throw badShape(dir, "has observers that are not a list of functions");
|
|
105
|
+
}
|
|
106
|
+
const wellFormed = (tool) => typeof tool?.name === "string" && typeof tool.definition === "object" && tool.definition !== null;
|
|
107
|
+
if (tools !== undefined && !(Array.isArray(tools) && tools.every(wellFormed))) {
|
|
108
|
+
throw badShape(dir, "has tools that are not a list of { name, definition }");
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
/** Throws `invalid_extension` unless the module's export has the shape of an `Extension`. */
|
|
112
|
+
function checkShape(extension, dir) {
|
|
113
|
+
if (typeof extension?.name !== "string" || typeof extension.version !== "string") {
|
|
114
|
+
throw badShape(dir, "does not export a name and a version");
|
|
115
|
+
}
|
|
116
|
+
checkInterceptors(extension.interceptors, dir);
|
|
117
|
+
checkLists(extension.observers, extension.tools, dir);
|
|
118
|
+
}
|
|
119
|
+
async function importExtension(dir, hash) {
|
|
120
|
+
const loaded = (await import(/* @vite-ignore */ pathToFileURL(await entryFile(dir)).href));
|
|
121
|
+
importedHashes.set(await canonicalPath(dir), hash);
|
|
122
|
+
const made = typeof loaded.default === "function" ? await loaded.default() : loaded.default;
|
|
123
|
+
const extension = made;
|
|
124
|
+
checkShape(extension, dir);
|
|
125
|
+
return extension;
|
|
126
|
+
}
|
|
127
|
+
/** Why a project's extensions are not loaded, or `undefined` when they may be. */
|
|
128
|
+
async function skipReason(root, base, options) {
|
|
129
|
+
if (options.headless && options.loadInHeadless !== true) {
|
|
130
|
+
return `the project extensions of ${base} are skipped: this run is headless`;
|
|
131
|
+
}
|
|
132
|
+
if (!(await projectTrusted(options.trust, root)))
|
|
133
|
+
return `the project extensions of ${base} are skipped: the project is not trusted`;
|
|
134
|
+
return undefined;
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Loads the extensions in a project, or skips them with a notice. Every folder is hashed and checked against the lock
|
|
138
|
+
* file before any is imported, so a refusal runs none of the project's code. A folder whose hash differs from the lock
|
|
139
|
+
* file, that the lock file does not list, or that the lock file lists and the project no longer holds is refused with
|
|
140
|
+
* `extension_hash_mismatch`; with no lock file the extensions load and a notice says they are unpinned.
|
|
141
|
+
*
|
|
142
|
+
* The pin covers the files inside each extension folder, and nothing an extension imports from outside it, such as a
|
|
143
|
+
* relative path that leaves the folder or a package from the project's `node_modules`. The lock file sits inside the
|
|
144
|
+
* project it pins, so anyone who can edit the project can pin their own changes: the pin catches a change nobody
|
|
145
|
+
* meant, not an attacker who holds the project.
|
|
146
|
+
*/
|
|
147
|
+
export async function loadProjectExtensions(root, options) {
|
|
148
|
+
const base = await canonicalPath(root);
|
|
149
|
+
const result = { extensions: [], records: [], notices: [] };
|
|
150
|
+
const { dir, lock } = await places(base, options);
|
|
151
|
+
// Nothing of a project is read, other than whether it has extensions at all, until trust and headless are decided.
|
|
152
|
+
if (!(await exists(dir)) && !(await exists(lock)))
|
|
153
|
+
return result;
|
|
154
|
+
const reason = await skipReason(root, base, options);
|
|
155
|
+
if (reason !== undefined) {
|
|
156
|
+
result.notices.push(reason);
|
|
157
|
+
return result;
|
|
158
|
+
}
|
|
159
|
+
const names = await folders(dir);
|
|
160
|
+
const pins = await readLock(lock);
|
|
161
|
+
if (names.length === 0 && (pins === undefined || pins.size === 0))
|
|
162
|
+
return result;
|
|
163
|
+
if (pins === undefined)
|
|
164
|
+
result.notices.push(`the extensions of ${base} are not pinned: there is no ${lock}`);
|
|
165
|
+
const hashes = await checkedHashes(dir, names, pins);
|
|
166
|
+
const seen = new Set();
|
|
167
|
+
for (const name of names) {
|
|
168
|
+
const hash = hashes.get(name);
|
|
169
|
+
const extension = await importExtension(join(dir, name), hash);
|
|
170
|
+
if (seen.has(extension.name))
|
|
171
|
+
throw new HarnessError("invalid_extension", `two project extensions are named "${extension.name}"`);
|
|
172
|
+
seen.add(extension.name);
|
|
173
|
+
result.extensions.push(extension);
|
|
174
|
+
result.records.push({ name: extension.name, tier: "in_process", contentHash: hash });
|
|
175
|
+
}
|
|
176
|
+
return result;
|
|
177
|
+
}
|
|
178
|
+
/** The hash of every folder, after checking each against the pins: none of the project's code has run yet. */
|
|
179
|
+
async function checkedHashes(dir, names, pins) {
|
|
180
|
+
const hashes = new Map();
|
|
181
|
+
for (const name of names) {
|
|
182
|
+
const hash = await hashExtensionDir(join(dir, name));
|
|
183
|
+
hashes.set(name, hash);
|
|
184
|
+
refuseChanged(await canonicalPath(join(dir, name)), hash);
|
|
185
|
+
}
|
|
186
|
+
if (pins === undefined)
|
|
187
|
+
return hashes;
|
|
188
|
+
for (const name of pins.keys()) {
|
|
189
|
+
if (!hashes.has(name)) {
|
|
190
|
+
throw new HarnessError("extension_hash_mismatch", `the extension "${name}" is pinned but the project no longer holds it`);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
for (const [name, hash] of hashes) {
|
|
194
|
+
const pinned = pins.get(name);
|
|
195
|
+
if (pinned === hash)
|
|
196
|
+
continue;
|
|
197
|
+
const why = pinned === undefined ? "the lock file does not list it" : "its files changed since they were pinned";
|
|
198
|
+
throw new HarnessError("extension_hash_mismatch", `the extension "${name}" is refused: ${why}`);
|
|
199
|
+
}
|
|
200
|
+
return hashes;
|
|
201
|
+
}
|
|
202
|
+
/** Writes the lock file for every extension folder as it is now. A person runs it, which is what pins the code. */
|
|
203
|
+
export async function pinProjectExtensions(root, options = {}) {
|
|
204
|
+
const { dir, lock } = await places(await canonicalPath(root), options);
|
|
205
|
+
const pins = new Map();
|
|
206
|
+
for (const name of await folders(dir))
|
|
207
|
+
pins.set(name, await hashExtensionDir(join(dir, name)));
|
|
208
|
+
await writeLock(lock, pins);
|
|
209
|
+
return pins;
|
|
210
|
+
}
|
|
211
|
+
//# sourceMappingURL=load.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"load.js","sourceRoot":"","sources":["../../src/extensions/load.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AACpE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,gBAAgB,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAwBlE,8GAA8G;AAC9G,MAAM,CAAC,KAAK,UAAU,aAAa,CAAC,IAAY;IAC9C,IAAI,CAAC;QACH,OAAO,MAAM,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC;IACvC,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC;IACvB,CAAC;AACH,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,cAAc,CAAC,KAAiB,EAAE,IAAY;IAClE,OAAO,KAAK,CAAC,SAAS,CAAC,MAAM,aAAa,CAAC,IAAI,CAAC,CAAC,CAAC;AACpD,CAAC;AAED,MAAM,MAAM,GAAG,KAAK,EAAE,IAAY,EAAE,OAAwD,EAAE,EAAE,CAAC,CAAC;IAChG,8GAA8G;IAC9G,GAAG,EAAE,MAAM,aAAa,CAAC,OAAO,CAAC,aAAa,IAAI,IAAI,CAAC,IAAI,EAAE,SAAS,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H,CAAC;IACD,KAAK,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,MAAM,EAAE,CAAC;QAClC,MAAM,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAC9B,IAAI,MAAM,KAAK,IAAI;YAAE,SAAS;QAC9B,MAAM,GAAG,GAAG,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,gCAAgC,CAAC,CAAC,CAAC,0CAA0C,CAAC;QACjH,MAAM,IAAI,YAAY,CAAC,yBAAyB,EAAE,kBAAkB,IAAI,iBAAiB,GAAG,EAAE,CAAC,CAAC;IAClG,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,mHAAmH;AACnH,MAAM,CAAC,KAAK,UAAU,oBAAoB,CACxC,IAAY,EACZ,OAAO,GAAoD,EAAE;IAE7D,MAAM,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,MAAM,MAAM,CAAC,MAAM,aAAa,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC,CAAC;IACvE,MAAM,IAAI,GAAG,IAAI,GAAG,EAAkB,CAAC;IACvC,KAAK,MAAM,IAAI,IAAI,MAAM,OAAO,CAAC,GAAG,CAAC;QAAE,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,MAAM,gBAAgB,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC;IAC/F,MAAM,SAAS,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAC5B,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["/**\n * Loading the extensions a project supplies. A project's extensions live in `.agents/extensions/<folder>/`, each with an\n * `index.mjs` or `index.js` whose default export is an `Extension`, or a function returning one. They load only when the\n * project is trusted and the run is not headless, and only when every folder's hash matches the lock file. Trust gates\n * loading, not execution: an extension that loads runs with the harness's own permissions. Node-only.\n */\nimport { access, lstat, readdir, realpath } from \"node:fs/promises\";\nimport { join, resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { HarnessError } from \"../errors.js\";\nimport { hashExtensionDir, readLock, writeLock } from \"./lock.js\";\nimport type { Extension, ExtensionLoadedRecord, TrustStore } from \"./types.js\";\n\n/** What `loadProjectExtensions()` needs to decide. */\nexport interface LoadOptions {\n readonly trust: TrustStore;\n /** True for a run nobody can answer: project extensions are skipped unless `loadInHeadless` is set. */\n readonly headless: boolean;\n /** Lets a headless run load the extensions of a project the trust store already trusts. Default false. */\n readonly loadInHeadless?: boolean;\n /** The lock file. Default `<root>/.agents/extensions.lock.json`. */\n readonly lockFile?: string;\n /** The folder that holds the extensions. Default `<root>/.agents/extensions`. */\n readonly extensionsDir?: string;\n}\n\n/** The extensions a project supplied, what to record about them, and why any were skipped. */\nexport interface ProjectExtensions {\n readonly extensions: Extension[];\n readonly records: ExtensionLoadedRecord[];\n /** One line for each reason the load was skipped or left unpinned, for the caller to show. */\n readonly notices: string[];\n}\n\n/** The path with symlinks resolved, so a symlinked root and its target are one project to the trust store. */\nexport async function canonicalPath(path: string): Promise<string> {\n try {\n return await realpath(resolve(path));\n } catch {\n return resolve(path);\n }\n}\n\n/**\n * Whether the trust store trusts the project at `root`, asked about its real path only. A link that the store trusted\n * can be pointed at another folder later, so the spelling the caller wrote is never what is trusted: the folder it\n * resolves to now is. Every loader asks through this, so the extensions and the skills of a project are trusted alike.\n */\nexport async function projectTrusted(trust: TrustStore, root: string): Promise<boolean> {\n return trust.isTrusted(await canonicalPath(root));\n}\n\nconst places = async (root: string, options: Pick<LoadOptions, \"lockFile\" | \"extensionsDir\">) => ({\n // The folder is canonical, so a relative or symlinked spelling of it is one folder to the import-cache check.\n dir: await canonicalPath(options.extensionsDir ?? join(root, \".agents\", \"extensions\")),\n lock: options.lockFile ?? join(root, \".agents\", \"extensions.lock.json\"),\n});\n\n/** Whether `path` exists, without following a link or reading it. */\nasync function exists(path: string): Promise<boolean> {\n try {\n await lstat(path);\n return true;\n } catch {\n return false;\n }\n}\n\n/** The extension folders under `dir`, by name; none when the folder does not exist. */\nasync function folders(dir: string): Promise<string[]> {\n try {\n const entries = await readdir(dir, { withFileTypes: true });\n // A linked folder is not hashed as the folder it points at, so it cannot be pinned.\n const linked = entries.find((entry) => entry.isSymbolicLink());\n if (linked !== undefined) {\n throw new HarnessError(\n \"invalid_extension\",\n `${join(dir, linked.name)} is a link, which an extension folder may not be`,\n );\n }\n return entries\n .filter((entry) => entry.isDirectory())\n .map((entry) => entry.name)\n .sort();\n } catch (error) {\n const code = (error as { code?: string }).code;\n if (code === \"ENOENT\" || code === \"ENOTDIR\") return [];\n throw error;\n }\n}\n\nasync function entryFile(dir: string): Promise<string> {\n for (const name of [\"index.mjs\", \"index.js\"]) {\n try {\n await access(join(dir, name));\n return join(dir, name);\n } catch {\n // try the next name\n }\n }\n throw new HarnessError(\"invalid_extension\", `the extension folder ${dir} has no index.mjs or index.js`);\n}\n\n// The hash each folder had when this process first imported it. Node caches modules for the life of the process, so a\n// folder that changed since then would run its old code while the log recorded the new hash.\nconst importedHashes = new Map<string, string>();\n\n/** Refuses a folder this process has imported with other files, before any folder of the project is imported. */\nfunction refuseChanged(folder: string, hash: string): void {\n const before = importedHashes.get(folder);\n if (before !== undefined && before !== hash) {\n throw new HarnessError(\n \"extension_hash_mismatch\",\n `the extension in ${folder} changed after this process loaded it; restart the process to load the new files`,\n );\n }\n}\n\nconst isFunction = (value: unknown): boolean => typeof value === \"function\";\n\nconst badShape = (dir: string, why: string) => new HarnessError(\"invalid_extension\", `the extension in ${dir} ${why}`);\n\n/** Throws unless `interceptors` is an object whose hooks are functions, apart from the `onFailure` setting. */\nfunction checkInterceptors(interceptors: unknown, dir: string): void {\n if (interceptors === undefined) return;\n if (typeof interceptors !== \"object\" || interceptors === null) {\n throw badShape(dir, \"has interceptors that are not an object\");\n }\n for (const [name, hook] of Object.entries(interceptors)) {\n if (name !== \"onFailure\" && !isFunction(hook))\n throw badShape(dir, `has an interceptor \"${name}\" that is not a function`);\n }\n}\n\n/** Throws unless `observers` is a list of functions and `tools` a list of `{ name, definition }`. */\nfunction checkLists(observers: unknown, tools: unknown, dir: string): void {\n if (observers !== undefined && !(Array.isArray(observers) && observers.every(isFunction))) {\n throw badShape(dir, \"has observers that are not a list of functions\");\n }\n const wellFormed = (tool: { name?: unknown; definition?: unknown } | null) =>\n typeof tool?.name === \"string\" && typeof tool.definition === \"object\" && tool.definition !== null;\n if (tools !== undefined && !(Array.isArray(tools) && tools.every(wellFormed))) {\n throw badShape(dir, \"has tools that are not a list of { name, definition }\");\n }\n}\n\n/** Throws `invalid_extension` unless the module's export has the shape of an `Extension`. */\nfunction checkShape(extension: Partial<Extension> | undefined, dir: string): asserts extension is Extension {\n if (typeof extension?.name !== \"string\" || typeof extension.version !== \"string\") {\n throw badShape(dir, \"does not export a name and a version\");\n }\n checkInterceptors(extension.interceptors, dir);\n checkLists(extension.observers, extension.tools, dir);\n}\n\nasync function importExtension(dir: string, hash: string): Promise<Extension> {\n const loaded = (await import(/* @vite-ignore */ pathToFileURL(await entryFile(dir)).href)) as { default?: unknown };\n importedHashes.set(await canonicalPath(dir), hash);\n const made = typeof loaded.default === \"function\" ? await (loaded.default as () => unknown)() : loaded.default;\n const extension = made as Partial<Extension> | undefined;\n checkShape(extension, dir);\n return extension;\n}\n\n/** Why a project's extensions are not loaded, or `undefined` when they may be. */\nasync function skipReason(root: string, base: string, options: LoadOptions): Promise<string | undefined> {\n if (options.headless && options.loadInHeadless !== true) {\n return `the project extensions of ${base} are skipped: this run is headless`;\n }\n if (!(await projectTrusted(options.trust, root)))\n return `the project extensions of ${base} are skipped: the project is not trusted`;\n return undefined;\n}\n\n/**\n * Loads the extensions in a project, or skips them with a notice. Every folder is hashed and checked against the lock\n * file before any is imported, so a refusal runs none of the project's code. A folder whose hash differs from the lock\n * file, that the lock file does not list, or that the lock file lists and the project no longer holds is refused with\n * `extension_hash_mismatch`; with no lock file the extensions load and a notice says they are unpinned.\n *\n * The pin covers the files inside each extension folder, and nothing an extension imports from outside it, such as a\n * relative path that leaves the folder or a package from the project's `node_modules`. The lock file sits inside the\n * project it pins, so anyone who can edit the project can pin their own changes: the pin catches a change nobody\n * meant, not an attacker who holds the project.\n */\nexport async function loadProjectExtensions(root: string, options: LoadOptions): Promise<ProjectExtensions> {\n const base = await canonicalPath(root);\n const result: ProjectExtensions = { extensions: [], records: [], notices: [] };\n const { dir, lock } = await places(base, options);\n // Nothing of a project is read, other than whether it has extensions at all, until trust and headless are decided.\n if (!(await exists(dir)) && !(await exists(lock))) return result;\n const reason = await skipReason(root, base, options);\n if (reason !== undefined) {\n result.notices.push(reason);\n return result;\n }\n const names = await folders(dir);\n const pins = await readLock(lock);\n if (names.length === 0 && (pins === undefined || pins.size === 0)) return result;\n if (pins === undefined) result.notices.push(`the extensions of ${base} are not pinned: there is no ${lock}`);\n const hashes = await checkedHashes(dir, names, pins);\n const seen = new Set<string>();\n for (const name of names) {\n const hash = hashes.get(name) as string;\n const extension = await importExtension(join(dir, name), hash);\n if (seen.has(extension.name))\n throw new HarnessError(\"invalid_extension\", `two project extensions are named \"${extension.name}\"`);\n seen.add(extension.name);\n result.extensions.push(extension);\n result.records.push({ name: extension.name, tier: \"in_process\", contentHash: hash });\n }\n return result;\n}\n\n/** The hash of every folder, after checking each against the pins: none of the project's code has run yet. */\nasync function checkedHashes(\n dir: string,\n names: readonly string[],\n pins: ReadonlyMap<string, string> | undefined,\n): Promise<Map<string, string>> {\n const hashes = new Map<string, string>();\n for (const name of names) {\n const hash = await hashExtensionDir(join(dir, name));\n hashes.set(name, hash);\n refuseChanged(await canonicalPath(join(dir, name)), hash);\n }\n if (pins === undefined) return hashes;\n for (const name of pins.keys()) {\n if (!hashes.has(name)) {\n throw new HarnessError(\n \"extension_hash_mismatch\",\n `the extension \"${name}\" is pinned but the project no longer holds it`,\n );\n }\n }\n for (const [name, hash] of hashes) {\n const pinned = pins.get(name);\n if (pinned === hash) continue;\n const why = pinned === undefined ? \"the lock file does not list it\" : \"its files changed since they were pinned\";\n throw new HarnessError(\"extension_hash_mismatch\", `the extension \"${name}\" is refused: ${why}`);\n }\n return hashes;\n}\n\n/** Writes the lock file for every extension folder as it is now. A person runs it, which is what pins the code. */\nexport async function pinProjectExtensions(\n root: string,\n options: Pick<LoadOptions, \"lockFile\" | \"extensionsDir\"> = {},\n): Promise<ReadonlyMap<string, string>> {\n const { dir, lock } = await places(await canonicalPath(root), options);\n const pins = new Map<string, string>();\n for (const name of await folders(dir)) pins.set(name, await hashExtensionDir(join(dir, name)));\n await writeLock(lock, pins);\n return pins;\n}\n"]}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** The hash of an extension folder: `sha256:` and the digest over each file's path and content digest, in sorted order. */
|
|
2
|
+
export declare function hashExtensionDir(dir: string): Promise<string>;
|
|
3
|
+
/** Parses JSON that must be an object, or throws `invalid_extension` naming the file. */
|
|
4
|
+
export declare function parseObject(text: string, file: string): Record<string, unknown>;
|
|
5
|
+
/** The pins in a lock file, by extension folder name, or `undefined` when there is no lock file. */
|
|
6
|
+
export declare function readLock(file: string): Promise<ReadonlyMap<string, string> | undefined>;
|
|
7
|
+
/** Writes the lock file for these pins, replacing the old one in one step. */
|
|
8
|
+
export declare function writeLock(file: string, pins: ReadonlyMap<string, string>): Promise<void>;
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Content-hash pins for project extensions. An extension is a folder; its hash covers every file in it, in sorted
|
|
3
|
+
* order, each by its path and its own SHA-256, so a changed, added, removed or renamed file changes the hash. The lock
|
|
4
|
+
* file, `extensions.lock.json`, holds one hash per extension folder. Node-only: it reads and writes files.
|
|
5
|
+
*/
|
|
6
|
+
import { createHash } from "node:crypto";
|
|
7
|
+
import { mkdir, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
8
|
+
import { dirname, join } from "node:path";
|
|
9
|
+
import { HarnessError } from "../errors.js";
|
|
10
|
+
const LOCK_VERSION = 1;
|
|
11
|
+
/** Every file under `dir`, as paths relative to it with `/` separators, in sorted order. */
|
|
12
|
+
async function filesUnder(dir, prefix = "") {
|
|
13
|
+
const entries = await readdir(join(dir, prefix), { withFileTypes: true });
|
|
14
|
+
const found = [];
|
|
15
|
+
for (const entry of entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))) {
|
|
16
|
+
const relative = prefix === "" ? entry.name : `${prefix}/${entry.name}`;
|
|
17
|
+
if (entry.isDirectory())
|
|
18
|
+
found.push(...(await filesUnder(dir, relative)));
|
|
19
|
+
else if (entry.isFile())
|
|
20
|
+
found.push(relative);
|
|
21
|
+
// A link or a device file is not hashed but would still be followed by an import, so it cannot be pinned.
|
|
22
|
+
else
|
|
23
|
+
throw new HarnessError("invalid_extension", `${join(dir, relative)} is a link or a special file, which an extension may not contain`);
|
|
24
|
+
}
|
|
25
|
+
return found;
|
|
26
|
+
}
|
|
27
|
+
/** The hash of an extension folder: `sha256:` and the digest over each file's path and content digest, in sorted order. */
|
|
28
|
+
export async function hashExtensionDir(dir) {
|
|
29
|
+
const total = createHash("sha256");
|
|
30
|
+
for (const file of await filesUnder(dir)) {
|
|
31
|
+
const content = createHash("sha256")
|
|
32
|
+
.update(await readFile(join(dir, file)))
|
|
33
|
+
.digest("hex");
|
|
34
|
+
total.update(`${file}\0${content}\n`);
|
|
35
|
+
}
|
|
36
|
+
return `sha256:${total.digest("hex")}`;
|
|
37
|
+
}
|
|
38
|
+
/** Parses JSON that must be an object, or throws `invalid_extension` naming the file. */
|
|
39
|
+
export function parseObject(text, file) {
|
|
40
|
+
let parsed;
|
|
41
|
+
try {
|
|
42
|
+
parsed = JSON.parse(text);
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
throw new HarnessError("invalid_extension", `${file} is not valid JSON`);
|
|
46
|
+
}
|
|
47
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
48
|
+
throw new HarnessError("invalid_extension", `${file} is not a JSON object`);
|
|
49
|
+
}
|
|
50
|
+
return parsed;
|
|
51
|
+
}
|
|
52
|
+
/** The pins in a lock file, by extension folder name, or `undefined` when there is no lock file. */
|
|
53
|
+
export async function readLock(file) {
|
|
54
|
+
let text;
|
|
55
|
+
try {
|
|
56
|
+
// A pipe or a device would hang or never end, so only a regular file is read.
|
|
57
|
+
if (!(await stat(file)).isFile())
|
|
58
|
+
throw new HarnessError("invalid_extension", `${file} is not a regular file`);
|
|
59
|
+
text = await readFile(file, "utf8");
|
|
60
|
+
}
|
|
61
|
+
catch (error) {
|
|
62
|
+
if (error.code === "ENOENT")
|
|
63
|
+
return undefined;
|
|
64
|
+
throw error;
|
|
65
|
+
}
|
|
66
|
+
const parsed = parseObject(text, file);
|
|
67
|
+
if (parsed.version !== LOCK_VERSION || typeof parsed.extensions !== "object" || parsed.extensions === null) {
|
|
68
|
+
throw new HarnessError("invalid_extension", `the lock file ${file} is not an extensions.lock.json of version 1`);
|
|
69
|
+
}
|
|
70
|
+
const pins = new Map();
|
|
71
|
+
for (const [name, hash] of Object.entries(parsed.extensions)) {
|
|
72
|
+
if (typeof hash !== "string")
|
|
73
|
+
throw new HarnessError("invalid_extension", `the lock file pins "${name}" to no hash`);
|
|
74
|
+
pins.set(name, hash);
|
|
75
|
+
}
|
|
76
|
+
return pins;
|
|
77
|
+
}
|
|
78
|
+
/** Writes the lock file for these pins, replacing the old one in one step. */
|
|
79
|
+
export async function writeLock(file, pins) {
|
|
80
|
+
const body = {
|
|
81
|
+
version: LOCK_VERSION,
|
|
82
|
+
extensions: Object.fromEntries([...pins].sort(([a], [b]) => (a < b ? -1 : 1))),
|
|
83
|
+
};
|
|
84
|
+
await mkdir(dirname(file), { recursive: true });
|
|
85
|
+
const temp = `${file}.${globalThis.crypto.randomUUID()}.tmp`;
|
|
86
|
+
try {
|
|
87
|
+
await writeFile(temp, `${JSON.stringify(body, null, 2)}\n`);
|
|
88
|
+
await rename(temp, file);
|
|
89
|
+
}
|
|
90
|
+
catch (error) {
|
|
91
|
+
await rm(temp, { force: true });
|
|
92
|
+
throw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AC;QACzF,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IACvB,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED,8EAA8E;AAC9E,MAAM,CAAC,KAAK,UAAU,SAAS,CAAC,IAAY,EAAE,IAAiC;IAC7E,MAAM,IAAI,GAAG;QACX,OAAO,EAAE,YAAY;QACrB,UAAU,EAAE,MAAM,CAAC,WAAW,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;KAC/E,CAAC;IACF,MAAM,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;IAChD,MAAM,IAAI,GAAG,GAAG,IAAI,IAAI,UAAU,CAAC,MAAM,CAAC,UAAU,EAAE,MAAM,CAAC;IAC7D,IAAI,CAAC;QACH,MAAM,SAAS,CAAC,IAAI,EAAE,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC;QAC5D,MAAM,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAC3B,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,EAAE,CAAC,IAAI,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;QAChC,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["/**\n * Content-hash pins for project extensions. An extension is a folder; its hash covers every file in it, in sorted\n * order, each by its path and its own SHA-256, so a changed, added, removed or renamed file changes the hash. The lock\n * file, `extensions.lock.json`, holds one hash per extension folder. Node-only: it reads and writes files.\n */\nimport { createHash } from \"node:crypto\";\nimport { mkdir, readdir, readFile, rename, rm, stat, writeFile } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport { HarnessError } from \"../errors.js\";\n\nconst LOCK_VERSION = 1;\n\n/** Every file under `dir`, as paths relative to it with `/` separators, in sorted order. */\nasync function filesUnder(dir: string, prefix = \"\"): Promise<string[]> {\n const entries = await readdir(join(dir, prefix), { withFileTypes: true });\n const found: string[] = [];\n for (const entry of entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))) {\n const relative = prefix === \"\" ? entry.name : `${prefix}/${entry.name}`;\n if (entry.isDirectory()) found.push(...(await filesUnder(dir, relative)));\n else if (entry.isFile()) found.push(relative);\n // A link or a device file is not hashed but would still be followed by an import, so it cannot be pinned.\n else\n throw new HarnessError(\n \"invalid_extension\",\n `${join(dir, relative)} is a link or a special file, which an extension may not contain`,\n );\n }\n return found;\n}\n\n/** The hash of an extension folder: `sha256:` and the digest over each file's path and content digest, in sorted order. */\nexport async function hashExtensionDir(dir: string): Promise<string> {\n const total = createHash(\"sha256\");\n for (const file of await filesUnder(dir)) {\n const content = createHash(\"sha256\")\n .update(await readFile(join(dir, file)))\n .digest(\"hex\");\n total.update(`${file}\\0${content}\\n`);\n }\n return `sha256:${total.digest(\"hex\")}`;\n}\n\n/** Parses JSON that must be an object, or throws `invalid_extension` naming the file. */\nexport function parseObject(text: string, file: string): Record<string, unknown> {\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n throw new HarnessError(\"invalid_extension\", `${file} is not valid JSON`);\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new HarnessError(\"invalid_extension\", `${file} is not a JSON object`);\n }\n return parsed as Record<string, unknown>;\n}\n\n/** The pins in a lock file, by extension folder name, or `undefined` when there is no lock file. */\nexport async function readLock(file: string): Promise<ReadonlyMap<string, string> | undefined> {\n let text: string;\n try {\n // A pipe or a device would hang or never end, so only a regular file is read.\n if (!(await stat(file)).isFile()) throw new HarnessError(\"invalid_extension\", `${file} is not a regular file`);\n text = await readFile(file, \"utf8\");\n } catch (error) {\n if ((error as { code?: string }).code === \"ENOENT\") return undefined;\n throw error;\n }\n const parsed = parseObject(text, file) as { version?: unknown; extensions?: Record<string, unknown> };\n if (parsed.version !== LOCK_VERSION || typeof parsed.extensions !== \"object\" || parsed.extensions === null) {\n throw new HarnessError(\"invalid_extension\", `the lock file ${file} is not an extensions.lock.json of version 1`);\n }\n const pins = new Map<string, string>();\n for (const [name, hash] of Object.entries(parsed.extensions)) {\n if (typeof hash !== \"string\")\n throw new HarnessError(\"invalid_extension\", `the lock file pins \"${name}\" to no hash`);\n pins.set(name, hash);\n }\n return pins;\n}\n\n/** Writes the lock file for these pins, replacing the old one in one step. */\nexport async function writeLock(file: string, pins: ReadonlyMap<string, string>): Promise<void> {\n const body = {\n version: LOCK_VERSION,\n extensions: Object.fromEntries([...pins].sort(([a], [b]) => (a < b ? -1 : 1))),\n };\n await mkdir(dirname(file), { recursive: true });\n const temp = `${file}.${globalThis.crypto.randomUUID()}.tmp`;\n try {\n await writeFile(temp, `${JSON.stringify(body, null, 2)}\\n`);\n await rename(temp, file);\n } catch (error) {\n await rm(temp, { force: true });\n throw error;\n }\n}\n"]}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@buildanagent/harness/extensions/node`: loading the extensions a project supplies, with the trust file and the lock
|
|
3
|
+
* file. It needs Node's file system; the portable parts are in `@buildanagent/harness/extensions`.
|
|
4
|
+
*/
|
|
5
|
+
export { contextFiles, type FoundContextFiles, planFileSource } from "./context-files-node.js";
|
|
6
|
+
export { type LoadOptions, loadProjectExtensions, type ProjectExtensions, pinProjectExtensions } from "./load.js";
|
|
7
|
+
export { hashExtensionDir, readLock, writeLock } from "./lock.js";
|
|
8
|
+
export { type DiscoveredSkills, type DiscoverSkillsOptions, discoverSkills } from "./skills-node.js";
|
|
9
|
+
export { fileTrustStore } from "./trust-file.js";
|
|
10
|
+
export { realPathTrustStore } from "./trust-store-node.js";
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@buildanagent/harness/extensions/node`: loading the extensions a project supplies, with the trust file and the lock
|
|
3
|
+
* file. It needs Node's file system; the portable parts are in `@buildanagent/harness/extensions`.
|
|
4
|
+
*/
|
|
5
|
+
export { contextFiles, planFileSource } from "./context-files-node.js";
|
|
6
|
+
export { loadProjectExtensions, pinProjectExtensions } from "./load.js";
|
|
7
|
+
export { hashExtensionDir, readLock, writeLock } from "./lock.js";
|
|
8
|
+
export { discoverSkills } from "./skills-node.js";
|
|
9
|
+
export { fileTrustStore } from "./trust-file.js";
|
|
10
|
+
export { realPathTrustStore } from "./trust-store-node.js";
|
|
11
|
+
//# sourceMappingURL=node.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"node.js","sourceRoot":"","sources":["../../src/extensions/node.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,YAAY,EAA0B,cAAc,EAAE,MAAM,yBAAyB,CAAC;AAC/F,OAAO,EAAoB,qBAAqB,EAA0B,oBAAoB,EAAE,MAAM,WAAW,CAAC;AAClH,OAAO,EAAE,gBAAgB,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAClE,OAAO,EAAqD,cAAc,EAAE,MAAM,kBAAkB,CAAC;AACrG,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC","sourcesContent":["/**\n * `@buildanagent/harness/extensions/node`: loading the extensions a project supplies, with the trust file and the lock\n * file. It needs Node's file system; the portable parts are in `@buildanagent/harness/extensions`.\n */\n\nexport { contextFiles, type FoundContextFiles, planFileSource } from \"./context-files-node.js\";\nexport { type LoadOptions, loadProjectExtensions, type ProjectExtensions, pinProjectExtensions } from \"./load.js\";\nexport { hashExtensionDir, readLock, writeLock } from \"./lock.js\";\nexport { type DiscoveredSkills, type DiscoverSkillsOptions, discoverSkills } from \"./skills-node.js\";\nexport { fileTrustStore } from \"./trust-file.js\";\nexport { realPathTrustStore } from \"./trust-store-node.js\";\n"]}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The folders from `cwd` up to the repository root, nearest first. The root is the first folder that holds a `.git`
|
|
3
|
+
* file or folder. A `cwd` inside no repository gives only itself, so a stray file in a parent such as `/tmp` or a home
|
|
4
|
+
* folder is never read as the project's.
|
|
5
|
+
*/
|
|
6
|
+
export declare function projectDirs(cwd: string): Promise<string[]>;
|
|
7
|
+
/** Whether `path` is `root` or inside it, once both are real paths. */
|
|
8
|
+
export declare function isInside(root: string, path: string): boolean;
|
|
9
|
+
/**
|
|
10
|
+
* The text of a project file and its real path, or why it was not read. A file whose real path leaves `root` is
|
|
11
|
+
* refused: a link in a cloned repository must not pull a file such as `~/.ssh/id_rsa` into a prompt. The refusal's
|
|
12
|
+
* notice percent-encodes the paths it names wherever they hold a quote, `<`, `>`, `&`, `%` or a control character. A
|
|
13
|
+
* missing file, a folder or anything else that is not a regular file is not an error and gives `undefined`. At most `maxBytes` and one
|
|
14
|
+
* more are read, however long the file is: a longer file is cut at the start of the character that crosses `maxBytes`,
|
|
15
|
+
* so `text` never ends in half a character, and `bytes` holds exactly the bytes `text` was decoded from.
|
|
16
|
+
*/
|
|
17
|
+
export declare function readProjectFile(root: string, path: string, maxBytes: number): Promise<{
|
|
18
|
+
text: string;
|
|
19
|
+
bytes: Uint8Array;
|
|
20
|
+
real: string;
|
|
21
|
+
truncated: boolean;
|
|
22
|
+
} | {
|
|
23
|
+
notice: string;
|
|
24
|
+
} | undefined>;
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/** Where a project's own files are looked for: the folders from the working directory up to the repository root. Node-only. */
|
|
2
|
+
import { lstat, open, realpath, stat } from "node:fs/promises";
|
|
3
|
+
import { dirname, join, resolve, sep } from "node:path";
|
|
4
|
+
import { attribute } from "./context-files.js";
|
|
5
|
+
/** Whether `path` exists, without following a link. */
|
|
6
|
+
async function exists(path) {
|
|
7
|
+
try {
|
|
8
|
+
await lstat(path);
|
|
9
|
+
return true;
|
|
10
|
+
}
|
|
11
|
+
catch {
|
|
12
|
+
return false;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* The folders from `cwd` up to the repository root, nearest first. The root is the first folder that holds a `.git`
|
|
17
|
+
* file or folder. A `cwd` inside no repository gives only itself, so a stray file in a parent such as `/tmp` or a home
|
|
18
|
+
* folder is never read as the project's.
|
|
19
|
+
*/
|
|
20
|
+
export async function projectDirs(cwd) {
|
|
21
|
+
const start = resolve(cwd);
|
|
22
|
+
const dirs = [];
|
|
23
|
+
for (let dir = start;; dir = dirname(dir)) {
|
|
24
|
+
dirs.push(dir);
|
|
25
|
+
if (await exists(join(dir, ".git")))
|
|
26
|
+
return dirs;
|
|
27
|
+
if (dirname(dir) === dir)
|
|
28
|
+
return [start];
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/** Whether `path` is `root` or inside it, once both are real paths. */
|
|
32
|
+
export function isInside(root, path) {
|
|
33
|
+
return path === root || path.startsWith(root.endsWith(sep) ? root : `${root}${sep}`);
|
|
34
|
+
}
|
|
35
|
+
/** The most continuation bytes one UTF-8 character has: a cut moves back at most this far. */
|
|
36
|
+
const MAX_CONTINUATION = 3;
|
|
37
|
+
/** `cut` moved back to the start of the UTF-8 character it falls inside, so a cut never splits a character. */
|
|
38
|
+
function characterStart(bytes, cut) {
|
|
39
|
+
let start = cut;
|
|
40
|
+
// A continuation byte is 10xxxxxx: the character it belongs to started before it.
|
|
41
|
+
while (start > 0 && cut - start < MAX_CONTINUATION && (bytes[start] & 0xc0) === 0x80)
|
|
42
|
+
start--;
|
|
43
|
+
return (bytes[start] & 0xc0) === 0x80 ? cut : start;
|
|
44
|
+
}
|
|
45
|
+
/** At most `limit` bytes from the start of the open file. */
|
|
46
|
+
async function readStart(handle, limit) {
|
|
47
|
+
const buffer = new Uint8Array(limit);
|
|
48
|
+
let length = 0;
|
|
49
|
+
while (length < limit) {
|
|
50
|
+
const { bytesRead } = await handle.read(buffer, length, limit - length, length);
|
|
51
|
+
if (bytesRead === 0)
|
|
52
|
+
break;
|
|
53
|
+
length += bytesRead;
|
|
54
|
+
}
|
|
55
|
+
return buffer.subarray(0, length);
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* The text of a project file and its real path, or why it was not read. A file whose real path leaves `root` is
|
|
59
|
+
* refused: a link in a cloned repository must not pull a file such as `~/.ssh/id_rsa` into a prompt. The refusal's
|
|
60
|
+
* notice percent-encodes the paths it names wherever they hold a quote, `<`, `>`, `&`, `%` or a control character. A
|
|
61
|
+
* missing file, a folder or anything else that is not a regular file is not an error and gives `undefined`. At most `maxBytes` and one
|
|
62
|
+
* more are read, however long the file is: a longer file is cut at the start of the character that crosses `maxBytes`,
|
|
63
|
+
* so `text` never ends in half a character, and `bytes` holds exactly the bytes `text` was decoded from.
|
|
64
|
+
*/
|
|
65
|
+
export async function readProjectFile(root, path, maxBytes) {
|
|
66
|
+
let real;
|
|
67
|
+
try {
|
|
68
|
+
real = await realpath(path);
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
return undefined;
|
|
72
|
+
}
|
|
73
|
+
if (!isInside(await realpath(root), real)) {
|
|
74
|
+
// The notice can reach the model's text, so the names in it, which the project chose, are kept to one line.
|
|
75
|
+
return { notice: `${attribute(path)} is skipped: it is a link to ${attribute(real)}, outside ${attribute(root)}` };
|
|
76
|
+
}
|
|
77
|
+
try {
|
|
78
|
+
// Opening a pipe would wait for a writer, so only a regular file is opened.
|
|
79
|
+
if (!(await stat(real)).isFile())
|
|
80
|
+
return undefined;
|
|
81
|
+
const handle = await open(real, "r");
|
|
82
|
+
try {
|
|
83
|
+
const start = await readStart(handle, maxBytes + 1);
|
|
84
|
+
const truncated = start.length > maxBytes;
|
|
85
|
+
const bytes = truncated ? start.subarray(0, characterStart(start, maxBytes)) : start;
|
|
86
|
+
return { text: new TextDecoder().decode(bytes), bytes, real, truncated };
|
|
87
|
+
}
|
|
88
|
+
finally {
|
|
89
|
+
await handle.close();
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
// A file that cannot be read is not a project file.
|
|
94
|
+
return undefined;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
//# sourceMappingURL=project-dirs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"project-dirs.js","sourceRoot":"","sources":["../../src/extensions/project-dirs.ts"],"names":[],"mappings":"AAAA,+HAA+H;AAC/H,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAC/D,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AACxD,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAE/C,uDAAuD;AACvD,KAAK,UAAU,MAAM,CAAC,IAAY;IAChC,IAAI,CAAC;QACH,MAAM,KAAK,CAAC,IAAI,CAAC,CAAC;QAClB,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAAC,GAAW;IAC3C,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC;IAC3B,MAAM,IAAI,GAAa,EAAE,CAAC;IAC1B,KAAK,IAAI,GAAG,GAAG,KAAK,GAAI,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;QAC3C,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QACf,IAAI,MAAM,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;YAAE,OAAO,IAAI,CAAC;QACjD,IAA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E,SAAS,EAAE,CAAC;QAC3E,CAAC;gBAAS,CAAC;YACT,MAAM,MAAM,CAAC,KAAK,EAAE,CAAC;QACvB,CAAC;IACH,CAAC;IAAC,MAAM,CAAC;QACP,oDAAoD;QACpD,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC","sourcesContent":["/** Where a project's own files are looked for: the folders from the working directory up to the repository root. Node-only. */\nimport { lstat, open, realpath, stat } from \"node:fs/promises\";\nimport { dirname, join, resolve, sep } from \"node:path\";\nimport { attribute } from \"./context-files.js\";\n\n/** Whether `path` exists, without following a link. */\nasync function exists(path: string): Promise<boolean> {\n try {\n await lstat(path);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * The folders from `cwd` up to the repository root, nearest first. The root is the first folder that holds a `.git`\n * file or folder. A `cwd` inside no repository gives only itself, so a stray file in a parent such as `/tmp` or a home\n * folder is never read as the project's.\n */\nexport async function projectDirs(cwd: string): Promise<string[]> {\n const start = resolve(cwd);\n const dirs: string[] = [];\n for (let dir = start; ; dir = dirname(dir)) {\n dirs.push(dir);\n if (await exists(join(dir, \".git\"))) return dirs;\n if (dirname(dir) === dir) return [start];\n }\n}\n\n/** Whether `path` is `root` or inside it, once both are real paths. */\nexport function isInside(root: string, path: string): boolean {\n return path === root || path.startsWith(root.endsWith(sep) ? root : `${root}${sep}`);\n}\n\n/** The most continuation bytes one UTF-8 character has: a cut moves back at most this far. */\nconst MAX_CONTINUATION = 3;\n\n/** `cut` moved back to the start of the UTF-8 character it falls inside, so a cut never splits a character. */\nfunction characterStart(bytes: Uint8Array, cut: number): number {\n let start = cut;\n // A continuation byte is 10xxxxxx: the character it belongs to started before it.\n while (start > 0 && cut - start < MAX_CONTINUATION && ((bytes[start] as number) & 0xc0) === 0x80) start--;\n return ((bytes[start] as number) & 0xc0) === 0x80 ? cut : start;\n}\n\n/** At most `limit` bytes from the start of the open file. */\nasync function readStart(handle: import(\"node:fs/promises\").FileHandle, limit: number): Promise<Uint8Array> {\n const buffer = new Uint8Array(limit);\n let length = 0;\n while (length < limit) {\n const { bytesRead } = await handle.read(buffer, length, limit - length, length);\n if (bytesRead === 0) break;\n length += bytesRead;\n }\n return buffer.subarray(0, length);\n}\n\n/**\n * The text of a project file and its real path, or why it was not read. A file whose real path leaves `root` is\n * refused: a link in a cloned repository must not pull a file such as `~/.ssh/id_rsa` into a prompt. The refusal's\n * notice percent-encodes the paths it names wherever they hold a quote, `<`, `>`, `&`, `%` or a control character. A\n * missing file, a folder or anything else that is not a regular file is not an error and gives `undefined`. At most `maxBytes` and one\n * more are read, however long the file is: a longer file is cut at the start of the character that crosses `maxBytes`,\n * so `text` never ends in half a character, and `bytes` holds exactly the bytes `text` was decoded from.\n */\nexport async function readProjectFile(\n root: string,\n path: string,\n maxBytes: number,\n): Promise<{ text: string; bytes: Uint8Array; real: string; truncated: boolean } | { notice: string } | undefined> {\n let real: string;\n try {\n real = await realpath(path);\n } catch {\n return undefined;\n }\n if (!isInside(await realpath(root), real)) {\n // The notice can reach the model's text, so the names in it, which the project chose, are kept to one line.\n return { notice: `${attribute(path)} is skipped: it is a link to ${attribute(real)}, outside ${attribute(root)}` };\n }\n try {\n // Opening a pipe would wait for a writer, so only a regular file is opened.\n if (!(await stat(real)).isFile()) return undefined;\n const handle = await open(real, \"r\");\n try {\n const start = await readStart(handle, maxBytes + 1);\n const truncated = start.length > maxBytes;\n const bytes = truncated ? start.subarray(0, characterStart(start, maxBytes)) : start;\n return { text: new TextDecoder().decode(bytes), bytes, real, truncated };\n } finally {\n await handle.close();\n }\n } catch {\n // A file that cannot be read is not a project file.\n return undefined;\n }\n}\n"]}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { type Skill } from "./skills.js";
|
|
2
|
+
import type { ExtensionLoadedRecord, TrustStore } from "./types.js";
|
|
3
|
+
/** The settings of `discoverSkills()`. */
|
|
4
|
+
export interface DiscoverSkillsOptions {
|
|
5
|
+
/**
|
|
6
|
+
* The project-trust gate, required as it is for extensions: a project's skills are listed only when the store trusts
|
|
7
|
+
* the project and the run is not headless. A skill's name and description go into the system prompt, so an untrusted
|
|
8
|
+
* checkout must not reach it. A host that trusts every project it opens says so with a store that trusts them.
|
|
9
|
+
*/
|
|
10
|
+
readonly trust: TrustStore;
|
|
11
|
+
/** True for a run nobody can answer: project skills are skipped unless `loadInHeadless` is set. Default false. */
|
|
12
|
+
readonly headless?: boolean;
|
|
13
|
+
/** Lets a headless run list a trusted project's skills. Default false. */
|
|
14
|
+
readonly loadInHeadless?: boolean;
|
|
15
|
+
}
|
|
16
|
+
/** The skills found, what to record about them, and why any were left out. */
|
|
17
|
+
export interface DiscoveredSkills {
|
|
18
|
+
/** Nearest folder first, then by path. A name found twice keeps the nearer one. */
|
|
19
|
+
readonly skills: Skill[];
|
|
20
|
+
/** `extension_loaded` records with tier `skill`, for `HarnessOptions.extensionRecords`. */
|
|
21
|
+
readonly records: ExtensionLoadedRecord[];
|
|
22
|
+
/** One line for each file or folder skipped and each skill that shares a name. */
|
|
23
|
+
readonly notices: string[];
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Finds the skills of the project `cwd` is in: each folder under `.agents/skills` holding a `SKILL.md`, in `cwd` and
|
|
27
|
+
* every folder above it up to the repository root (the first folder with a `.git`). A `cwd` in no repository searches
|
|
28
|
+
* only itself. A file that is not a skill, a `SKILL.md` that is a link leaving the project, a name already taken by
|
|
29
|
+
* a nearer skill, and a folder whose name holds a control character, or a `\` on POSIX, are skipped with a notice, and
|
|
30
|
+
* the rest still load. The skills' paths are absolute. No skill file is read
|
|
31
|
+
* until the trust store and `headless` allow it: an untrusted project, or a headless run without `loadInHeadless`,
|
|
32
|
+
* lists no skills and returns one notice saying why.
|
|
33
|
+
*/
|
|
34
|
+
export declare function discoverSkills(cwd: string, options: DiscoverSkillsOptions): Promise<DiscoveredSkills>;
|