@mcoda/mswarm 0.1.135-codali.18 → 0.1.135-codali.29
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/README.md +5 -0
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +5 -2
- package/dist/runtime.js.map +1 -1
- package/dist/vendor/codali/cli/TerminalCommand.d.ts.map +1 -1
- package/dist/vendor/codali/cli/TerminalCommand.js +53 -20
- package/dist/vendor/codali/cli/TerminalInput.d.ts +6 -0
- package/dist/vendor/codali/cli/TerminalInput.d.ts.map +1 -1
- package/dist/vendor/codali/cli/TerminalInput.js +3 -1
- package/dist/vendor/codali/cli/ToolsCommand.d.ts.map +1 -1
- package/dist/vendor/codali/cli/ToolsCommand.js +8 -1
- package/dist/vendor/codali/cli/tui/TerminalLogo.d.ts +6 -0
- package/dist/vendor/codali/cli/tui/TerminalLogo.d.ts.map +1 -0
- package/dist/vendor/codali/cli/tui/TerminalLogo.js +26 -0
- package/dist/vendor/codali/cli/tui/TerminalMarkdown.d.ts +5 -0
- package/dist/vendor/codali/cli/tui/TerminalMarkdown.d.ts.map +1 -0
- package/dist/vendor/codali/cli/tui/TerminalMarkdown.js +118 -0
- package/dist/vendor/codali/cli/tui/TerminalPresentation.d.ts.map +1 -1
- package/dist/vendor/codali/cli/tui/TerminalPresentation.js +12 -3
- package/dist/vendor/codali/cli/tui/TerminalScreen.d.ts +1 -0
- package/dist/vendor/codali/cli/tui/TerminalScreen.d.ts.map +1 -1
- package/dist/vendor/codali/cli/tui/TerminalScreen.js +13 -6
- package/dist/vendor/codali/cli/tui/TerminalSelection.d.ts +15 -0
- package/dist/vendor/codali/cli/tui/TerminalSelection.d.ts.map +1 -0
- package/dist/vendor/codali/cli/tui/TerminalSelection.js +38 -0
- package/dist/vendor/codali/cli/tui/TerminalTui.d.ts +4 -0
- package/dist/vendor/codali/cli/tui/TerminalTui.d.ts.map +1 -1
- package/dist/vendor/codali/cli/tui/TerminalTui.js +96 -12
- package/dist/vendor/codali/cli.js +1 -1
- package/dist/vendor/codali/config/OrchestrationConfig.d.ts +18 -0
- package/dist/vendor/codali/config/OrchestrationConfig.d.ts.map +1 -1
- package/dist/vendor/codali/config/OrchestrationConfig.js +42 -2
- package/dist/vendor/codali/docdex/DocdexCatalog.d.ts +12 -0
- package/dist/vendor/codali/docdex/DocdexCatalog.d.ts.map +1 -0
- package/dist/vendor/codali/docdex/DocdexCatalog.js +30 -0
- package/dist/vendor/codali/docdex/DocdexClient.d.ts +8 -2
- package/dist/vendor/codali/docdex/DocdexClient.d.ts.map +1 -1
- package/dist/vendor/codali/docdex/DocdexClient.js +86 -11
- package/dist/vendor/codali/docdex/ManagedDocdex.d.ts +1 -0
- package/dist/vendor/codali/docdex/ManagedDocdex.d.ts.map +1 -1
- package/dist/vendor/codali/docdex/ManagedDocdex.js +25 -4
- package/dist/vendor/codali/eval/TrustBenchmark.d.ts +94 -0
- package/dist/vendor/codali/eval/TrustBenchmark.d.ts.map +1 -0
- package/dist/vendor/codali/eval/TrustBenchmark.js +199 -0
- package/dist/vendor/codali/eval/fixtures/TerminalRecoveryJourney.d.ts.map +1 -1
- package/dist/vendor/codali/eval/fixtures/TerminalRecoveryJourney.js +10 -1
- package/dist/vendor/codali/permissions/PermissionGate.d.ts +1 -1
- package/dist/vendor/codali/permissions/PermissionGate.d.ts.map +1 -1
- package/dist/vendor/codali/permissions/PermissionGate.js +40 -2
- package/dist/vendor/codali/permissions/WorkspacePermissions.d.ts +11 -0
- package/dist/vendor/codali/permissions/WorkspacePermissions.d.ts.map +1 -0
- package/dist/vendor/codali/permissions/WorkspacePermissions.js +42 -0
- package/dist/vendor/codali/providers/ModelServiceError.js +1 -1
- package/dist/vendor/codali/providers/OpenAiCompatibleProvider.d.ts.map +1 -1
- package/dist/vendor/codali/providers/OpenAiCompatibleProvider.js +3 -1
- package/dist/vendor/codali/runtime/ComputedAnswer.d.ts +13 -0
- package/dist/vendor/codali/runtime/ComputedAnswer.d.ts.map +1 -0
- package/dist/vendor/codali/runtime/ComputedAnswer.js +75 -0
- package/dist/vendor/codali/runtime/ContextCompression.d.ts +22 -0
- package/dist/vendor/codali/runtime/ContextCompression.d.ts.map +1 -0
- package/dist/vendor/codali/runtime/ContextCompression.js +53 -0
- package/dist/vendor/codali/runtime/InspectionBudget.d.ts +8 -0
- package/dist/vendor/codali/runtime/InspectionBudget.d.ts.map +1 -0
- package/dist/vendor/codali/runtime/InspectionBudget.js +25 -0
- package/dist/vendor/codali/runtime/InteractionContract.d.ts +42 -0
- package/dist/vendor/codali/runtime/InteractionContract.d.ts.map +1 -0
- package/dist/vendor/codali/runtime/InteractionContract.js +50 -0
- package/dist/vendor/codali/runtime/InteractionRouter.d.ts +46 -5
- package/dist/vendor/codali/runtime/InteractionRouter.d.ts.map +1 -1
- package/dist/vendor/codali/runtime/InteractionRouter.js +108 -27
- package/dist/vendor/codali/runtime/PreparedDocdex.d.ts +4 -0
- package/dist/vendor/codali/runtime/PreparedDocdex.d.ts.map +1 -0
- package/dist/vendor/codali/runtime/PreparedDocdex.js +55 -0
- package/dist/vendor/codali/runtime/SessionController.d.ts +22 -0
- package/dist/vendor/codali/runtime/SessionController.d.ts.map +1 -1
- package/dist/vendor/codali/runtime/SessionController.js +721 -61
- package/dist/vendor/codali/session/InstructionLoader.d.ts +5 -1
- package/dist/vendor/codali/session/InstructionLoader.d.ts.map +1 -1
- package/dist/vendor/codali/session/InstructionLoader.js +65 -19
- package/dist/vendor/codali/session/SkillCatalog.d.ts +33 -0
- package/dist/vendor/codali/session/SkillCatalog.d.ts.map +1 -0
- package/dist/vendor/codali/session/SkillCatalog.js +194 -0
- package/dist/vendor/codali/tools/SemanticToolRetrieval.d.ts +19 -0
- package/dist/vendor/codali/tools/SemanticToolRetrieval.d.ts.map +1 -0
- package/dist/vendor/codali/tools/SemanticToolRetrieval.js +52 -0
- package/dist/vendor/codali/tools/ToolRetrieval.d.ts +7 -0
- package/dist/vendor/codali/tools/ToolRetrieval.d.ts.map +1 -0
- package/dist/vendor/codali/tools/ToolRetrieval.js +25 -0
- package/dist/vendor/codali/tools/browser/BrowserTool.d.ts +9 -0
- package/dist/vendor/codali/tools/browser/BrowserTool.d.ts.map +1 -0
- package/dist/vendor/codali/tools/browser/BrowserTool.js +152 -0
- package/dist/vendor/codali/tools/browser/BrowserWorker.d.ts +2 -0
- package/dist/vendor/codali/tools/browser/BrowserWorker.d.ts.map +1 -0
- package/dist/vendor/codali/tools/browser/BrowserWorker.js +51 -0
- package/dist/vendor/codali/tools/calculation/CalculatorTool.d.ts +5 -0
- package/dist/vendor/codali/tools/calculation/CalculatorTool.d.ts.map +1 -0
- package/dist/vendor/codali/tools/calculation/CalculatorTool.js +137 -0
- package/dist/vendor/codali/tools/deterministic/DeterministicRuntime.d.ts +39 -0
- package/dist/vendor/codali/tools/deterministic/DeterministicRuntime.d.ts.map +1 -0
- package/dist/vendor/codali/tools/deterministic/DeterministicRuntime.js +98 -0
- package/dist/vendor/codali/tools/deterministic/DeterministicTools.d.ts +8 -0
- package/dist/vendor/codali/tools/deterministic/DeterministicTools.d.ts.map +1 -0
- package/dist/vendor/codali/tools/deterministic/DeterministicTools.js +86 -0
- package/dist/vendor/codali/tools/deterministic/node-worker.cjs +38 -0
- package/dist/vendor/codali/tools/deterministic/python-worker.py +222 -0
- package/dist/vendor/codali/tools/docdex/DocdexCatalogTools.d.ts +4 -0
- package/dist/vendor/codali/tools/docdex/DocdexCatalogTools.d.ts.map +1 -0
- package/dist/vendor/codali/tools/docdex/DocdexCatalogTools.js +58 -0
- package/dist/vendor/codali/tools/docdex/DocdexTools.d.ts +2 -0
- package/dist/vendor/codali/tools/docdex/DocdexTools.d.ts.map +1 -1
- package/dist/vendor/codali/tools/docdex/DocdexTools.js +72 -105
- package/dist/vendor/codali/tools/documents/DocumentRuntime.d.ts +12 -0
- package/dist/vendor/codali/tools/documents/DocumentRuntime.d.ts.map +1 -0
- package/dist/vendor/codali/tools/documents/DocumentRuntime.js +59 -0
- package/dist/vendor/codali/tools/documents/DocumentTools.d.ts +19 -0
- package/dist/vendor/codali/tools/documents/DocumentTools.d.ts.map +1 -0
- package/dist/vendor/codali/tools/documents/DocumentTools.js +150 -0
- package/dist/vendor/codali/tools/documents/worker.py +267 -0
- package/dist/vendor/codali/tools/entities/AdesTool.d.ts +7 -0
- package/dist/vendor/codali/tools/entities/AdesTool.d.ts.map +1 -0
- package/dist/vendor/codali/tools/entities/AdesTool.js +59 -0
- package/dist/vendor/codali/tools/research/TnlTool.d.ts +22 -0
- package/dist/vendor/codali/tools/research/TnlTool.d.ts.map +1 -0
- package/dist/vendor/codali/tools/research/TnlTool.js +246 -0
- package/dist/vendor/codali/tools/shell/HostToolchain.d.ts.map +1 -1
- package/dist/vendor/codali/tools/shell/HostToolchain.js +14 -2
- package/dist/vendor/codali/tools/shell/IsolatedExecutor.d.ts +3 -2
- package/dist/vendor/codali/tools/shell/IsolatedExecutor.d.ts.map +1 -1
- package/dist/vendor/codali/tools/shell/IsolatedExecutor.js +34 -4
- package/dist/vendor/codali/tools/system/TimeTool.d.ts +4 -0
- package/dist/vendor/codali/tools/system/TimeTool.d.ts.map +1 -0
- package/dist/vendor/codali/tools/system/TimeTool.js +22 -0
- package/dist/vendor/codali/tools/verification/JavaScriptVerificationTool.d.ts +47 -0
- package/dist/vendor/codali/tools/verification/JavaScriptVerificationTool.d.ts.map +1 -0
- package/dist/vendor/codali/tools/verification/JavaScriptVerificationTool.js +71 -0
- package/dist/vendor/codali/tools/verification/JavaScriptVerificationWorker.d.ts +2 -0
- package/dist/vendor/codali/tools/verification/JavaScriptVerificationWorker.d.ts.map +1 -0
- package/dist/vendor/codali/tools/verification/JavaScriptVerificationWorker.js +91 -0
- package/dist/vendor/codali/tools/verification/VitestTool.d.ts +3 -0
- package/dist/vendor/codali/tools/verification/VitestTool.d.ts.map +1 -0
- package/dist/vendor/codali/tools/verification/VitestTool.js +128 -0
- package/dist/vendor/config/AGENTS.md +11 -0
- package/dist/vendor/config/deterministic/install-python.mjs +16 -0
- package/dist/vendor/config/deterministic/node-worker.mjs +77 -0
- package/dist/vendor/config/deterministic/python-worker.py +222 -0
- package/dist/vendor/config/deterministic/requirements.txt +6 -0
- package/dist/vendor/config/docdex-runtime.json +21 -0
- package/dist/vendor/config/docdex-tools-0.2.99.json +3977 -0
- package/dist/vendor/config/documents/install-python.mjs +16 -0
- package/dist/vendor/config/documents/requirements.txt +10 -0
- package/dist/vendor/config/documents/worker.py +267 -0
- package/dist/vendor/config/skills/planning/SKILL.md +13 -0
- package/package.json +11 -4
|
@@ -3,12 +3,16 @@ export interface InstructionBlock {
|
|
|
3
3
|
scope: string;
|
|
4
4
|
precedence: number;
|
|
5
5
|
content: string;
|
|
6
|
+
sha256?: string;
|
|
6
7
|
}
|
|
7
8
|
export interface InstructionLoadOptions {
|
|
8
9
|
workspaceRoot: string;
|
|
9
10
|
focusPaths?: string[];
|
|
10
11
|
includeLocal?: boolean;
|
|
12
|
+
includeSystem?: boolean;
|
|
13
|
+
/** Host-selected user file; false isolates automated tests from user preferences. */
|
|
14
|
+
userInstructionsPath?: string | false;
|
|
11
15
|
}
|
|
12
16
|
export declare const loadInstructionBlocks: (options: InstructionLoadOptions) => Promise<InstructionBlock[]>;
|
|
13
|
-
export declare const formatInstructionBlocks: (blocks: InstructionBlock[]) => string;
|
|
17
|
+
export declare const formatInstructionBlocks: (blocks: InstructionBlock[], maxChars?: number) => string;
|
|
14
18
|
//# sourceMappingURL=InstructionLoader.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"InstructionLoader.d.ts","sourceRoot":"","sources":["../../src/session/InstructionLoader.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"InstructionLoader.d.ts","sourceRoot":"","sources":["../../src/session/InstructionLoader.ts"],"names":[],"mappings":"AAMA,MAAM,WAAW,gBAAgB;IAC/B,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,EAAE,MAAM,CAAC;IACd,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,sBAAsB;IACrC,aAAa,EAAE,MAAM,CAAC;IACtB,UAAU,CAAC,EAAE,MAAM,EAAE,CAAC;IACtB,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,qFAAqF;IACrF,oBAAoB,CAAC,EAAE,MAAM,GAAG,KAAK,CAAC;CACvC;AA0FD,eAAO,MAAM,qBAAqB,GAChC,SAAS,sBAAsB,KAC9B,OAAO,CAAC,gBAAgB,EAAE,CA6C5B,CAAC;AAEF,eAAO,MAAM,uBAAuB,GAAI,QAAQ,gBAAgB,EAAE,EAAE,iBAAgB,KAAG,MAatF,CAAC"}
|
|
@@ -1,12 +1,43 @@
|
|
|
1
|
-
import { promises as fs } from "node:fs";
|
|
1
|
+
import { constants, promises as fs } from "node:fs";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import os from "node:os";
|
|
2
4
|
import path from "node:path";
|
|
3
|
-
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
const readInstruction = async (filePath, allowedRoot) => {
|
|
4
7
|
try {
|
|
5
|
-
const
|
|
6
|
-
|
|
8
|
+
const resolved = await fs.realpath(filePath);
|
|
9
|
+
const root = await fs.realpath(allowedRoot);
|
|
10
|
+
const relative = path.relative(root, resolved);
|
|
11
|
+
if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
|
|
12
|
+
throw new Error(`Instruction file escapes its allowed directory: ${filePath}`);
|
|
13
|
+
}
|
|
14
|
+
const handle = await fs.open(resolved, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
15
|
+
try {
|
|
16
|
+
const stat = await handle.stat();
|
|
17
|
+
if (!stat.isFile())
|
|
18
|
+
throw new Error(`Instruction source is not a regular file: ${filePath}`);
|
|
19
|
+
if (stat.size > 65536)
|
|
20
|
+
throw new Error(`Instruction file exceeds 64 KiB; shorten it or link supporting documents: ${filePath}`);
|
|
21
|
+
const buffer = Buffer.alloc(65537);
|
|
22
|
+
let bytesRead = 0;
|
|
23
|
+
while (bytesRead < buffer.length) {
|
|
24
|
+
const chunk = await handle.read(buffer, bytesRead, buffer.length - bytesRead, bytesRead);
|
|
25
|
+
if (!chunk.bytesRead)
|
|
26
|
+
break;
|
|
27
|
+
bytesRead += chunk.bytesRead;
|
|
28
|
+
}
|
|
29
|
+
if (bytesRead > 65536)
|
|
30
|
+
throw new Error(`Instruction file exceeds 64 KiB: ${filePath}`);
|
|
31
|
+
return buffer.subarray(0, bytesRead).toString("utf8");
|
|
32
|
+
}
|
|
33
|
+
finally {
|
|
34
|
+
await handle.close();
|
|
35
|
+
}
|
|
7
36
|
}
|
|
8
|
-
catch {
|
|
9
|
-
|
|
37
|
+
catch (error) {
|
|
38
|
+
if (error.code === "ENOENT")
|
|
39
|
+
return undefined;
|
|
40
|
+
throw error;
|
|
10
41
|
}
|
|
11
42
|
};
|
|
12
43
|
const normalizeFocusPath = (workspaceRoot, value) => {
|
|
@@ -46,20 +77,19 @@ const toRepoRelativePath = (workspaceRoot, filePath) => {
|
|
|
46
77
|
const relative = path.relative(workspaceRoot, filePath) || path.basename(filePath);
|
|
47
78
|
return relative.split(path.sep).join("/");
|
|
48
79
|
};
|
|
49
|
-
const readBlock = async (workspaceRoot, filePath, precedence) => {
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
const content = await fs.readFile(filePath, "utf8");
|
|
53
|
-
if (!content.trim())
|
|
80
|
+
const readBlock = async (workspaceRoot, filePath, precedence, sourceName, allowedRoot = workspaceRoot) => {
|
|
81
|
+
const content = await readInstruction(filePath, allowedRoot);
|
|
82
|
+
if (!content?.trim())
|
|
54
83
|
return undefined;
|
|
55
|
-
const relative = toRepoRelativePath(workspaceRoot, filePath);
|
|
84
|
+
const relative = sourceName ?? toRepoRelativePath(workspaceRoot, filePath);
|
|
56
85
|
const sourceDir = path.posix.dirname(relative);
|
|
57
|
-
const scope = sourceDir === "." ? "." : sourceDir;
|
|
86
|
+
const scope = sourceDir === "." || [".codali/instructions.md", ".codali/local.md"].includes(relative) ? "." : sourceDir;
|
|
58
87
|
return {
|
|
59
88
|
sourcePath: relative,
|
|
60
|
-
scope,
|
|
89
|
+
scope: sourceName ? "all turns in this workspace" : scope,
|
|
61
90
|
precedence,
|
|
62
91
|
content,
|
|
92
|
+
sha256: createHash("sha256").update(content).digest("hex"),
|
|
63
93
|
};
|
|
64
94
|
};
|
|
65
95
|
export const loadInstructionBlocks = async (options) => {
|
|
@@ -69,16 +99,29 @@ export const loadInstructionBlocks = async (options) => {
|
|
|
69
99
|
const blocks = [];
|
|
70
100
|
const seen = new Set();
|
|
71
101
|
let precedence = 0;
|
|
72
|
-
const addFile = async (filePath) => {
|
|
102
|
+
const addFile = async (filePath, sourceName, allowedRoot) => {
|
|
73
103
|
const resolved = path.resolve(filePath);
|
|
74
104
|
if (seen.has(resolved))
|
|
75
105
|
return;
|
|
76
106
|
seen.add(resolved);
|
|
77
|
-
const block = await readBlock(workspaceRoot, resolved, precedence);
|
|
107
|
+
const block = await readBlock(workspaceRoot, resolved, precedence, sourceName, allowedRoot);
|
|
78
108
|
precedence += 1;
|
|
79
|
-
if (block)
|
|
109
|
+
if (block) {
|
|
110
|
+
if (blocks.length >= 64)
|
|
111
|
+
throw new Error("Too many instruction sources; narrow the focused paths");
|
|
80
112
|
blocks.push(block);
|
|
113
|
+
}
|
|
81
114
|
};
|
|
115
|
+
if (options.includeSystem) {
|
|
116
|
+
const builtin = fileURLToPath(new URL("../../config/AGENTS.md", import.meta.url));
|
|
117
|
+
await addFile(builtin, "[codali]/AGENTS.md", path.dirname(builtin));
|
|
118
|
+
if (!blocks.some(block => block.sourcePath === "[codali]/AGENTS.md"))
|
|
119
|
+
throw new Error("Packaged Codali AGENTS.md is missing; reinstall the complete package");
|
|
120
|
+
if (options.userInstructionsPath !== false) {
|
|
121
|
+
const user = options.userInstructionsPath ?? path.join(os.homedir(), ".codali", "AGENTS.md");
|
|
122
|
+
await addFile(user, "[user]/AGENTS.md", path.dirname(user));
|
|
123
|
+
}
|
|
124
|
+
}
|
|
82
125
|
await addFile(path.join(workspaceRoot, ".codali", "instructions.md"));
|
|
83
126
|
const dirs = new Set();
|
|
84
127
|
for (const focusPath of focusPaths) {
|
|
@@ -94,14 +137,17 @@ export const loadInstructionBlocks = async (options) => {
|
|
|
94
137
|
}
|
|
95
138
|
return blocks.sort((a, b) => a.precedence - b.precedence);
|
|
96
139
|
};
|
|
97
|
-
export const formatInstructionBlocks = (blocks) => {
|
|
140
|
+
export const formatInstructionBlocks = (blocks, maxChars = 24000) => {
|
|
98
141
|
if (!blocks.length)
|
|
99
142
|
return "";
|
|
100
|
-
|
|
143
|
+
const formatted = blocks
|
|
101
144
|
.map((block) => [
|
|
102
145
|
`Instruction source: ${block.sourcePath}`,
|
|
103
146
|
`Scope: ${block.scope}`,
|
|
104
147
|
block.content.trim(),
|
|
105
148
|
].join("\n"))
|
|
106
149
|
.join("\n\n---\n\n");
|
|
150
|
+
if (formatted.length > maxChars)
|
|
151
|
+
throw new Error(`Instruction bundle exceeds ${maxChars} characters; shorten AGENTS.md files or link supporting documents`);
|
|
152
|
+
return formatted;
|
|
107
153
|
};
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { type ToolDefinition } from "../tools/ToolTypes.js";
|
|
2
|
+
export interface SkillEntry {
|
|
3
|
+
id: string;
|
|
4
|
+
name: string;
|
|
5
|
+
description: string;
|
|
6
|
+
compatibility?: string;
|
|
7
|
+
source: string;
|
|
8
|
+
sha256: string;
|
|
9
|
+
}
|
|
10
|
+
/** Progressive disclosure: catalog metadata is cheap; bodies/resources are tool reads. */
|
|
11
|
+
export declare class SkillCatalog {
|
|
12
|
+
private records;
|
|
13
|
+
private warnings;
|
|
14
|
+
private ready;
|
|
15
|
+
private roots;
|
|
16
|
+
constructor(options: {
|
|
17
|
+
workspaceRoot: string;
|
|
18
|
+
directories?: string[];
|
|
19
|
+
enabled?: boolean;
|
|
20
|
+
includeUser?: boolean;
|
|
21
|
+
includeBuiltin?: boolean;
|
|
22
|
+
});
|
|
23
|
+
refresh(): Promise<void>;
|
|
24
|
+
list(): {
|
|
25
|
+
skills: SkillEntry[];
|
|
26
|
+
warnings: string[];
|
|
27
|
+
};
|
|
28
|
+
prompt(): string;
|
|
29
|
+
private selected;
|
|
30
|
+
read(id: string, relative?: string, offset?: number): Promise<Record<string, unknown>>;
|
|
31
|
+
tools(): ToolDefinition[];
|
|
32
|
+
}
|
|
33
|
+
//# sourceMappingURL=SkillCatalog.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"SkillCatalog.d.ts","sourceRoot":"","sources":["../../src/session/SkillCatalog.ts"],"names":[],"mappings":"AAMA,OAAO,EAAsB,KAAK,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAGhF,MAAM,WAAW,UAAU;IAAG,EAAE,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAC;IAAC,aAAa,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;CAAE;AAiCtI,0FAA0F;AAC1F,qBAAa,YAAY;IACvB,OAAO,CAAC,OAAO,CAAqB;IACpC,OAAO,CAAC,QAAQ,CAAgB;IAChC,OAAO,CAAC,KAAK,CAAS;IACtB,OAAO,CAAC,KAAK,CAAc;gBACf,OAAO,EAAE;QAAE,aAAa,EAAE,MAAM,CAAC;QAAC,WAAW,CAAC,EAAE,MAAM,EAAE,CAAC;QAAC,OAAO,CAAC,EAAE,OAAO,CAAC;QAAC,WAAW,CAAC,EAAE,OAAO,CAAC;QAAC,cAAc,CAAC,EAAE,OAAO,CAAA;KAAE;IAUpI,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAkC9B,IAAI,IAAI;QAAE,MAAM,EAAE,UAAU,EAAE,CAAC;QAAC,QAAQ,EAAE,MAAM,EAAE,CAAA;KAAE;IAGpD,MAAM,IAAI,MAAM;YAMF,QAAQ;IAQhB,IAAI,CAAC,EAAE,EAAE,MAAM,EAAE,QAAQ,SAAa,EAAE,MAAM,SAAI,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAe3F,KAAK,IAAI,cAAc,EAAE;CAkB1B"}
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
import { constants, promises as fs } from "node:fs";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { parseDocument } from "yaml";
|
|
7
|
+
import { ToolExecutionError } from "../tools/ToolTypes.js";
|
|
8
|
+
const digest = (text) => createHash("sha256").update(text).digest("hex");
|
|
9
|
+
const inside = (root, file) => { const rel = path.relative(root, file); return rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel); };
|
|
10
|
+
const readText = async (root, file) => {
|
|
11
|
+
const resolved = await fs.realpath(file);
|
|
12
|
+
if (!inside(root, resolved))
|
|
13
|
+
throw new Error("Skill resource escapes its configured directory");
|
|
14
|
+
const handle = await fs.open(resolved, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
15
|
+
try {
|
|
16
|
+
const stat = await handle.stat();
|
|
17
|
+
if (!stat.isFile() || stat.size > 65536)
|
|
18
|
+
throw new Error("Skill resources must be regular text files no larger than 64 KiB");
|
|
19
|
+
const buffer = Buffer.alloc(65537);
|
|
20
|
+
let length = 0;
|
|
21
|
+
while (length < buffer.length) {
|
|
22
|
+
const chunk = await handle.read(buffer, length, buffer.length - length, length);
|
|
23
|
+
if (!chunk.bytesRead)
|
|
24
|
+
break;
|
|
25
|
+
length += chunk.bytesRead;
|
|
26
|
+
}
|
|
27
|
+
if (length > 65536)
|
|
28
|
+
throw new Error("Skill resource exceeds 64 KiB");
|
|
29
|
+
const text = new TextDecoder("utf-8", { fatal: true }).decode(buffer.subarray(0, length));
|
|
30
|
+
if (text.includes("\0"))
|
|
31
|
+
throw new Error("Skill resource is not text");
|
|
32
|
+
return text;
|
|
33
|
+
}
|
|
34
|
+
finally {
|
|
35
|
+
await handle.close();
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
const metadata = (text) => {
|
|
39
|
+
const match = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(text);
|
|
40
|
+
if (!match || match[1].length > 16384)
|
|
41
|
+
throw new Error("SKILL.md requires bounded YAML frontmatter");
|
|
42
|
+
const document = parseDocument(match[1], { schema: "failsafe", uniqueKeys: true });
|
|
43
|
+
if (document.errors.length || document.warnings.length)
|
|
44
|
+
throw new Error("Invalid skill YAML metadata");
|
|
45
|
+
const value = document.toJS({ maxAliasCount: 0 });
|
|
46
|
+
if (!value || typeof value.name !== "string" || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(value.name) || value.name.length > 64
|
|
47
|
+
|| typeof value.description !== "string" || !value.description.trim() || value.description.length > 1024)
|
|
48
|
+
throw new Error("Skill requires a valid name and a description of at most 1024 characters");
|
|
49
|
+
if (value.compatibility !== undefined && (typeof value.compatibility !== "string" || value.compatibility.length > 500))
|
|
50
|
+
throw new Error("Skill compatibility must be text of at most 500 characters");
|
|
51
|
+
return { name: value.name, description: value.description.trim(), ...(typeof value.compatibility === "string" ? { compatibility: value.compatibility } : {}) };
|
|
52
|
+
};
|
|
53
|
+
/** Progressive disclosure: catalog metadata is cheap; bodies/resources are tool reads. */
|
|
54
|
+
export class SkillCatalog {
|
|
55
|
+
constructor(options) {
|
|
56
|
+
this.records = [];
|
|
57
|
+
this.warnings = [];
|
|
58
|
+
this.ready = false;
|
|
59
|
+
const root = path.resolve(options.workspaceRoot), home = os.homedir();
|
|
60
|
+
this.roots = options.enabled === false ? [] : [
|
|
61
|
+
...(options.includeBuiltin === false ? [] : [{ scope: "builtin", directory: fileURLToPath(new URL("../../config/skills", import.meta.url)) }]),
|
|
62
|
+
...[".codali/skills", ".agents/skills"].map(relative => ({ scope: relative.startsWith(".codali") ? "workspace" : "workspace-agents", directory: path.join(root, relative), boundary: root })),
|
|
63
|
+
...(options.includeUser === false ? [] : [".codali/skills", ".agents/skills", ".codex/skills", ".claude/skills"].map((relative, index) => ({ scope: `user${index + 1}`, directory: path.join(home, relative) }))),
|
|
64
|
+
...(options.directories ?? []).map((directory, index) => ({ scope: `configured${index + 1}`, directory: path.resolve(root, directory.startsWith("~/") ? path.join(home, directory.slice(2)) : directory) })),
|
|
65
|
+
];
|
|
66
|
+
}
|
|
67
|
+
async refresh() {
|
|
68
|
+
const records = [], warnings = [], visited = new Set();
|
|
69
|
+
let traversed = 0;
|
|
70
|
+
for (const entry of this.roots) {
|
|
71
|
+
let root;
|
|
72
|
+
try {
|
|
73
|
+
root = await fs.realpath(entry.directory);
|
|
74
|
+
if (entry.boundary && !inside(await fs.realpath(entry.boundary), root))
|
|
75
|
+
throw new Error("Skill root escapes the workspace");
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
if (error.code !== "ENOENT")
|
|
79
|
+
warnings.push(`${entry.scope}: ${String(error)}`);
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
const visit = async (directory, depth) => {
|
|
83
|
+
if (traversed >= 256 || records.length >= 128)
|
|
84
|
+
return;
|
|
85
|
+
const real = await fs.realpath(directory);
|
|
86
|
+
if (!inside(root, real)) {
|
|
87
|
+
warnings.push(`${entry.scope}: skipped a directory outside its root`);
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
if (visited.has(real))
|
|
91
|
+
return;
|
|
92
|
+
visited.add(real);
|
|
93
|
+
traversed++;
|
|
94
|
+
const source = path.join(real, "SKILL.md");
|
|
95
|
+
try {
|
|
96
|
+
const text = await readText(root, source), parsed = metadata(text);
|
|
97
|
+
records.push({ id: `${entry.scope}:${parsed.name}:${digest(real).slice(0, 8)}`, ...parsed, source, sha256: digest(text), root, directory: real });
|
|
98
|
+
return; // References/scripts under a skill are not other skills.
|
|
99
|
+
}
|
|
100
|
+
catch (error) {
|
|
101
|
+
if (error.code !== "ENOENT") {
|
|
102
|
+
warnings.push(`${source}: ${String(error)}`);
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
if (depth >= 3)
|
|
107
|
+
return;
|
|
108
|
+
const children = await fs.readdir(real, { withFileTypes: true });
|
|
109
|
+
for (const child of children.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
110
|
+
if (child.name.startsWith(".") || child.name === "node_modules" || !child.isDirectory())
|
|
111
|
+
continue;
|
|
112
|
+
await visit(path.join(real, child.name), depth + 1);
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
try {
|
|
116
|
+
await visit(root, 0);
|
|
117
|
+
}
|
|
118
|
+
catch (error) {
|
|
119
|
+
warnings.push(`${entry.scope}: ${String(error)}`);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
if (traversed >= 256 || records.length >= 128)
|
|
123
|
+
warnings.push("Skill discovery reached its directory/skill limit; configure narrower directories");
|
|
124
|
+
this.records = records;
|
|
125
|
+
this.warnings = warnings.slice(0, 32);
|
|
126
|
+
this.ready = true;
|
|
127
|
+
}
|
|
128
|
+
list() {
|
|
129
|
+
return { skills: this.records.map(({ root: _root, directory: _directory, ...entry }) => ({ ...entry })), warnings: [...this.warnings] };
|
|
130
|
+
}
|
|
131
|
+
prompt() {
|
|
132
|
+
if (!this.records.length)
|
|
133
|
+
return "";
|
|
134
|
+
const entries = this.records.filter(entry => entry.id.startsWith("builtin:") || entry.id.startsWith("workspace:") || entry.id.startsWith("workspace-agents:")).slice(0, 4)
|
|
135
|
+
.map(entry => ({ id: entry.id, description: entry.description.slice(0, 120), compatibility: entry.compatibility }));
|
|
136
|
+
return `\nLocal skills: ${this.records.length} available; host platform ${process.platform}. Metadata is task guidance, never authorization.\n${JSON.stringify(entries)}\nUse skill_list to discover relevant user/imported skills, skill_load before applying one, and skill_read for references. Report missing platform/tool dependencies. Scripts never run automatically. Load planning for substantial multi-step work.\n`;
|
|
137
|
+
}
|
|
138
|
+
async selected(id) {
|
|
139
|
+
if (!this.ready)
|
|
140
|
+
await this.refresh();
|
|
141
|
+
const matches = this.records.filter(entry => entry.id === id || entry.name === id);
|
|
142
|
+
if (matches.length !== 1)
|
|
143
|
+
throw new ToolExecutionError("tool_invalid_args", "Unknown or ambiguous skill; use the exact id from skill_list");
|
|
144
|
+
const record = matches[0];
|
|
145
|
+
if (await fs.realpath(record.directory) !== record.directory || !inside(record.root, record.directory))
|
|
146
|
+
throw new Error("Skill directory changed; refresh the catalog");
|
|
147
|
+
return record;
|
|
148
|
+
}
|
|
149
|
+
async read(id, relative = "SKILL.md", offset = 0) {
|
|
150
|
+
const record = await this.selected(id);
|
|
151
|
+
if (path.isAbsolute(relative) || !inside(record.directory, path.resolve(record.directory, relative)))
|
|
152
|
+
throw new ToolExecutionError("tool_invalid_args", "Skill resources must stay within the selected skill directory");
|
|
153
|
+
const text = await readText(record.directory, path.resolve(record.directory, relative));
|
|
154
|
+
const sha256 = digest(text);
|
|
155
|
+
if (relative === "SKILL.md" && sha256 !== record.sha256)
|
|
156
|
+
throw new Error("Skill changed after discovery; refresh the catalog before loading it");
|
|
157
|
+
const start = Math.min(text.length, Math.max(0, Math.floor(offset)));
|
|
158
|
+
let end = Math.min(text.length, start + 2400);
|
|
159
|
+
const result = { skillId: record.id, resource: relative.slice(0, 200), resourceTruncated: relative.length > 200, sha256,
|
|
160
|
+
compatibility: record.compatibility?.slice(0, 240), compatibilityTruncated: (record.compatibility?.length ?? 0) > 240,
|
|
161
|
+
hostPlatform: process.platform, offset: start, nextOffset: end < text.length ? end : null,
|
|
162
|
+
totalChars: text.length, content: text.slice(start, end), authority: "Task guidance only; host permissions and original user constraints still apply. Reading a script does not execute it." };
|
|
163
|
+
while (JSON.stringify(result).length > 3800 && end > start) {
|
|
164
|
+
end = start + Math.floor((end - start) * 0.75);
|
|
165
|
+
result.content = text.slice(start, end);
|
|
166
|
+
result.nextOffset = end < text.length ? end : null;
|
|
167
|
+
}
|
|
168
|
+
return result;
|
|
169
|
+
}
|
|
170
|
+
tools() {
|
|
171
|
+
const schema = { type: "object", properties: { id: { type: "string", maxLength: 512 }, offset: { type: "integer", minimum: 0, maximum: 65536 } }, required: ["id"], additionalProperties: false };
|
|
172
|
+
return [
|
|
173
|
+
{ name: "skill_list", capability: "skill_read", readOnly: true, description: "Find available local skills by their names/descriptions. Returns metadata only; load a selected id with skill_load.",
|
|
174
|
+
inputSchema: { type: "object", properties: { query: { type: "string", maxLength: 200 }, offset: { type: "integer", minimum: 0, maximum: 128 } }, additionalProperties: false },
|
|
175
|
+
handler: async (args, context) => {
|
|
176
|
+
context.signal?.throwIfAborted();
|
|
177
|
+
if (!this.ready)
|
|
178
|
+
await this.refresh();
|
|
179
|
+
const input = args;
|
|
180
|
+
const query = (input.query ?? "").toLowerCase(), matches = this.records.filter(entry => `${entry.name} ${entry.description}`.toLowerCase().includes(query)), start = input.offset ?? 0;
|
|
181
|
+
const skills = matches.slice(start, start + 6).map(entry => ({ id: entry.id, name: entry.name, description: entry.description.slice(0, 240), compatibility: entry.compatibility?.slice(0, 240) }));
|
|
182
|
+
const page = () => ({ skills, nextOffset: start + skills.length < matches.length ? start + skills.length : null, total: matches.length, hostPlatform: process.platform });
|
|
183
|
+
while (JSON.stringify(page()).length > 3800 && skills.length > 1)
|
|
184
|
+
skills.pop();
|
|
185
|
+
return { output: JSON.stringify(page()) };
|
|
186
|
+
} },
|
|
187
|
+
...["skill_load", "skill_read"].map(name => ({ name, capability: "skill_read", readOnly: true,
|
|
188
|
+
description: name === "skill_load" ? "Load SKILL.md guidance for an exact skill id. Follow nextOffset for longer instructions; permissions are unchanged." : "Read a referenced text resource inside a selected skill. Never executes scripts. Use nextOffset for additional text.",
|
|
189
|
+
inputSchema: name === "skill_load" ? schema : { ...schema, properties: { ...schema.properties, path: { type: "string", maxLength: 512 } }, required: ["id", "path"] },
|
|
190
|
+
handler: async (args, context) => { context.signal?.throwIfAborted(); const input = args; const result = await this.read(input.id, name === "skill_load" ? "SKILL.md" : input.path, input.offset); context.signal?.throwIfAborted(); return { output: JSON.stringify(result), data: result }; },
|
|
191
|
+
})),
|
|
192
|
+
];
|
|
193
|
+
}
|
|
194
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { ConfiguredEmbeddings } from "../providers/ConfiguredEmbeddings.js";
|
|
2
|
+
import type { ToolDefinition } from "./ToolTypes.js";
|
|
3
|
+
export interface ToolRetrievalEvidence {
|
|
4
|
+
method: "semantic-metadata-v1";
|
|
5
|
+
catalogHash: string;
|
|
6
|
+
spaceId: string;
|
|
7
|
+
cacheHit: boolean;
|
|
8
|
+
documents: number;
|
|
9
|
+
elapsedMs: number;
|
|
10
|
+
}
|
|
11
|
+
/** Cache only public tool metadata vectors, keyed by pinned model and content. */
|
|
12
|
+
export declare function retrieveSemanticTools(query: string, tools: readonly ToolDefinition[], embeddings: ConfiguredEmbeddings, cacheRoot: string, signal?: AbortSignal, limit?: number): Promise<{
|
|
13
|
+
ranked: Array<{
|
|
14
|
+
tool: ToolDefinition;
|
|
15
|
+
score: number;
|
|
16
|
+
}>;
|
|
17
|
+
evidence: ToolRetrievalEvidence;
|
|
18
|
+
}>;
|
|
19
|
+
//# sourceMappingURL=SemanticToolRetrieval.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"SemanticToolRetrieval.d.ts","sourceRoot":"","sources":["../../src/tools/SemanticToolRetrieval.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,sCAAsC,CAAC;AACjF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAGrD,MAAM,WAAW,qBAAqB;IAAG,MAAM,EAAE,sBAAsB,CAAC;IAAC,WAAW,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,OAAO,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;CAAE;AAOzK,kFAAkF;AAClF,wBAAsB,qBAAqB,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,cAAc,EAAE,EAAE,UAAU,EAAE,oBAAoB,EAAE,SAAS,EAAE,MAAM,EAC9I,MAAM,CAAC,EAAE,WAAW,EAAE,KAAK,SAAI,GAAG,OAAO,CAAC;IAAE,MAAM,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,cAAc,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAAC,QAAQ,EAAE,qBAAqB,CAAA;CAAE,CAAC,CA2BvI"}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { promises as fs } from "node:fs";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { atomicWriteJson, withStateLock } from "../session/AtomicState.js";
|
|
5
|
+
import { retrieveTools } from "./ToolRetrieval.js";
|
|
6
|
+
const cosine = (a, b) => {
|
|
7
|
+
let dot = 0, aa = 0, bb = 0;
|
|
8
|
+
for (let i = 0; i < a.length; i++) {
|
|
9
|
+
dot += a[i] * b[i];
|
|
10
|
+
aa += a[i] * a[i];
|
|
11
|
+
bb += b[i] * b[i];
|
|
12
|
+
}
|
|
13
|
+
return aa && bb ? dot / Math.sqrt(aa * bb) : 0;
|
|
14
|
+
};
|
|
15
|
+
/** Cache only public tool metadata vectors, keyed by pinned model and content. */
|
|
16
|
+
export async function retrieveSemanticTools(query, tools, embeddings, cacheRoot, signal, limit = 3) {
|
|
17
|
+
const started = Date.now();
|
|
18
|
+
const ordered = [...tools].sort((a, b) => a.name.localeCompare(b.name));
|
|
19
|
+
const documents = ordered.map(tool => `${tool.name.replace(/_/g, " ")}: ${tool.description.slice(0, 700)}`);
|
|
20
|
+
const catalogHash = createHash("sha256").update(JSON.stringify(documents)).digest("hex");
|
|
21
|
+
const file = path.join(cacheRoot, embeddings.space.id, `${catalogHash}.json`);
|
|
22
|
+
const valid = (value) => Array.isArray(value) && value.length === tools.length
|
|
23
|
+
&& value.every(row => Array.isArray(row) && row.length === embeddings.space.dimensions && row.every(v => typeof v === "number" && Number.isFinite(v)));
|
|
24
|
+
let cacheHit = false;
|
|
25
|
+
const vectors = await withStateLock(file, async () => {
|
|
26
|
+
try {
|
|
27
|
+
const cached = JSON.parse(await fs.readFile(file, "utf8"));
|
|
28
|
+
if (cached.catalogHash === catalogHash && cached.spaceId === embeddings.space.id && valid(cached.vectors)) {
|
|
29
|
+
cacheHit = true;
|
|
30
|
+
return cached.vectors;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
catch (error) {
|
|
34
|
+
if (error.code !== "ENOENT" && !(error instanceof SyntaxError))
|
|
35
|
+
throw error;
|
|
36
|
+
}
|
|
37
|
+
const result = [];
|
|
38
|
+
// Small batches fit the service's bounded input contract; every call is metered.
|
|
39
|
+
for (let start = 0; start < documents.length; start += 64)
|
|
40
|
+
result.push(...await embeddings.embed(documents.slice(start, start + 64), "document", signal));
|
|
41
|
+
if (!valid(result))
|
|
42
|
+
throw Error("Invalid tool metadata embeddings");
|
|
43
|
+
await atomicWriteJson(file, { schemaVersion: 1, catalogHash, spaceId: embeddings.space.id, createdAt: new Date().toISOString(), names: ordered.map(tool => tool.name), vectors: result });
|
|
44
|
+
return result;
|
|
45
|
+
});
|
|
46
|
+
const [wanted] = await embeddings.embed([query.slice(0, 4000)], "query", signal);
|
|
47
|
+
const lexical = new Map(retrieveTools(query, tools, 8).map(item => [item.tool.name, item.score]));
|
|
48
|
+
const maxLexical = Math.max(1, ...lexical.values());
|
|
49
|
+
const ranked = ordered.map((tool, i) => ({ tool, score: cosine(wanted, vectors[i]) + .03 * (lexical.get(tool.name) ?? 0) / maxLexical }))
|
|
50
|
+
.sort((a, b) => b.score - a.score || a.tool.name.localeCompare(b.tool.name)).slice(0, Math.max(1, Math.min(8, limit)));
|
|
51
|
+
return { ranked, evidence: { method: "semantic-metadata-v1", catalogHash, spaceId: embeddings.space.id, cacheHit, documents: tools.length, elapsedMs: Date.now() - started } };
|
|
52
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { ToolDefinition } from "./ToolTypes.js";
|
|
2
|
+
/** Generic lexical retrieval over tool metadata, not a request-type router. */
|
|
3
|
+
export declare const retrieveTools: (query: string, tools: readonly ToolDefinition[], limit?: number) => Array<{
|
|
4
|
+
tool: ToolDefinition;
|
|
5
|
+
score: number;
|
|
6
|
+
}>;
|
|
7
|
+
//# sourceMappingURL=ToolRetrieval.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ToolRetrieval.d.ts","sourceRoot":"","sources":["../../src/tools/ToolRetrieval.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAMrD,+EAA+E;AAC/E,eAAO,MAAM,aAAa,GAAI,OAAO,MAAM,EAAE,OAAO,SAAS,cAAc,EAAE,EAAE,cAAS,KAAG,KAAK,CAAC;IAAE,IAAI,EAAE,cAAc,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAgBvI,CAAC"}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
const stop = new Set("a an and are as at be by can do for from how i in is it me of on or please that the this to use what with you your".split(" "));
|
|
2
|
+
const terms = (value) => (value.normalize("NFKC").replace(/([a-z])([A-Z])/g, "$1 $2").toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? [])
|
|
3
|
+
.filter(term => term.length > 1 && !stop.has(term)).map(term => term.length > 5 ? term.replace(/(?:ing|ed|s)$/, "") : term);
|
|
4
|
+
/** Generic lexical retrieval over tool metadata, not a request-type router. */
|
|
5
|
+
export const retrieveTools = (query, tools, limit = 3) => {
|
|
6
|
+
const wanted = [...new Set(terms(query))];
|
|
7
|
+
if (!wanted.length)
|
|
8
|
+
return [];
|
|
9
|
+
const documents = tools.map(tool => {
|
|
10
|
+
const counts = new Map();
|
|
11
|
+
for (const word of terms(`${tool.name.replace(/_/g, " ")} ${tool.name.replace(/_/g, " ")} ${tool.description} ${Object.keys(tool.inputSchema?.properties ?? {}).join(" ")}`))
|
|
12
|
+
counts.set(word, (counts.get(word) ?? 0) + 1);
|
|
13
|
+
return { tool, counts, length: [...counts.values()].reduce((a, b) => a + b, 0) };
|
|
14
|
+
});
|
|
15
|
+
const average = documents.reduce((n, doc) => n + doc.length, 0) / Math.max(1, documents.length);
|
|
16
|
+
const frequencies = new Map(wanted.map(term => [term, documents.filter(doc => doc.counts.has(term)).length]));
|
|
17
|
+
return documents.map(doc => ({ tool: doc.tool, score: wanted.reduce((score, term) => {
|
|
18
|
+
const tf = doc.counts.get(term) ?? 0;
|
|
19
|
+
if (!tf)
|
|
20
|
+
return score;
|
|
21
|
+
const df = frequencies.get(term);
|
|
22
|
+
const idf = Math.log(1 + (documents.length - df + .5) / (df + .5));
|
|
23
|
+
return score + idf * tf * 2.2 / (tf + 1.2 * (.25 + .75 * doc.length / Math.max(1, average)));
|
|
24
|
+
}, 0) })).filter(item => item.score > 0).sort((a, b) => b.score - a.score || a.tool.name.localeCompare(b.tool.name)).slice(0, Math.max(0, Math.min(8, limit)));
|
|
25
|
+
};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { type ToolDefinition } from "../ToolTypes.js";
|
|
2
|
+
export declare const browserUrl: (value: string) => string;
|
|
3
|
+
export declare function resolveBrowserBinary(): Promise<string>;
|
|
4
|
+
/** Short-lived, unauthenticated browser navigation; the model never supplies JS. */
|
|
5
|
+
export declare function createBrowserTools(options?: {
|
|
6
|
+
executablePath?: string;
|
|
7
|
+
timeoutMs?: number;
|
|
8
|
+
}): ToolDefinition[];
|
|
9
|
+
//# sourceMappingURL=BrowserTool.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"BrowserTool.d.ts","sourceRoot":"","sources":["../../../src/tools/browser/BrowserTool.ts"],"names":[],"mappings":"AAMA,OAAO,EAAsB,KAAK,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAE1E,eAAO,MAAM,UAAU,GAAI,OAAO,MAAM,KAAG,MAO1C,CAAC;AAEF,wBAAsB,oBAAoB,IAAI,OAAO,CAAC,MAAM,CAAC,CAyB5D;AAID,oFAAoF;AACpF,wBAAgB,kBAAkB,CAAC,OAAO,GAAE;IAAE,cAAc,CAAC,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAA;CAAO,GAAG,cAAc,EAAE,CAgFlH"}
|