@earendil-works/pi-coding-agent 1.0.3 → 1.1.0
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/CHANGELOG.md +75 -0
- package/dist/bundle/chunks/{anthropic-messages-Y22YDKSW.js → anthropic-messages-KT2ID7DZ.js} +1 -1
- package/dist/bundle/chunks/anthropic.js +1 -1
- package/dist/bundle/chunks/{azure-openai-responses-YJDJIIDQ.js → azure-openai-responses-6A4PNZTH.js} +1 -1
- package/dist/bundle/chunks/bedrock-converse-stream.js +2 -2
- package/dist/bundle/chunks/chunk-33CRHCAK.js +2 -0
- package/dist/bundle/chunks/{chunk-UBHCV62G.js → chunk-BK6FEHYX.js} +3 -3
- package/dist/bundle/chunks/chunk-CH4ZBH45.js +11 -0
- package/dist/bundle/chunks/{chunk-6DBOMCBS.js → chunk-GXLAGZ3Z.js} +1 -1
- package/dist/bundle/chunks/{chunk-J52J6TFP.js → chunk-HKYL362W.js} +1 -1
- package/dist/bundle/chunks/chunk-LPXNMA2W.js +2 -0
- package/dist/bundle/chunks/{chunk-TAOL3JFA.js → chunk-LTSARG5Q.js} +1 -1
- package/dist/bundle/chunks/{chunk-ZSQEXT6X.js → chunk-MXTZIDYW.js} +4 -4
- package/dist/bundle/chunks/chunk-O7YIWAPD.js +2 -0
- package/dist/bundle/chunks/{chunk-BFNE7BHG.js → chunk-OIM2DMFI.js} +83 -72
- package/dist/bundle/chunks/{chunk-AXOERKKW.js → chunk-OTL6MGLJ.js} +6 -4
- package/dist/bundle/chunks/{chunk-LD2P6SFZ.js → chunk-PMRZO46Y.js} +1 -1
- package/dist/bundle/chunks/{chunk-7TP2J6F2.js → chunk-SYCGMWFH.js} +1 -1
- package/dist/bundle/chunks/{chunk-2VBQLN7Y.js → chunk-UH5J7I7X.js} +9 -6
- package/dist/bundle/chunks/{chunk-WE4MXUQS.js → chunk-VLRCF7MR.js} +1 -1
- package/dist/bundle/chunks/chunk-W5MPVSHA.js +82 -0
- package/dist/bundle/chunks/chunk-Y4NYF362.js +2 -0
- package/dist/bundle/chunks/{cli-HTJP6F6Z.js → cli-OQYLWLA3.js} +2 -2
- package/dist/bundle/chunks/cloudflare-workers-ai-system-one-U3AH4ODQ.js +2 -0
- package/dist/bundle/chunks/codemode-worker.js +101 -5
- package/dist/bundle/chunks/{easter-egg-3d-6YCNESG3.js → easter-egg-3d-TQFQS342.js} +1 -1
- package/dist/bundle/chunks/{execute-JRUOLYDA.js → execute-7IRB5TUX.js} +110 -8
- package/dist/bundle/chunks/github-copilot.js +1 -1
- package/dist/bundle/chunks/{google-generative-ai-XMFHGQC5.js → google-generative-ai-X2VFFS4I.js} +1 -1
- package/dist/bundle/chunks/{google-vertex-4XRRNP74.js → google-vertex-KMGHFTSP.js} +1 -1
- package/dist/bundle/chunks/image-resize-worker.js +1 -1
- package/dist/bundle/chunks/{llama-cpp-classify-XT44PI3C.js → llama-cpp-classify-FYN623RH.js} +2 -2
- package/dist/bundle/chunks/{mistral-conversations-Q22M3IBG.js → mistral-conversations-PRZLM26U.js} +2 -2
- package/dist/bundle/chunks/openai-chatgpt.js +1 -1
- package/dist/bundle/chunks/{openai-codex-responses-4MYQSO5E.js → openai-codex-responses-ZSLJZYOE.js} +2 -2
- package/dist/bundle/chunks/openai-codex.js +1 -1
- package/dist/bundle/chunks/{openai-completions-OSRCWAAA.js → openai-completions-WWQW7S3V.js} +1 -1
- package/dist/bundle/chunks/openai-decisions-QLZKZLAK.js +5 -0
- package/dist/bundle/chunks/{openai-responses-UHF3DHNG.js → openai-responses-KV7QHJY6.js} +1 -1
- package/dist/bundle/chunks/{openrouter-images-ZVXWCSIM.js → openrouter-images-DUPG5DZO.js} +1 -1
- package/dist/bundle/chunks/{pi-messages-TM5SOOIW.js → pi-messages-YHKPQIHC.js} +1 -1
- package/dist/bundle/chunks/{runtime-NW7GPWKS.js → runtime-ROGZ2EXI.js} +1 -1
- package/dist/bundle/chunks/typesafe-system-one-B4NNEG67.js +2 -0
- package/dist/bundle/chunks/{virtual-modules-CFHJO5SY.js → virtual-modules-4YN2GNVW.js} +1 -1
- package/dist/bundle/cli-runtime.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/cli/args.d.ts +2 -1
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +24 -5
- package/dist/cli/args.js.map +1 -1
- package/dist/core/agent-session.d.ts +33 -4
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +59 -21
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/bash-executor.d.ts.map +1 -1
- package/dist/core/bash-executor.js +40 -45
- package/dist/core/bash-executor.js.map +1 -1
- package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
- package/dist/core/export-html/tool-renderer.js +2 -0
- package/dist/core/export-html/tool-renderer.js.map +1 -1
- package/dist/core/extensions/types.d.ts +13 -0
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/mcp-servers.d.ts +8 -0
- package/dist/core/mcp-servers.d.ts.map +1 -1
- package/dist/core/mcp-servers.js +30 -7
- package/dist/core/mcp-servers.js.map +1 -1
- package/dist/core/model-runtime.d.ts.map +1 -1
- package/dist/core/model-runtime.js +2 -1
- package/dist/core/model-runtime.js.map +1 -1
- package/dist/core/nested-tool-calls.d.ts +1 -0
- package/dist/core/nested-tool-calls.d.ts.map +1 -1
- package/dist/core/nested-tool-calls.js +1 -0
- package/dist/core/nested-tool-calls.js.map +1 -1
- package/dist/core/resource-loader.d.ts +3 -0
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +4 -3
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/sdk.d.ts +13 -4
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +19 -6
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/settings-manager.d.ts +13 -0
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +37 -13
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/skills.d.ts +4 -1
- package/dist/core/skills.d.ts.map +1 -1
- package/dist/core/skills.js +6 -1
- package/dist/core/skills.js.map +1 -1
- package/dist/core/system-prompt.d.ts +6 -0
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +9 -4
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/tools/read.d.ts +13 -0
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js +18 -1
- package/dist/core/tools/read.js.map +1 -1
- package/dist/core/tools/renderers/bash.d.ts.map +1 -1
- package/dist/core/tools/renderers/bash.js +8 -3
- package/dist/core/tools/renderers/bash.js.map +1 -1
- package/dist/core/tools/renderers/edit.d.ts.map +1 -1
- package/dist/core/tools/renderers/edit.js +5 -4
- package/dist/core/tools/renderers/edit.js.map +1 -1
- package/dist/extensions/codemode/execute.d.ts.map +1 -1
- package/dist/extensions/codemode/execute.js +65 -8
- package/dist/extensions/codemode/execute.js.map +1 -1
- package/dist/extensions/codemode/index.d.ts.map +1 -1
- package/dist/extensions/codemode/index.js +1 -0
- package/dist/extensions/codemode/index.js.map +1 -1
- package/dist/extensions/codemode/tool.d.ts +9 -2
- package/dist/extensions/codemode/tool.d.ts.map +1 -1
- package/dist/extensions/codemode/tool.js +14 -6
- package/dist/extensions/codemode/tool.js.map +1 -1
- package/dist/extensions/llama/provider.d.ts.map +1 -1
- package/dist/extensions/llama/provider.js +34 -11
- package/dist/extensions/llama/provider.js.map +1 -1
- package/dist/extensions/mcp/cli.js +17 -23
- package/dist/extensions/mcp/cli.js.map +1 -1
- package/dist/extensions/mcp/index.d.ts.map +1 -1
- package/dist/extensions/mcp/index.js +165 -64
- package/dist/extensions/mcp/index.js.map +1 -1
- package/dist/extensions/mcp/oauth.d.ts +5 -3
- package/dist/extensions/mcp/oauth.d.ts.map +1 -1
- package/dist/extensions/mcp/oauth.js +36 -10
- package/dist/extensions/mcp/oauth.js.map +1 -1
- package/dist/extensions/mcp/resources.d.ts +3 -4
- package/dist/extensions/mcp/resources.d.ts.map +1 -1
- package/dist/extensions/mcp/resources.js +3 -4
- package/dist/extensions/mcp/resources.js.map +1 -1
- package/dist/extensions/mcp/runtime.d.ts +4 -1
- package/dist/extensions/mcp/runtime.d.ts.map +1 -1
- package/dist/extensions/mcp/runtime.js +22 -5
- package/dist/extensions/mcp/runtime.js.map +1 -1
- package/dist/extensions/mcp/tools.d.ts +2 -1
- package/dist/extensions/mcp/tools.d.ts.map +1 -1
- package/dist/extensions/mcp/tools.js +2 -1
- package/dist/extensions/mcp/tools.js.map +1 -1
- package/dist/extensions/mcp/ui.d.ts +3 -3
- package/dist/extensions/mcp/ui.d.ts.map +1 -1
- package/dist/extensions/mcp/ui.js +10 -2
- package/dist/extensions/mcp/ui.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +1 -0
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/bash-execution.d.ts +5 -1
- package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/bash-execution.js +17 -14
- package/dist/modes/interactive/components/bash-execution.js.map +1 -1
- package/dist/modes/interactive/components/branch-summary-message.d.ts +2 -1
- package/dist/modes/interactive/components/branch-summary-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/branch-summary-message.js +5 -2
- package/dist/modes/interactive/components/branch-summary-message.js.map +1 -1
- package/dist/modes/interactive/components/compaction-summary-message.d.ts +2 -1
- package/dist/modes/interactive/components/compaction-summary-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/compaction-summary-message.js +5 -2
- package/dist/modes/interactive/components/compaction-summary-message.js.map +1 -1
- package/dist/modes/interactive/components/custom-entry.d.ts +3 -1
- package/dist/modes/interactive/components/custom-entry.d.ts.map +1 -1
- package/dist/modes/interactive/components/custom-entry.js +8 -2
- package/dist/modes/interactive/components/custom-entry.js.map +1 -1
- package/dist/modes/interactive/components/custom-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/custom-message.js +1 -0
- package/dist/modes/interactive/components/custom-message.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +1 -1
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/components/skill-invocation-message.d.ts +2 -1
- package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/skill-invocation-message.js +5 -2
- package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts +5 -0
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +10 -0
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +2 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +50 -29
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/program-status-reporter.d.ts +34 -0
- package/dist/modes/interactive/program-status-reporter.d.ts.map +1 -0
- package/dist/modes/interactive/program-status-reporter.js +110 -0
- package/dist/modes/interactive/program-status-reporter.js.map +1 -0
- package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
- package/dist/modes/interactive/theme/theme.js +1 -0
- package/dist/modes/interactive/theme/theme.js.map +1 -1
- package/dist/package-manager-cli.d.ts.map +1 -1
- package/dist/package-manager-cli.js +24 -0
- package/dist/package-manager-cli.js.map +1 -1
- package/dist/utils/ansi.d.ts +8 -0
- package/dist/utils/ansi.d.ts.map +1 -1
- package/dist/utils/ansi.js +30 -11
- package/dist/utils/ansi.js.map +1 -1
- package/dist/utils/clipboard.d.ts.map +1 -1
- package/dist/utils/clipboard.js +12 -11
- package/dist/utils/clipboard.js.map +1 -1
- package/dist/utils/image-resize-core.d.ts +12 -0
- package/dist/utils/image-resize-core.d.ts.map +1 -1
- package/dist/utils/image-resize-core.js +5 -0
- package/dist/utils/image-resize-core.js.map +1 -1
- package/dist/utils/image-resize-worker.js +3 -2
- package/dist/utils/image-resize-worker.js.map +1 -1
- package/dist/utils/image-resize.d.ts.map +1 -1
- package/dist/utils/image-resize.js +9 -10
- package/dist/utils/image-resize.js.map +1 -1
- package/dist/utils/syntax-highlight.d.ts.map +1 -1
- package/dist/utils/syntax-highlight.js +6 -1
- package/dist/utils/syntax-highlight.js.map +1 -1
- package/docs/cli.md +18 -6
- package/docs/codemode.md +26 -5
- package/docs/environment-variables.md +1 -0
- package/docs/extensions.md +1 -1
- package/docs/json.md +3 -3
- package/docs/llama-cpp.md +8 -1
- package/docs/mcp.md +3 -1
- package/docs/message-types.md +22 -4
- package/docs/models.md +4 -1
- package/docs/providers.md +27 -0
- package/docs/settings.md +3 -3
- package/docs/terminal-setup.md +14 -0
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/package.json +12 -12
- package/dist/bundle/chunks/chunk-A3JYRWB6.js +0 -2
- package/dist/bundle/chunks/chunk-C47CLQZK.js +0 -2
- package/dist/bundle/chunks/chunk-HQHD6PZI.js +0 -2
- package/dist/bundle/chunks/chunk-KJUDFE6Y.js +0 -11
- package/dist/bundle/chunks/chunk-PSQJVYXD.js +0 -82
- package/dist/bundle/chunks/cloudflare-workers-ai-system-one-NM3JRRWQ.js +0 -2
- package/dist/bundle/chunks/typesafe-system-one-PRR5K6CI.js +0 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool.d.ts","sourceRoot":"","sources":["../../../src/extensions/codemode/tool.ts"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,MAAM,EAAE,aAAa,CAAC,CAAC;IAChD,6FAA6F;IAC7F,QAAQ,CAAC,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;IAC/B,kFAAkF;IAClF,UAAU,CAAC,EAAE,WAAW,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,CAAC,CAAC;IACpD;;;OAGG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;CACtB;AA6CD;;;;;;GAMG;AACH,wBAAgB,yBAAyB,CACxC,KAAK,EAAE,SAAS,SAAS,CAAC,GAAG,CAAC,EAAE,EAChC,OAAO,GAAE,0BAA+B,GACtC,MAAM,CA+CR;AAkFD,wBAAgB,4BAA4B,CAC3C,OAAO,GAAE,mBAAwB,GAC/B,cAAc,CAAC,OAAO,cAAc,EAAE,mBAAmB,GAAG,SAAS,CAAC,CAmBxE;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CACjC,KAAK,GAAE,SAAS,SAAS,CAAC,GAAG,CAAC,EAAO,EACrC,OAAO,GAAE,mBAAwB,GAC/B,SAAS,CAAC,OAAO,cAAc,CAAC,CASlC"}
|
|
@@ -59,9 +59,9 @@ const DESCRIPTION_INTRO = `Run JavaScript that calls other tools. The input is r
|
|
|
59
59
|
function describeGlobals(models) {
|
|
60
60
|
const lines = [
|
|
61
61
|
"Globals:",
|
|
62
|
-
"- `text(value)`, `image(dataUrlOrImageBlock)`, `console.log(...)`, and top-level `return` add output; `exit()` ends the script. `image()` also saves the image to a temp file and the result names its path.",
|
|
62
|
+
"- `text(value)`, `image(dataUrlOrImageBlock)`, `console.log(...)`, and top-level `return` add output; `exit()` ends the script. With several text items, each starts with a `==> text N/M <==` line, and `console` lines follow the other output in one `<console_output>` block. `image()` also saves the image to a temp file and the result names its path.",
|
|
63
63
|
"- `store(key, value)` and `load(key)` keep JSON values across codemode calls.",
|
|
64
|
-
"- `ALL_TOOLS`, `searchTools(query, { limit?, namespace? })`, `describeTool(name)`, `describeNamespace(name)`: find unlisted tools, such as MCP tools.",
|
|
64
|
+
"- `ALL_TOOLS`, `await searchTools(query, { limit?, namespace? })`, `await describeTool(name)`, `await describeNamespace(name)`: find unlisted tools, such as MCP tools.",
|
|
65
65
|
];
|
|
66
66
|
if (models) {
|
|
67
67
|
lines.push(`- \`models\`: classifiers and image generation. Read ${CODEMODE_DOCS_PATH} first.`);
|
|
@@ -72,11 +72,15 @@ function describeGlobals(models) {
|
|
|
72
72
|
export const DEFAULT_CODEMODE_INLINE_BUDGET = 3000;
|
|
73
73
|
/** Characters per token when estimating the cost of a tool section. */
|
|
74
74
|
const CHARS_PER_TOKEN = 4;
|
|
75
|
-
/**
|
|
76
|
-
|
|
75
|
+
/**
|
|
76
|
+
* What a script sees of a tool: its description followed by its prompt guidelines, which the system
|
|
77
|
+
* prompt only has for declared tools. Tools without an output schema resolve to their text output.
|
|
78
|
+
*/
|
|
79
|
+
export function toCodemodeDeclaration(tool, guidelines = []) {
|
|
80
|
+
const bullets = guidelines.flatMap((guideline) => (guideline.trim() ? [`- ${guideline.trim()}`] : []));
|
|
77
81
|
return {
|
|
78
82
|
name: tool.name,
|
|
79
|
-
description: tool.description,
|
|
83
|
+
description: bullets.length > 0 ? `${tool.description.trim()}\n\n${bullets.join("\n")}` : tool.description,
|
|
80
84
|
inputSchema: tool.parameters,
|
|
81
85
|
outputSchema: tool.outputSchema ?? TEXT_OUTPUT_SCHEMA,
|
|
82
86
|
};
|
|
@@ -127,7 +131,7 @@ function selectCatalog(groups, budget) {
|
|
|
127
131
|
export function createCodemodeDescription(tools, options = {}) {
|
|
128
132
|
const declarations = getCodemodeCallableTools(tools)
|
|
129
133
|
.filter((tool) => !options.deferred?.has(tool.name))
|
|
130
|
-
.map(toCodemodeDeclaration);
|
|
134
|
+
.map((tool) => toCodemodeDeclaration(tool, options.guidelines?.get(tool.name)));
|
|
131
135
|
const groups = new Map([["", { namespace: undefined, entries: [] }]]);
|
|
132
136
|
for (const declaration of declarations) {
|
|
133
137
|
const namespace = options.namespaces?.get(declaration.name);
|
|
@@ -198,6 +202,8 @@ function describeScriptCall(tool) {
|
|
|
198
202
|
* - `only`: the codemode description lists every callable tool, and requests leave out the
|
|
199
203
|
* declarations of active `direct` tools.
|
|
200
204
|
*
|
|
205
|
+
* Listed tools carry their prompt guidelines, which the system prompt only has for declared tools.
|
|
206
|
+
*
|
|
201
207
|
* Listing by exposure, not by the active set, keeps the codemode description unchanged when
|
|
202
208
|
* `tool_search` loads a tool, so loads do not redeclare codemode.
|
|
203
209
|
*/
|
|
@@ -218,9 +224,11 @@ function prepareCodemodeLoadout(loadout, options) {
|
|
|
218
224
|
const namespace = loadout.getNamespace(tool.name);
|
|
219
225
|
return namespace ? [[tool.name, namespace]] : [];
|
|
220
226
|
}));
|
|
227
|
+
const guidelines = new Map(listed.map((tool) => [tool.name, loadout.getPromptGuidelines(tool.name)]));
|
|
221
228
|
descriptions[CODEMODE_TOOL_NAME] = createCodemodeDescription(listed, {
|
|
222
229
|
models: options.models === true,
|
|
223
230
|
namespaces,
|
|
231
|
+
guidelines,
|
|
224
232
|
deferred: new Set(listed.filter((tool) => loadout.getExposure(tool.name) === "deferred").map((tool) => tool.name)),
|
|
225
233
|
inlineBudget: options.getInlineBudget?.() ?? DEFAULT_CODEMODE_INLINE_BUDGET,
|
|
226
234
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool.js","sourceRoot":"","sources":["../../../src/extensions/codemode/tool.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAGjC,OAAO,EACN,uBAAuB,EACvB,0BAA0B,EAC1B,oBAAoB,EACpB,gBAAgB,EAChB,oBAAoB,GACpB,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,uBAAuB,EAAE,MAAM,oCAAoC,CAAC;AAC7E,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,WAAW,EAAE,MAAM,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AM,KAAK,IAAI,EAAE,CAAC;QAClF,aAAa,EAAE,UAAU,CAAC,aAAa;QACvC,gBAAgB,EAAE,UAAU,CAAC,gBAAgB;KAC7C,CAAC,CAAC;IACH,OAAO,IAAI,CAAC;AACb,CAAC","sourcesContent":["/**\n * The `codemode` tool: the model writes JavaScript that calls other tools. Scripts use `tools`,\n * `ALL_TOOLS`, `text()`, `image()`, `exit()`, `store()`/`load()`, `console.*`, and `return <value>`,\n * may start with a `// @options:` line, and reach the model catalog, classifiers, and image models\n * through `models.*`. Results start with a \"Script completed\" or \"Script failed\" header.\n *\n * Scripts can call the agent loop's nested tools: active `direct` tools and every `codemode` or\n * `deferred` tool. Nested calls run through the agent loop's tool pipeline (`ctx.executeTool`), so\n * validation, `tool_call`/`tool_result` hooks, and permission checks apply exactly as for direct\n * calls. Only the script's output reaches the model; nested results do not.\n *\n * Nested results are handed to the script as follows:\n * - A tool that declares `outputSchema` resolves to its `structuredContent`, also for error\n * results that carry one (MCP tools resolve to their `CallToolResult`, including `isError`).\n * - Any other tool resolves to its text content as one string.\n * - A failed, blocked, or invalid call rejects with an Error carrying the tool's error text.\n *\n * A script that fails returns a normal error result that keeps its partial output, followed by\n * \"Script error:\" and the error. `store(key, value)` and `load(key)` keep JSON values across\n * calls; successful scripts append their writes to the session as `codemode-store` custom entries,\n * so each branch sees the values written on its own path.\n */\n\nimport { join } from \"node:path\";\nimport type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport type { CodemodeJsonSchema, CodemodeTool } from \"@earendil-works/pi-codemode\";\nimport {\n\tMCP_TYPESCRIPT_PREAMBLE,\n\tmcpStructuredContentSchema,\n\trenderToolOutputType,\n\trenderToolSample,\n\ttoCodemodeIdentifier,\n} from \"@earendil-works/pi-codemode/declarations\";\nimport { CODEMODE_SOURCE_GRAMMAR } from \"@earendil-works/pi-codemode/source\";\nimport { type Static, Type } from \"typebox\";\nimport { getDocsPath } from \"../../config.ts\";\nimport type {\n\tToolDefinition,\n\tToolInfo,\n\tToolLoadout,\n\tToolLoadoutChanges,\n\tToolNamespace,\n} from \"../../core/extensions/types.ts\";\nimport type { ModelRegistry } from \"../../core/model-registry.ts\";\nimport type { CodemodeMode } from \"../../core/settings-manager.ts\";\nimport { wrapToolDefinition } from \"../../core/tools/tool-definition-wrapper.ts\";\nimport { loadCodemodeExecutor } from \"./execute.lazy.ts\";\nimport { codemodeRenderers } from \"./renderer.ts\";\n\nexport const CODEMODE_TOOL_NAME = \"codemode\";\n\n/** Custom entry type holding one script's `store()` writes: {@link CodemodeStoreEntryData}. */\nexport const CODEMODE_STORE_ENTRY_TYPE = \"codemode-store\";\n\nexport interface CodemodeStoreEntryData {\n\tset: Record<string, unknown>;\n\tdelete: string[];\n}\n\n/** The part of the model registry that scripts reach through `models`. */\nexport type CodemodeModelRuntime = Pick<\n\tModelRegistry,\n\t\"getModelsOfType\" | \"getAvailableOfType\" | \"getModelOfType\" | \"classify\" | \"generateImages\"\n>;\n\nexport interface CodemodeToolOptions {\n\t/** Namespace of a tool, for `searchTools()` ranking and its `namespace` filter. */\n\tgetToolNamespace?: (toolName: string) => ToolNamespace | undefined;\n\t/**\n\t * Expose the `models` namespace to scripts, backed by the session's model registry\n\t * (`ctx.modelRegistry`). Without it, `models` is not declared.\n\t */\n\tmodels?: boolean;\n\t/**\n\t * Persists `store()` writes as a session custom entry. Without it, writes last only for the\n\t * current script; `load()` still reads entries already on the branch.\n\t */\n\tappendEntry?: (customType: string, data: CodemodeStoreEntryData) => void;\n\t/** How the tool presents the loadout while active (the `codemode.mode` setting). Default: `on`. */\n\tgetMode?: () => CodemodeMode;\n\t/** Token budget for tool declarations in the description. Default: {@link DEFAULT_CODEMODE_INLINE_BUDGET}. */\n\tgetInlineBudget?: () => number | undefined;\n}\n\nconst TEXT_OUTPUT_SCHEMA: CodemodeJsonSchema = { type: \"string\" };\n\nexport const codemodeSchema = Type.Object({\n\tcode: Type.String({\n\t\tdescription: \"Raw JavaScript source.\",\n\t}),\n});\n\nexport type CodemodeToolInput = Static<typeof codemodeSchema>;\n\n/**\n * Whether a registered tool is this package's `codemode` tool rather than another extension's tool\n * with the same name. Compares the parameter schema, which the definition passes through by reference.\n */\nexport function isCodemodeTool(tool: Pick<ToolInfo, \"name\" | \"parameters\">): boolean {\n\treturn tool.name === CODEMODE_TOOL_NAME && tool.parameters === codemodeSchema;\n}\n\nexport type CodemodeNestedCallStatus = \"running\" | \"ok\" | \"error\" | \"cancelled\";\n\nexport interface CodemodeNestedCall {\n\t/** Tool call id of the nested call, `<codemode call id>/<n>`. */\n\tid: string;\n\tname: string;\n\t/** Compact JSON of the arguments, truncated for display. */\n\targs: string;\n\tstatus: CodemodeNestedCallStatus;\n\tdurationMs?: number;\n\t/** Error text, truncated for display. */\n\terror?: string;\n\t/** Cost in USD of a `models.*` call that reported usage. */\n\tcost?: number;\n}\n\nexport interface CodemodeToolDetails {\n\tcalls: CodemodeNestedCall[];\n\t/** Temp file with the full text output, when the output was truncated. */\n\tfullOutputPath?: string;\n}\n\nexport const codemodeToolSystemPromptContribution = {\n\tsnippet: \"Run JavaScript that calls other tools\",\n\tguidelines: [\n\t\t\"Use codemode to batch independent tool calls (Promise.allSettled), chain them, or filter large output, instead of many separate calls.\",\n\t],\n} as const;\n\n/** The reference for scripts: globals, tool results, `store()`, the `models` API, and limits. */\nexport const CODEMODE_DOCS_PATH = join(getDocsPath(), \"codemode.md\");\n\nconst DESCRIPTION_INTRO = `Run JavaScript that calls other tools. The input is raw JavaScript (not JSON, no code fence), run as an async function body in a QuickJS sandbox: top-level \\`await\\` and \\`return\\` work. No Node, file system, network, or timers.\n- \\`await tools.<name>({ ...args })\\` resolves to a string, or an object if the tool's declaration says so, and rejects with an Error on failure. Calls still running when the script ends are cancelled.\n- Optional first line: \\`// @options: {\"max_output_tokens\": 10000, \"timeout_ms\": 60000}\\``;\n\n/** One line per global. The details live in {@link CODEMODE_DOCS_PATH}. */\nfunction describeGlobals(models: boolean): string {\n\tconst lines = [\n\t\t\"Globals:\",\n\t\t\"- `text(value)`, `image(dataUrlOrImageBlock)`, `console.log(...)`, and top-level `return` add output; `exit()` ends the script. `image()` also saves the image to a temp file and the result names its path.\",\n\t\t\"- `store(key, value)` and `load(key)` keep JSON values across codemode calls.\",\n\t\t\"- `ALL_TOOLS`, `searchTools(query, { limit?, namespace? })`, `describeTool(name)`, `describeNamespace(name)`: find unlisted tools, such as MCP tools.\",\n\t];\n\tif (models) {\n\t\tlines.push(`- \\`models\\`: classifiers and image generation. Read ${CODEMODE_DOCS_PATH} first.`);\n\t}\n\treturn lines.join(\"\\n\");\n}\n\n/** Default for {@link CodemodeDescriptionOptions.inlineBudget}, in estimated tokens. */\nexport const DEFAULT_CODEMODE_INLINE_BUDGET = 3000;\n/** Characters per token when estimating the cost of a tool section. */\nconst CHARS_PER_TOKEN = 4;\n\n/** What a script sees of a tool. Tools without an output schema resolve to their text output. */\nexport function toCodemodeDeclaration(tool: AgentTool<any>): Omit<CodemodeTool, \"execute\"> {\n\treturn {\n\t\tname: tool.name,\n\t\tdescription: tool.description,\n\t\tinputSchema: tool.parameters as CodemodeJsonSchema,\n\t\toutputSchema: (tool.outputSchema as CodemodeJsonSchema | undefined) ?? TEXT_OUTPUT_SCHEMA,\n\t};\n}\n\n/** Tools a script may call: every given tool except the codemode tool itself. */\nexport function getCodemodeCallableTools(tools: readonly AgentTool<any>[]): AgentTool<any>[] {\n\treturn tools.filter((tool) => tool.name !== CODEMODE_TOOL_NAME);\n}\n\nexport interface CodemodeDescriptionOptions {\n\t/** Declare the `models` namespace; only for tools created with model access. */\n\tmodels?: boolean;\n\t/** Namespace of each tool, by tool name. Tools of one namespace are listed under one heading. */\n\tnamespaces?: ReadonlyMap<string, ToolNamespace>;\n\t/** Tools that are callable but never listed with their declaration (`deferred` exposure). */\n\tdeferred?: ReadonlySet<string>;\n\t/**\n\t * Estimated tokens (characters / 4) the tool sections may use. Tools that do not fit are left\n\t * out, like deferred tools. Unset lists every tool that is not deferred.\n\t */\n\tinlineBudget?: number;\n}\n\n/** `### \\`id\\` (\\`raw name\\`)` followed by the tool's description and declaration. */\nfunction renderToolSection(declaration: Omit<CodemodeTool, \"execute\">): string {\n\tconst id = toCodemodeIdentifier(declaration.name);\n\tconst heading = id === declaration.name ? `### \\`${id}\\`` : `### \\`${id}\\` (\\`${declaration.name}\\`)`;\n\treturn `${heading}\\n${renderToolSample(declaration).trim()}`;\n}\n\ninterface CatalogEntry {\n\tname: string;\n\tsection: string;\n\tcost: number;\n}\n\ninterface CatalogGroup {\n\tnamespace: ToolNamespace | undefined;\n\tentries: CatalogEntry[];\n}\n\n/**\n * Pick the tool sections that fit the budget, like OpenCode's catalog: in each round every group\n * (tools without a namespace first, then namespaces by name) places its cheapest remaining tool; a\n * group whose next tool does not fit drops out while the others continue. Every namespace is\n * represented before any namespace is complete.\n */\nfunction selectCatalog(groups: readonly CatalogGroup[], budget: number | undefined): Set<string> {\n\tif (budget === undefined) return new Set(groups.flatMap((group) => group.entries.map((entry) => entry.name)));\n\tconst queues = groups.map((group) => [...group.entries].sort((a, b) => a.cost - b.cost));\n\tconst shown = new Set<string>();\n\tlet remaining = budget;\n\tlet active = queues.filter((queue) => queue.length > 0);\n\twhile (active.length > 0) {\n\t\tactive = active.filter((queue) => {\n\t\t\tconst next = queue[0];\n\t\t\tif (next.cost > remaining) return false;\n\t\t\tremaining -= next.cost;\n\t\t\tshown.add(next.name);\n\t\t\tqueue.shift();\n\t\t\treturn queue.length > 0;\n\t\t});\n\t}\n\treturn shown;\n}\n\n/**\n * Model-facing description: the helper list, guidance for finding tools that are not listed, the\n * shared MCP types when listed tools need them, the `models` API, and one section per listed tool,\n * grouped by namespace. Deferred tools are never listed and do not affect the description at all, so\n * it stays the same while MCP servers connect or change their tools. Tool sections are limited to\n * `inlineBudget`.\n */\nexport function createCodemodeDescription(\n\ttools: readonly AgentTool<any>[],\n\toptions: CodemodeDescriptionOptions = {},\n): string {\n\tconst declarations = getCodemodeCallableTools(tools)\n\t\t.filter((tool) => !options.deferred?.has(tool.name))\n\t\t.map(toCodemodeDeclaration);\n\tconst groups = new Map<string, CatalogGroup>([[\"\", { namespace: undefined, entries: [] }]]);\n\tfor (const declaration of declarations) {\n\t\tconst namespace = options.namespaces?.get(declaration.name);\n\t\tconst key = namespace ? `ns:${namespace.name}` : \"\";\n\t\tconst group = groups.get(key) ?? { namespace, entries: [] };\n\t\tgroups.set(key, group);\n\t\tconst section = renderToolSection(declaration);\n\t\tgroup.entries.push({ name: declaration.name, section, cost: Math.ceil(section.length / CHARS_PER_TOKEN) });\n\t}\n\tconst ordered = [...groups.values()].sort((a, b) =>\n\t\ta.namespace === undefined ? -1 : b.namespace === undefined ? 1 : a.namespace.name.localeCompare(b.namespace.name),\n\t);\n\tconst shown = selectCatalog(ordered, options.inlineBudget);\n\n\tconst sections = [DESCRIPTION_INTRO, describeGlobals(options.models === true)];\n\tif (\n\t\tdeclarations.some(\n\t\t\t(declaration) =>\n\t\t\t\tshown.has(declaration.name) && mcpStructuredContentSchema(declaration.outputSchema) !== undefined,\n\t\t)\n\t) {\n\t\tsections.push(`Shared MCP Types:\\n\\`\\`\\`ts\\n${MCP_TYPESCRIPT_PREAMBLE}\\n\\`\\`\\``);\n\t}\n\tif (declarations.length === 0) return sections.join(\"\\n\\n\");\n\n\tconst toolSections = [\"Nested tools:\"];\n\tfor (const { namespace, entries } of ordered) {\n\t\tconst visible = entries.filter((entry) => shown.has(entry.name));\n\t\tif (namespace) {\n\t\t\t// Only tools that did not fit the budget are counted as not listed here.\n\t\t\tconst listing =\n\t\t\t\tvisible.length === entries.length\n\t\t\t\t\t? \"\"\n\t\t\t\t\t: visible.length === 0\n\t\t\t\t\t\t? \" (tools not listed)\"\n\t\t\t\t\t\t: \" (some tools not listed)\";\n\t\t\tconst description = namespace.description?.trim();\n\t\t\ttoolSections.push(`## ${namespace.name}${listing}${description ? `\\n${description}` : \"\"}`);\n\t\t}\n\t\tfor (const entry of visible) toolSections.push(entry.section);\n\t}\n\tsections.push(toolSections.join(\"\\n\\n\"));\n\treturn sections.join(\"\\n\\n\");\n}\n\n/**\n * What a script call resolves to, in one line: `a string`, the field names of an object\n * (`{ output, exit_code, full_output_path? }`), or the rendered type for anything else.\n */\nfunction describeOutput(schema: CodemodeJsonSchema | undefined): string {\n\tconst type = renderToolOutputType(schema);\n\tif (type === \"string\") return \"a string\";\n\tconst object = typeof schema === \"object\" ? schema : undefined;\n\tconst properties = object?.properties;\n\tif (\n\t\tobject?.type === \"object\" &&\n\t\ttypeof properties === \"object\" &&\n\t\tproperties !== null &&\n\t\tmcpStructuredContentSchema(schema) === undefined\n\t) {\n\t\tconst required = new Set(Array.isArray(object.required) ? object.required : []);\n\t\tconst fields = Object.keys(properties).map((name) => (required.has(name) ? name : `${name}?`));\n\t\treturn `\\`{ ${fields.join(\", \")} }\\``;\n\t}\n\treturn `\\`${type.replace(/\\s+/g, \" \")}\\``;\n}\n\n/**\n * A declared tool's description followed by how scripts call it and what the call resolves to. The\n * arguments are the tool's declared parameters, so they are not repeated.\n */\nfunction describeScriptCall(tool: AgentTool<any>): string {\n\treturn `${tool.description.trim()}\\n\\nCodemode: \\`tools.${toCodemodeIdentifier(tool.name)}(args)\\` resolves to ${describeOutput(toCodemodeDeclaration(tool).outputSchema)}.`;\n}\n\n/**\n * How the codemode tool presents tools that are both declared and callable from scripts:\n * - `on`: their descriptions say how scripts call them, and the codemode description\n * lists only the callable tools without `direct` exposure.\n * - `only`: the codemode description lists every callable tool, and requests leave out the\n * declarations of active `direct` tools.\n *\n * Listing by exposure, not by the active set, keeps the codemode description unchanged when\n * `tool_search` loads a tool, so loads do not redeclare codemode.\n */\nfunction prepareCodemodeLoadout(loadout: ToolLoadout, options: CodemodeToolOptions): ToolLoadoutChanges {\n\tconst mode = options.getMode?.() ?? \"on\";\n\tconst isDirect = (tool: AgentTool) => loadout.getExposure(tool.name) === \"direct\";\n\tconst callable = getCodemodeCallableTools(loadout.callable);\n\tconst callableNames = new Set(callable.map((tool) => tool.name));\n\tconst descriptions: Record<string, string> = {};\n\tif (mode === \"on\") {\n\t\tfor (const tool of loadout.declared) {\n\t\t\tif (callableNames.has(tool.name)) descriptions[tool.name] = describeScriptCall(tool);\n\t\t}\n\t}\n\tconst listed = mode === \"only\" ? callable : callable.filter((tool) => !isDirect(tool));\n\tconst namespaces = new Map(\n\t\tlisted.flatMap((tool) => {\n\t\t\tconst namespace = loadout.getNamespace(tool.name);\n\t\t\treturn namespace ? [[tool.name, namespace] as const] : [];\n\t\t}),\n\t);\n\tdescriptions[CODEMODE_TOOL_NAME] = createCodemodeDescription(listed, {\n\t\tmodels: options.models === true,\n\t\tnamespaces,\n\t\tdeferred: new Set(\n\t\t\tlisted.filter((tool) => loadout.getExposure(tool.name) === \"deferred\").map((tool) => tool.name),\n\t\t),\n\t\tinlineBudget: options.getInlineBudget?.() ?? DEFAULT_CODEMODE_INLINE_BUDGET,\n\t});\n\tconst declaredNames = new Set(loadout.declared.map((tool) => tool.name));\n\treturn {\n\t\tdescriptions,\n\t\thiddenDeclarations:\n\t\t\tmode === \"only\"\n\t\t\t\t? callable.filter((tool) => isDirect(tool) && declaredNames.has(tool.name)).map((tool) => tool.name)\n\t\t\t\t: [],\n\t};\n}\n\nexport function createCodemodeToolDefinition(\n\toptions: CodemodeToolOptions = {},\n): ToolDefinition<typeof codemodeSchema, CodemodeToolDetails | undefined> {\n\treturn {\n\t\tname: CODEMODE_TOOL_NAME,\n\t\tlabel: CODEMODE_TOOL_NAME,\n\t\t// Replaced with the declarations of the callable tools when the tool is activated.\n\t\tdescription: createCodemodeDescription([], { models: options.models === true }),\n\t\tpromptSnippet: codemodeToolSystemPromptContribution.snippet,\n\t\tpromptGuidelines: [...codemodeToolSystemPromptContribution.guidelines],\n\t\tparameters: codemodeSchema,\n\t\t// Scripts must not start other scripts.\n\t\texposure: \"model-only\",\n\t\tprepareLoadout: (loadout) => prepareCodemodeLoadout(loadout, options),\n\t\t// Capable models write the script as raw text instead of a JSON-escaped string.\n\t\tconstrainedSampling: { type: \"grammar\", variants: { openai_lark: CODEMODE_SOURCE_GRAMMAR } },\n\t\t// The sandbox (worker, QuickJS wasm) loads on the first call, not at startup.\n\t\texecute: async (toolCallId, params, signal, onUpdate, ctx) =>\n\t\t\t(await loadCodemodeExecutor()).executeCodemode(toolCallId, params, signal, onUpdate, ctx, options),\n\t\t...codemodeRenderers,\n\t};\n}\n\n/**\n * Create the codemode tool as an AgentTool. The description lists the given tools; the script can\n * call whatever tools the agent loop provides at execution time.\n */\nexport function createCodemodeTool(\n\ttools: readonly AgentTool<any>[] = [],\n\toptions: CodemodeToolOptions = {},\n): AgentTool<typeof codemodeSchema> {\n\tconst definition = createCodemodeToolDefinition(options);\n\tconst tool = wrapToolDefinition(definition);\n\tObject.assign(tool, {\n\t\tdescription: createCodemodeDescription(tools, { models: options.models === true }),\n\t\tpromptSnippet: definition.promptSnippet,\n\t\tpromptGuidelines: definition.promptGuidelines,\n\t});\n\treturn tool;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"tool.js","sourceRoot":"","sources":["../../../src/extensions/codemode/tool.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAGjC,OAAO,EACN,uBAAuB,EACvB,0BAA0B,EAC1B,oBAAoB,EACpB,gBAAgB,EAChB,oBAAoB,GACpB,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,uBAAuB,EAAE,MAAM,oCAAoC,CAAC;AAC7E,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAU9C,OAAO,EAAE,kBAAkB,EAAE,MAAM,6CAA6C,CAAC;AACjF,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAElD,MAAM,CAAC,MAAM,kBAAkB,GAAG,UAAU,CAAC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AE,CAC5D,CAAC,MAAM,oBAAoB,EAAE,CAAC,CAAC,eAAe,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,EAAE,OAAO,CAAC;QACnG,GAAG,iBAAiB;KACpB,CAAC;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,kBAAkB,CACjC,KAAK,GAA8B,EAAE,EACrC,OAAO,GAAwB,EAAE;IAEjC,MAAM,UAAU,GAAG,4BAA4B,CAAC,OAAO,CAAC,CAAC;IACzD,MAAM,IAAI,GAAG,kBAAkB,CAAC,UAAU,CAAC,CAAC;IAC5C,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE;QACnB,WAAW,EAAE,yBAAyB,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,KAAK,IAAI,EAAE,CAAC;QAClF,aAAa,EAAE,UAAU,CAAC,aAAa;QACvC,gBAAgB,EAAE,UAAU,CAAC,gBAAgB;KAC7C,CAAC,CAAC;IACH,OAAO,IAAI,CAAC;AACb,CAAC","sourcesContent":["/**\n * The `codemode` tool: the model writes JavaScript that calls other tools. Scripts use `tools`,\n * `ALL_TOOLS`, `text()`, `image()`, `exit()`, `store()`/`load()`, `console.*`, and `return <value>`,\n * may start with a `// @options:` line, and reach the model catalog, classifiers, and image models\n * through `models.*`. Results start with a \"Script completed\" or \"Script failed\" header.\n *\n * Scripts can call the agent loop's nested tools: active `direct` tools and every `codemode` or\n * `deferred` tool. Nested calls run through the agent loop's tool pipeline (`ctx.executeTool`), so\n * validation, `tool_call`/`tool_result` hooks, and permission checks apply exactly as for direct\n * calls. Only the script's output reaches the model; nested results do not.\n *\n * Nested results are handed to the script as follows:\n * - A tool that declares `outputSchema` resolves to its `structuredContent`, also for error\n * results that carry one (MCP tools resolve to their `CallToolResult`, including `isError`).\n * - Any other tool resolves to its text content as one string.\n * - A failed, blocked, or invalid call rejects with an Error carrying the tool's error text.\n *\n * A script that fails returns a normal error result that keeps its partial output, followed by\n * \"Script error:\" and the error. `store(key, value)` and `load(key)` keep JSON values across\n * calls; successful scripts append their writes to the session as `codemode-store` custom entries,\n * so each branch sees the values written on its own path.\n */\n\nimport { join } from \"node:path\";\nimport type { AgentTool } from \"@earendil-works/pi-agent-core\";\nimport type { CodemodeJsonSchema, CodemodeTool } from \"@earendil-works/pi-codemode\";\nimport {\n\tMCP_TYPESCRIPT_PREAMBLE,\n\tmcpStructuredContentSchema,\n\trenderToolOutputType,\n\trenderToolSample,\n\ttoCodemodeIdentifier,\n} from \"@earendil-works/pi-codemode/declarations\";\nimport { CODEMODE_SOURCE_GRAMMAR } from \"@earendil-works/pi-codemode/source\";\nimport { type Static, Type } from \"typebox\";\nimport { getDocsPath } from \"../../config.ts\";\nimport type {\n\tToolDefinition,\n\tToolInfo,\n\tToolLoadout,\n\tToolLoadoutChanges,\n\tToolNamespace,\n} from \"../../core/extensions/types.ts\";\nimport type { ModelRegistry } from \"../../core/model-registry.ts\";\nimport type { CodemodeMode } from \"../../core/settings-manager.ts\";\nimport { wrapToolDefinition } from \"../../core/tools/tool-definition-wrapper.ts\";\nimport { loadCodemodeExecutor } from \"./execute.lazy.ts\";\nimport { codemodeRenderers } from \"./renderer.ts\";\n\nexport const CODEMODE_TOOL_NAME = \"codemode\";\n\n/** Custom entry type holding one script's `store()` writes: {@link CodemodeStoreEntryData}. */\nexport const CODEMODE_STORE_ENTRY_TYPE = \"codemode-store\";\n\nexport interface CodemodeStoreEntryData {\n\tset: Record<string, unknown>;\n\tdelete: string[];\n}\n\n/** The part of the model registry that scripts reach through `models`. */\nexport type CodemodeModelRuntime = Pick<\n\tModelRegistry,\n\t\"getModelsOfType\" | \"getAvailableOfType\" | \"getModelOfType\" | \"classify\" | \"generateImages\"\n>;\n\nexport interface CodemodeToolOptions {\n\t/** Namespace of a tool, for `searchTools()` ranking and its `namespace` filter. */\n\tgetToolNamespace?: (toolName: string) => ToolNamespace | undefined;\n\t/** Prompt guidelines of every tool, by tool name, shown with declarations by `describeTool()` and `ALL_TOOLS`. */\n\tgetToolGuidelines?: () => ReadonlyMap<string, readonly string[]>;\n\t/**\n\t * Expose the `models` namespace to scripts, backed by the session's model registry\n\t * (`ctx.modelRegistry`). Without it, `models` is not declared.\n\t */\n\tmodels?: boolean;\n\t/**\n\t * Persists `store()` writes as a session custom entry. Without it, writes last only for the\n\t * current script; `load()` still reads entries already on the branch.\n\t */\n\tappendEntry?: (customType: string, data: CodemodeStoreEntryData) => void;\n\t/** How the tool presents the loadout while active (the `codemode.mode` setting). Default: `on`. */\n\tgetMode?: () => CodemodeMode;\n\t/** Token budget for tool declarations in the description. Default: {@link DEFAULT_CODEMODE_INLINE_BUDGET}. */\n\tgetInlineBudget?: () => number | undefined;\n}\n\nconst TEXT_OUTPUT_SCHEMA: CodemodeJsonSchema = { type: \"string\" };\n\nexport const codemodeSchema = Type.Object({\n\tcode: Type.String({\n\t\tdescription: \"Raw JavaScript source.\",\n\t}),\n});\n\nexport type CodemodeToolInput = Static<typeof codemodeSchema>;\n\n/**\n * Whether a registered tool is this package's `codemode` tool rather than another extension's tool\n * with the same name. Compares the parameter schema, which the definition passes through by reference.\n */\nexport function isCodemodeTool(tool: Pick<ToolInfo, \"name\" | \"parameters\">): boolean {\n\treturn tool.name === CODEMODE_TOOL_NAME && tool.parameters === codemodeSchema;\n}\n\nexport type CodemodeNestedCallStatus = \"running\" | \"ok\" | \"error\" | \"cancelled\";\n\nexport interface CodemodeNestedCall {\n\t/** Tool call id of the nested call, `<codemode call id>/<n>`. */\n\tid: string;\n\tname: string;\n\t/** Compact JSON of the arguments, truncated for display. */\n\targs: string;\n\tstatus: CodemodeNestedCallStatus;\n\tdurationMs?: number;\n\t/** Error text, truncated for display. */\n\terror?: string;\n\t/** Cost in USD of a `models.*` call that reported usage. */\n\tcost?: number;\n}\n\nexport interface CodemodeToolDetails {\n\tcalls: CodemodeNestedCall[];\n\t/** Temp file with the full text output, when the output was truncated. */\n\tfullOutputPath?: string;\n}\n\nexport const codemodeToolSystemPromptContribution = {\n\tsnippet: \"Run JavaScript that calls other tools\",\n\tguidelines: [\n\t\t\"Use codemode to batch independent tool calls (Promise.allSettled), chain them, or filter large output, instead of many separate calls.\",\n\t],\n} as const;\n\n/** The reference for scripts: globals, tool results, `store()`, the `models` API, and limits. */\nexport const CODEMODE_DOCS_PATH = join(getDocsPath(), \"codemode.md\");\n\nconst DESCRIPTION_INTRO = `Run JavaScript that calls other tools. The input is raw JavaScript (not JSON, no code fence), run as an async function body in a QuickJS sandbox: top-level \\`await\\` and \\`return\\` work. No Node, file system, network, or timers.\n- \\`await tools.<name>({ ...args })\\` resolves to a string, or an object if the tool's declaration says so, and rejects with an Error on failure. Calls still running when the script ends are cancelled.\n- Optional first line: \\`// @options: {\"max_output_tokens\": 10000, \"timeout_ms\": 60000}\\``;\n\n/** One line per global. The details live in {@link CODEMODE_DOCS_PATH}. */\nfunction describeGlobals(models: boolean): string {\n\tconst lines = [\n\t\t\"Globals:\",\n\t\t\"- `text(value)`, `image(dataUrlOrImageBlock)`, `console.log(...)`, and top-level `return` add output; `exit()` ends the script. With several text items, each starts with a `==> text N/M <==` line, and `console` lines follow the other output in one `<console_output>` block. `image()` also saves the image to a temp file and the result names its path.\",\n\t\t\"- `store(key, value)` and `load(key)` keep JSON values across codemode calls.\",\n\t\t\"- `ALL_TOOLS`, `await searchTools(query, { limit?, namespace? })`, `await describeTool(name)`, `await describeNamespace(name)`: find unlisted tools, such as MCP tools.\",\n\t];\n\tif (models) {\n\t\tlines.push(`- \\`models\\`: classifiers and image generation. Read ${CODEMODE_DOCS_PATH} first.`);\n\t}\n\treturn lines.join(\"\\n\");\n}\n\n/** Default for {@link CodemodeDescriptionOptions.inlineBudget}, in estimated tokens. */\nexport const DEFAULT_CODEMODE_INLINE_BUDGET = 3000;\n/** Characters per token when estimating the cost of a tool section. */\nconst CHARS_PER_TOKEN = 4;\n\n/**\n * What a script sees of a tool: its description followed by its prompt guidelines, which the system\n * prompt only has for declared tools. Tools without an output schema resolve to their text output.\n */\nexport function toCodemodeDeclaration(\n\ttool: AgentTool<any>,\n\tguidelines: readonly string[] = [],\n): Omit<CodemodeTool, \"execute\"> {\n\tconst bullets = guidelines.flatMap((guideline) => (guideline.trim() ? [`- ${guideline.trim()}`] : []));\n\treturn {\n\t\tname: tool.name,\n\t\tdescription: bullets.length > 0 ? `${tool.description.trim()}\\n\\n${bullets.join(\"\\n\")}` : tool.description,\n\t\tinputSchema: tool.parameters as CodemodeJsonSchema,\n\t\toutputSchema: (tool.outputSchema as CodemodeJsonSchema | undefined) ?? TEXT_OUTPUT_SCHEMA,\n\t};\n}\n\n/** Tools a script may call: every given tool except the codemode tool itself. */\nexport function getCodemodeCallableTools(tools: readonly AgentTool<any>[]): AgentTool<any>[] {\n\treturn tools.filter((tool) => tool.name !== CODEMODE_TOOL_NAME);\n}\n\nexport interface CodemodeDescriptionOptions {\n\t/** Declare the `models` namespace; only for tools created with model access. */\n\tmodels?: boolean;\n\t/** Namespace of each tool, by tool name. Tools of one namespace are listed under one heading. */\n\tnamespaces?: ReadonlyMap<string, ToolNamespace>;\n\t/** Tools that are callable but never listed with their declaration (`deferred` exposure). */\n\tdeferred?: ReadonlySet<string>;\n\t/** Prompt guidelines of each tool, by tool name, listed after its description. */\n\tguidelines?: ReadonlyMap<string, readonly string[]>;\n\t/**\n\t * Estimated tokens (characters / 4) the tool sections may use. Tools that do not fit are left\n\t * out, like deferred tools. Unset lists every tool that is not deferred.\n\t */\n\tinlineBudget?: number;\n}\n\n/** `### \\`id\\` (\\`raw name\\`)` followed by the tool's description and declaration. */\nfunction renderToolSection(declaration: Omit<CodemodeTool, \"execute\">): string {\n\tconst id = toCodemodeIdentifier(declaration.name);\n\tconst heading = id === declaration.name ? `### \\`${id}\\`` : `### \\`${id}\\` (\\`${declaration.name}\\`)`;\n\treturn `${heading}\\n${renderToolSample(declaration).trim()}`;\n}\n\ninterface CatalogEntry {\n\tname: string;\n\tsection: string;\n\tcost: number;\n}\n\ninterface CatalogGroup {\n\tnamespace: ToolNamespace | undefined;\n\tentries: CatalogEntry[];\n}\n\n/**\n * Pick the tool sections that fit the budget, like OpenCode's catalog: in each round every group\n * (tools without a namespace first, then namespaces by name) places its cheapest remaining tool; a\n * group whose next tool does not fit drops out while the others continue. Every namespace is\n * represented before any namespace is complete.\n */\nfunction selectCatalog(groups: readonly CatalogGroup[], budget: number | undefined): Set<string> {\n\tif (budget === undefined) return new Set(groups.flatMap((group) => group.entries.map((entry) => entry.name)));\n\tconst queues = groups.map((group) => [...group.entries].sort((a, b) => a.cost - b.cost));\n\tconst shown = new Set<string>();\n\tlet remaining = budget;\n\tlet active = queues.filter((queue) => queue.length > 0);\n\twhile (active.length > 0) {\n\t\tactive = active.filter((queue) => {\n\t\t\tconst next = queue[0];\n\t\t\tif (next.cost > remaining) return false;\n\t\t\tremaining -= next.cost;\n\t\t\tshown.add(next.name);\n\t\t\tqueue.shift();\n\t\t\treturn queue.length > 0;\n\t\t});\n\t}\n\treturn shown;\n}\n\n/**\n * Model-facing description: the helper list, guidance for finding tools that are not listed, the\n * shared MCP types when listed tools need them, the `models` API, and one section per listed tool,\n * grouped by namespace. Deferred tools are never listed and do not affect the description at all, so\n * it stays the same while MCP servers connect or change their tools. Tool sections are limited to\n * `inlineBudget`.\n */\nexport function createCodemodeDescription(\n\ttools: readonly AgentTool<any>[],\n\toptions: CodemodeDescriptionOptions = {},\n): string {\n\tconst declarations = getCodemodeCallableTools(tools)\n\t\t.filter((tool) => !options.deferred?.has(tool.name))\n\t\t.map((tool) => toCodemodeDeclaration(tool, options.guidelines?.get(tool.name)));\n\tconst groups = new Map<string, CatalogGroup>([[\"\", { namespace: undefined, entries: [] }]]);\n\tfor (const declaration of declarations) {\n\t\tconst namespace = options.namespaces?.get(declaration.name);\n\t\tconst key = namespace ? `ns:${namespace.name}` : \"\";\n\t\tconst group = groups.get(key) ?? { namespace, entries: [] };\n\t\tgroups.set(key, group);\n\t\tconst section = renderToolSection(declaration);\n\t\tgroup.entries.push({ name: declaration.name, section, cost: Math.ceil(section.length / CHARS_PER_TOKEN) });\n\t}\n\tconst ordered = [...groups.values()].sort((a, b) =>\n\t\ta.namespace === undefined ? -1 : b.namespace === undefined ? 1 : a.namespace.name.localeCompare(b.namespace.name),\n\t);\n\tconst shown = selectCatalog(ordered, options.inlineBudget);\n\n\tconst sections = [DESCRIPTION_INTRO, describeGlobals(options.models === true)];\n\tif (\n\t\tdeclarations.some(\n\t\t\t(declaration) =>\n\t\t\t\tshown.has(declaration.name) && mcpStructuredContentSchema(declaration.outputSchema) !== undefined,\n\t\t)\n\t) {\n\t\tsections.push(`Shared MCP Types:\\n\\`\\`\\`ts\\n${MCP_TYPESCRIPT_PREAMBLE}\\n\\`\\`\\``);\n\t}\n\tif (declarations.length === 0) return sections.join(\"\\n\\n\");\n\n\tconst toolSections = [\"Nested tools:\"];\n\tfor (const { namespace, entries } of ordered) {\n\t\tconst visible = entries.filter((entry) => shown.has(entry.name));\n\t\tif (namespace) {\n\t\t\t// Only tools that did not fit the budget are counted as not listed here.\n\t\t\tconst listing =\n\t\t\t\tvisible.length === entries.length\n\t\t\t\t\t? \"\"\n\t\t\t\t\t: visible.length === 0\n\t\t\t\t\t\t? \" (tools not listed)\"\n\t\t\t\t\t\t: \" (some tools not listed)\";\n\t\t\tconst description = namespace.description?.trim();\n\t\t\ttoolSections.push(`## ${namespace.name}${listing}${description ? `\\n${description}` : \"\"}`);\n\t\t}\n\t\tfor (const entry of visible) toolSections.push(entry.section);\n\t}\n\tsections.push(toolSections.join(\"\\n\\n\"));\n\treturn sections.join(\"\\n\\n\");\n}\n\n/**\n * What a script call resolves to, in one line: `a string`, the field names of an object\n * (`{ output, exit_code, full_output_path? }`), or the rendered type for anything else.\n */\nfunction describeOutput(schema: CodemodeJsonSchema | undefined): string {\n\tconst type = renderToolOutputType(schema);\n\tif (type === \"string\") return \"a string\";\n\tconst object = typeof schema === \"object\" ? schema : undefined;\n\tconst properties = object?.properties;\n\tif (\n\t\tobject?.type === \"object\" &&\n\t\ttypeof properties === \"object\" &&\n\t\tproperties !== null &&\n\t\tmcpStructuredContentSchema(schema) === undefined\n\t) {\n\t\tconst required = new Set(Array.isArray(object.required) ? object.required : []);\n\t\tconst fields = Object.keys(properties).map((name) => (required.has(name) ? name : `${name}?`));\n\t\treturn `\\`{ ${fields.join(\", \")} }\\``;\n\t}\n\treturn `\\`${type.replace(/\\s+/g, \" \")}\\``;\n}\n\n/**\n * A declared tool's description followed by how scripts call it and what the call resolves to. The\n * arguments are the tool's declared parameters, so they are not repeated.\n */\nfunction describeScriptCall(tool: AgentTool<any>): string {\n\treturn `${tool.description.trim()}\\n\\nCodemode: \\`tools.${toCodemodeIdentifier(tool.name)}(args)\\` resolves to ${describeOutput(toCodemodeDeclaration(tool).outputSchema)}.`;\n}\n\n/**\n * How the codemode tool presents tools that are both declared and callable from scripts:\n * - `on`: their descriptions say how scripts call them, and the codemode description\n * lists only the callable tools without `direct` exposure.\n * - `only`: the codemode description lists every callable tool, and requests leave out the\n * declarations of active `direct` tools.\n *\n * Listed tools carry their prompt guidelines, which the system prompt only has for declared tools.\n *\n * Listing by exposure, not by the active set, keeps the codemode description unchanged when\n * `tool_search` loads a tool, so loads do not redeclare codemode.\n */\nfunction prepareCodemodeLoadout(loadout: ToolLoadout, options: CodemodeToolOptions): ToolLoadoutChanges {\n\tconst mode = options.getMode?.() ?? \"on\";\n\tconst isDirect = (tool: AgentTool) => loadout.getExposure(tool.name) === \"direct\";\n\tconst callable = getCodemodeCallableTools(loadout.callable);\n\tconst callableNames = new Set(callable.map((tool) => tool.name));\n\tconst descriptions: Record<string, string> = {};\n\tif (mode === \"on\") {\n\t\tfor (const tool of loadout.declared) {\n\t\t\tif (callableNames.has(tool.name)) descriptions[tool.name] = describeScriptCall(tool);\n\t\t}\n\t}\n\tconst listed = mode === \"only\" ? callable : callable.filter((tool) => !isDirect(tool));\n\tconst namespaces = new Map(\n\t\tlisted.flatMap((tool) => {\n\t\t\tconst namespace = loadout.getNamespace(tool.name);\n\t\t\treturn namespace ? [[tool.name, namespace] as const] : [];\n\t\t}),\n\t);\n\tconst guidelines = new Map(listed.map((tool) => [tool.name, loadout.getPromptGuidelines(tool.name)] as const));\n\tdescriptions[CODEMODE_TOOL_NAME] = createCodemodeDescription(listed, {\n\t\tmodels: options.models === true,\n\t\tnamespaces,\n\t\tguidelines,\n\t\tdeferred: new Set(\n\t\t\tlisted.filter((tool) => loadout.getExposure(tool.name) === \"deferred\").map((tool) => tool.name),\n\t\t),\n\t\tinlineBudget: options.getInlineBudget?.() ?? DEFAULT_CODEMODE_INLINE_BUDGET,\n\t});\n\tconst declaredNames = new Set(loadout.declared.map((tool) => tool.name));\n\treturn {\n\t\tdescriptions,\n\t\thiddenDeclarations:\n\t\t\tmode === \"only\"\n\t\t\t\t? callable.filter((tool) => isDirect(tool) && declaredNames.has(tool.name)).map((tool) => tool.name)\n\t\t\t\t: [],\n\t};\n}\n\nexport function createCodemodeToolDefinition(\n\toptions: CodemodeToolOptions = {},\n): ToolDefinition<typeof codemodeSchema, CodemodeToolDetails | undefined> {\n\treturn {\n\t\tname: CODEMODE_TOOL_NAME,\n\t\tlabel: CODEMODE_TOOL_NAME,\n\t\t// Replaced with the declarations of the callable tools when the tool is activated.\n\t\tdescription: createCodemodeDescription([], { models: options.models === true }),\n\t\tpromptSnippet: codemodeToolSystemPromptContribution.snippet,\n\t\tpromptGuidelines: [...codemodeToolSystemPromptContribution.guidelines],\n\t\tparameters: codemodeSchema,\n\t\t// Scripts must not start other scripts.\n\t\texposure: \"model-only\",\n\t\tprepareLoadout: (loadout) => prepareCodemodeLoadout(loadout, options),\n\t\t// Capable models write the script as raw text instead of a JSON-escaped string.\n\t\tconstrainedSampling: { type: \"grammar\", variants: { openai_lark: CODEMODE_SOURCE_GRAMMAR } },\n\t\t// The sandbox (worker, QuickJS wasm) loads on the first call, not at startup.\n\t\texecute: async (toolCallId, params, signal, onUpdate, ctx) =>\n\t\t\t(await loadCodemodeExecutor()).executeCodemode(toolCallId, params, signal, onUpdate, ctx, options),\n\t\t...codemodeRenderers,\n\t};\n}\n\n/**\n * Create the codemode tool as an AgentTool. The description lists the given tools; the script can\n * call whatever tools the agent loop provides at execution time.\n */\nexport function createCodemodeTool(\n\ttools: readonly AgentTool<any>[] = [],\n\toptions: CodemodeToolOptions = {},\n): AgentTool<typeof codemodeSchema> {\n\tconst definition = createCodemodeToolDefinition(options);\n\tconst tool = wrapToolDefinition(definition);\n\tObject.assign(tool, {\n\t\tdescription: createCodemodeDescription(tools, { models: options.models === true }),\n\t\tpromptSnippet: definition.promptSnippet,\n\t\tpromptGuidelines: definition.promptGuidelines,\n\t});\n\treturn tool;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../../../src/extensions/llama/provider.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../../../src/extensions/llama/provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAQN,KAAK,QAAQ,EAGb,MAAM,uBAAuB,CAAC;AAI/B,OAAO,EAEN,KAAK,cAAc,EAInB,MAAM,aAAa,CAAC;AAErB,eAAO,MAAM,iBAAiB,cAAc,CAAC;AAC7C,eAAO,MAAM,wBAAwB,0BAA0B,CAAC;AAwIhE,MAAM,WAAW,uBAAuB;IACvC,QAAQ,EAAE,QAAQ,CAAC,oBAAoB,CAAC,CAAC;IACzC,UAAU,CAAC,MAAM,EAAE,SAAS,cAAc,EAAE,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,cAAc,CAAC,EAAE,OAAO,CAAA;KAAE,GAAG,IAAI,CAAC;CAC/G;AAED,wBAAgB,mBAAmB,IAAI,uBAAuB,CAqI7D"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { isModelType, } from "@earendil-works/pi-ai";
|
|
2
2
|
import { llamaCppClassifyApi } from "@earendil-works/pi-ai/api/llama-cpp-classify.lazy";
|
|
3
|
+
import { typesafeSystemOneApi } from "@earendil-works/pi-ai/api/typesafe-system-one.lazy";
|
|
3
4
|
import { stream, streamSimple } from "@earendil-works/pi-ai/compat";
|
|
4
5
|
import { LlamaClient, llamaInferenceUrl, normalizeLlamaServerUrl, } from "./client.js";
|
|
5
6
|
export const LLAMA_PROVIDER_ID = "llama.cpp";
|
|
@@ -55,20 +56,40 @@ function contextWindowOf(model, cachedContextWindow) {
|
|
|
55
56
|
const trainingContextWindow = model.meta?.n_ctx_train;
|
|
56
57
|
return trainingContextWindow && trainingContextWindow > 0 ? trainingContextWindow : 128000;
|
|
57
58
|
}
|
|
58
|
-
/**
|
|
59
|
+
/**
|
|
60
|
+
* Whether llama.cpp reports a native decision model. Since llama.cpp 0.6.0, `GET /models` lists
|
|
61
|
+
* `decisions` in `architecture.output_modalities` for these models, including unloaded and sleeping ones.
|
|
62
|
+
* Older servers report `["text"]` or omit `architecture`, so their models are treated as chat models.
|
|
63
|
+
*/
|
|
64
|
+
function isDecisionModel(model) {
|
|
65
|
+
return model.architecture?.output_modalities?.includes("decisions") === true;
|
|
66
|
+
}
|
|
67
|
+
/** Decision-only models cannot generate text and are not listed for chat. */
|
|
68
|
+
function isChatModel(model) {
|
|
69
|
+
return !isDecisionModel(model) || model.architecture?.output_modalities?.includes("text") === true;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* A llama.cpp model used as a classifier. Decision models answer natively through llama.cpp's
|
|
73
|
+
* System One endpoint (`/v1/systemone`). Chat models fall back to `llama-cpp-classify`, which reads
|
|
74
|
+
* answers from next-token label probabilities.
|
|
75
|
+
*/
|
|
59
76
|
function toPiClassifierModel(model, serverUrl, cachedContextWindow) {
|
|
77
|
+
const decision = isDecisionModel(model);
|
|
60
78
|
return {
|
|
61
79
|
type: "classifier",
|
|
62
80
|
id: model.id,
|
|
63
81
|
name: model.id,
|
|
64
|
-
api: "llama-cpp-classify",
|
|
82
|
+
api: decision ? "typesafe-system-one" : "llama-cpp-classify",
|
|
65
83
|
provider: LLAMA_PROVIDER_ID,
|
|
66
|
-
baseUrl: serverUrl,
|
|
84
|
+
baseUrl: decision ? llamaInferenceUrl(serverUrl) : serverUrl,
|
|
67
85
|
input: ["text"],
|
|
68
86
|
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
69
87
|
contextWindow: contextWindowOf(model, cachedContextWindow),
|
|
70
88
|
};
|
|
71
89
|
}
|
|
90
|
+
function isLlamaClassifierModel(model) {
|
|
91
|
+
return (isModelType(model, "classifier") && (model.api === "llama-cpp-classify" || model.api === "typesafe-system-one"));
|
|
92
|
+
}
|
|
72
93
|
function toPiModel(model, serverUrl, props, cachedContextWindow) {
|
|
73
94
|
const contextWindow = contextWindowOf(model, cachedContextWindow);
|
|
74
95
|
const reasoning = props?.chat_template?.includes("enable_thinking") === true;
|
|
@@ -100,10 +121,11 @@ function toPiModel(model, serverUrl, props, cachedContextWindow) {
|
|
|
100
121
|
export function createLlamaProvider() {
|
|
101
122
|
let models = [];
|
|
102
123
|
let classifiers = [];
|
|
103
|
-
const
|
|
124
|
+
const fallbackClassifier = llamaCppClassifyApi();
|
|
125
|
+
const decisionClassifier = typesafeSystemOneApi();
|
|
104
126
|
const setCatalog = (catalog, serverUrl, options = {}) => {
|
|
105
127
|
const selectable = catalog.filter((model) => modelIsSelectable(model, options.routerAutoload === true));
|
|
106
|
-
models = selectable.map((model) => toPiModel(model, serverUrl));
|
|
128
|
+
models = selectable.filter(isChatModel).map((model) => toPiModel(model, serverUrl));
|
|
107
129
|
classifiers = selectable.map((model) => toPiClassifierModel(model, serverUrl));
|
|
108
130
|
};
|
|
109
131
|
const provider = {
|
|
@@ -157,7 +179,7 @@ export function createLlamaProvider() {
|
|
|
157
179
|
if (context.stored) {
|
|
158
180
|
const stored = context.stored.models.filter((model) => model.provider === LLAMA_PROVIDER_ID);
|
|
159
181
|
const restored = stored.filter((model) => isModelType(model, "chat") && model.api === "openai-completions");
|
|
160
|
-
const restoredClassifiers = stored.filter(
|
|
182
|
+
const restoredClassifiers = stored.filter(isLlamaClassifierModel);
|
|
161
183
|
for (const model of [...restored, ...restoredClassifiers]) {
|
|
162
184
|
cachedContextWindows.set(model.id, model.contextWindow);
|
|
163
185
|
}
|
|
@@ -183,11 +205,12 @@ export function createLlamaProvider() {
|
|
|
183
205
|
if (context.signal.aborted)
|
|
184
206
|
return;
|
|
185
207
|
const selectable = catalog.filter((model) => modelIsSelectable(model, routerAutoload));
|
|
186
|
-
|
|
208
|
+
// Only loaded models expose their chat template without side effects. Unloaded autoload presets would
|
|
209
|
+
// need to be loaded, while querying sleeping models may wake them. Those models remain without thinking
|
|
210
|
+
// support until they are loaded and a later catalog refresh discovers it. Decision models need no
|
|
211
|
+
// template, and llama.cpp reports them in the catalog regardless of their status.
|
|
212
|
+
const refreshed = await Promise.all(selectable.filter(isChatModel).map(async (model) => {
|
|
187
213
|
const cachedContextWindow = cachedContextWindows.get(model.id);
|
|
188
|
-
// Only loaded models expose their template without side effects. Unloaded autoload presets
|
|
189
|
-
// would need to be loaded, while querying sleeping models may wake them. Those models remain
|
|
190
|
-
// unclassified until they are loaded or woken and a later catalog refresh discovers them.
|
|
191
214
|
if (model.status.value !== "loaded")
|
|
192
215
|
return toPiModel(model, serverUrl, undefined, cachedContextWindow);
|
|
193
216
|
const props = await client.props({ model: model.id, signal: context.signal });
|
|
@@ -206,7 +229,7 @@ export function createLlamaProvider() {
|
|
|
206
229
|
},
|
|
207
230
|
stream: (model, context, options) => stream(model, context, options),
|
|
208
231
|
streamSimple: (model, context, options) => streamSimple(model, context, options),
|
|
209
|
-
classify: (model, context, options) =>
|
|
232
|
+
classify: (model, context, options) => (model.api === "typesafe-system-one" ? decisionClassifier : fallbackClassifier).classify(model, context, options),
|
|
210
233
|
};
|
|
211
234
|
return { provider, setCatalog };
|
|
212
235
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provider.js","sourceRoot":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oBAAoB,GAAG,UAAU,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CACrD,mBAAmB,CAAC,KAAK,EAAE,SAAS,EAAE,oBAAoB,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CACzE,CAAC;YACF,IAAI,OAAO,CAAC,MAAM,CAAC,OAAO;gBAAE,OAAO;YACnC,MAAM,OAAO,CAAC,OAAO,CAAC;gBACrB,OAAO,EAAE,EAAE,MAAM,EAAE,CAAC,GAAG,SAAS,EAAE,GAAG,oBAAoB,CAAC,EAAE,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE;gBACnF,MAAM,EAAE,GAAG,EAAE;oBACZ,MAAM,GAAG,SAAS,CAAC;oBACnB,WAAW,GAAG,oBAAoB,CAAC;gBACpC,CAAC;aACD,CAAC,CAAC;QACJ,CAAC;QACD,MAAM,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,EAAE,OAAO,EAAE,OAA4C,CAAC;QACzG,YAAY,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,CAAC,YAAY,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC;QAChF,QAAQ,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC;KACnF,CAAC;IAEF,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,CAAC;AACjC,CAAC","sourcesContent":["import {\n\ttype ApiKeyCredential,\n\ttype AuthContext,\n\ttype AuthResult,\n\ttype ClassifierModel,\n\tisModelType,\n\ttype Model,\n\ttype Provider,\n\ttype ProviderStreamOptions,\n\ttype RefreshModelsContext,\n} from \"@earendil-works/pi-ai\";\nimport { llamaCppClassifyApi } from \"@earendil-works/pi-ai/api/llama-cpp-classify.lazy\";\nimport { stream, streamSimple } from \"@earendil-works/pi-ai/compat\";\nimport {\n\tLlamaClient,\n\ttype LlamaModelInfo,\n\ttype LlamaServerProps,\n\tllamaInferenceUrl,\n\tnormalizeLlamaServerUrl,\n} from \"./client.ts\";\n\nexport const LLAMA_PROVIDER_ID = \"llama.cpp\";\nexport const DEFAULT_LLAMA_SERVER_URL = \"http://127.0.0.1:8080\";\nfunction credentialServerUrl(credential: ApiKeyCredential | undefined): string | undefined {\n\tconst value = credential?.env?.LLAMA_BASE_URL;\n\treturn typeof value === \"string\" && value.trim() ? normalizeLlamaServerUrl(value) : undefined;\n}\n\nasync function resolveServerUrl(\n\tctx: AuthContext,\n\tcredential: ApiKeyCredential | undefined,\n): Promise<string | undefined> {\n\tconst configured = credentialServerUrl(credential) ?? (await ctx.env(\"LLAMA_BASE_URL\"))?.trim();\n\treturn configured ? normalizeLlamaServerUrl(configured) : undefined;\n}\n\nfunction modelIsSelectable(model: LlamaModelInfo, routerAutoload: boolean): boolean {\n\tif (model.status.value === \"loaded\") return true;\n\t// llama.cpp reports idle-slept models as \"sleeping\"; requests wake them automatically.\n\tif (model.status.value === \"sleeping\") return true;\n\t// Unloaded presets are routable only when llama.cpp router autoload can load them on first use.\n\treturn routerAutoload && model.status.value === \"unloaded\" && !model.status.failed && model.source === \"preset\";\n}\n\nasync function routerAutoloadEnabled(\n\tclient: LlamaClient,\n\tcatalog: readonly LlamaModelInfo[],\n\tsignal: AbortSignal,\n): Promise<boolean> {\n\tif (!catalog.some((model) => model.status.value === \"unloaded\" && model.source === \"preset\")) return false;\n\ttry {\n\t\treturn (await client.props({ signal })).models_autoload === true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction configuredContextWindow(model: LlamaModelInfo): number | undefined {\n\tconst args = model.status.args ?? [];\n\tfor (let index = 0; index < args.length - 1; index++) {\n\t\tconst flag = args[index];\n\t\tif (flag !== \"--ctx-size\" && flag !== \"-c\" && flag !== \"-ctx\") continue;\n\t\tconst contextWindow = Number(args[index + 1]);\n\t\tif (Number.isSafeInteger(contextWindow) && contextWindow > 0) return contextWindow;\n\t}\n\treturn undefined;\n}\n\nfunction contextWindowOf(model: LlamaModelInfo, cachedContextWindow?: number): number {\n\tconst runtimeContextWindow = model.meta?.n_ctx;\n\tif (runtimeContextWindow && runtimeContextWindow > 0) return runtimeContextWindow;\n\tconst configuredContext = configuredContextWindow(model);\n\tif (configuredContext) return configuredContext;\n\tif (cachedContextWindow && cachedContextWindow > 0) return cachedContextWindow;\n\tconst trainingContextWindow = model.meta?.n_ctx_train;\n\treturn trainingContextWindow && trainingContextWindow > 0 ? trainingContextWindow : 128000;\n}\n\n/** The same llama.cpp model used as a classifier: answers are read from next-token label probabilities. */\nfunction toPiClassifierModel(\n\tmodel: LlamaModelInfo,\n\tserverUrl: string,\n\tcachedContextWindow?: number,\n): ClassifierModel<\"llama-cpp-classify\"> {\n\treturn {\n\t\ttype: \"classifier\",\n\t\tid: model.id,\n\t\tname: model.id,\n\t\tapi: \"llama-cpp-classify\",\n\t\tprovider: LLAMA_PROVIDER_ID,\n\t\tbaseUrl: serverUrl,\n\t\tinput: [\"text\"],\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t\tcontextWindow: contextWindowOf(model, cachedContextWindow),\n\t};\n}\n\nfunction toPiModel(\n\tmodel: LlamaModelInfo,\n\tserverUrl: string,\n\tprops?: LlamaServerProps,\n\tcachedContextWindow?: number,\n): Model<\"openai-completions\"> {\n\tconst contextWindow = contextWindowOf(model, cachedContextWindow);\n\tconst reasoning = props?.chat_template?.includes(\"enable_thinking\") === true;\n\treturn {\n\t\tid: model.id,\n\t\tname: model.id,\n\t\tapi: \"openai-completions\",\n\t\tprovider: LLAMA_PROVIDER_ID,\n\t\tbaseUrl: llamaInferenceUrl(serverUrl),\n\t\treasoning,\n\t\t...(reasoning && {\n\t\t\tthinkingLevelMap: { off: \"off\", minimal: null, low: null, medium: \"medium\", high: null, xhigh: null },\n\t\t}),\n\t\tinput: model.architecture?.input_modalities?.includes(\"image\") ? [\"text\", \"image\"] : [\"text\"],\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t\tcontextWindow,\n\t\tmaxTokens: contextWindow,\n\t\tcompat: {\n\t\t\tsupportsStore: false,\n\t\t\tsupportsDeveloperRole: false,\n\t\t\tsupportsReasoningEffort: false,\n\t\t\tsupportsUsageInStreaming: true,\n\t\t\tsupportsStrictMode: false,\n\t\t\tmaxTokensField: \"max_tokens\",\n\t\t\t...(reasoning && { thinkingFormat: \"qwen-chat-template\" }),\n\t\t},\n\t};\n}\n\nexport interface LlamaProviderController {\n\tprovider: Provider<\"openai-completions\">;\n\tsetCatalog(models: readonly LlamaModelInfo[], serverUrl: string, options?: { routerAutoload?: boolean }): void;\n}\n\nexport function createLlamaProvider(): LlamaProviderController {\n\tlet models: readonly Model<\"openai-completions\">[] = [];\n\tlet classifiers: readonly ClassifierModel<\"llama-cpp-classify\">[] = [];\n\tconst classifier = llamaCppClassifyApi();\n\n\tconst setCatalog = (\n\t\tcatalog: readonly LlamaModelInfo[],\n\t\tserverUrl: string,\n\t\toptions: { routerAutoload?: boolean } = {},\n\t): void => {\n\t\tconst selectable = catalog.filter((model) => modelIsSelectable(model, options.routerAutoload === true));\n\t\tmodels = selectable.map((model) => toPiModel(model, serverUrl));\n\t\tclassifiers = selectable.map((model) => toPiClassifierModel(model, serverUrl));\n\t};\n\n\tconst provider: Provider<\"openai-completions\"> = {\n\t\tid: LLAMA_PROVIDER_ID,\n\t\tname: \"llama.cpp\",\n\t\tbaseUrl: llamaInferenceUrl(DEFAULT_LLAMA_SERVER_URL),\n\t\tauth: {\n\t\t\tapiKey: {\n\t\t\t\tname: \"llama.cpp server\",\n\t\t\t\tlogin: async (interaction): Promise<ApiKeyCredential> => {\n\t\t\t\t\tconst enteredUrl = await interaction.prompt({\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\tmessage: \"llama.cpp server URL\",\n\t\t\t\t\t\tplaceholder: process.env.LLAMA_BASE_URL ?? DEFAULT_LLAMA_SERVER_URL,\n\t\t\t\t\t});\n\t\t\t\t\tconst serverUrl = normalizeLlamaServerUrl(\n\t\t\t\t\t\tenteredUrl.trim() || process.env.LLAMA_BASE_URL || DEFAULT_LLAMA_SERVER_URL,\n\t\t\t\t\t);\n\t\t\t\t\tconst apiKey = (\n\t\t\t\t\t\tawait interaction.prompt({\n\t\t\t\t\t\t\ttype: \"secret\",\n\t\t\t\t\t\t\tmessage: \"API key (optional)\",\n\t\t\t\t\t\t})\n\t\t\t\t\t).trim();\n\t\t\t\t\tawait new LlamaClient(serverUrl, apiKey || undefined).list({ signal: interaction.signal });\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"api_key\",\n\t\t\t\t\t\tkey: apiKey || undefined,\n\t\t\t\t\t\tenv: { LLAMA_BASE_URL: serverUrl },\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t\tcheck: async ({ ctx, credential }) => {\n\t\t\t\t\tconst serverUrl = await resolveServerUrl(ctx, credential);\n\t\t\t\t\treturn serverUrl\n\t\t\t\t\t\t? { type: \"api_key\", source: credential ? \"stored credential\" : \"LLAMA_BASE_URL\" }\n\t\t\t\t\t\t: undefined;\n\t\t\t\t},\n\t\t\t\tresolve: async ({ ctx, credential }): Promise<AuthResult | undefined> => {\n\t\t\t\t\tconst serverUrl = await resolveServerUrl(ctx, credential);\n\t\t\t\t\tif (!serverUrl) return undefined;\n\t\t\t\t\tconst apiKey = credential?.key ?? (await ctx.env(\"LLAMA_API_KEY\")) ?? \"local\";\n\t\t\t\t\treturn {\n\t\t\t\t\t\tauth: { apiKey, baseUrl: llamaInferenceUrl(serverUrl) },\n\t\t\t\t\t\tenv: { ...credential?.env, LLAMA_BASE_URL: serverUrl },\n\t\t\t\t\t\tsource: credential ? \"stored credential\" : \"LLAMA_BASE_URL\",\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tgetModels: () => models,\n\t\tgetAllModels: () => [...models, ...classifiers],\n\t\trefreshModels: async (context: RefreshModelsContext): Promise<void> => {\n\t\t\tconst cachedContextWindows = new Map<string, number>();\n\t\t\tif (context.stored) {\n\t\t\t\tconst stored = context.stored.models.filter((model) => model.provider === LLAMA_PROVIDER_ID);\n\t\t\t\tconst restored = stored.filter(\n\t\t\t\t\t(model): model is Model<\"openai-completions\"> =>\n\t\t\t\t\t\tisModelType(model, \"chat\") && model.api === \"openai-completions\",\n\t\t\t\t);\n\t\t\t\tconst restoredClassifiers = stored.filter(\n\t\t\t\t\t(model): model is ClassifierModel<\"llama-cpp-classify\"> =>\n\t\t\t\t\t\tisModelType(model, \"classifier\") && model.api === \"llama-cpp-classify\",\n\t\t\t\t);\n\t\t\t\tfor (const model of [...restored, ...restoredClassifiers]) {\n\t\t\t\t\tcachedContextWindows.set(model.id, model.contextWindow);\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\t!(await context.publish({\n\t\t\t\t\t\tupdate: () => {\n\t\t\t\t\t\t\tmodels = restored;\n\t\t\t\t\t\t\tclassifiers = restoredClassifiers;\n\t\t\t\t\t\t},\n\t\t\t\t\t}))\n\t\t\t\t) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!context.allowNetwork || context.signal.aborted || context.credential?.type !== \"api_key\") return;\n\t\t\tconst serverUrl = credentialServerUrl(context.credential);\n\t\t\tif (!serverUrl) return;\n\t\t\tconst client = new LlamaClient(serverUrl, context.credential.key);\n\t\t\tconst catalog = await client.list({ signal: context.signal });\n\t\t\tif (context.signal.aborted) return;\n\t\t\tconst routerAutoload = await routerAutoloadEnabled(client, catalog, context.signal);\n\t\t\tif (context.signal.aborted) return;\n\t\t\tconst selectable = catalog.filter((model) => modelIsSelectable(model, routerAutoload));\n\t\t\tconst refreshed = await Promise.all(\n\t\t\t\tselectable.map(async (model) => {\n\t\t\t\t\tconst cachedContextWindow = cachedContextWindows.get(model.id);\n\t\t\t\t\t// Only loaded models expose their template without side effects. Unloaded autoload presets\n\t\t\t\t\t// would need to be loaded, while querying sleeping models may wake them. Those models remain\n\t\t\t\t\t// unclassified until they are loaded or woken and a later catalog refresh discovers them.\n\t\t\t\t\tif (model.status.value !== \"loaded\") return toPiModel(model, serverUrl, undefined, cachedContextWindow);\n\t\t\t\t\tconst props = await client.props({ model: model.id, signal: context.signal });\n\t\t\t\t\treturn toPiModel(model, serverUrl, props, cachedContextWindow);\n\t\t\t\t}),\n\t\t\t);\n\t\t\tconst refreshedClassifiers = selectable.map((model) =>\n\t\t\t\ttoPiClassifierModel(model, serverUrl, cachedContextWindows.get(model.id)),\n\t\t\t);\n\t\t\tif (context.signal.aborted) return;\n\t\t\tawait context.publish({\n\t\t\t\tpersist: { models: [...refreshed, ...refreshedClassifiers], checkedAt: Date.now() },\n\t\t\t\tupdate: () => {\n\t\t\t\t\tmodels = refreshed;\n\t\t\t\t\tclassifiers = refreshedClassifiers;\n\t\t\t\t},\n\t\t\t});\n\t\t},\n\t\tstream: (model, context, options) => stream(model, context, options as ProviderStreamOptions | undefined),\n\t\tstreamSimple: (model, context, options) => streamSimple(model, context, options),\n\t\tclassify: (model, context, options) => classifier.classify(model, context, options),\n\t};\n\n\treturn { provider, setCatalog };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"provider.js","sourceRoot":"","sources":["../../../src/extensions/llama/provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAMN,WAAW,GAKX,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,mBAAmB,EAAE,MAAM,mDAAmD,CAAC;AACxF,OAAO,EAAE,oBAAoB,EAAE,MAAM,oDAAoD,CAAC;AAC1F,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AACpE,OAAO,EACN,WAAW,EAGX,iBAAiB,EACjB,uBAAuB,GACvB,MAAM,aAAa,CAAC;AAErB,MAAM,CAAC,MAAM,iBAAiB,GAAG,WAAW,CAAC;AAC7C,MAAM,CAAC,MAAM,wBAAwB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GAAG,KAAK,qBAAqB,CAAC,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC,kBAAkB,CAAC,CAAC,QAAQ,CACvF,KAAK,EACL,OAAO,EACP,OAAO,CACP;KACF,CAAC;IAEF,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,CAAC;AACjC,CAAC","sourcesContent":["import {\n\ttype AnyModel,\n\ttype ApiKeyCredential,\n\ttype AuthContext,\n\ttype AuthResult,\n\ttype ClassifierModel,\n\tisModelType,\n\ttype Model,\n\ttype Provider,\n\ttype ProviderStreamOptions,\n\ttype RefreshModelsContext,\n} from \"@earendil-works/pi-ai\";\nimport { llamaCppClassifyApi } from \"@earendil-works/pi-ai/api/llama-cpp-classify.lazy\";\nimport { typesafeSystemOneApi } from \"@earendil-works/pi-ai/api/typesafe-system-one.lazy\";\nimport { stream, streamSimple } from \"@earendil-works/pi-ai/compat\";\nimport {\n\tLlamaClient,\n\ttype LlamaModelInfo,\n\ttype LlamaServerProps,\n\tllamaInferenceUrl,\n\tnormalizeLlamaServerUrl,\n} from \"./client.ts\";\n\nexport const LLAMA_PROVIDER_ID = \"llama.cpp\";\nexport const DEFAULT_LLAMA_SERVER_URL = \"http://127.0.0.1:8080\";\nfunction credentialServerUrl(credential: ApiKeyCredential | undefined): string | undefined {\n\tconst value = credential?.env?.LLAMA_BASE_URL;\n\treturn typeof value === \"string\" && value.trim() ? normalizeLlamaServerUrl(value) : undefined;\n}\n\nasync function resolveServerUrl(\n\tctx: AuthContext,\n\tcredential: ApiKeyCredential | undefined,\n): Promise<string | undefined> {\n\tconst configured = credentialServerUrl(credential) ?? (await ctx.env(\"LLAMA_BASE_URL\"))?.trim();\n\treturn configured ? normalizeLlamaServerUrl(configured) : undefined;\n}\n\nfunction modelIsSelectable(model: LlamaModelInfo, routerAutoload: boolean): boolean {\n\tif (model.status.value === \"loaded\") return true;\n\t// llama.cpp reports idle-slept models as \"sleeping\"; requests wake them automatically.\n\tif (model.status.value === \"sleeping\") return true;\n\t// Unloaded presets are routable only when llama.cpp router autoload can load them on first use.\n\treturn routerAutoload && model.status.value === \"unloaded\" && !model.status.failed && model.source === \"preset\";\n}\n\nasync function routerAutoloadEnabled(\n\tclient: LlamaClient,\n\tcatalog: readonly LlamaModelInfo[],\n\tsignal: AbortSignal,\n): Promise<boolean> {\n\tif (!catalog.some((model) => model.status.value === \"unloaded\" && model.source === \"preset\")) return false;\n\ttry {\n\t\treturn (await client.props({ signal })).models_autoload === true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction configuredContextWindow(model: LlamaModelInfo): number | undefined {\n\tconst args = model.status.args ?? [];\n\tfor (let index = 0; index < args.length - 1; index++) {\n\t\tconst flag = args[index];\n\t\tif (flag !== \"--ctx-size\" && flag !== \"-c\" && flag !== \"-ctx\") continue;\n\t\tconst contextWindow = Number(args[index + 1]);\n\t\tif (Number.isSafeInteger(contextWindow) && contextWindow > 0) return contextWindow;\n\t}\n\treturn undefined;\n}\n\nfunction contextWindowOf(model: LlamaModelInfo, cachedContextWindow?: number): number {\n\tconst runtimeContextWindow = model.meta?.n_ctx;\n\tif (runtimeContextWindow && runtimeContextWindow > 0) return runtimeContextWindow;\n\tconst configuredContext = configuredContextWindow(model);\n\tif (configuredContext) return configuredContext;\n\tif (cachedContextWindow && cachedContextWindow > 0) return cachedContextWindow;\n\tconst trainingContextWindow = model.meta?.n_ctx_train;\n\treturn trainingContextWindow && trainingContextWindow > 0 ? trainingContextWindow : 128000;\n}\n\ntype LlamaClassifierApi = \"llama-cpp-classify\" | \"typesafe-system-one\";\n\n/**\n * Whether llama.cpp reports a native decision model. Since llama.cpp 0.6.0, `GET /models` lists\n * `decisions` in `architecture.output_modalities` for these models, including unloaded and sleeping ones.\n * Older servers report `[\"text\"]` or omit `architecture`, so their models are treated as chat models.\n */\nfunction isDecisionModel(model: LlamaModelInfo): boolean {\n\treturn model.architecture?.output_modalities?.includes(\"decisions\") === true;\n}\n\n/** Decision-only models cannot generate text and are not listed for chat. */\nfunction isChatModel(model: LlamaModelInfo): boolean {\n\treturn !isDecisionModel(model) || model.architecture?.output_modalities?.includes(\"text\") === true;\n}\n\n/**\n * A llama.cpp model used as a classifier. Decision models answer natively through llama.cpp's\n * System One endpoint (`/v1/systemone`). Chat models fall back to `llama-cpp-classify`, which reads\n * answers from next-token label probabilities.\n */\nfunction toPiClassifierModel(\n\tmodel: LlamaModelInfo,\n\tserverUrl: string,\n\tcachedContextWindow?: number,\n): ClassifierModel<LlamaClassifierApi> {\n\tconst decision = isDecisionModel(model);\n\treturn {\n\t\ttype: \"classifier\",\n\t\tid: model.id,\n\t\tname: model.id,\n\t\tapi: decision ? \"typesafe-system-one\" : \"llama-cpp-classify\",\n\t\tprovider: LLAMA_PROVIDER_ID,\n\t\tbaseUrl: decision ? llamaInferenceUrl(serverUrl) : serverUrl,\n\t\tinput: [\"text\"],\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t\tcontextWindow: contextWindowOf(model, cachedContextWindow),\n\t};\n}\n\nfunction isLlamaClassifierModel(model: AnyModel): model is ClassifierModel<LlamaClassifierApi> {\n\treturn (\n\t\tisModelType(model, \"classifier\") && (model.api === \"llama-cpp-classify\" || model.api === \"typesafe-system-one\")\n\t);\n}\n\nfunction toPiModel(\n\tmodel: LlamaModelInfo,\n\tserverUrl: string,\n\tprops?: LlamaServerProps,\n\tcachedContextWindow?: number,\n): Model<\"openai-completions\"> {\n\tconst contextWindow = contextWindowOf(model, cachedContextWindow);\n\tconst reasoning = props?.chat_template?.includes(\"enable_thinking\") === true;\n\treturn {\n\t\tid: model.id,\n\t\tname: model.id,\n\t\tapi: \"openai-completions\",\n\t\tprovider: LLAMA_PROVIDER_ID,\n\t\tbaseUrl: llamaInferenceUrl(serverUrl),\n\t\treasoning,\n\t\t...(reasoning && {\n\t\t\tthinkingLevelMap: { off: \"off\", minimal: null, low: null, medium: \"medium\", high: null, xhigh: null },\n\t\t}),\n\t\tinput: model.architecture?.input_modalities?.includes(\"image\") ? [\"text\", \"image\"] : [\"text\"],\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },\n\t\tcontextWindow,\n\t\tmaxTokens: contextWindow,\n\t\tcompat: {\n\t\t\tsupportsStore: false,\n\t\t\tsupportsDeveloperRole: false,\n\t\t\tsupportsReasoningEffort: false,\n\t\t\tsupportsUsageInStreaming: true,\n\t\t\tsupportsStrictMode: false,\n\t\t\tmaxTokensField: \"max_tokens\",\n\t\t\t...(reasoning && { thinkingFormat: \"qwen-chat-template\" }),\n\t\t},\n\t};\n}\n\nexport interface LlamaProviderController {\n\tprovider: Provider<\"openai-completions\">;\n\tsetCatalog(models: readonly LlamaModelInfo[], serverUrl: string, options?: { routerAutoload?: boolean }): void;\n}\n\nexport function createLlamaProvider(): LlamaProviderController {\n\tlet models: readonly Model<\"openai-completions\">[] = [];\n\tlet classifiers: readonly ClassifierModel<LlamaClassifierApi>[] = [];\n\tconst fallbackClassifier = llamaCppClassifyApi();\n\tconst decisionClassifier = typesafeSystemOneApi();\n\n\tconst setCatalog = (\n\t\tcatalog: readonly LlamaModelInfo[],\n\t\tserverUrl: string,\n\t\toptions: { routerAutoload?: boolean } = {},\n\t): void => {\n\t\tconst selectable = catalog.filter((model) => modelIsSelectable(model, options.routerAutoload === true));\n\t\tmodels = selectable.filter(isChatModel).map((model) => toPiModel(model, serverUrl));\n\t\tclassifiers = selectable.map((model) => toPiClassifierModel(model, serverUrl));\n\t};\n\n\tconst provider: Provider<\"openai-completions\"> = {\n\t\tid: LLAMA_PROVIDER_ID,\n\t\tname: \"llama.cpp\",\n\t\tbaseUrl: llamaInferenceUrl(DEFAULT_LLAMA_SERVER_URL),\n\t\tauth: {\n\t\t\tapiKey: {\n\t\t\t\tname: \"llama.cpp server\",\n\t\t\t\tlogin: async (interaction): Promise<ApiKeyCredential> => {\n\t\t\t\t\tconst enteredUrl = await interaction.prompt({\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\tmessage: \"llama.cpp server URL\",\n\t\t\t\t\t\tplaceholder: process.env.LLAMA_BASE_URL ?? DEFAULT_LLAMA_SERVER_URL,\n\t\t\t\t\t});\n\t\t\t\t\tconst serverUrl = normalizeLlamaServerUrl(\n\t\t\t\t\t\tenteredUrl.trim() || process.env.LLAMA_BASE_URL || DEFAULT_LLAMA_SERVER_URL,\n\t\t\t\t\t);\n\t\t\t\t\tconst apiKey = (\n\t\t\t\t\t\tawait interaction.prompt({\n\t\t\t\t\t\t\ttype: \"secret\",\n\t\t\t\t\t\t\tmessage: \"API key (optional)\",\n\t\t\t\t\t\t})\n\t\t\t\t\t).trim();\n\t\t\t\t\tawait new LlamaClient(serverUrl, apiKey || undefined).list({ signal: interaction.signal });\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"api_key\",\n\t\t\t\t\t\tkey: apiKey || undefined,\n\t\t\t\t\t\tenv: { LLAMA_BASE_URL: serverUrl },\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t\tcheck: async ({ ctx, credential }) => {\n\t\t\t\t\tconst serverUrl = await resolveServerUrl(ctx, credential);\n\t\t\t\t\treturn serverUrl\n\t\t\t\t\t\t? { type: \"api_key\", source: credential ? \"stored credential\" : \"LLAMA_BASE_URL\" }\n\t\t\t\t\t\t: undefined;\n\t\t\t\t},\n\t\t\t\tresolve: async ({ ctx, credential }): Promise<AuthResult | undefined> => {\n\t\t\t\t\tconst serverUrl = await resolveServerUrl(ctx, credential);\n\t\t\t\t\tif (!serverUrl) return undefined;\n\t\t\t\t\tconst apiKey = credential?.key ?? (await ctx.env(\"LLAMA_API_KEY\")) ?? \"local\";\n\t\t\t\t\treturn {\n\t\t\t\t\t\tauth: { apiKey, baseUrl: llamaInferenceUrl(serverUrl) },\n\t\t\t\t\t\tenv: { ...credential?.env, LLAMA_BASE_URL: serverUrl },\n\t\t\t\t\t\tsource: credential ? \"stored credential\" : \"LLAMA_BASE_URL\",\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tgetModels: () => models,\n\t\tgetAllModels: () => [...models, ...classifiers],\n\t\trefreshModels: async (context: RefreshModelsContext): Promise<void> => {\n\t\t\tconst cachedContextWindows = new Map<string, number>();\n\t\t\tif (context.stored) {\n\t\t\t\tconst stored = context.stored.models.filter((model) => model.provider === LLAMA_PROVIDER_ID);\n\t\t\t\tconst restored = stored.filter(\n\t\t\t\t\t(model): model is Model<\"openai-completions\"> =>\n\t\t\t\t\t\tisModelType(model, \"chat\") && model.api === \"openai-completions\",\n\t\t\t\t);\n\t\t\t\tconst restoredClassifiers = stored.filter(isLlamaClassifierModel);\n\t\t\t\tfor (const model of [...restored, ...restoredClassifiers]) {\n\t\t\t\t\tcachedContextWindows.set(model.id, model.contextWindow);\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\t!(await context.publish({\n\t\t\t\t\t\tupdate: () => {\n\t\t\t\t\t\t\tmodels = restored;\n\t\t\t\t\t\t\tclassifiers = restoredClassifiers;\n\t\t\t\t\t\t},\n\t\t\t\t\t}))\n\t\t\t\t) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!context.allowNetwork || context.signal.aborted || context.credential?.type !== \"api_key\") return;\n\t\t\tconst serverUrl = credentialServerUrl(context.credential);\n\t\t\tif (!serverUrl) return;\n\t\t\tconst client = new LlamaClient(serverUrl, context.credential.key);\n\t\t\tconst catalog = await client.list({ signal: context.signal });\n\t\t\tif (context.signal.aborted) return;\n\t\t\tconst routerAutoload = await routerAutoloadEnabled(client, catalog, context.signal);\n\t\t\tif (context.signal.aborted) return;\n\t\t\tconst selectable = catalog.filter((model) => modelIsSelectable(model, routerAutoload));\n\t\t\t// Only loaded models expose their chat template without side effects. Unloaded autoload presets would\n\t\t\t// need to be loaded, while querying sleeping models may wake them. Those models remain without thinking\n\t\t\t// support until they are loaded and a later catalog refresh discovers it. Decision models need no\n\t\t\t// template, and llama.cpp reports them in the catalog regardless of their status.\n\t\t\tconst refreshed = await Promise.all(\n\t\t\t\tselectable.filter(isChatModel).map(async (model) => {\n\t\t\t\t\tconst cachedContextWindow = cachedContextWindows.get(model.id);\n\t\t\t\t\tif (model.status.value !== \"loaded\") return toPiModel(model, serverUrl, undefined, cachedContextWindow);\n\t\t\t\t\tconst props = await client.props({ model: model.id, signal: context.signal });\n\t\t\t\t\treturn toPiModel(model, serverUrl, props, cachedContextWindow);\n\t\t\t\t}),\n\t\t\t);\n\t\t\tconst refreshedClassifiers = selectable.map((model) =>\n\t\t\t\ttoPiClassifierModel(model, serverUrl, cachedContextWindows.get(model.id)),\n\t\t\t);\n\t\t\tif (context.signal.aborted) return;\n\t\t\tawait context.publish({\n\t\t\t\tpersist: { models: [...refreshed, ...refreshedClassifiers], checkedAt: Date.now() },\n\t\t\t\tupdate: () => {\n\t\t\t\t\tmodels = refreshed;\n\t\t\t\t\tclassifiers = refreshedClassifiers;\n\t\t\t\t},\n\t\t\t});\n\t\t},\n\t\tstream: (model, context, options) => stream(model, context, options as ProviderStreamOptions | undefined),\n\t\tstreamSimple: (model, context, options) => streamSimple(model, context, options),\n\t\tclassify: (model, context, options) =>\n\t\t\t(model.api === \"typesafe-system-one\" ? decisionClassifier : fallbackClassifier).classify(\n\t\t\t\tmodel,\n\t\t\t\tcontext,\n\t\t\t\toptions,\n\t\t\t),\n\t};\n\n\treturn { provider, setCatalog };\n}\n"]}
|
|
@@ -449,8 +449,9 @@ async function login(entry, connection, url, timeoutMs, options, credentials, lo
|
|
|
449
449
|
log(`Sign in to MCP server "${name}" in your browser:\n${authorizationUrl.href}`);
|
|
450
450
|
openUrl(authorizationUrl.href);
|
|
451
451
|
},
|
|
452
|
-
promptForRedirectUrl: (signal) => waitForRedirectUrl(signal,
|
|
452
|
+
promptForRedirectUrl: (signal) => waitForRedirectUrl(signal, interactive),
|
|
453
453
|
},
|
|
454
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
454
455
|
});
|
|
455
456
|
}
|
|
456
457
|
catch (signInError) {
|
|
@@ -472,32 +473,25 @@ async function login(entry, connection, url, timeoutMs, options, credentials, lo
|
|
|
472
473
|
}
|
|
473
474
|
/**
|
|
474
475
|
* The pasted redirect URL in a terminal; otherwise only the browser callback can finish the sign-in.
|
|
475
|
-
* Resolves to undefined
|
|
476
|
+
* Resolves to undefined when `signal` aborts: the callback arrived, or the sign-in timed out.
|
|
476
477
|
*/
|
|
477
|
-
async function waitForRedirectUrl(signal,
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
478
|
+
async function waitForRedirectUrl(signal, interactive) {
|
|
479
|
+
if (!interactive) {
|
|
480
|
+
if (!signal.aborted)
|
|
481
|
+
await new Promise((resolve) => signal.addEventListener("abort", resolve, { once: true }));
|
|
482
|
+
return undefined;
|
|
483
|
+
}
|
|
484
|
+
const readline = createInterface({ input: process.stdin, output: process.stderr });
|
|
482
485
|
try {
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
return await readline.question("If the browser cannot reach this machine, paste the URL it was redirected to: ", { signal: controller.signal });
|
|
490
|
-
}
|
|
491
|
-
catch {
|
|
492
|
-
return undefined;
|
|
493
|
-
}
|
|
494
|
-
finally {
|
|
495
|
-
readline.close();
|
|
496
|
-
}
|
|
486
|
+
return await readline.question("If the browser cannot reach this machine, paste the URL it was redirected to: ", {
|
|
487
|
+
signal,
|
|
488
|
+
});
|
|
489
|
+
}
|
|
490
|
+
catch {
|
|
491
|
+
return undefined;
|
|
497
492
|
}
|
|
498
493
|
finally {
|
|
499
|
-
|
|
500
|
-
signal.removeEventListener("abort", abort);
|
|
494
|
+
readline.close();
|
|
501
495
|
}
|
|
502
496
|
}
|
|
503
497
|
//# sourceMappingURL=cli.js.map
|