pi-namespace-patch 1.0.2-namespace.2 → 1.0.4-namespace.1
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 +50 -0
- package/README.md +8 -8
- package/dist/bundle/chunks/{anthropic-messages-MVG2FL56.js → anthropic-messages-Y22YDKSW.js} +1 -1
- package/dist/bundle/chunks/azure-openai-responses-YJDJIIDQ.js +2 -0
- package/dist/bundle/chunks/chunk-22CYIUS4.js +2 -0
- package/dist/bundle/chunks/{chunk-WCQZGZ6I.js → chunk-2QSWSXFK.js} +4 -4
- package/dist/bundle/chunks/{chunk-6FX7UEPL.js → chunk-64GOPQSC.js} +6 -4
- package/dist/bundle/chunks/{chunk-OSKPX3Z5.js → chunk-C47CLQZK.js} +1 -1
- package/dist/bundle/chunks/{chunk-OLBCNJCL.js → chunk-ERIW6MDO.js} +51 -47
- package/dist/bundle/chunks/chunk-F4TCZWQO.js +20 -0
- package/dist/bundle/chunks/{chunk-2KAZSACP.js → chunk-FKGBRPJC.js} +1 -1
- package/dist/bundle/chunks/{chunk-IKZJX7ZT.js → chunk-HQHD6PZI.js} +1 -1
- package/dist/bundle/chunks/chunk-KJUDFE6Y.js +11 -0
- package/dist/bundle/chunks/{chunk-G7EDXK4D.js → chunk-TAOL3JFA.js} +1 -1
- package/dist/bundle/chunks/chunk-VLMAON6X.js +15 -0
- package/dist/bundle/chunks/{chunk-BYB6ZAAQ.js → chunk-WE4MXUQS.js} +1 -1
- package/dist/bundle/chunks/{chunk-ZSI3BL5Q.js → chunk-XXKX4I4Z.js} +1 -1
- package/dist/bundle/chunks/{chunk-SYF2TF6W.js → chunk-YKYP4C4A.js} +9 -6
- package/dist/bundle/chunks/{chunk-DN3QEIXS.js → chunk-YTMEKMOC.js} +1 -1
- package/dist/bundle/chunks/chunk-ZBURYEWF.js +2 -0
- package/dist/bundle/chunks/{cli-KILDDGW3.js → cli-FRW732V6.js} +1 -1
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-X5PVWWYJ.js → cloudflare-workers-ai-system-one-NM3JRRWQ.js} +1 -1
- package/dist/bundle/chunks/codemode-worker.js +99 -4
- package/dist/bundle/chunks/{easter-egg-3d-T5FFWIBR.js → easter-egg-3d-GBYHZI2E.js} +1 -1
- package/dist/bundle/chunks/execute-MNHU53Y5.js +484 -0
- package/dist/bundle/chunks/{google-generative-ai-ZOK6CV7D.js → google-generative-ai-XMFHGQC5.js} +1 -1
- package/dist/bundle/chunks/{google-vertex-VKWZQ3AY.js → google-vertex-4XRRNP74.js} +1 -1
- package/dist/bundle/chunks/{mistral-conversations-7DAUEE4N.js → mistral-conversations-Q22M3IBG.js} +1 -1
- package/dist/bundle/chunks/{openai-codex-responses-TC3OK7B4.js → openai-codex-responses-4MYQSO5E.js} +1 -1
- package/dist/bundle/chunks/{openai-completions-GWHGMQ3T.js → openai-completions-OSRCWAAA.js} +1 -1
- package/dist/bundle/chunks/{openai-responses-EZ7FJ2KL.js → openai-responses-UHF3DHNG.js} +1 -1
- package/dist/bundle/chunks/{runtime-D5I2NTIF.js → runtime-FW2HXAJ6.js} +1 -1
- package/dist/bundle/chunks/{typesafe-system-one-A4CZTQWZ.js → typesafe-system-one-PRR5K6CI.js} +1 -1
- package/dist/bundle/chunks/virtual-modules-3HQKVCRO.js +2 -0
- 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 +1 -0
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +11 -4
- package/dist/cli/args.js.map +1 -1
- package/dist/config.d.ts +18 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +44 -6
- package/dist/config.js.map +1 -1
- package/dist/core/agent-session.d.ts +26 -4
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +47 -14
- 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 +2 -7
- package/dist/core/bash-executor.js.map +1 -1
- package/dist/core/extensions/types.d.ts +2 -0
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/keybindings.d.ts +4 -4
- 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-resolver.js +1 -1
- package/dist/core/model-resolver.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 +9 -4
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +3 -2
- package/dist/core/sdk.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/output-accumulator.d.ts.map +1 -1
- package/dist/core/tools/output-accumulator.js +4 -10
- package/dist/core/tools/output-accumulator.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/extensions/codemode/execute.d.ts.map +1 -1
- package/dist/extensions/codemode/execute.js +51 -9
- 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 +13 -5
- package/dist/extensions/codemode/tool.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 +6 -10
- package/dist/extensions/mcp/tools.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/interactive-mode.d.ts +7 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +42 -6
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- 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/utils/output-files.d.ts +15 -0
- package/dist/utils/output-files.d.ts.map +1 -0
- package/dist/utils/output-files.js +30 -0
- package/dist/utils/output-files.js.map +1 -0
- 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 +15 -3
- package/docs/codemode.md +6 -5
- package/docs/extensions.md +1 -1
- package/docs/keybindings.md +4 -4
- package/docs/mcp.md +3 -1
- 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 +10 -10
- package/dist/bundle/chunks/azure-openai-responses-7AMFUIWJ.js +0 -2
- package/dist/bundle/chunks/chunk-7JGR3GZN.js +0 -11
- package/dist/bundle/chunks/chunk-OYBSLV7Y.js +0 -16
- package/dist/bundle/chunks/chunk-PDFMCAOZ.js +0 -19
- package/dist/bundle/chunks/chunk-VIV3CWXG.js +0 -2
- package/dist/bundle/chunks/execute-RYVK27GT.js +0 -388
- package/dist/bundle/chunks/virtual-modules-J2M3WAR2.js +0 -2
|
@@ -0,0 +1,484 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
+
import{Bm25Ranker,CODEMODE_DOCS_PATH,CODEMODE_STORE_ENTRY_TYPE,DEFAULT_TOOL_SEARCH_LIMIT,combineUsage,createToolSearchDocument,getCodemodeCallableTools,parseCodemodeSource,renderToolSample,toCodemodeDeclaration,toCodemodeIdentifier}from"./chunk-YKYP4C4A.js";import{formatSize,writeOutputFile}from"./chunk-F4TCZWQO.js";import{getCodemodeWorkerSpecifier,getQuickJSWasmPath}from"./chunk-64GOPQSC.js";import"./chunk-S3GGRYIO.js";import"./chunk-4L3WN2XY.js";import{Worker}from"node:worker_threads";import{readFile}from"node:fs/promises";import{createRequire}from"node:module";var modules=new Map;function loadQuickJSWasm(path){let resolved=path??createRequire(import.meta.url).resolve("quickjs-wasi/quickjs.wasm"),module=modules.get(resolved);if(!module){let{WebAssembly}=globalThis;module=readFile(resolved).then(bytes=>WebAssembly.compile(bytes)).catch(error=>{throw modules.delete(resolved),error}),modules.set(resolved,module)}return module}function isWorkerToHostMessage(value){if(typeof value!="object"||value===null)return!1;let type=value.type;return type==="call"||type==="output"||type==="done"||type==="crash"}var DEFAULT_TIMEOUT_MS=3e5,IDENTIFIER=/^[A-Za-z_$][A-Za-z0-9_$]*$/,RESERVED_GLOBALS=new Set(["tools","ALL_TOOLS","console","text","image","exit","globalThis","store","load"]);function errorMessage(error){return error instanceof Error?error.message:String(error)}function serializeStore(store){let serialized={};for(let[key,value]of Object.entries(store??{})){let json=JSON.stringify(value);json!==void 0&&(serialized[key]=json)}return serialized}var BridgeError=class extends Error{};function parseBridgeJson(json,what){try{return JSON.parse(json)}catch{throw new BridgeError(`${what} is not valid JSON`)}}function parseStoreWrites(json){let entries=parseBridgeJson(json,"store writes");if(!Array.isArray(entries))throw new BridgeError("store writes are not an array");let writes={set:{},delete:[]};for(let entry of entries){if(!Array.isArray(entry)||typeof entry[0]!="string"||(entry.length===2?typeof entry[1]!="string":entry.length!==1))throw new BridgeError("store writes contain a malformed entry");let[key,value]=entry;value===void 0?writes.delete.push(key):writes.set[key]=parseBridgeJson(value,`store value for ${JSON.stringify(key)}`)}return writes}function parseScriptError(json){let parsed=parseBridgeJson(json,"script error");if(typeof parsed!="object"||parsed===null)throw new BridgeError("script error is not an object");let{name,message,stack}=parsed;if(typeof message!="string"||name!==void 0&&typeof name!="string"||stack!==void 0&&typeof stack!="string")throw new BridgeError("script error is malformed");return{kind:"script",name,message,stack}}function defaultWorkerUrl(){return new URL(import.meta.url.endsWith(".ts")?"./worker.ts":"./worker.js",import.meta.url)}var Execution=class{promise;resolveResult;worker;interrupt=new SharedArrayBuffer(4);tools;globals;signal;timer;output=[];calls=[];pending=new Map;finished=!1;constructor(options){this.promise=new Promise(resolve=>{this.resolveResult=resolve}),this.tools=options.tools,this.globals=options.globals,this.signal=options.signal,Number.isFinite(options.timeoutMs)&&(this.timer=setTimeout(()=>{this.finish({kind:"timeout",message:`Execution timed out after ${options.timeoutMs} ms`})},options.timeoutMs)),options.signal&&(options.signal.aborted?this.onAbort():options.signal.addEventListener("abort",this.onAbort,{once:!0})),options.wasm.then(wasm=>this.start(options,wasm),error=>{this.finish({kind:"sandbox",message:`Failed to load QuickJS: ${errorMessage(error)}`})})}abort(message){return this.finish({kind:"aborted",message}),this.promise}start(options,wasm){if(this.finished)return;let workerData={code:options.code,tools:[...options.tools.values()].map(tool=>({name:tool.name,jsName:toCodemodeIdentifier(tool.name),description:tool.description??""})),globals:[...options.globals.values()].map(global=>({name:global.name,spread:global.spread===!0})),wasm,memoryLimitBytes:options.memoryLimitBytes,store:options.store,interrupt:this.interrupt},worker;try{worker=new Worker(options.workerUrl,{workerData})}catch(error){this.finish({kind:"sandbox",message:`Failed to start worker: ${errorMessage(error)}`});return}this.worker=worker,worker.on("message",message=>{try{this.handleMessage(message)}catch(error){this.finish({kind:"sandbox",message:error instanceof BridgeError?`Sandbox bridge broken: ${error.message}. The script may have modified built-ins such as a prototype's toJSON.`:`Sandbox host failed: ${errorMessage(error)}`})}}),worker.on("error",error=>{this.finish({kind:"sandbox",name:error instanceof Error?error.name:void 0,message:errorMessage(error)})}),worker.on("exit",code=>{this.finish({kind:"sandbox",message:`Worker exited with code ${code} before the script settled`})})}onAbort=()=>{let reason=this.signal?.reason;this.finish({kind:"aborted",message:reason instanceof Error?reason.message:"Execution aborted"})};post(message){this.worker?.postMessage(message)}handleMessage(message){if(!this.finished){if(!isWorkerToHostMessage(message))throw new BridgeError("unknown message from the worker");switch(message.type){case"output":this.output.push(message.item);break;case"call":if(this.pending.has(message.id))throw new BridgeError(`duplicate call id ${message.id}`);this.handleCall(message);break;case"done":this.handleDone(message);break;case"crash":this.finish({kind:"sandbox",message:message.message});break}}}handleDone(message){if(!message.ok){this.finish(parseScriptError(message.error));return}let value=message.value===void 0?void 0:parseBridgeJson(message.value,"return value");this.finish(void 0,value,parseStoreWrites(message.writes))}async handleCall(message){let{id,name}=message,isTool=message.target==="tool",record=isTool?{name,status:"cancelled",durationMs:0}:void 0;record&&this.calls.push(record);let pending={record,startedAt:performance.now(),controller:new AbortController};this.pending.set(id,pending);let status,reply;try{let tool=(isTool?this.tools:this.globals).get(name);if(!tool)throw new Error(`Unknown ${isTool?"tool":"global"} "${name}"`);let args=message.args===void 0?void 0:JSON.parse(message.args),value=await tool.execute(args,{signal:pending.controller.signal});reply={type:"result",id,ok:!0,payload:value===void 0?void 0:JSON.stringify(value)},status="ok"}catch(error){reply={type:"result",id,ok:!1,payload:errorMessage(error)},status="error"}this.pending.delete(id)&&(record&&(record.status=status,record.durationMs=performance.now()-pending.startedAt),this.post(reply))}finish(error,value,writes){if(this.finished)return;this.finished=!0,clearTimeout(this.timer),this.signal?.removeEventListener("abort",this.onAbort);let now=performance.now();for(let pending of this.pending.values())pending.record&&(pending.record.durationMs=now-pending.startedAt),pending.controller.abort();this.pending.clear();let result=error?{ok:!1,error,output:this.output,calls:this.calls}:{ok:!0,value,output:this.output,calls:this.calls,storeWrites:writes??{set:{},delete:[]}};if(!this.worker){this.resolveResult(result);return}Atomics.store(new Int32Array(this.interrupt),0,1),this.worker.terminate().catch(()=>{}).then(()=>this.resolveResult(result))}},CodemodeSandbox=class{toolsByName=new Map;globalsByName=new Map;timeoutMs;memoryLimitBytes;wasm;workerUrl;running=new Set;closed=!1;constructor(options={}){this.timeoutMs=options.timeoutMs??DEFAULT_TIMEOUT_MS,this.memoryLimitBytes=options.memoryLimitBytes,this.wasm=options.wasm,this.workerUrl=options.workerUrl??defaultWorkerUrl();for(let tool of options.tools??[])this.registerTool(tool);let namespaces=new Set;for(let global of options.globals??[]){let parts=global.name.split(".");if(parts.length>2||!parts.every(part=>IDENTIFIER.test(part))||RESERVED_GLOBALS.has(parts[0]))throw new Error(`Invalid global name "${global.name}"`);if(this.globalsByName.has(global.name))throw new Error(`Global "${global.name}" is already registered`);parts.length===2&&namespaces.add(parts[0]),this.globalsByName.set(global.name,global)}for(let name of namespaces)if(this.globalsByName.has(name))throw new Error(`Global "${name}" conflicts with the namespace "${name}"`)}registerTool(tool){if(this.toolsByName.has(tool.name))throw new Error(`Tool "${tool.name}" is already registered`);this.toolsByName.set(tool.name,tool)}unregisterTool(name){return this.toolsByName.delete(name)}get tools(){return[...this.toolsByName.values()]}get globals(){return[...this.globalsByName.values()]}execute(code,options={}){if(this.closed)return Promise.reject(new Error("Sandbox is closed"));let execution=new Execution({code,tools:new Map(this.toolsByName),globals:this.globalsByName,timeoutMs:options.timeoutMs??this.timeoutMs,signal:options.signal,memoryLimitBytes:this.memoryLimitBytes,store:serializeStore(options.store),wasm:this.wasm===void 0?loadQuickJSWasm():Promise.resolve(this.wasm),workerUrl:this.workerUrl});return this.running.add(execution),execution.promise.finally(()=>this.running.delete(execution))}async close(){this.closed=!0,await Promise.all([...this.running].map(execution=>execution.abort("Sandbox closed")))}};var IMAGE_HELPER_EXPECTS="image expects a non-empty image URL string, an object with image_url, or a raw MCP image block",PRELUDE_SOURCE=`(function (bridge, toolsJson, globalsJson, storeJson) {
|
|
3
|
+
"use strict";
|
|
4
|
+
|
|
5
|
+
// Freeze every object reachable from the built-in globals, plus the intrinsics that are only
|
|
6
|
+
// reachable from instances (iterator and generator prototypes, %TypedArray%).
|
|
7
|
+
//
|
|
8
|
+
// Freezing alone breaks ordinary code through the "override mistake": a data property that is
|
|
9
|
+
// read-only on a prototype cannot be assigned on an instance either, so
|
|
10
|
+
// this.name = "MyError" in an Error subclass would throw. Commonly overridden properties
|
|
11
|
+
// become accessors whose setter defines an own property on the instance instead.
|
|
12
|
+
(function lockdown() {
|
|
13
|
+
const OVERRIDABLE = new Set(["constructor", "name", "message", "toString", "toLocaleString", "valueOf", "toJSON"]);
|
|
14
|
+
const seen = new Set([globalThis]);
|
|
15
|
+
const queue = [];
|
|
16
|
+
const add = (value) => {
|
|
17
|
+
if ((typeof value === "object" && value !== null) || typeof value === "function") {
|
|
18
|
+
if (!seen.has(value)) {
|
|
19
|
+
seen.add(value);
|
|
20
|
+
queue.push(value);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
// Accessors from an object literal have no own prototype object, unlike function expressions,
|
|
26
|
+
// whose prototype.constructor would be converted again without end.
|
|
27
|
+
function allowOverride(object, key, value, enumerable) {
|
|
28
|
+
const { get, set } = Object.getOwnPropertyDescriptor(
|
|
29
|
+
{
|
|
30
|
+
get accessor() {
|
|
31
|
+
return value;
|
|
32
|
+
},
|
|
33
|
+
set accessor(next) {
|
|
34
|
+
if (this === object) {
|
|
35
|
+
throw new TypeError("Cannot assign to read only property '" + String(key) + "' of a built-in");
|
|
36
|
+
}
|
|
37
|
+
if ((typeof this !== "object" || this === null) && typeof this !== "function") return;
|
|
38
|
+
Object.defineProperty(this, key, { value: next, writable: true, enumerable: true, configurable: true });
|
|
39
|
+
},
|
|
40
|
+
},
|
|
41
|
+
"accessor",
|
|
42
|
+
);
|
|
43
|
+
Object.defineProperty(object, key, { get, set, enumerable, configurable: false });
|
|
44
|
+
add(get);
|
|
45
|
+
add(set);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
for (const key of Reflect.ownKeys(globalThis)) {
|
|
49
|
+
const descriptor = Object.getOwnPropertyDescriptor(globalThis, key);
|
|
50
|
+
add(descriptor.value);
|
|
51
|
+
add(descriptor.get);
|
|
52
|
+
add(descriptor.set);
|
|
53
|
+
if ("value" in descriptor && descriptor.configurable) {
|
|
54
|
+
Object.defineProperty(globalThis, key, { writable: false, configurable: false });
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
add(Object.getPrototypeOf(function* () {}));
|
|
58
|
+
add(Object.getPrototypeOf(async function () {}));
|
|
59
|
+
add(Object.getPrototypeOf(async function* () {}));
|
|
60
|
+
add(Object.getPrototypeOf(Int8Array));
|
|
61
|
+
add(Object.getPrototypeOf([][Symbol.iterator]()));
|
|
62
|
+
add(Object.getPrototypeOf(new Map()[Symbol.iterator]()));
|
|
63
|
+
add(Object.getPrototypeOf(new Set()[Symbol.iterator]()));
|
|
64
|
+
add(Object.getPrototypeOf(""[Symbol.iterator]()));
|
|
65
|
+
add(Object.getPrototypeOf(/a/[Symbol.matchAll]("")));
|
|
66
|
+
if (typeof Iterator === "function") {
|
|
67
|
+
if (typeof Iterator.prototype.map === "function") add(Object.getPrototypeOf([].values().map((x) => x)));
|
|
68
|
+
if (typeof Iterator.from === "function") add(Object.getPrototypeOf(Iterator.from({ next() {} })));
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
while (queue.length > 0) {
|
|
72
|
+
const object = queue.pop();
|
|
73
|
+
add(Object.getPrototypeOf(object));
|
|
74
|
+
const descriptors = Object.getOwnPropertyDescriptors(object);
|
|
75
|
+
for (const key of Reflect.ownKeys(descriptors)) {
|
|
76
|
+
const descriptor = descriptors[key];
|
|
77
|
+
if ("value" in descriptor) {
|
|
78
|
+
add(descriptor.value);
|
|
79
|
+
if (
|
|
80
|
+
descriptor.writable &&
|
|
81
|
+
descriptor.configurable &&
|
|
82
|
+
(object === Object.prototype || OVERRIDABLE.has(key))
|
|
83
|
+
) {
|
|
84
|
+
allowOverride(object, key, descriptor.value, descriptor.enumerable);
|
|
85
|
+
}
|
|
86
|
+
} else {
|
|
87
|
+
add(descriptor.get);
|
|
88
|
+
add(descriptor.set);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
Object.freeze(object);
|
|
92
|
+
}
|
|
93
|
+
})();
|
|
94
|
+
const stringify = JSON.stringify;
|
|
95
|
+
const parse = JSON.parse;
|
|
96
|
+
const promiseThen = Promise.prototype.then;
|
|
97
|
+
const ErrorCtor = Error;
|
|
98
|
+
const TypeErrorCtor = TypeError;
|
|
99
|
+
const RangeErrorCtor = RangeError;
|
|
100
|
+
const pending = new Map();
|
|
101
|
+
let nextId = 1;
|
|
102
|
+
let finished = false;
|
|
103
|
+
// Thrown by exit() to unwind the script after it already reported success.
|
|
104
|
+
const EXIT = Object.freeze({});
|
|
105
|
+
|
|
106
|
+
function done(ok, payload, writes) {
|
|
107
|
+
if (finished) return;
|
|
108
|
+
finished = true;
|
|
109
|
+
bridge("done", ok, payload, writes);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function serialize(value) {
|
|
113
|
+
return value === undefined ? undefined : stringify(value);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// QuickJS stacks list frames only. Prefix "Name: message" like V8 so the
|
|
117
|
+
// text reads the same as a Node error, and drop this prelude's frames.
|
|
118
|
+
function errorText(error) {
|
|
119
|
+
const head = error.message ? error.name + ": " + error.message : String(error.name);
|
|
120
|
+
const frames =
|
|
121
|
+
typeof error.stack === "string"
|
|
122
|
+
? error.stack.split("\\n").filter((line) => line.trim() && !line.includes("codemode-prelude.js"))
|
|
123
|
+
: [];
|
|
124
|
+
return [head, ...frames].join("\\n");
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function format(value) {
|
|
128
|
+
if (typeof value === "string") return value;
|
|
129
|
+
if (value instanceof ErrorCtor) return errorText(value);
|
|
130
|
+
try {
|
|
131
|
+
const json = stringify(value);
|
|
132
|
+
return json === undefined ? String(value) : json;
|
|
133
|
+
} catch {
|
|
134
|
+
return String(value);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// The host requires string fields. A script can set an error's name or message to anything, so
|
|
139
|
+
// they are coerced, and a value whose coercion throws gets a placeholder.
|
|
140
|
+
function describeError(error) {
|
|
141
|
+
try {
|
|
142
|
+
if (error instanceof ErrorCtor) {
|
|
143
|
+
return stringify({ name: String(error.name), message: String(error.message), stack: errorText(error) });
|
|
144
|
+
}
|
|
145
|
+
return stringify({ message: String(format(error)) });
|
|
146
|
+
} catch {
|
|
147
|
+
return stringify({ message: "The script threw a value that cannot be described" });
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function caller(kind, name, spread) {
|
|
152
|
+
return (...args) =>
|
|
153
|
+
new Promise((resolve, reject) => {
|
|
154
|
+
let json;
|
|
155
|
+
try {
|
|
156
|
+
json = serialize(spread ? args : args[0]);
|
|
157
|
+
} catch (error) {
|
|
158
|
+
reject(error);
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
const id = nextId++;
|
|
162
|
+
pending.set(id, { resolve, reject });
|
|
163
|
+
bridge(kind, id, name, json);
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const tools = Object.create(null);
|
|
168
|
+
const allTools = [];
|
|
169
|
+
for (const { name, jsName, description } of parse(toolsJson)) {
|
|
170
|
+
const fn = caller("call", name);
|
|
171
|
+
// The first tool wins when two names normalize to the same identifier.
|
|
172
|
+
if (!(jsName in tools)) {
|
|
173
|
+
tools[jsName] = fn;
|
|
174
|
+
allTools.push(Object.freeze({ name: jsName, description }));
|
|
175
|
+
}
|
|
176
|
+
if (!(name in tools)) tools[name] = fn;
|
|
177
|
+
}
|
|
178
|
+
Object.freeze(tools);
|
|
179
|
+
Object.freeze(allTools);
|
|
180
|
+
|
|
181
|
+
// Reading a member that does not exist throws an error that names the close matches, instead of
|
|
182
|
+
// a later "not a function". \`in\` checks still work.
|
|
183
|
+
const comparable = (name) => name.toLowerCase().replace(/[^a-z0-9]/g, "");
|
|
184
|
+
function guard(target, label, names, hint) {
|
|
185
|
+
return new Proxy(target, {
|
|
186
|
+
get(object, property, receiver) {
|
|
187
|
+
if (typeof property !== "string" || property in object || property in Object.prototype || property === "then" || property === "toJSON") {
|
|
188
|
+
return Reflect.get(object, property, receiver);
|
|
189
|
+
}
|
|
190
|
+
const wanted = comparable(property);
|
|
191
|
+
const exact = names.filter((name) => comparable(name) === wanted);
|
|
192
|
+
const close = exact.length > 0 ? exact : names.filter((name) => wanted && (comparable(name).includes(wanted) || wanted.includes(comparable(name))));
|
|
193
|
+
let message = label + "." + property + " does not exist.";
|
|
194
|
+
if (close.length > 0) message += " Did you mean " + close.slice(0, 5).map((name) => label + "." + name).join(", ") + "?";
|
|
195
|
+
else if (names.length <= 20) message += " Available: " + names.join(", ") + ".";
|
|
196
|
+
if (hint) message += " " + hint;
|
|
197
|
+
message += ' Check for a member with "' + property + '" in ' + label + ".";
|
|
198
|
+
throw new TypeErrorCtor(message);
|
|
199
|
+
},
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
const toolsProxy = guard(
|
|
203
|
+
tools,
|
|
204
|
+
"tools",
|
|
205
|
+
allTools.map((tool) => tool.name),
|
|
206
|
+
"ALL_TOOLS lists every tool; searchTools(query) finds tools by topic.",
|
|
207
|
+
);
|
|
208
|
+
|
|
209
|
+
const namespaces = new Map();
|
|
210
|
+
for (const { name, spread } of parse(globalsJson)) {
|
|
211
|
+
const fn = caller("global", name, spread);
|
|
212
|
+
const dot = name.indexOf(".");
|
|
213
|
+
if (dot === -1) {
|
|
214
|
+
Object.defineProperty(globalThis, name, { value: fn, enumerable: true });
|
|
215
|
+
continue;
|
|
216
|
+
}
|
|
217
|
+
const namespace = name.slice(0, dot);
|
|
218
|
+
if (!namespaces.has(namespace)) namespaces.set(namespace, Object.create(null));
|
|
219
|
+
namespaces.get(namespace)[name.slice(dot + 1)] = fn;
|
|
220
|
+
}
|
|
221
|
+
for (const [namespace, members] of namespaces) {
|
|
222
|
+
Object.freeze(members);
|
|
223
|
+
const value = guard(members, namespace, Object.keys(members));
|
|
224
|
+
Object.defineProperty(globalThis, namespace, { value, enumerable: true });
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// key -> JSON text. Sizes count key and JSON characters.
|
|
228
|
+
const stored = new Map(Object.entries(parse(storeJson)));
|
|
229
|
+
const writes = new Map();
|
|
230
|
+
let storedChars = 0;
|
|
231
|
+
for (const [key, json] of stored) storedChars += key.length + json.length;
|
|
232
|
+
|
|
233
|
+
const STORE_HINT =
|
|
234
|
+
"store() is for small state such as IDs or summaries. Show images with image(), keep large data in variables, or write it to a file with a tool.";
|
|
235
|
+
|
|
236
|
+
function checkKey(name, key) {
|
|
237
|
+
if (typeof key !== "string") throw new TypeError(name + "() key must be a string");
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function store(key, value) {
|
|
241
|
+
checkKey("store", key);
|
|
242
|
+
const previous = stored.has(key) ? key.length + stored.get(key).length : 0;
|
|
243
|
+
if (value === undefined) {
|
|
244
|
+
stored.delete(key);
|
|
245
|
+
storedChars -= previous;
|
|
246
|
+
writes.set(key, undefined);
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
let json;
|
|
250
|
+
try {
|
|
251
|
+
json = stringify(value);
|
|
252
|
+
} catch (error) {
|
|
253
|
+
throw new TypeError("store(" + stringify(key) + ") value is not JSON-serializable: " + format(error));
|
|
254
|
+
}
|
|
255
|
+
if (json === undefined) {
|
|
256
|
+
throw new TypeError("store(" + stringify(key) + ") value is not JSON-serializable");
|
|
257
|
+
}
|
|
258
|
+
if (json.length > 262144) {
|
|
259
|
+
throw new RangeError(
|
|
260
|
+
"store(" + stringify(key) + ") value has " + json.length + " characters of JSON, more than the limit of 262144. " +
|
|
261
|
+
STORE_HINT,
|
|
262
|
+
);
|
|
263
|
+
}
|
|
264
|
+
const next = storedChars - previous + key.length + json.length;
|
|
265
|
+
if (next > 1048576) {
|
|
266
|
+
throw new RangeError(
|
|
267
|
+
"store is full: stored values would exceed 1048576 characters of JSON. Delete keys with store(key, undefined). " +
|
|
268
|
+
STORE_HINT,
|
|
269
|
+
);
|
|
270
|
+
}
|
|
271
|
+
stored.set(key, json);
|
|
272
|
+
storedChars = next;
|
|
273
|
+
writes.set(key, json);
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
function load(key) {
|
|
277
|
+
checkKey("load", key);
|
|
278
|
+
const json = stored.get(key);
|
|
279
|
+
return json === undefined ? undefined : parse(json);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function serializeWrites() {
|
|
283
|
+
const entries = [];
|
|
284
|
+
for (const [key, json] of writes) entries.push(json === undefined ? [key] : [key, json]);
|
|
285
|
+
return stringify(entries);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
Object.defineProperty(globalThis, "store", { value: store, enumerable: true });
|
|
289
|
+
Object.defineProperty(globalThis, "load", { value: load, enumerable: true });
|
|
290
|
+
|
|
291
|
+
let outputChars = 0;
|
|
292
|
+
let outputItems = 0;
|
|
293
|
+
|
|
294
|
+
// Past the output limits the script fails: done() reports the error, so catching it does not
|
|
295
|
+
// resume output, and the host ends the script.
|
|
296
|
+
function output(kind, data, mimeType) {
|
|
297
|
+
if (finished) return;
|
|
298
|
+
outputChars += data.length;
|
|
299
|
+
outputItems++;
|
|
300
|
+
if (outputChars > 16777216 || outputItems > 100000) {
|
|
301
|
+
const error = new RangeErrorCtor(
|
|
302
|
+
"script output exceeded the limit of 16777216 characters or 100000 text(), image(), and console calls. " +
|
|
303
|
+
"Print a summary instead, or write large data to a file with a tool.",
|
|
304
|
+
);
|
|
305
|
+
done(false, describeError(error));
|
|
306
|
+
throw error;
|
|
307
|
+
}
|
|
308
|
+
bridge("output", kind, data, mimeType);
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// Primitives become their string form, everything else JSON.
|
|
312
|
+
function outputText(value) {
|
|
313
|
+
if (value === undefined || value === null || typeof value !== "object" && typeof value !== "function") {
|
|
314
|
+
return String(value);
|
|
315
|
+
}
|
|
316
|
+
const json = stringify(value);
|
|
317
|
+
return json === undefined ? String(value) : json;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
function text(value) {
|
|
321
|
+
let rendered;
|
|
322
|
+
try {
|
|
323
|
+
rendered = outputText(value);
|
|
324
|
+
} catch (error) {
|
|
325
|
+
throw new TypeErrorCtor(error instanceof ErrorCtor ? error.message : String(error));
|
|
326
|
+
}
|
|
327
|
+
output("text", rendered);
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
function imageUrl(value) {
|
|
331
|
+
if (typeof value === "string") return value;
|
|
332
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
333
|
+
throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});
|
|
334
|
+
}
|
|
335
|
+
if (value.image_url !== undefined) {
|
|
336
|
+
if (typeof value.image_url !== "string") throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});
|
|
337
|
+
return value.image_url;
|
|
338
|
+
}
|
|
339
|
+
if (typeof value.type !== "string") throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});
|
|
340
|
+
if (value.type !== "image") {
|
|
341
|
+
throw new TypeErrorCtor('image only accepts MCP image blocks, got "' + value.type + '"');
|
|
342
|
+
}
|
|
343
|
+
if (typeof value.data !== "string" || value.data === "") throw new TypeErrorCtor("image expected MCP image data");
|
|
344
|
+
if (value.data.toLowerCase().startsWith("data:")) return value.data;
|
|
345
|
+
return "data:;base64," + value.data;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
// Base64 of the signatures of the formats providers accept inline (PNG, JPEG except
|
|
349
|
+
// JPEG-LS, GIF, "RIFF....WEBP"). Signatures start at byte 0, so their encodings are prefixes.
|
|
350
|
+
const IMAGE_SIGNATURES = [
|
|
351
|
+
["image/png", /^iVBORw0KGg/],
|
|
352
|
+
["image/jpeg", /^[/]9j[/](?!9)/],
|
|
353
|
+
["image/gif", /^R0lGOD[dl]h/],
|
|
354
|
+
["image/webp", /^UklG.{8}RUJQ/],
|
|
355
|
+
];
|
|
356
|
+
|
|
357
|
+
function image(value) {
|
|
358
|
+
const url = imageUrl(value);
|
|
359
|
+
if (url === "") throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});
|
|
360
|
+
const colon = url.indexOf(":");
|
|
361
|
+
const scheme = colon === -1 ? "" : url.slice(0, colon).toLowerCase();
|
|
362
|
+
if (scheme === "http" || scheme === "https") {
|
|
363
|
+
throw new TypeErrorCtor("remote image URLs are not supported in tool outputs. Pass a base64 data URI instead");
|
|
364
|
+
}
|
|
365
|
+
const comma = url.indexOf(",");
|
|
366
|
+
const header = comma === -1 ? [] : url.slice(colon + 1, comma).split(";");
|
|
367
|
+
if (scheme !== "data" || comma === -1 || header.slice(1).every((part) => part.toLowerCase() !== "base64")) {
|
|
368
|
+
throw new TypeErrorCtor("invalid image output. Pass a base64 data URI instead");
|
|
369
|
+
}
|
|
370
|
+
// Providers reject the whole request on a bad image, and a persisted image block would be
|
|
371
|
+
// resent on every later turn. Line breaks from wrapped base64 are dropped. The declared type
|
|
372
|
+
// is ignored in favor of the detected one, as providers also reject mismatches.
|
|
373
|
+
const data = url.slice(comma + 1).replace(/\\s+/g, "");
|
|
374
|
+
if (data.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(data)) {
|
|
375
|
+
throw new TypeErrorCtor("invalid image output. The image data is not valid base64 (truncated or corrupted?)");
|
|
376
|
+
}
|
|
377
|
+
const head = data.slice(0, 16);
|
|
378
|
+
const signature = IMAGE_SIGNATURES.find(([, pattern]) => pattern.test(head));
|
|
379
|
+
if (!signature) {
|
|
380
|
+
throw new TypeErrorCtor("invalid image output. The image data is not a PNG, JPEG, GIF, or WebP image");
|
|
381
|
+
}
|
|
382
|
+
output("image", data, signature[0]);
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
function exit() {
|
|
386
|
+
let writesJson;
|
|
387
|
+
try {
|
|
388
|
+
writesJson = serializeWrites();
|
|
389
|
+
} catch (error) {
|
|
390
|
+
done(false, describeError(error));
|
|
391
|
+
throw EXIT;
|
|
392
|
+
}
|
|
393
|
+
done(true, undefined, writesJson);
|
|
394
|
+
throw EXIT;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
const console = {};
|
|
398
|
+
for (const level of ["log", "info", "warn", "error", "debug"]) {
|
|
399
|
+
console[level] = (...args) => {
|
|
400
|
+
output("text", args.map(format).join(" "));
|
|
401
|
+
};
|
|
402
|
+
}
|
|
403
|
+
Object.freeze(console);
|
|
404
|
+
|
|
405
|
+
Object.defineProperty(globalThis, "tools", { value: toolsProxy, enumerable: true });
|
|
406
|
+
Object.defineProperty(globalThis, "ALL_TOOLS", { value: allTools, enumerable: true });
|
|
407
|
+
Object.defineProperty(globalThis, "console", { value: console, enumerable: true });
|
|
408
|
+
Object.defineProperty(globalThis, "text", { value: text, enumerable: true });
|
|
409
|
+
Object.defineProperty(globalThis, "image", { value: image, enumerable: true });
|
|
410
|
+
Object.defineProperty(globalThis, "exit", { value: exit, enumerable: true });
|
|
411
|
+
|
|
412
|
+
return {
|
|
413
|
+
settle(id, ok, payload) {
|
|
414
|
+
const entry = pending.get(id);
|
|
415
|
+
if (!entry) return;
|
|
416
|
+
pending.delete(id);
|
|
417
|
+
if (!ok) {
|
|
418
|
+
entry.reject(new ErrorCtor(payload));
|
|
419
|
+
return;
|
|
420
|
+
}
|
|
421
|
+
let value;
|
|
422
|
+
try {
|
|
423
|
+
value = payload === undefined ? undefined : parse(payload);
|
|
424
|
+
} catch (error) {
|
|
425
|
+
entry.reject(error);
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
entry.resolve(value);
|
|
429
|
+
},
|
|
430
|
+
run(fn) {
|
|
431
|
+
let promise;
|
|
432
|
+
try {
|
|
433
|
+
promise = fn(toolsProxy, console);
|
|
434
|
+
} catch (error) {
|
|
435
|
+
done(false, describeError(error));
|
|
436
|
+
return;
|
|
437
|
+
}
|
|
438
|
+
promiseThen.call(
|
|
439
|
+
promise,
|
|
440
|
+
(value) => {
|
|
441
|
+
let json;
|
|
442
|
+
try {
|
|
443
|
+
json = serialize(value);
|
|
444
|
+
} catch (error) {
|
|
445
|
+
done(false, describeError(error));
|
|
446
|
+
return;
|
|
447
|
+
}
|
|
448
|
+
done(true, json, serializeWrites());
|
|
449
|
+
},
|
|
450
|
+
(error) => {
|
|
451
|
+
done(false, describeError(error));
|
|
452
|
+
},
|
|
453
|
+
);
|
|
454
|
+
},
|
|
455
|
+
stalled() {
|
|
456
|
+
if (finished || pending.size > 0) return false;
|
|
457
|
+
done(
|
|
458
|
+
false,
|
|
459
|
+
stringify({
|
|
460
|
+
name: "Error",
|
|
461
|
+
message:
|
|
462
|
+
"The script is waiting on a promise that can never settle: no tool call is pending, and timers do not exist here.",
|
|
463
|
+
}),
|
|
464
|
+
);
|
|
465
|
+
return true;
|
|
466
|
+
},
|
|
467
|
+
};
|
|
468
|
+
})`;var ARGS_PREVIEW_CHARS=200,ERROR_PREVIEW_CHARS=500,MAX_CONCURRENT_MODEL_CALLS=4,CODEMODE_MEMORY_LIMIT_BYTES=256*1024*1024,MODEL_TYPES=new Set(["chat","image","classifier"]);function truncateText(text,maxChars){return text.length>maxChars?`${text.slice(0,maxChars-3)}...`:text}function previewArgs(args){if(args===void 0)return"";try{return truncateText(JSON.stringify(args)??"",ARGS_PREVIEW_CHARS)}catch{return""}}function textOf(result){return(result.content??[]).filter(block=>block.type==="text").map(block=>block.text).join(`
|
|
469
|
+
`)}function toModelType(value){if(typeof value=="string"&&MODEL_TYPES.has(value))return value;throw new Error(`Unknown model type ${JSON.stringify(value)}. Use "chat", "image", or "classifier".`)}function toProvider(value){if(value!=null){if(typeof value!="string")throw new Error("provider must be a string");return value}}function toModelInfo(model){let info={...model};return delete info.headers,info}function withArticle(word){return`${/^[aeiou]/.test(word)?"an":"a"} ${word}`}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function describeValue(value){if(value==null)return String(value);if(Array.isArray(value))return value.length===0?"an empty array":"an array";if(typeof value=="object"){let keys=Object.keys(value);return keys.length===0?"{}":`{ ${keys.slice(0,6).join(", ")}${keys.length>6?", ...":""} }`}return typeof value=="string"?"a string":`a ${typeof value}`}var CLASSIFIER_CONTEXT_SHAPE='{ state: { ... }, questions: { <id>: { type: "choice", instructions, criteria: { <label>: <meaning> } } | { type: "score", instructions, criteria: [<lowest level>, ..., <highest level>] } | { type: "bool", instructions, criteria: { true: <meaning>, false: <meaning> } } } }';function checkClassifierContext(context){let fail=problem=>new Error(`models.classify() ${problem}. Expected context: ${CLASSIFIER_CONTEXT_SHAPE}. See "Classify" in ${CODEMODE_DOCS_PATH}.`);if(!isRecord(context))throw fail(`expects a context object as its second argument, got ${describeValue(context)}`);if(!isRecord(context.state))throw fail(`context.state must be an object, got ${describeValue(context.state)}`);let{questions}=context;if(!isRecord(questions)||Object.keys(questions).length===0)throw fail(`context.questions must map question IDs to questions, got ${describeValue(questions)}`);let isStrings=values=>values.length>0&&values.every(value=>typeof value=="string");for(let[id,question]of Object.entries(questions)){let at=`context.questions.${id}`;if(!isRecord(question))throw fail(`${at} must be a question object, got ${describeValue(question)}`);if(typeof question.instructions!="string")throw fail(`${at}.instructions must be a string`);let{criteria}=question;if(question.type==="choice"){if(!isRecord(criteria)||!isStrings(Object.values(criteria)))throw fail(`${at} is a "choice" question, so criteria must map each label to its meaning`)}else if(question.type==="score"){if(!Array.isArray(criteria)||!isStrings(criteria))throw fail(`${at} is a "score" question, so criteria must list the levels as strings, lowest first`)}else if(question.type==="bool"){if(!isRecord(criteria)||typeof criteria.true!="string"||typeof criteria.false!="string")throw fail(`${at} is a "bool" question, so criteria must be { true: string, false: string }`)}else throw fail(`${at}.type must be "choice", "score", or "bool", got ${JSON.stringify(question.type)}`)}return context}function checkImagesContext(context){let fail=problem=>new Error(`models.generateImages() ${problem}. Expected context: { input: [{ type: "text", text: <prompt> }, ...optional { type: "image", data: <base64>, mimeType } references] }. See "Generate images" in ${CODEMODE_DOCS_PATH}.`);if(!isRecord(context))throw fail(`expects a context object as its second argument, got ${describeValue(context)}`);let{input}=context;if(!Array.isArray(input)||input.length===0)throw fail(`context.input must be a non-empty array of blocks, got ${describeValue(input)}`);return input.forEach((block,index)=>{if(!(isRecord(block)&&block.type==="text"&&typeof block.text=="string")&&!(isRecord(block)&&block.type==="image"&&typeof block.data=="string"&&typeof block.mimeType=="string"))throw fail(`context.input[${index}] must be a text or image block, got ${describeValue(block)}`)}),context}function createLimiter(limit){let active=0,waiting=[];return async run=>{active>=limit&&await new Promise(resolve=>waiting.push(resolve)),active++;try{return await run()}finally{active--,waiting.shift()?.()}}}function isStoreEntryData(data){if(typeof data!="object"||data===null)return!1;let{set,delete:deleted}=data;return typeof set=="object"&&set!==null&&Array.isArray(deleted)&&deleted.every(key=>typeof key=="string")}function readCodemodeStore(branch){let store=new Map;for(let entry of branch)if(!(entry.type!=="custom"||entry.customType!==CODEMODE_STORE_ENTRY_TYPE||!isStoreEntryData(entry.data))){for(let key of entry.data.delete)store.delete(key);for(let[key,value]of Object.entries(entry.data.set))store.set(key,value)}return Object.fromEntries(store)}var DEFAULT_MAX_OUTPUT_TOKENS=1e4,CHARS_PER_TOKEN=4;function valueText(value){return typeof value=="string"?value:JSON.stringify(value)??String(value)}function formatCallSummary(calls){return calls.length===0?"No tool calls were made.":`Tool calls made before the failure (they are not undone): ${calls.map(call=>`${call.name} (${call.status})`).join(", ")}`}function formatError(result,calls){let{error}=result;return`${error.kind==="script"?error.stack??`${error.name??"Error"}: ${error.message}`:error.kind==="timeout"?`Script timed out: ${error.message}`:error.kind==="aborted"?`Script aborted: ${error.message}`:`Script sandbox failed: ${error.message}`}
|
|
470
|
+
|
|
471
|
+
${formatCallSummary(calls)}`}async function spillOutput(text){try{return{path:await writeOutputFile("pi-codemode",".txt",text)}}catch(error){return{error:error instanceof Error?error.message:String(error)}}}var IMAGE_EXTENSIONS={"image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp"};async function saveImages(items){let labels=new Map,label=async({data,mimeType})=>{let bytes=Buffer.from(data,"base64"),kind=`${mimeType}, ${formatSize(bytes.length)}`,extension=IMAGE_EXTENSIONS[mimeType];if(!extension)throw new Error(`No file extension for image type ${mimeType}`);try{return`[Image saved to ${await writeOutputFile("pi-codemode",extension,bytes)} (${kind})]`}catch(error){return`[Image (${kind}) could not be saved: ${error instanceof Error?error.message:String(error)}]`}};return(await Promise.all(items.map(async item=>{if(item.type!=="image")return[item];let pending=labels.get(item.data);return pending||(pending=label(item),labels.set(item.data,pending)),[{type:"text",text:await pending},item]}))).flat()}async function truncateOutput(items,maxTokens){let texts=items.filter(item=>item.type==="text").map(item=>item.text),combined=texts.join(`
|
|
472
|
+
`),budget=maxTokens*CHARS_PER_TOKEN;if(texts.length===0||combined.length<=budget)return{items};let headChars=Math.floor(budget/2),tailChars=budget-headChars,removed=combined.length-headChars-tailChars,head=combined.slice(0,headChars),tail=tailChars>0?combined.slice(-tailChars):"",text=`Warning: truncated output (original token count: ${Math.ceil(combined.length/CHARS_PER_TOKEN)})
|
|
473
|
+
Total output lines: ${combined.split(`
|
|
474
|
+
`).length}
|
|
475
|
+
|
|
476
|
+
${head}\u2026${Math.ceil(removed/CHARS_PER_TOKEN)} tokens truncated\u2026${tail}`,spilled=await spillOutput(combined);return text+="path"in spilled?`
|
|
477
|
+
|
|
478
|
+
[Full output: ${spilled.path} (read with offset/limit)]`:`
|
|
479
|
+
|
|
480
|
+
[Could not save the full output: ${spilled.error}]`,{items:[{type:"text",text},...items.filter(item=>item.type==="image")],..."path"in spilled?{fullOutputPath:spilled.path}:{}}}function toScriptValue(tool,outcome){let{result}=outcome;if(tool.outputSchema&&result.structuredContent!==void 0)return result.structuredContent;let text=textOf(result);if(outcome.isError)throw new Error(text||`Tool "${tool.name}" failed`);return text}async function executeCodemode(toolCallId,input,signal,onUpdate,ctx,options={}){let startedAt=performance.now(),{code,options:sourceOptions}=parseCodemodeSource(input.code),calls=[],modelUsage,generatedImages=0,addGeneratedImages=count=>{generatedImages+=count},addModelUsage=usage=>{modelUsage=modelUsage?combineUsage(modelUsage,usage):usage},snapshot=()=>({calls:calls.map(call=>({...call}))}),publish=()=>onUpdate?.({content:[],details:snapshot()}),callable=ctx?getCodemodeCallableTools(ctx.tools):[],guidelines=options.getToolGuidelines?.(),samples=new Map(callable.map(tool=>[tool.name,renderToolSample(toCodemodeDeclaration(tool,guidelines?.get(tool.name)))])),sandboxTools=callable.map(tool=>({name:tool.name,description:samples.get(tool.name),execute:async(args,{signal:callSignal})=>{let record={id:`${toolCallId}/?`,name:tool.name,args:previewArgs(args),status:"running"};calls.push(record),publish();let callStartedAt=performance.now();if(!ctx)throw new Error("Tool calls need a session");let outcome=await ctx.executeTool(tool.name,args,{signal:callSignal});return record.id=outcome.toolCall.id,record.durationMs=performance.now()-callStartedAt,outcome.isError?(record.status=callSignal.aborted?"cancelled":"error",record.error=truncateText(textOf(outcome.result)||`Tool "${tool.name}" failed`,ERROR_PREVIEW_CHARS)):record.status="ok",publish(),toScriptValue(tool,outcome)}})),sandbox=new CodemodeSandbox({tools:sandboxTools,globals:[...createDiscoveryGlobals(callable,samples,options),...options.models&&ctx?createModelGlobals(ctx.modelRegistry,toolCallId,calls,publish,addModelUsage,addGeneratedImages):[]],timeoutMs:sourceOptions.timeoutMs??Number.POSITIVE_INFINITY,memoryLimitBytes:CODEMODE_MEMORY_LIMIT_BYTES,wasm:loadQuickJSWasm(getQuickJSWasmPath()),workerUrl:getCodemodeWorkerSpecifier()}),result;try{let store=ctx?readCodemodeStore(ctx.sessionManager.getBranch()):{};result=await sandbox.execute(code,{signal,store})}finally{await sandbox.close()}for(let call of calls)call.status==="running"&&(call.status="cancelled");let items=result.output.map(item=>item.type==="text"?{type:"text",text:item.text}:item);if(result.ok){let{set,delete:deleted}=result.storeWrites;(Object.keys(set).length>0||deleted.length>0)&&options.appendEntry?.(CODEMODE_STORE_ENTRY_TYPE,{set,delete:deleted}),result.value!==void 0&&items.push({type:"text",text:valueText(result.value)})}else items.push({type:"text",text:`Script error:
|
|
481
|
+
${formatError(result,calls)}`});generatedImages>0&&!items.some(item=>item.type==="image")&&items.push({type:"text",text:`Note: models.generateImages() returned ${generatedImages} image${generatedImages===1?"":"s"} that the script did not show. Show each image block of result.output with image(block).`});let truncated=await truncateOutput(items,sourceOptions.maxOutputTokens??DEFAULT_MAX_OUTPUT_TOKENS),output=await saveImages(truncated.items),wallTime=((performance.now()-startedAt)/1e3).toFixed(1),header=`${result.ok?"Script completed":"Script failed"}
|
|
482
|
+
Wall time ${wallTime} seconds
|
|
483
|
+
Output:
|
|
484
|
+
`,details=snapshot();return truncated.fullOutputPath&&(details.fullOutputPath=truncated.fullOutputPath),{content:[{type:"text",text:header},...output],details,...modelUsage?{usage:modelUsage}:{},...result.ok?{}:{isError:!0}}}function isNamespaceName(namespace,query){let id=toCodemodeIdentifier(namespace),queryId=toCodemodeIdentifier(query),suffix=name=>name.includes("__")?name.slice(name.lastIndexOf("__")+2):void 0;return namespace===query||id===queryId||suffix(namespace)===query||suffix(id)===queryId}function createDiscoveryGlobals(tools,samples,options){let ranker=new Bm25Ranker,entry=name=>({name:toCodemodeIdentifier(name),description:samples.get(name)??""});return[{name:"searchTools",spread:!0,execute:args=>{let[query,searchOptions]=args;if(typeof query!="string")throw new Error("searchTools() expects a query string");let limit=searchOptions?.limit??DEFAULT_TOOL_SEARCH_LIMIT;if(typeof limit!="number"||!Number.isInteger(limit)||limit<=0)throw new Error("searchTools() limit must be a positive integer");let namespace=searchOptions?.namespace;if(namespace!=null&&typeof namespace!="string")throw new Error("searchTools() namespace must be a string");let documents=tools.flatMap(tool=>{let toolNamespace=options.getToolNamespace?.(tool.name);return namespace&&(!toolNamespace||!isNamespaceName(toolNamespace.name,namespace))?[]:[createToolSearchDocument(tool,toolNamespace)]});return ranker.rank(query,documents,limit).map(match=>entry(match.name))}},{name:"describeTool",spread:!0,execute:args=>{let[name]=args;if(typeof name!="string")throw new Error("describeTool() expects a tool name");let tool=tools.find(candidate=>candidate.name===name||toCodemodeIdentifier(candidate.name)===name);return tool?samples.get(tool.name):void 0}},{name:"describeNamespace",spread:!0,execute:args=>{let[name]=args;if(typeof name!="string")throw new Error("describeNamespace() expects a namespace name");let namespace,names=[];for(let tool of tools){let toolNamespace=options.getToolNamespace?.(tool.name);!toolNamespace||!isNamespaceName(toolNamespace.name,name)||(namespace??=toolNamespace,names.push(toCodemodeIdentifier(tool.name)))}if(namespace)return{name:namespace.name,...namespace.description?{description:namespace.description}:{},...namespace.instructions?{instructions:namespace.instructions}:{},tools:names}}}]}function createModelGlobals(models,toolCallId,calls,publish,addUsage,addGeneratedImages){let limit=createLimiter(MAX_CONCURRENT_MODEL_CALLS),callCount=0,runModelCall=async(name,type,[model,context],checkContext,run)=>{let listHint=`List the ${type} models you can use with models.getAvailableOfType("${type}").`;if(!isRecord(model)||typeof model.provider!="string"||typeof model.id!="string"){let undefinedHint=model==null?" models.getModelOfType() returns undefined for an unknown provider or id.":"";throw new Error(`${name}() expects ${withArticle(type)} model as its first argument, got ${describeValue(model)}.${undefinedHint} ${listHint}`)}let{provider,id}=model,ref=`${provider}/${id}`,resolved=models.getModelOfType(type,provider,id);if(!resolved){let actualType=[...MODEL_TYPES].find(other=>other!==type&&models.getModelOfType(other,provider,id)!==void 0);throw new Error(actualType?`"${ref}" is ${withArticle(actualType)} model, not ${withArticle(type)} model. ${listHint}`:`Unknown ${type} model "${ref}". ${listHint}`)}let checked=checkContext(context),record={id:`${toolCallId}/${name}/${++callCount}`,name,args:`${resolved.provider}/${resolved.id}`,status:"running"};calls.push(record),publish();let startedAt=performance.now(),result=await limit(()=>run(resolved,checked));return record.durationMs=performance.now()-startedAt,record.status=result.stopReason==="stop"?"ok":result.stopReason==="aborted"?"cancelled":"error",result.errorMessage&&(record.error=truncateText(result.errorMessage,ERROR_PREVIEW_CHARS)),result.usage&&(record.cost=result.usage.cost.total,addUsage(result.usage)),publish(),result};return Object.entries({"models.getModelsOfType":args=>{let[type,provider]=args;return models.getModelsOfType(toModelType(type),toProvider(provider)).map(toModelInfo)},"models.getAvailableOfType":async(args,{signal})=>{let[type,provider]=args;return(await models.getAvailableOfType(toModelType(type),toProvider(provider),{signal})).map(toModelInfo)},"models.getModelOfType":args=>{let[type,provider,id]=args;if(typeof provider!="string"||typeof id!="string")throw new Error(`models.getModelOfType(type, provider, id) expects three strings, got (${args.map(describeValue).join(", ")}). The provider and the id are separate arguments, for example models.getModelOfType("classifier", "typesafe", "jev-latest").`);let model=models.getModelOfType(toModelType(type),provider,id);return model===void 0?void 0:toModelInfo(model)},"models.classify":(args,{signal})=>runModelCall("models.classify","classifier",args,checkClassifierContext,(resolved,context)=>models.classify(resolved,context,{signal})),"models.generateImages":(args,{signal})=>runModelCall("models.generateImages","image",args,checkImagesContext,async(resolved,context)=>{let result=await models.generateImages(resolved,context,{signal});return addGeneratedImages(result.output.filter(block=>block.type==="image").length),result})}).map(([name,execute])=>({name,spread:!0,execute}))}export{executeCodemode,readCodemodeStore};
|
package/dist/bundle/chunks/{google-generative-ai-ZOK6CV7D.js → google-generative-ai-XMFHGQC5.js}
RENAMED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{GoogleGenAI,convertMessages,convertTools,getDisabledGoogleThinkingConfig,isThinkingPart,mapStopReason,resolveGoogleFunctionCallingMode,resolveGoogleThinkingLevel,retainThoughtSignature,retryGoogleRequest,supportsGoogleStrictToolSampling,toGoogleSdkThinkingLevel,toGoogleThinkingLevel,usesGoogleThinkingLevel}from"./chunk-
|
|
2
|
+
import{GoogleGenAI,convertMessages,convertTools,getDisabledGoogleThinkingConfig,isThinkingPart,mapStopReason,resolveGoogleFunctionCallingMode,resolveGoogleThinkingLevel,retainThoughtSignature,retryGoogleRequest,supportsGoogleStrictToolSampling,toGoogleSdkThinkingLevel,toGoogleThinkingLevel,usesGoogleThinkingLevel}from"./chunk-TAOL3JFA.js";import{formatProviderError,normalizeProviderError}from"./chunk-TEPMHNKQ.js";import"./chunk-LD2P6SFZ.js";import{buildBaseOptions,getPiUserAgent}from"./chunk-HQHD6PZI.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{providerHeadersToRecord}from"./chunk-UTB4DTYQ.js";import{calculateCost,clampThinkingLevel,collapseSystemMessages,getCurrentTools,getInitialSystemMessage,getSystemMessageText}from"./chunk-KJUDFE6Y.js";import{AssistantMessageEventStream}from"./chunk-A3JYRWB6.js";import"./chunk-4L3WN2XY.js";var toolCallCounter=0,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=collapseSystemMessages(context);return(async()=>{let output={role:"assistant",content:[],api:"google-generative-ai",provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{if(options?.fetch&&options.fetch!==globalThis.fetch)throw new Error("Custom fetch is not supported by the Google Generative AI adapter");let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let client=createClient(model,apiKey,options?.headers),params=buildParams(model,normalizedContext,options),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let googleStream=await retryGoogleRequest(()=>client.models.generateContentStream(params),options);stream2.push({type:"start",partial:output});let currentBlock=null,blocks=output.content,blockIndex=()=>blocks.length-1;for await(let chunk of googleStream){await options?.onProviderStreamEvent?.(chunk,model),output.responseId||=chunk.responseId;let candidate=chunk.candidates?.[0];if(candidate?.content?.parts)for(let part of candidate.content.parts){if(part.text!==void 0){let isThinking=isThinkingPart(part);(!currentBlock||isThinking&¤tBlock.type!=="thinking"||!isThinking&¤tBlock.type!=="text")&&(currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blocks.length-1,content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),isThinking?(currentBlock={type:"thinking",thinking:"",thinkingSignature:void 0},output.content.push(currentBlock),stream2.push({type:"thinking_start",contentIndex:blockIndex(),partial:output})):(currentBlock={type:"text",text:""},output.content.push(currentBlock),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output}))),currentBlock.type==="thinking"?(currentBlock.thinking+=part.text,currentBlock.thinkingSignature=retainThoughtSignature(currentBlock.thinkingSignature,part.thoughtSignature),stream2.push({type:"thinking_delta",contentIndex:blockIndex(),delta:part.text,partial:output})):(currentBlock.text+=part.text,currentBlock.textSignature=retainThoughtSignature(currentBlock.textSignature,part.thoughtSignature),stream2.push({type:"text_delta",contentIndex:blockIndex(),delta:part.text,partial:output}))}if(part.functionCall){currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output}),currentBlock=null);let providedId=part.functionCall.id,toolCall={type:"toolCall",id:!providedId||output.content.some(b=>b.type==="toolCall"&&b.id===providedId)?`${part.functionCall.name}_${Date.now()}_${++toolCallCounter}`:providedId,name:part.functionCall.name||"",arguments:part.functionCall.args??{},...part.thoughtSignature&&{thoughtSignature:part.thoughtSignature}};output.content.push(toolCall),stream2.push({type:"toolcall_start",contentIndex:blockIndex(),partial:output}),stream2.push({type:"toolcall_delta",contentIndex:blockIndex(),delta:JSON.stringify(toolCall.arguments),partial:output}),stream2.push({type:"toolcall_end",contentIndex:blockIndex(),toolCall,partial:output})}}candidate?.finishReason&&(output.rawStopReason=candidate.finishReason,output.stopReason=mapStopReason(candidate.finishReason),output.content.some(b=>b.type==="toolCall")&&output.stopReason==="stop"&&(output.stopReason="toolUse")),chunk.usageMetadata&&(output.usage={input:(chunk.usageMetadata.promptTokenCount||0)-(chunk.usageMetadata.cachedContentTokenCount||0),output:(chunk.usageMetadata.candidatesTokenCount||0)+(chunk.usageMetadata.thoughtsTokenCount||0),cacheRead:chunk.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,reasoning:chunk.usageMetadata.thoughtsTokenCount||0,totalTokens:chunk.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},calculateCost(model,output.usage))}if(currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Google stream ended without a finish reason");if(output.stopReason==="aborted"||output.stopReason==="error"){let errorMessage=output.rawStopReason?`Provider stopped with: ${output.rawStopReason}`:"An unknown error occurred";throw new Error(errorMessage)}stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)"index"in block&&delete block.index;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error)),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let base={...buildBaseOptions(model,context,options,apiKey),toolChoice:options?.toolChoice};if(!options?.reasoning)return stream(model,context,{...base,thinking:{enabled:!1}});let clampedReasoning=clampThinkingLevel(model,options.reasoning);if(clampedReasoning==="off")return stream(model,context,{...base,thinking:{enabled:!1}});let resolvedLevel=resolveGoogleThinkingLevel(model,clampedReasoning);return usesGoogleThinkingLevel(model)?stream(model,context,{...base,thinking:{enabled:!0,level:toGoogleThinkingLevel(resolvedLevel)}}):stream(model,context,{...base,thinking:{enabled:!0,budgetTokens:getGoogleBudget(model,resolvedLevel,options.thinkingBudgets)}})};function createClient(model,apiKey,optionsHeaders){let httpOptions={};model.baseUrl&&(httpOptions.baseUrl=model.baseUrl,httpOptions.apiVersion="");let headers=providerHeadersToRecord({"User-Agent":getPiUserAgent(),...model.headers,...optionsHeaders});return headers&&(httpOptions.headers=headers),new GoogleGenAI({apiKey,httpOptions:Object.keys(httpOptions).length>0?httpOptions:void 0})}function buildParams(model,context,options={}){let contents=convertMessages(model,context),initialSystemMessage=getInitialSystemMessage(context.messages),currentTools=getCurrentTools(context.messages),generationConfig={};options.temperature!==void 0&&(generationConfig.temperature=options.temperature),options.maxTokens!==void 0&&(generationConfig.maxOutputTokens=options.maxTokens);let supportsStrictMode=supportsGoogleStrictToolSampling(model.id),functionCallingMode=currentTools.length>0?resolveGoogleFunctionCallingMode(currentTools,options.toolChoice,supportsStrictMode):void 0,systemInstruction=initialSystemMessage?getSystemMessageText(initialSystemMessage):"",config={...Object.keys(generationConfig).length>0&&generationConfig,...systemInstruction&&{systemInstruction:sanitizeSurrogates(systemInstruction)},...currentTools.length>0&&{tools:convertTools(currentTools,!1,supportsStrictMode)},...functionCallingMode!==void 0&&{toolConfig:{functionCallingConfig:{mode:functionCallingMode}}}};if(options.thinking?.enabled&&model.reasoning){let thinkingConfig={includeThoughts:!0};options.thinking.level!==void 0?thinkingConfig.thinkingLevel=toGoogleSdkThinkingLevel(options.thinking.level):options.thinking.budgetTokens!==void 0&&(thinkingConfig.thinkingBudget=options.thinking.budgetTokens),config.thinkingConfig=thinkingConfig}else model.reasoning&&options.thinking&&!options.thinking.enabled&&(config.thinkingConfig=getDisabledGoogleThinkingConfig(model));if(options.signal){if(options.signal.aborted)throw new Error("Request aborted");config.abortSignal=options.signal}return{model:model.id,contents,config}}function getGoogleBudget(model,level,customBudgets){return customBudgets?.[level]!==void 0?customBudgets[level]:model.id.includes("2.5-pro")?{minimal:128,low:2048,medium:8192,high:32768}[level]:model.id.includes("2.5-flash-lite")?{minimal:512,low:2048,medium:8192,high:24576}[level]:model.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[level]:-1}export{stream,streamSimple};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{GoogleGenAI,ResourceScope,convertMessages,convertTools,getDisabledGoogleThinkingConfig,isThinkingPart,mapStopReason,resolveGoogleFunctionCallingMode,resolveGoogleThinkingLevel,retainThoughtSignature,retryGoogleRequest,supportsGoogleStrictToolSampling,toGoogleSdkThinkingLevel,toGoogleThinkingLevel,usesGoogleThinkingLevel}from"./chunk-G7EDXK4D.js";import{formatProviderError,normalizeProviderError}from"./chunk-TEPMHNKQ.js";import"./chunk-LD2P6SFZ.js";import{buildBaseOptions,getPiUserAgent}from"./chunk-IKZJX7ZT.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{providerHeadersToRecord}from"./chunk-UTB4DTYQ.js";import{getProviderEnvValue}from"./chunk-DRQDKNXA.js";import{calculateCost,clampThinkingLevel,collapseSystemMessages,getCurrentTools,getInitialSystemMessage,getSystemMessageText}from"./chunk-7JGR3GZN.js";import{AssistantMessageEventStream}from"./chunk-A3JYRWB6.js";import"./chunk-4L3WN2XY.js";var API_VERSION="v1",GCP_VERTEX_CREDENTIALS_MARKER="gcp-vertex-credentials",toolCallCounter=0,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=collapseSystemMessages(context);return(async()=>{let output={role:"assistant",content:[],api:"google-vertex",provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{if(options?.fetch&&options.fetch!==globalThis.fetch)throw new Error("Custom fetch is not supported by the Google Vertex adapter");let apiKey=resolveApiKey(options),client=apiKey?createClientWithApiKey(model,apiKey,options?.headers):createClient(model,resolveProject(options),resolveLocation(options),options?.headers,options?.env),params=buildParams(model,normalizedContext,options),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let googleStream=await retryGoogleRequest(()=>client.models.generateContentStream(params),options);stream2.push({type:"start",partial:output});let currentBlock=null,blocks=output.content,blockIndex=()=>blocks.length-1;for await(let chunk of googleStream){await options?.onProviderStreamEvent?.(chunk,model),output.responseId||=chunk.responseId;let candidate=chunk.candidates?.[0];if(candidate?.content?.parts)for(let part of candidate.content.parts){if(part.text!==void 0){let isThinking=isThinkingPart(part);(!currentBlock||isThinking&¤tBlock.type!=="thinking"||!isThinking&¤tBlock.type!=="text")&&(currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blocks.length-1,content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),isThinking?(currentBlock={type:"thinking",thinking:"",thinkingSignature:void 0},output.content.push(currentBlock),stream2.push({type:"thinking_start",contentIndex:blockIndex(),partial:output})):(currentBlock={type:"text",text:""},output.content.push(currentBlock),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output}))),currentBlock.type==="thinking"?(currentBlock.thinking+=part.text,currentBlock.thinkingSignature=retainThoughtSignature(currentBlock.thinkingSignature,part.thoughtSignature),stream2.push({type:"thinking_delta",contentIndex:blockIndex(),delta:part.text,partial:output})):(currentBlock.text+=part.text,currentBlock.textSignature=retainThoughtSignature(currentBlock.textSignature,part.thoughtSignature),stream2.push({type:"text_delta",contentIndex:blockIndex(),delta:part.text,partial:output}))}if(part.functionCall){currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output}),currentBlock=null);let providedId=part.functionCall.id,toolCall={type:"toolCall",id:!providedId||output.content.some(b=>b.type==="toolCall"&&b.id===providedId)?`${part.functionCall.name}_${Date.now()}_${++toolCallCounter}`:providedId,name:part.functionCall.name||"",arguments:part.functionCall.args??{},...part.thoughtSignature&&{thoughtSignature:part.thoughtSignature}};output.content.push(toolCall),stream2.push({type:"toolcall_start",contentIndex:blockIndex(),partial:output}),stream2.push({type:"toolcall_delta",contentIndex:blockIndex(),delta:JSON.stringify(toolCall.arguments),partial:output}),stream2.push({type:"toolcall_end",contentIndex:blockIndex(),toolCall,partial:output})}}candidate?.finishReason&&(output.rawStopReason=candidate.finishReason,output.stopReason=mapStopReason(candidate.finishReason),output.content.some(b=>b.type==="toolCall")&&output.stopReason==="stop"&&(output.stopReason="toolUse")),chunk.usageMetadata&&(output.usage={input:(chunk.usageMetadata.promptTokenCount||0)-(chunk.usageMetadata.cachedContentTokenCount||0),output:(chunk.usageMetadata.candidatesTokenCount||0)+(chunk.usageMetadata.thoughtsTokenCount||0),cacheRead:chunk.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,reasoning:chunk.usageMetadata.thoughtsTokenCount||0,totalTokens:chunk.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},calculateCost(model,output.usage))}if(currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Google Vertex stream ended without a finish reason");if(output.stopReason==="aborted"||output.stopReason==="error"){let errorMessage=output.rawStopReason?`Provider stopped with: ${output.rawStopReason}`:"An unknown error occurred";throw new Error(errorMessage)}stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)"index"in block&&delete block.index;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error)),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let base={...buildBaseOptions(model,context,options,void 0),toolChoice:options?.toolChoice};if(!options?.reasoning)return stream(model,context,{...base,thinking:{enabled:!1}});let clampedReasoning=clampThinkingLevel(model,options.reasoning);if(clampedReasoning==="off")return stream(model,context,{...base,thinking:{enabled:!1}});let resolvedLevel=resolveGoogleThinkingLevel(model,clampedReasoning);return usesGoogleThinkingLevel(model)?stream(model,context,{...base,thinking:{enabled:!0,level:toGoogleThinkingLevel(resolvedLevel)}}):stream(model,context,{...base,thinking:{enabled:!0,budgetTokens:getGoogleBudget(model,resolvedLevel,options.thinkingBudgets)}})};function createClient(model,project,location,optionsHeaders,env){let googleAuthOptions=buildGoogleAuthOptions(env);return new GoogleGenAI({vertexai:!0,project,location,apiVersion:API_VERSION,...googleAuthOptions?{googleAuthOptions}:{},httpOptions:buildHttpOptions(model,optionsHeaders)})}function createClientWithApiKey(model,apiKey,optionsHeaders){return new GoogleGenAI({vertexai:!0,apiKey,apiVersion:API_VERSION,httpOptions:buildHttpOptions(model,optionsHeaders)})}function buildHttpOptions(model,optionsHeaders){let httpOptions={},baseUrl=resolveCustomBaseUrl(model.baseUrl);baseUrl&&(httpOptions.baseUrl=baseUrl,httpOptions.baseUrlResourceScope=ResourceScope.COLLECTION,baseUrlIncludesApiVersion(baseUrl)&&(httpOptions.apiVersion=""));let headers=providerHeadersToRecord({"User-Agent":getPiUserAgent(),...model.headers,...optionsHeaders});return headers&&(httpOptions.headers=headers),Object.keys(httpOptions).length>0?httpOptions:void 0}function resolveCustomBaseUrl(baseUrl){let trimmed=baseUrl.trim();if(!(!trimmed||trimmed.includes("{location}")))return trimmed}function baseUrlIncludesApiVersion(baseUrl){try{return new URL(baseUrl).pathname.split("/").some(part=>/^v\d+(?:beta\d*)?$/.test(part))}catch{return/(?:^|\/)v\d+(?:beta\d*)?(?:\/|$)/.test(baseUrl)}}function buildGoogleAuthOptions(env){let keyFilename=getProviderEnvValue("GOOGLE_APPLICATION_CREDENTIALS",env);return keyFilename?{keyFilename}:void 0}function resolveApiKey(options){let apiKey=options?.apiKey?.trim();if(!(!apiKey||apiKey===GCP_VERTEX_CREDENTIALS_MARKER||isPlaceholderApiKey(apiKey)))return apiKey}function isPlaceholderApiKey(apiKey){return/^<[^>]+>$/.test(apiKey)}function resolveProject(options){let project=options?.project||getProviderEnvValue("GOOGLE_CLOUD_PROJECT",options?.env)||getProviderEnvValue("GCLOUD_PROJECT",options?.env);if(!project)throw new Error("Vertex AI requires a project ID. Set GOOGLE_CLOUD_PROJECT/GCLOUD_PROJECT or pass project in options.");return project}function resolveLocation(options){let location=options?.location||getProviderEnvValue("GOOGLE_CLOUD_LOCATION",options?.env);if(!location)throw new Error("Vertex AI requires a location. Set GOOGLE_CLOUD_LOCATION or pass location in options.");return location}function buildParams(model,context,options={}){let contents=convertMessages(model,context),initialSystemMessage=getInitialSystemMessage(context.messages),currentTools=getCurrentTools(context.messages),generationConfig={};options.temperature!==void 0&&(generationConfig.temperature=options.temperature),options.maxTokens!==void 0&&(generationConfig.maxOutputTokens=options.maxTokens);let supportsStrictMode=supportsGoogleStrictToolSampling(model.id),functionCallingMode=currentTools.length>0?resolveGoogleFunctionCallingMode(currentTools,options.toolChoice,supportsStrictMode):void 0,systemInstruction=initialSystemMessage?getSystemMessageText(initialSystemMessage):"",config={...Object.keys(generationConfig).length>0&&generationConfig,...systemInstruction&&{systemInstruction:sanitizeSurrogates(systemInstruction)},...currentTools.length>0&&{tools:convertTools(currentTools,!1,supportsStrictMode)},...functionCallingMode!==void 0&&{toolConfig:{functionCallingConfig:{mode:functionCallingMode}}}};if(options.thinking?.enabled&&model.reasoning){let thinkingConfig={includeThoughts:!0};options.thinking.level!==void 0?thinkingConfig.thinkingLevel=toGoogleSdkThinkingLevel(options.thinking.level):options.thinking.budgetTokens!==void 0&&(thinkingConfig.thinkingBudget=options.thinking.budgetTokens),config.thinkingConfig=thinkingConfig}else model.reasoning&&options.thinking&&!options.thinking.enabled&&(config.thinkingConfig=getDisabledGoogleThinkingConfig(model));if(options.signal){if(options.signal.aborted)throw new Error("Request aborted");config.abortSignal=options.signal}return{model:model.id,contents,config}}function getGoogleBudget(model,level,customBudgets){return customBudgets?.[level]!==void 0?customBudgets[level]:model.id.includes("2.5-pro")?{minimal:128,low:2048,medium:8192,high:32768}[level]:model.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[level]:-1}export{stream,streamSimple};
|
|
2
|
+
import{GoogleGenAI,ResourceScope,convertMessages,convertTools,getDisabledGoogleThinkingConfig,isThinkingPart,mapStopReason,resolveGoogleFunctionCallingMode,resolveGoogleThinkingLevel,retainThoughtSignature,retryGoogleRequest,supportsGoogleStrictToolSampling,toGoogleSdkThinkingLevel,toGoogleThinkingLevel,usesGoogleThinkingLevel}from"./chunk-TAOL3JFA.js";import{formatProviderError,normalizeProviderError}from"./chunk-TEPMHNKQ.js";import"./chunk-LD2P6SFZ.js";import{buildBaseOptions,getPiUserAgent}from"./chunk-HQHD6PZI.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{providerHeadersToRecord}from"./chunk-UTB4DTYQ.js";import{getProviderEnvValue}from"./chunk-DRQDKNXA.js";import{calculateCost,clampThinkingLevel,collapseSystemMessages,getCurrentTools,getInitialSystemMessage,getSystemMessageText}from"./chunk-KJUDFE6Y.js";import{AssistantMessageEventStream}from"./chunk-A3JYRWB6.js";import"./chunk-4L3WN2XY.js";var API_VERSION="v1",GCP_VERTEX_CREDENTIALS_MARKER="gcp-vertex-credentials",toolCallCounter=0,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=collapseSystemMessages(context);return(async()=>{let output={role:"assistant",content:[],api:"google-vertex",provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{if(options?.fetch&&options.fetch!==globalThis.fetch)throw new Error("Custom fetch is not supported by the Google Vertex adapter");let apiKey=resolveApiKey(options),client=apiKey?createClientWithApiKey(model,apiKey,options?.headers):createClient(model,resolveProject(options),resolveLocation(options),options?.headers,options?.env),params=buildParams(model,normalizedContext,options),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let googleStream=await retryGoogleRequest(()=>client.models.generateContentStream(params),options);stream2.push({type:"start",partial:output});let currentBlock=null,blocks=output.content,blockIndex=()=>blocks.length-1;for await(let chunk of googleStream){await options?.onProviderStreamEvent?.(chunk,model),output.responseId||=chunk.responseId;let candidate=chunk.candidates?.[0];if(candidate?.content?.parts)for(let part of candidate.content.parts){if(part.text!==void 0){let isThinking=isThinkingPart(part);(!currentBlock||isThinking&¤tBlock.type!=="thinking"||!isThinking&¤tBlock.type!=="text")&&(currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blocks.length-1,content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),isThinking?(currentBlock={type:"thinking",thinking:"",thinkingSignature:void 0},output.content.push(currentBlock),stream2.push({type:"thinking_start",contentIndex:blockIndex(),partial:output})):(currentBlock={type:"text",text:""},output.content.push(currentBlock),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output}))),currentBlock.type==="thinking"?(currentBlock.thinking+=part.text,currentBlock.thinkingSignature=retainThoughtSignature(currentBlock.thinkingSignature,part.thoughtSignature),stream2.push({type:"thinking_delta",contentIndex:blockIndex(),delta:part.text,partial:output})):(currentBlock.text+=part.text,currentBlock.textSignature=retainThoughtSignature(currentBlock.textSignature,part.thoughtSignature),stream2.push({type:"text_delta",contentIndex:blockIndex(),delta:part.text,partial:output}))}if(part.functionCall){currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output}),currentBlock=null);let providedId=part.functionCall.id,toolCall={type:"toolCall",id:!providedId||output.content.some(b=>b.type==="toolCall"&&b.id===providedId)?`${part.functionCall.name}_${Date.now()}_${++toolCallCounter}`:providedId,name:part.functionCall.name||"",arguments:part.functionCall.args??{},...part.thoughtSignature&&{thoughtSignature:part.thoughtSignature}};output.content.push(toolCall),stream2.push({type:"toolcall_start",contentIndex:blockIndex(),partial:output}),stream2.push({type:"toolcall_delta",contentIndex:blockIndex(),delta:JSON.stringify(toolCall.arguments),partial:output}),stream2.push({type:"toolcall_end",contentIndex:blockIndex(),toolCall,partial:output})}}candidate?.finishReason&&(output.rawStopReason=candidate.finishReason,output.stopReason=mapStopReason(candidate.finishReason),output.content.some(b=>b.type==="toolCall")&&output.stopReason==="stop"&&(output.stopReason="toolUse")),chunk.usageMetadata&&(output.usage={input:(chunk.usageMetadata.promptTokenCount||0)-(chunk.usageMetadata.cachedContentTokenCount||0),output:(chunk.usageMetadata.candidatesTokenCount||0)+(chunk.usageMetadata.thoughtsTokenCount||0),cacheRead:chunk.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,reasoning:chunk.usageMetadata.thoughtsTokenCount||0,totalTokens:chunk.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},calculateCost(model,output.usage))}if(currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Google Vertex stream ended without a finish reason");if(output.stopReason==="aborted"||output.stopReason==="error"){let errorMessage=output.rawStopReason?`Provider stopped with: ${output.rawStopReason}`:"An unknown error occurred";throw new Error(errorMessage)}stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)"index"in block&&delete block.index;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error)),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let base={...buildBaseOptions(model,context,options,void 0),toolChoice:options?.toolChoice};if(!options?.reasoning)return stream(model,context,{...base,thinking:{enabled:!1}});let clampedReasoning=clampThinkingLevel(model,options.reasoning);if(clampedReasoning==="off")return stream(model,context,{...base,thinking:{enabled:!1}});let resolvedLevel=resolveGoogleThinkingLevel(model,clampedReasoning);return usesGoogleThinkingLevel(model)?stream(model,context,{...base,thinking:{enabled:!0,level:toGoogleThinkingLevel(resolvedLevel)}}):stream(model,context,{...base,thinking:{enabled:!0,budgetTokens:getGoogleBudget(model,resolvedLevel,options.thinkingBudgets)}})};function createClient(model,project,location,optionsHeaders,env){let googleAuthOptions=buildGoogleAuthOptions(env);return new GoogleGenAI({vertexai:!0,project,location,apiVersion:API_VERSION,...googleAuthOptions?{googleAuthOptions}:{},httpOptions:buildHttpOptions(model,optionsHeaders)})}function createClientWithApiKey(model,apiKey,optionsHeaders){return new GoogleGenAI({vertexai:!0,apiKey,apiVersion:API_VERSION,httpOptions:buildHttpOptions(model,optionsHeaders)})}function buildHttpOptions(model,optionsHeaders){let httpOptions={},baseUrl=resolveCustomBaseUrl(model.baseUrl);baseUrl&&(httpOptions.baseUrl=baseUrl,httpOptions.baseUrlResourceScope=ResourceScope.COLLECTION,baseUrlIncludesApiVersion(baseUrl)&&(httpOptions.apiVersion=""));let headers=providerHeadersToRecord({"User-Agent":getPiUserAgent(),...model.headers,...optionsHeaders});return headers&&(httpOptions.headers=headers),Object.keys(httpOptions).length>0?httpOptions:void 0}function resolveCustomBaseUrl(baseUrl){let trimmed=baseUrl.trim();if(!(!trimmed||trimmed.includes("{location}")))return trimmed}function baseUrlIncludesApiVersion(baseUrl){try{return new URL(baseUrl).pathname.split("/").some(part=>/^v\d+(?:beta\d*)?$/.test(part))}catch{return/(?:^|\/)v\d+(?:beta\d*)?(?:\/|$)/.test(baseUrl)}}function buildGoogleAuthOptions(env){let keyFilename=getProviderEnvValue("GOOGLE_APPLICATION_CREDENTIALS",env);return keyFilename?{keyFilename}:void 0}function resolveApiKey(options){let apiKey=options?.apiKey?.trim();if(!(!apiKey||apiKey===GCP_VERTEX_CREDENTIALS_MARKER||isPlaceholderApiKey(apiKey)))return apiKey}function isPlaceholderApiKey(apiKey){return/^<[^>]+>$/.test(apiKey)}function resolveProject(options){let project=options?.project||getProviderEnvValue("GOOGLE_CLOUD_PROJECT",options?.env)||getProviderEnvValue("GCLOUD_PROJECT",options?.env);if(!project)throw new Error("Vertex AI requires a project ID. Set GOOGLE_CLOUD_PROJECT/GCLOUD_PROJECT or pass project in options.");return project}function resolveLocation(options){let location=options?.location||getProviderEnvValue("GOOGLE_CLOUD_LOCATION",options?.env);if(!location)throw new Error("Vertex AI requires a location. Set GOOGLE_CLOUD_LOCATION or pass location in options.");return location}function buildParams(model,context,options={}){let contents=convertMessages(model,context),initialSystemMessage=getInitialSystemMessage(context.messages),currentTools=getCurrentTools(context.messages),generationConfig={};options.temperature!==void 0&&(generationConfig.temperature=options.temperature),options.maxTokens!==void 0&&(generationConfig.maxOutputTokens=options.maxTokens);let supportsStrictMode=supportsGoogleStrictToolSampling(model.id),functionCallingMode=currentTools.length>0?resolveGoogleFunctionCallingMode(currentTools,options.toolChoice,supportsStrictMode):void 0,systemInstruction=initialSystemMessage?getSystemMessageText(initialSystemMessage):"",config={...Object.keys(generationConfig).length>0&&generationConfig,...systemInstruction&&{systemInstruction:sanitizeSurrogates(systemInstruction)},...currentTools.length>0&&{tools:convertTools(currentTools,!1,supportsStrictMode)},...functionCallingMode!==void 0&&{toolConfig:{functionCallingConfig:{mode:functionCallingMode}}}};if(options.thinking?.enabled&&model.reasoning){let thinkingConfig={includeThoughts:!0};options.thinking.level!==void 0?thinkingConfig.thinkingLevel=toGoogleSdkThinkingLevel(options.thinking.level):options.thinking.budgetTokens!==void 0&&(thinkingConfig.thinkingBudget=options.thinking.budgetTokens),config.thinkingConfig=thinkingConfig}else model.reasoning&&options.thinking&&!options.thinking.enabled&&(config.thinkingConfig=getDisabledGoogleThinkingConfig(model));if(options.signal){if(options.signal.aborted)throw new Error("Request aborted");config.abortSignal=options.signal}return{model:model.id,contents,config}}function getGoogleBudget(model,level,customBudgets){return customBudgets?.[level]!==void 0?customBudgets[level]:model.id.includes("2.5-pro")?{minimal:128,low:2048,medium:8192,high:32768}[level]:model.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[level]:-1}export{stream,streamSimple};
|