@earendil-works/pi-coding-agent 1.0.0 → 1.0.2
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 +54 -0
- package/README.md +32 -7
- package/dist/bundle/chunks/{anthropic-messages-UID2PALB.js → anthropic-messages-MVG2FL56.js} +3 -3
- package/dist/bundle/chunks/azure-openai-responses-7AMFUIWJ.js +2 -0
- package/dist/bundle/chunks/bedrock-converse-stream.js +2 -2
- package/dist/bundle/chunks/chunk-2KAZSACP.js +2 -0
- package/dist/bundle/chunks/{chunk-2KTBZM5G.js → chunk-6FX7UEPL.js} +5 -5
- package/dist/bundle/chunks/{chunk-2VNGUWBO.js → chunk-BYB6ZAAQ.js} +1 -1
- package/dist/bundle/chunks/chunk-F5ZABL6Z.js +20 -0
- package/dist/bundle/chunks/{chunk-3LH3ZQKY.js → chunk-G7EDXK4D.js} +1 -1
- package/dist/bundle/chunks/chunk-IKZJX7ZT.js +2 -0
- package/dist/bundle/chunks/{chunk-PRD6WYBT.js → chunk-OYBSLV7Y.js} +1 -1
- package/dist/bundle/chunks/{chunk-IBCPYVFK.js → chunk-PDFMCAOZ.js} +4 -4
- package/dist/bundle/chunks/{chunk-LTXEMVMA.js → chunk-SYF2TF6W.js} +2 -2
- package/dist/bundle/chunks/chunk-U7B62NSC.js +2 -0
- package/dist/bundle/chunks/chunk-WCQZGZ6I.js +82 -0
- package/dist/bundle/chunks/{chunk-33XOIQ5N.js → chunk-ZSBPJAJ2.js} +31 -32
- package/dist/bundle/chunks/{chunk-KDN6RCEQ.js → chunk-ZSI3BL5Q.js} +2 -2
- package/dist/bundle/chunks/{cli-QOMC26IJ.js → cli-KILDDGW3.js} +2 -2
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-NPQN263E.js → cloudflare-workers-ai-system-one-X5PVWWYJ.js} +1 -1
- package/dist/bundle/chunks/codemode-worker.js +24 -3
- package/dist/bundle/chunks/easter-egg-3d-T5FFWIBR.js +2 -0
- package/dist/bundle/chunks/{execute-GVRSEGHL.js → execute-RYVK27GT.js} +25 -4
- package/dist/bundle/chunks/{google-generative-ai-APTPZOQL.js → google-generative-ai-ZOK6CV7D.js} +1 -1
- package/dist/bundle/chunks/{google-vertex-MXCOSOY3.js → google-vertex-VKWZQ3AY.js} +1 -1
- package/dist/bundle/chunks/{mistral-conversations-DKVFNQL6.js → mistral-conversations-7DAUEE4N.js} +1 -1
- package/dist/bundle/chunks/node-N5BSDOA5.js +16 -0
- package/dist/bundle/chunks/openai-chatgpt.js +1 -1
- package/dist/bundle/chunks/{openai-codex-responses-GK67DQQJ.js → openai-codex-responses-TC3OK7B4.js} +1 -1
- package/dist/bundle/chunks/openai-completions-GWHGMQ3T.js +7 -0
- package/dist/bundle/chunks/openai-responses-EZ7FJ2KL.js +3 -0
- package/dist/bundle/chunks/{runtime-2SO2JDWM.js → runtime-D5I2NTIF.js} +1 -1
- package/dist/bundle/chunks/virtual-modules-KVWJD3T3.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.map +1 -1
- package/dist/cli/args.js +4 -1
- package/dist/cli/args.js.map +1 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +3 -0
- package/dist/config.js.map +1 -1
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +1 -1
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/export-html/tool-renderer.d.ts +3 -3
- package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
- package/dist/core/export-html/tool-renderer.js +3 -3
- package/dist/core/export-html/tool-renderer.js.map +1 -1
- package/dist/core/extensions/index.d.ts +1 -1
- package/dist/core/extensions/index.d.ts.map +1 -1
- package/dist/core/extensions/index.js.map +1 -1
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +5 -0
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/runner.d.ts +3 -1
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +6 -0
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/types.d.ts +9 -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 +6 -0
- package/dist/core/mcp-servers.d.ts.map +1 -1
- package/dist/core/mcp-servers.js +11 -0
- package/dist/core/mcp-servers.js.map +1 -1
- package/dist/core/model-config.d.ts +36 -0
- package/dist/core/model-config.d.ts.map +1 -1
- package/dist/core/model-config.js +14 -2
- package/dist/core/model-config.js.map +1 -1
- package/dist/core/model-resolver.js +1 -1
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/provider-composer.d.ts +2 -1
- package/dist/core/provider-composer.d.ts.map +1 -1
- package/dist/core/provider-composer.js +13 -0
- package/dist/core/provider-composer.js.map +1 -1
- package/dist/core/tools/renderers/index.d.ts +2 -2
- package/dist/core/tools/renderers/index.d.ts.map +1 -1
- package/dist/core/tools/renderers/index.js.map +1 -1
- package/dist/extensions/mcp/cli.d.ts.map +1 -1
- package/dist/extensions/mcp/cli.js +3 -0
- package/dist/extensions/mcp/cli.js.map +1 -1
- package/dist/extensions/mcp/config.d.ts +15 -3
- package/dist/extensions/mcp/config.d.ts.map +1 -1
- package/dist/extensions/mcp/config.js +46 -10
- package/dist/extensions/mcp/config.js.map +1 -1
- package/dist/extensions/mcp/index.d.ts +4 -1
- package/dist/extensions/mcp/index.d.ts.map +1 -1
- package/dist/extensions/mcp/index.js +80 -45
- package/dist/extensions/mcp/index.js.map +1 -1
- package/dist/extensions/mcp/oauth.d.ts +4 -1
- package/dist/extensions/mcp/oauth.d.ts.map +1 -1
- package/dist/extensions/mcp/oauth.js +54 -10
- package/dist/extensions/mcp/oauth.js.map +1 -1
- package/dist/extensions/mcp/runtime.d.ts.map +1 -1
- package/dist/extensions/mcp/runtime.js +1 -0
- package/dist/extensions/mcp/runtime.js.map +1 -1
- package/dist/extensions/mcp/tools.d.ts +3 -1
- package/dist/extensions/mcp/tools.d.ts.map +1 -1
- package/dist/extensions/mcp/tools.js +19 -13
- package/dist/extensions/mcp/tools.js.map +1 -1
- package/dist/extensions/mcp/ui.d.ts.map +1 -1
- package/dist/extensions/mcp/ui.js +8 -4
- package/dist/extensions/mcp/ui.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/modes/interactive/components/armin.d.ts +3 -0
- package/dist/modes/interactive/components/armin.d.ts.map +1 -1
- package/dist/modes/interactive/components/armin.js +7 -5
- package/dist/modes/interactive/components/armin.js.map +1 -1
- package/dist/modes/interactive/components/auth-url.d.ts +14 -0
- package/dist/modes/interactive/components/auth-url.d.ts.map +1 -0
- package/dist/modes/interactive/components/auth-url.js +37 -0
- package/dist/modes/interactive/components/auth-url.js.map +1 -0
- package/dist/modes/interactive/components/easter-egg-3d.d.ts +104 -0
- package/dist/modes/interactive/components/easter-egg-3d.d.ts.map +1 -0
- package/dist/modes/interactive/components/{pi-logo-animation.js → easter-egg-3d.js} +127 -74
- package/dist/modes/interactive/components/easter-egg-3d.js.map +1 -0
- package/dist/modes/interactive/components/easter-egg-3d.lazy.d.ts +6 -0
- package/dist/modes/interactive/components/easter-egg-3d.lazy.d.ts.map +1 -0
- package/dist/modes/interactive/components/easter-egg-3d.lazy.js +23 -0
- package/dist/modes/interactive/components/easter-egg-3d.lazy.js.map +1 -0
- package/dist/modes/interactive/components/index.d.ts +0 -1
- package/dist/modes/interactive/components/index.d.ts.map +1 -1
- package/dist/modes/interactive/components/index.js +0 -1
- package/dist/modes/interactive/components/index.js.map +1 -1
- package/dist/modes/interactive/components/login-dialog.d.ts +2 -0
- package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
- package/dist/modes/interactive/components/login-dialog.js +11 -5
- package/dist/modes/interactive/components/login-dialog.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts +6 -18
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +22 -45
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +2 -2
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +15 -17
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/package-manager-cli.d.ts.map +1 -1
- package/dist/package-manager-cli.js +12 -0
- package/dist/package-manager-cli.js.map +1 -1
- package/dist/utils/image-convert.d.ts +12 -0
- package/dist/utils/image-convert.d.ts.map +1 -1
- package/dist/utils/image-convert.js +45 -6
- package/dist/utils/image-convert.js.map +1 -1
- package/docs/cli.md +2 -0
- package/docs/codemode.md +1 -1
- package/docs/extensions.md +4 -0
- package/docs/keybindings.md +1 -1
- package/docs/mcp.md +23 -1
- package/docs/models.md +28 -2
- package/docs/quickstart.md +16 -2
- 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 +13 -14
- package/dist/bundle/chunks/azure-openai-responses-AFMVM6NP.js +0 -2
- package/dist/bundle/chunks/chunk-4KU537KD.js +0 -2
- package/dist/bundle/chunks/chunk-6D7LHLKG.js +0 -2
- package/dist/bundle/chunks/chunk-7FH3BDRG.js +0 -82
- package/dist/bundle/chunks/chunk-DTD7JQ7Y.js +0 -42
- package/dist/bundle/chunks/node-O3RIBJRH.js +0 -16
- package/dist/bundle/chunks/openai-completions-JXDDPZ23.js +0 -7
- package/dist/bundle/chunks/openai-responses-CQDDLDQF.js +0 -3
- package/dist/bundle/chunks/pi-logo-animation-MPKZE4EK.js +0 -2
- package/dist/bundle/chunks/virtual-modules-6ZMK7GDO.js +0 -2
- package/dist/modes/interactive/components/daxnuts.d.ts +0 -23
- package/dist/modes/interactive/components/daxnuts.d.ts.map +0 -1
- package/dist/modes/interactive/components/daxnuts.js +0 -140
- package/dist/modes/interactive/components/daxnuts.js.map +0 -1
- package/dist/modes/interactive/components/pi-logo-animation.d.ts +0 -68
- package/dist/modes/interactive/components/pi-logo-animation.d.ts.map +0 -1
- package/dist/modes/interactive/components/pi-logo-animation.js.map +0 -1
- package/dist/modes/interactive/components/pi-logo-animation.lazy.d.ts +0 -7
- package/dist/modes/interactive/components/pi-logo-animation.lazy.d.ts.map +0 -1
- package/dist/modes/interactive/components/pi-logo-animation.lazy.js +0 -12
- package/dist/modes/interactive/components/pi-logo-animation.lazy.js.map +0 -1
- package/npm-shrinkwrap.json +0 -1952
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{mcpNamespace,require_proper_lockfile,validateMcpServerConfig}from"./chunk-
|
|
3
|
-
`,"utf-8")}function acquireTrustLockSync(path){let trustDir=dirname(path);mkdirSync(trustDir,{recursive:!0});let maxAttempts=10,delayMs=20,lastError;for(let attempt=1;attempt<=maxAttempts;attempt++)try{return import_proper_lockfile.default.lockSync(trustDir,{realpath:!1,lockfilePath:`${path}.lock`})}catch(error){if((typeof error=="object"&&error!==null&&"code"in error?String(error.code):void 0)!=="ELOCKED"||attempt===maxAttempts)throw error;lastError=error;let start=Date.now();for(;Date.now()-start<delayMs;);}throw lastError instanceof Error?lastError:new Error("Failed to acquire trust store lock")}function withTrustFileLock(path,fn){let release=acquireTrustLockSync(path);try{return fn()}finally{release()}}function hasTrustRequiringProjectResources(cwd){let homeDir=canonicalizePath(resolvePath(process.env.HOME||homedir())),userAgentsSkillsDir=join(homeDir,".agents","skills"),currentDir=canonicalizePath(resolvePath(cwd)),configDir=join(currentDir,CONFIG_DIR_NAME);if(TRUST_REQUIRING_PROJECT_CONFIG_RESOURCES.some(entry=>existsSync(join(configDir,entry))))return!0;for(;;){let agentsSkillsDir=join(currentDir,".agents","skills");if(agentsSkillsDir!==userAgentsSkillsDir&&existsSync(agentsSkillsDir))return!0;let parentDir=dirname(currentDir);if(parentDir===currentDir)return!1;currentDir=parentDir}}var ProjectTrustStore=class{trustPath;constructor(agentDir){this.trustPath=join(resolvePath(agentDir),"trust.json")}get(cwd){return this.getEntry(cwd)?.decision??null}getEntry(cwd){return withTrustFileLock(this.trustPath,()=>{let data=readTrustFile(this.trustPath);return findNearestTrustEntry(data,cwd)})}set(cwd,decision){this.setMany([{path:cwd,decision}])}setMany(decisions){withTrustFileLock(this.trustPath,()=>{let data=readTrustFile(this.trustPath);for(let{path,decision}of decisions){let key=normalizeCwd(path);decision===null?delete data[key]:data[key]=decision}writeTrustFile(this.trustPath,data)})}};import{spawn}from"node:child_process";function openBrowser(target){let[cmd,args]=process.platform==="darwin"?["open",[target]]:process.platform==="win32"?["rundll32",["url.dll,FileProtocolHandler",target]]:["xdg-open",[target]];spawn(cmd,args,{stdio:"ignore",detached:!0}).on("error",()=>{}).unref()}import{existsSync as existsSync2,mkdirSync as mkdirSync2,readFileSync as readFileSync2,writeFileSync as writeFileSync2}from"node:fs";import{dirname as dirname2,join as join2}from"node:path";function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function readConfigFile(path,scope,state){let{servers,errors}=state;if(!existsSync2(path))return;let parsed;try{parsed=JSON.parse(readFileSync2(path,"utf8"))}catch(error){errors.push(`${path}: ${error instanceof Error?error.message:String(error)}`);return}if(!isRecord(parsed)||parsed.mcpServers!==void 0&&!isRecord(parsed.mcpServers)){errors.push(`${path}: expected an object with an "mcpServers" object`);return}typeof parsed.autoEnableCodemode=="boolean"?state.autoEnableCodemode=parsed.autoEnableCodemode:parsed.autoEnableCodemode!==void 0&&errors.push(`${path}: autoEnableCodemode must be a boolean`);for(let[name,value]of Object.entries(parsed.mcpServers??{})){let config=validateMcpServerConfig(name,value);if(typeof config=="string"){errors.push(`${path}: ${config}`);continue}let clash=[...servers.keys()].find(other=>other!==name&&mcpNamespace(other)===mcpNamespace(name));if(clash){errors.push(`${path}: server "${name}" conflicts with "${clash}"`);continue}if(scope==="project"&&"url"in config&&config.auth){errors.push(`${path}: server "${name}": auth is only allowed in the global mcp.json`);continue}servers.set(name,{name,config,source:path,scope})}}function loadMcpConfig(options){let state={servers:new Map,errors:[]};
|
|
2
|
+
import{mcpNamespace,require_proper_lockfile,validateMcpServerConfig}from"./chunk-PDFMCAOZ.js";import{CONFIG_DIR_NAME,canonicalizePath,resolvePath,stripBom}from"./chunk-6FX7UEPL.js";import{__toESM}from"./chunk-4L3WN2XY.js";var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import{existsSync,mkdirSync,readFileSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{dirname,join}from"node:path";var TRUST_REQUIRING_PROJECT_CONFIG_RESOURCES=["settings.json","mcp.json","extensions","skills","prompts","themes","SYSTEM.md","APPEND_SYSTEM.md"];function normalizeCwd(cwd){return canonicalizePath(resolvePath(cwd))}function findNearestTrustEntry(data,cwd){let currentDir=normalizeCwd(cwd);for(;;){let value=data[currentDir];if(value===!0||value===!1)return{path:currentDir,decision:value};let parentDir=dirname(currentDir);if(parentDir===currentDir)return null;currentDir=parentDir}}function getProjectTrustParentPath(cwd){let trustPath=normalizeCwd(cwd),parentDir=dirname(trustPath);return parentDir===trustPath?void 0:parentDir}function getProjectTrustOptions(cwd,options){let trustPath=normalizeCwd(cwd),trustOptions=[{label:"Trust",trusted:!0,updates:[{path:trustPath,decision:!0}],savedPath:trustPath}],parentPath=getProjectTrustParentPath(cwd);return parentPath!==void 0&&trustOptions.push({label:`Trust parent folder (${parentPath})`,trusted:!0,updates:[{path:parentPath,decision:!0},{path:trustPath,decision:null}],savedPath:parentPath}),options?.includeSessionOnly&&trustOptions.push({label:"Trust (this session only)",trusted:!0,updates:[]}),trustOptions.push({label:"Do not trust",trusted:!1,updates:[{path:trustPath,decision:!1}],savedPath:trustPath}),options?.includeSessionOnly&&trustOptions.push({label:"Do not trust (this session only)",trusted:!1,updates:[]}),trustOptions}function readTrustFile(path){if(!existsSync(path))return{};let parsed;try{parsed=JSON.parse(stripBom(readFileSync(path,"utf-8")))}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`Failed to read trust store ${path}: ${message}`)}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))throw new Error(`Invalid trust store ${path}: expected an object`);let data={};for(let[key,value]of Object.entries(parsed)){if(value!==!0&&value!==!1&&value!==null)throw new Error(`Invalid trust store ${path}: value for ${JSON.stringify(key)} must be true, false, or null`);data[key]=value}return data}function writeTrustFile(path,data){let sorted={};for(let key of Object.keys(data).sort()){let value=data[key];(value===!0||value===!1||value===null)&&(sorted[key]=value)}mkdirSync(dirname(path),{recursive:!0}),writeFileSync(path,`${JSON.stringify(sorted,null,2)}
|
|
3
|
+
`,"utf-8")}function acquireTrustLockSync(path){let trustDir=dirname(path);mkdirSync(trustDir,{recursive:!0});let maxAttempts=10,delayMs=20,lastError;for(let attempt=1;attempt<=maxAttempts;attempt++)try{return import_proper_lockfile.default.lockSync(trustDir,{realpath:!1,lockfilePath:`${path}.lock`})}catch(error){if((typeof error=="object"&&error!==null&&"code"in error?String(error.code):void 0)!=="ELOCKED"||attempt===maxAttempts)throw error;lastError=error;let start=Date.now();for(;Date.now()-start<delayMs;);}throw lastError instanceof Error?lastError:new Error("Failed to acquire trust store lock")}function withTrustFileLock(path,fn){let release=acquireTrustLockSync(path);try{return fn()}finally{release()}}function hasTrustRequiringProjectResources(cwd){let homeDir=canonicalizePath(resolvePath(process.env.HOME||homedir())),userAgentsSkillsDir=join(homeDir,".agents","skills"),currentDir=canonicalizePath(resolvePath(cwd)),configDir=join(currentDir,CONFIG_DIR_NAME);if(TRUST_REQUIRING_PROJECT_CONFIG_RESOURCES.some(entry=>existsSync(join(configDir,entry))))return!0;for(;;){let agentsSkillsDir=join(currentDir,".agents","skills");if(agentsSkillsDir!==userAgentsSkillsDir&&existsSync(agentsSkillsDir))return!0;let parentDir=dirname(currentDir);if(parentDir===currentDir)return!1;currentDir=parentDir}}var ProjectTrustStore=class{trustPath;constructor(agentDir){this.trustPath=join(resolvePath(agentDir),"trust.json")}get(cwd){return this.getEntry(cwd)?.decision??null}getEntry(cwd){return withTrustFileLock(this.trustPath,()=>{let data=readTrustFile(this.trustPath);return findNearestTrustEntry(data,cwd)})}set(cwd,decision){this.setMany([{path:cwd,decision}])}setMany(decisions){withTrustFileLock(this.trustPath,()=>{let data=readTrustFile(this.trustPath);for(let{path,decision}of decisions){let key=normalizeCwd(path);decision===null?delete data[key]:data[key]=decision}writeTrustFile(this.trustPath,data)})}};import{spawn}from"node:child_process";function openBrowser(target){let[cmd,args]=process.platform==="darwin"?["open",[target]]:process.platform==="win32"?["rundll32",["url.dll,FileProtocolHandler",target]]:["xdg-open",[target]];spawn(cmd,args,{stdio:"ignore",detached:!0}).on("error",()=>{}).unref()}import{existsSync as existsSync2,mkdirSync as mkdirSync2,readFileSync as readFileSync2,writeFileSync as writeFileSync2}from"node:fs";import{dirname as dirname2,join as join2}from"node:path";var OVERRIDE_KEYS=["enabled","exposure","toolExposure"];function isOverride(value){return value.command===void 0&&value.url===void 0&&value.type===void 0}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function readConfigFile(path,scope,state){let{servers,errors}=state;if(!existsSync2(path))return;let parsed;try{parsed=JSON.parse(readFileSync2(path,"utf8"))}catch(error){errors.push(`${path}: ${error instanceof Error?error.message:String(error)}`);return}if(!isRecord(parsed)||parsed.mcpServers!==void 0&&!isRecord(parsed.mcpServers)){errors.push(`${path}: expected an object with an "mcpServers" object`);return}typeof parsed.autoEnableCodemode=="boolean"?state.autoEnableCodemode=parsed.autoEnableCodemode:parsed.autoEnableCodemode!==void 0&&errors.push(`${path}: autoEnableCodemode must be a boolean`);for(let[name,value]of Object.entries(parsed.mcpServers??{})){if(scope==="project"&&isRecord(value)&&isOverride(value)){let base=servers.get(name),extra=Object.keys(value).filter(key=>!OVERRIDE_KEYS.includes(key));if(!base)errors.push(`${path}: server "${name}" needs "command" or "url", or a global server to override`);else if(extra.length>0)errors.push(`${path}: server "${name}": an override can only set ${OVERRIDE_KEYS.join(", ")}`);else{let config2=validateMcpServerConfig(name,{...base.config,...value});typeof config2=="string"?errors.push(`${path}: ${config2}`):servers.set(name,{...base,config:config2,override:path})}continue}let config=validateMcpServerConfig(name,value);if(typeof config=="string"){errors.push(`${path}: ${config}`);continue}let clash=[...servers.keys()].find(other=>other!==name&&mcpNamespace(other)===mcpNamespace(name));if(clash){errors.push(`${path}: server "${name}" conflicts with "${clash}"`);continue}if(scope==="project"&&"url"in config&&config.auth){errors.push(`${path}: server "${name}": auth is only allowed in the global mcp.json`);continue}servers.set(name,{name,config,source:path,scope})}}function loadMcpConfig(options){let state={servers:new Map,errors:[]};readConfigFile(join2(options.agentDir,"mcp.json"),"global",state);let projectConfig=options.projectTrusted?join2(options.cwd,CONFIG_DIR_NAME,"mcp.json"):void 0;return projectConfig&&readConfigFile(projectConfig,"project",state),{servers:[...state.servers.values()],...state.autoEnableCodemode===void 0?{}:{autoEnableCodemode:state.autoEnableCodemode},errors:state.errors,...projectConfig?{projectConfig}:{}}}function updateMcpServerConfig(path,name,patch,options={}){editMcpServers(path,(servers,parsed)=>{let server=servers?.[name];if(server===void 0&&options.override&&(server={},parsed.mcpServers={...servers,[name]:server}),!isRecord(server))throw new Error(`${path} does not define MCP server "${name}"`);let keepDefaults=isOverride(server);return patch.enabled!==void 0&&(patch.enabled&&!keepDefaults?delete server.enabled:server.enabled=patch.enabled),patch.exposure!==void 0&&(patch.exposure==="codemode"&&!keepDefaults?delete server.exposure:server.exposure=patch.exposure),!0})}function addMcpServerConfig(path,name,config){let replaced=!1;return editMcpServers(path,(servers,parsed)=>{let target=servers??{};return replaced=target[name]!==void 0,target[name]=config,parsed.mcpServers=target,!0}),replaced}function removeMcpServerConfig(path,name){if(!existsSync2(path))return!1;let removed=!1;return editMcpServers(path,servers=>!servers||servers[name]===void 0?!1:(delete servers[name],removed=!0,!0)),removed}function editMcpServers(path,edit){let text=existsSync2(path)?readFileSync2(path,"utf8"):void 0,parsed=text===void 0?{}:JSON.parse(text);if(!isRecord(parsed)||parsed.mcpServers!==void 0&&!isRecord(parsed.mcpServers))throw new Error(`${path}: expected an object with an "mcpServers" object`);let servers=isRecord(parsed.mcpServers)?parsed.mcpServers:void 0;if(!edit(servers,parsed))return;let indent=text&&/^([ \t]+)\S/m.exec(text)?.[1]||" ";mkdirSync2(dirname2(path),{recursive:!0}),writeFileSync2(path,`${JSON.stringify(parsed,null,indent)}
|
|
4
4
|
`)}export{getProjectTrustOptions,hasTrustRequiringProjectResources,ProjectTrustStore,openBrowser,loadMcpConfig,updateMcpServerConfig,addMcpServerConfig,removeMcpServerConfig};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{McpOAuthCredentialStore,McpServerConnection,McpServerLog,McpSignInCancelledError,createDefaultTransport,signInMcpServer}from"./chunk-
|
|
2
|
+
import{McpOAuthCredentialStore,McpServerConnection,McpServerLog,McpSignInCancelledError,createDefaultTransport,signInMcpServer}from"./chunk-WCQZGZ6I.js";import{ProjectTrustStore,addMcpServerConfig,loadMcpConfig,openBrowser,removeMcpServerConfig}from"./chunk-ZSI3BL5Q.js";import{getMcpToolExposure,validateMcpServerConfig}from"./chunk-PDFMCAOZ.js";import"./chunk-OYBSLV7Y.js";import{APP_NAME,CONFIG_DIR_NAME,source_default}from"./chunk-6FX7UEPL.js";import"./chunk-S3GGRYIO.js";import"./chunk-4L3WN2XY.js";import{existsSync}from"node:fs";import{join}from"node:path";import{createInterface}from"node:readline/promises";var HELP=`${source_default.bold("Usage:")}
|
|
3
3
|
${APP_NAME} mcp add <server> [options] -- <command> [args...]
|
|
4
4
|
${APP_NAME} mcp add <server> [options] --url <url>
|
|
5
5
|
${APP_NAME} mcp remove <server> [-l]
|
|
@@ -45,7 +45,7 @@ ${HELP_HINT}`),1):list(loaded,parsed.values.has("json"),untrustedNote,options,cr
|
|
|
45
45
|
${HELP_HINT}`),1;let entry=loaded.servers.find(server=>server.name===name);if(!entry)return error(`No MCP server named "${name}".${untrustedNote?` ${untrustedNote}`:""} Configured: ${loaded.servers.map(server=>server.name).join(", ")||"none"}.`),1;let connection=createConnection(entry,options,credentials),url=connection.oauthUrl;if(!url)return error(`MCP server "${name}" does not use OAuth. Only HTTP servers without an Authorization header do.`),1;if(command==="logout"){let removed=credentials.remove(name,url);return log(removed?`Signed out of MCP server "${name}".`:`No stored credentials for MCP server "${name}".`),0}let timeout=Number(parsed.values.get("timeout")??DEFAULT_LOGIN_TIMEOUT_SECONDS);if(!Number.isFinite(timeout)||timeout<=0)return error("--timeout must be a positive number of seconds."),1;try{return await login(entry,connection,url,timeout*1e3,options,credentials,log,error)}finally{await connection.close()}}default:return error(`Unknown mcp command "${command}".
|
|
46
46
|
${HELP_HINT}`),1}}function parsePairs(option,pairs,error){if(!pairs)return{};let record={};for(let pair of pairs){let separator=pair.indexOf("=");if(separator<=0){error(`--${option} expects KEY=VALUE, got "${pair}".`);return}record[pair.slice(0,separator)]=pair.slice(separator+1)}return record}function add(args,projectConfig,options,log,error){let usage=`Usage: ${APP_NAME} mcp add <server> [options] (--url <url> | -- <command> [args...])
|
|
47
47
|
${HELP_HINT}`,parsed=parseOptions(args,{local:"flag",url:"value",env:"list",cwd:"value",header:"list","bearer-token-env-var":"value","oauth-client-id":"value","oauth-client-secret":"value","oauth-callback-port":"value","oauth-client-name":"value",exposure:"value",description:"value"},error,2);if(!parsed)return 1;let{positional,values,lists}=parsed,[name,...command]=positional,url=values.get("url");if(!name||url===void 0==(command.length===0))return error(usage),1;let value=option=>{let found=values.get(option);return typeof found=="string"?found:void 0},exposure=value("exposure"),misplaced=(url===void 0?["header","bearer-token-env-var","oauth-client-id","oauth-client-secret","oauth-callback-port","oauth-client-name"]:["env","cwd"]).find(option=>values.has(option)||lists.has(option));if(misplaced)return error(`--${misplaced} only applies to ${url===void 0?"HTTP servers (--url)":"stdio servers"}.`),1;let config;if(typeof url=="string"){let headers=parsePairs("header",lists.get("header"),error);if(!headers)return 1;let bearer=value("bearer-token-env-var");bearer!==void 0&&(headers.Authorization=`Bearer \${${bearer}}`);let port=value("oauth-callback-port"),oauth={...value("oauth-client-id")===void 0?{}:{clientId:value("oauth-client-id")},...value("oauth-client-secret")===void 0?{}:{clientSecret:value("oauth-client-secret")},...port===void 0?{}:{callbackPort:Number(port)},...value("oauth-client-name")===void 0?{}:{clientName:value("oauth-client-name")}};config={url,...Object.keys(headers).length>0?{headers}:{},...Object.keys(oauth).length>0?{oauth}:{}}}else{let env=parsePairs("env",lists.get("env"),error);if(!env)return 1;let[executable,...commandArgs]=command;config={command:executable,...commandArgs.length>0?{args:commandArgs}:{},...Object.keys(env).length>0?{env}:{},...value("cwd")===void 0?{}:{cwd:value("cwd")}}}exposure!==void 0&&(config.exposure=exposure);let description=value("description");description!==void 0&&(config.description=description);let validated=validateMcpServerConfig(name,config);if(typeof validated=="string")return error(validated),1;let project=values.has("local"),path=project?projectConfig:join(options.agentDir,"mcp.json"),scope=project?"project":"global",replaced;try{replaced=addMcpServerConfig(path,name,validated)}catch(addError){return error(`Could not update ${path}: ${errorMessage(addError)}`),1}log(`${replaced?"Replaced":"Added"} ${scope} MCP server "${name}" in ${path}.`),project&&new ProjectTrustStore(options.agentDir).get(options.cwd)!==!0&&log(`The project is not trusted, so ${path} is ignored until you start ${APP_NAME} in the project and trust it.`);let mayNeedSignIn="url"in validated&&!Object.keys(validated.headers??{}).some(header=>header.toLowerCase()==="authorization");return log(`Check it with: ${APP_NAME} mcp list${mayNeedSignIn?`. If it requires sign-in: ${APP_NAME} mcp login ${name}`:""}`),0}function remove(args,projectConfig,options,log,error){let parsed=parseOptions(args,{local:"flag"},error);if(!parsed)return 1;let[name,...extra]=parsed.positional;if(!name||extra.length>0)return error(`Usage: ${APP_NAME} mcp remove <server> [-l]
|
|
48
|
-
${HELP_HINT}`),1;let project=parsed.values.has("local"),globalConfig=join(options.agentDir,"mcp.json"),path=project?projectConfig:globalConfig,scope=project?"project":"global",removed;try{removed=removeMcpServerConfig(path,name)}catch(removeError){return error(`Could not update ${path}: ${errorMessage(removeError)}`),1}if(removed)return log(`Removed ${scope} MCP server "${name}" from ${path}.`),0;let other=loadMcpConfig({agentDir:options.agentDir,cwd:options.cwd,projectTrusted:!0}).servers.find(server=>server.name===name&&server.scope!==scope);return error(`No ${scope} MCP server named "${name}" in ${path}.${other?` It is defined in ${other.source}${other.scope==="project"?"; use --local":"; omit --local"}.`:""}`),1}async function list(loaded,json,untrustedNote,options,credentials,log){let reports=await Promise.all(loaded.servers.map(async entry=>{let report={name:entry.name,scope:entry.scope??"global",source:entry.source,enabled:entry.config.enabled!==!1,exposure:entry.config.exposure??"codemode",transport:describeTransport(entry),state:"disabled",tools:[]};if(!report.enabled)return report;let connection=createConnection(entry,options,credentials);try{await connection.getClient()}catch{}report.state=connection.state,report.tools=connection.tools.map(tool=>tool.name);let overrides=connection.tools.flatMap(tool=>{let exposure=getMcpToolExposure(entry.config,tool.name);return exposure===report.exposure?[]:[[tool.name,exposure]]});return overrides.length>0&&(report.toolExposure=Object.fromEntries(overrides)),connection.hasResources&&(report.resources=connection.resources.length,report.resourceTemplates=connection.resourceTemplates.length),connection.state!=="connected"&&connection.error&&(report.error=connection.error),await connection.close(),report})),failed=loaded.errors.length>0||reports.some(report=>report.enabled&&report.state!=="connected");if(json)return log(JSON.stringify({servers:reports,errors:loaded.errors,...untrustedNote?{note:untrustedNote}:{}},null,2)),failed?1:0;reports.length===0&&loaded.errors.length===0&&log(`No MCP servers configured. Add them to ${join(options.agentDir,"mcp.json")} or .pi/mcp.json.`);for(let report of reports){let state=report.state==="connected"?`connected, ${report.tools.length} tool${report.tools.length===1?"":"s"}`:report.state==="needs-auth"?"needs sign-in":report.state;if(log(`${report.name}: ${state} (${report.exposure}, ${report.scope})`),log(` ${report.transport}`),report.state==="needs-auth"&&log(` sign in with: ${APP_NAME} mcp login ${report.name}`),report.tools.length>0){let tools=report.tools.map(tool=>{let exposure=report.toolExposure?.[tool];return exposure?`${tool} [${exposure}]`:tool});log(` tools: ${tools.join(", ")}`)}report.resources!==void 0&&log(` resources: ${report.resources}, URI templates: ${report.resourceTemplates??0}`),report.error&&log(` ${report.error.split(`
|
|
48
|
+
${HELP_HINT}`),1;let project=parsed.values.has("local"),globalConfig=join(options.agentDir,"mcp.json"),path=project?projectConfig:globalConfig,scope=project?"project":"global",removed;try{removed=removeMcpServerConfig(path,name)}catch(removeError){return error(`Could not update ${path}: ${errorMessage(removeError)}`),1}if(removed)return log(`Removed ${scope} MCP server "${name}" from ${path}.`),0;let other=loadMcpConfig({agentDir:options.agentDir,cwd:options.cwd,projectTrusted:!0}).servers.find(server=>server.name===name&&server.scope!==scope);return error(`No ${scope} MCP server named "${name}" in ${path}.${other?` It is defined in ${other.source}${other.scope==="project"?"; use --local":"; omit --local"}.`:""}`),1}async function list(loaded,json,untrustedNote,options,credentials,log){let reports=await Promise.all(loaded.servers.map(async entry=>{let report={name:entry.name,scope:entry.scope??"global",source:entry.source,...entry.override?{override:entry.override}:{},enabled:entry.config.enabled!==!1,exposure:entry.config.exposure??"codemode",transport:describeTransport(entry),state:"disabled",tools:[]};if(!report.enabled)return report;let connection=createConnection(entry,options,credentials);try{await connection.getClient()}catch{}report.state=connection.state,report.tools=connection.tools.map(tool=>tool.name);let overrides=connection.tools.flatMap(tool=>{let exposure=getMcpToolExposure(entry.config,tool.name);return exposure===report.exposure?[]:[[tool.name,exposure]]});return overrides.length>0&&(report.toolExposure=Object.fromEntries(overrides)),connection.hasResources&&(report.resources=connection.resources.length,report.resourceTemplates=connection.resourceTemplates.length),connection.state!=="connected"&&connection.error&&(report.error=connection.error),await connection.close(),report})),failed=loaded.errors.length>0||reports.some(report=>report.enabled&&report.state!=="connected");if(json)return log(JSON.stringify({servers:reports,errors:loaded.errors,...untrustedNote?{note:untrustedNote}:{}},null,2)),failed?1:0;reports.length===0&&loaded.errors.length===0&&log(`No MCP servers configured. Add them to ${join(options.agentDir,"mcp.json")} or .pi/mcp.json.`);for(let report of reports){let state=report.state==="connected"?`connected, ${report.tools.length} tool${report.tools.length===1?"":"s"}`:report.state==="needs-auth"?"needs sign-in":report.state;if(log(`${report.name}: ${state} (${report.exposure}, ${report.scope})`),log(` ${report.transport}`),report.override&&log(` project override: ${report.override}`),report.state==="needs-auth"&&log(` sign in with: ${APP_NAME} mcp login ${report.name}`),report.tools.length>0){let tools=report.tools.map(tool=>{let exposure=report.toolExposure?.[tool];return exposure?`${tool} [${exposure}]`:tool});log(` tools: ${tools.join(", ")}`)}report.resources!==void 0&&log(` resources: ${report.resources}, URI templates: ${report.resourceTemplates??0}`),report.error&&log(` ${report.error.split(`
|
|
49
49
|
`).join(`
|
|
50
50
|
`)}`)}for(let configError of loaded.errors)log(`config error: ${configError}`);return untrustedNote&&log(untrustedNote),failed?1:0}async function login(entry,connection,url,timeoutMs,options,credentials,log,error){let{name}=entry;try{return await connection.getClient(),log(`Already signed in to MCP server "${name}" (${connection.tools.length} tools).`),0}catch{if(connection.state!=="needs-auth")return error(`MCP server "${name}" failed to connect: ${connection.error??"unknown error"}`),1}let openUrl=options.openUrl??openBrowser,interactive=process.stdin.isTTY===!0&&options.openUrl===void 0;try{await signInMcpServer({serverUrl:url,store:credentials.forServer(name,url),settings:connection.oauthSettings(),challenge:connection.challenge,prompt:{showAuthorizationUrl:authorizationUrl=>{log(`Sign in to MCP server "${name}" in your browser:
|
|
51
51
|
${authorizationUrl.href}`),openUrl(authorizationUrl.href)},promptForRedirectUrl:signal=>waitForRedirectUrl(signal,timeoutMs,interactive)}})}catch(signInError){return error(signInError instanceof McpSignInCancelledError?`Sign-in to MCP server "${name}" was cancelled or not completed within ${Math.round(timeoutMs/1e3)} seconds.`:`Sign-in to MCP server "${name}" failed: ${errorMessage(signInError)}`),1}connection.challenge=void 0;try{await connection.reconnect()}catch(connectError){return error(`Signed in, but ${errorMessage(connectError)}`),1}return log(`Signed in to MCP server "${name}" (${connection.tools.length} tools).`),0}async function waitForRedirectUrl(signal,timeoutMs,interactive){let controller=new AbortController,abort=()=>controller.abort();signal.addEventListener("abort",abort,{once:!0});let timer=setTimeout(abort,timeoutMs);try{if(!interactive){await new Promise(resolve=>controller.signal.addEventListener("abort",()=>resolve(),{once:!0}));return}let readline=createInterface({input:process.stdin,output:process.stderr});try{return await readline.question("If the browser cannot reach this machine, paste the URL it was redirected to: ",{signal:controller.signal})}catch{return}finally{readline.close()}}finally{clearTimeout(timer),signal.removeEventListener("abort",abort)}}export{runMcpCommand};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{classifySystemOne,isRecord}from"./chunk-OSKPX3Z5.js";import"./chunk-TEPMHNKQ.js";import"./chunk-LD2P6SFZ.js";import"./chunk-UTB4DTYQ.js";import"./chunk-7JGR3GZN.js";import"./chunk-A3JYRWB6.js";import"./chunk-4L3WN2XY.js";var LABEL="Cloudflare Workers AI";function cloudflareErrorMessage(errors){if(Array.isArray(errors)){let messages=errors.map(error=>isRecord(error)&&typeof error.message=="string"?error.message:void 0).filter(message=>message!==void 0);if(messages.length>0)return`${LABEL} error: ${messages.join("; ")}`}return`${LABEL} request failed`}var transport={api:"cloudflare-workers-ai-system-one",label:LABEL,url:model=>new URL("run",`${model.baseUrl.replace(/\/+$/u,"")}/`),payload:(model,request)=>({model:model.id,input:request}),output:body=>{if(!isRecord(body))throw new Error(`${LABEL} returned an unexpected response`);if(body.success===!1)throw new Error(cloudflareErrorMessage(body.errors));let
|
|
2
|
+
import{classifySystemOne,isRecord}from"./chunk-OSKPX3Z5.js";import"./chunk-TEPMHNKQ.js";import"./chunk-LD2P6SFZ.js";import"./chunk-UTB4DTYQ.js";import"./chunk-7JGR3GZN.js";import"./chunk-A3JYRWB6.js";import"./chunk-4L3WN2XY.js";var LABEL="Cloudflare Workers AI";function cloudflareErrorMessage(errors){if(Array.isArray(errors)){let messages=errors.map(error=>isRecord(error)&&typeof error.message=="string"?error.message:void 0).filter(message=>message!==void 0);if(messages.length>0)return`${LABEL} error: ${messages.join("; ")}`}return`${LABEL} request failed`}var transport={api:"cloudflare-workers-ai-system-one",label:LABEL,url:model=>new URL("run",`${model.baseUrl.replace(/\/+$/u,"")}/`),payload:(model,request)=>({model:model.id,input:request}),output:body=>{if(!isRecord(body))throw new Error(`${LABEL} returned an unexpected response`);if(body.success===!1)throw new Error(cloudflareErrorMessage(body.errors));let result=body.result;if(!isRecord(result))throw new Error(`${LABEL} returned an unexpected response`);if("answers"in result)return result;if(result.state!=="Completed")throw new Error(`${LABEL} run did not complete (state: ${String(result.state)})`);if(!isRecord(result.result))throw new Error(`${LABEL} returned an unexpected response`);return result.result}},classify=(model,context,options)=>classifySystemOne(transport,model,context,options);export{classify};
|
|
@@ -7,6 +7,7 @@ import{parentPort,workerData}from"node:worker_threads";function createWasiShim(m
|
|
|
7
7
|
const promiseThen = Promise.prototype.then;
|
|
8
8
|
const ErrorCtor = Error;
|
|
9
9
|
const TypeErrorCtor = TypeError;
|
|
10
|
+
const RangeErrorCtor = RangeError;
|
|
10
11
|
const pending = new Map();
|
|
11
12
|
let nextId = 1;
|
|
12
13
|
let finished = false;
|
|
@@ -192,6 +193,26 @@ import{parentPort,workerData}from"node:worker_threads";function createWasiShim(m
|
|
|
192
193
|
Object.defineProperty(globalThis, "store", { value: store, enumerable: true });
|
|
193
194
|
Object.defineProperty(globalThis, "load", { value: load, enumerable: true });
|
|
194
195
|
|
|
196
|
+
let outputChars = 0;
|
|
197
|
+
let outputItems = 0;
|
|
198
|
+
|
|
199
|
+
// Past the output limits the script fails: done() reports the error, so catching it does not
|
|
200
|
+
// resume output, and the host ends the script.
|
|
201
|
+
function output(kind, data, mimeType) {
|
|
202
|
+
if (finished) return;
|
|
203
|
+
outputChars += data.length;
|
|
204
|
+
outputItems++;
|
|
205
|
+
if (outputChars > 16777216 || outputItems > 100000) {
|
|
206
|
+
const error = new RangeErrorCtor(
|
|
207
|
+
"script output exceeded the limit of 16777216 characters or 100000 text(), image(), and console calls. " +
|
|
208
|
+
"Print a summary instead, or write large data to a file with a tool.",
|
|
209
|
+
);
|
|
210
|
+
done(false, describeError(error));
|
|
211
|
+
throw error;
|
|
212
|
+
}
|
|
213
|
+
bridge("output", kind, data, mimeType);
|
|
214
|
+
}
|
|
215
|
+
|
|
195
216
|
// Primitives become their string form, everything else JSON.
|
|
196
217
|
function outputText(value) {
|
|
197
218
|
if (value === undefined || value === null || typeof value !== "object" && typeof value !== "function") {
|
|
@@ -208,7 +229,7 @@ import{parentPort,workerData}from"node:worker_threads";function createWasiShim(m
|
|
|
208
229
|
} catch (error) {
|
|
209
230
|
throw new TypeErrorCtor(error instanceof ErrorCtor ? error.message : String(error));
|
|
210
231
|
}
|
|
211
|
-
|
|
232
|
+
output("text", rendered);
|
|
212
233
|
}
|
|
213
234
|
|
|
214
235
|
function imageUrl(value) {
|
|
@@ -263,7 +284,7 @@ import{parentPort,workerData}from"node:worker_threads";function createWasiShim(m
|
|
|
263
284
|
if (!signature) {
|
|
264
285
|
throw new TypeErrorCtor("invalid image output. The image data is not a PNG, JPEG, GIF, or WebP image");
|
|
265
286
|
}
|
|
266
|
-
|
|
287
|
+
output("image", data, signature[0]);
|
|
267
288
|
}
|
|
268
289
|
|
|
269
290
|
function exit() {
|
|
@@ -281,7 +302,7 @@ import{parentPort,workerData}from"node:worker_threads";function createWasiShim(m
|
|
|
281
302
|
const console = {};
|
|
282
303
|
for (const level of ["log", "info", "warn", "error", "debug"]) {
|
|
283
304
|
console[level] = (...args) => {
|
|
284
|
-
|
|
305
|
+
output("text", args.map(format).join(" "));
|
|
285
306
|
};
|
|
286
307
|
}
|
|
287
308
|
Object.freeze(console);
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
+
import{ARMIN_HEIGHT,ARMIN_WIDTH,isArminPixel}from"./chunk-2KAZSACP.js";import{backgroundAnsi,colorToRgb,foregroundAnsi,formatKeyText,getKeybindings,indexedColor,rgbColor,theme,visibleWidth}from"./chunk-6FX7UEPL.js";import"./chunk-S3GGRYIO.js";import"./chunk-4L3WN2XY.js";var DEPTH=.7,FLY_START=.1,FLY_DURATION=1.3,START_SCALE=.1;function createModel(columns,rows,pixel,options){let blocks=[];for(let row=0;row<rows;row++)for(let column=0;column<columns;column++){let color=pixel(column,row);color&&blocks.push({home:[column,row,0],color})}return{columns,rows,blocks,cameraDistance:options.cameraDistance,radius:Math.hypot(columns/2,rows/2,1+DEPTH/2),widthShare:options.widthShare,puzzleMoves:random=>options.puzzleMoves(random,blocks.length),origin:options.origin}}var CORAL=[228,138,122],BLUE=[79,142,179],YELLOW=[234,182,93],PI_LOGO_PIXELS=["ccc.","b.c.","bb.y","b..y"],PI_LOGO_COLORS={c:CORAL,b:BLUE,y:YELLOW};function piLogoModel(origin){return createModel(4,4,(column,row)=>PI_LOGO_COLORS[PI_LOGO_PIXELS[row][column]],{cameraDistance:10,widthShare:.35,puzzleMoves:random=>random<.4?2:1,origin})}function arminModel(color){return createModel(ARMIN_WIDTH,ARMIN_HEIGHT,(column,row)=>isArminPixel(column,row)?color:void 0,{cameraDistance:80,widthShare:.45,puzzleMoves:(random,blockCount)=>Math.round(blockCount*(.03+random*.04)),origin:void 0})}var PUZZLE_START=FLY_START+FLY_DURATION+3,PUZZLE_STEP=.3,PUZZLE_STEPS=12,PUZZLE_RETURN=1,PUZZLE_HOLD=.6,PUZZLE_CYCLE=PUZZLE_STEP*PUZZLE_STEPS+PUZZLE_RETURN+PUZZLE_HOLD,PUZZLE_MOVES=[[1,0,0],[-1,0,0],[0,1,0],[0,-1,0],[1,0,0],[-1,0,0],[0,1,0],[0,-1,0],[0,0,1],[0,0,-1]];function shuffleSteps(model,cycle){let{columns,rows}=model,positions=model.blocks.map(block=>block.home),steps=[positions],lastMoved=new Set,random=cycle*7919+1,next=()=>hash(random++),key=([x,y,z])=>((z+1)*rows+y)*columns+x;for(let step=0;step<PUZZLE_STEPS;step++){let occupied=new Set(positions.map(key)),nextPositions=[...positions],moved=new Set,moveCount=model.puzzleMoves(next());for(let move=0;move<moveCount;move++){let candidates=[];for(let block=0;block<positions.length;block++){if(moved.has(block))continue;let[x,y,z]=positions[block];for(let[dx,dy,dz]of PUZZLE_MOVES){let target=[x+dx,y+dy,z+dz];target[0]<0||target[0]>=columns||target[1]<0||target[1]>=rows||target[2]<-1||target[2]>1||occupied.has(key(target))||candidates.push({block,target})}}let fresh=candidates.filter(candidate=>!lastMoved.has(candidate.block)),pool=fresh.length>0?fresh:candidates,choice=pool[Math.floor(next()*pool.length)];if(!choice)break;occupied.add(key(choice.target)),nextPositions[choice.block]=choice.target,moved.add(choice.block)}lastMoved.clear();for(let block of moved)lastMoved.add(block);positions=nextPositions,steps.push(positions)}return steps}var FRAME_MS=1e3/30,DUST_DURATION=.35,WAVE_SPREAD=.55,WAVE_JITTER=.12,DISSOLVE_END=FLY_START+WAVE_SPREAD+WAVE_JITTER+DUST_DURATION,BACKGROUND_FADE=.5,EXIT_DURATION=1.1,STARS_START=2.5,STARS_FADE=2,STAR_DENSITY=.018,STAR_TINTS=[[255,255,255],[170,195,255],[255,225,170],[255,190,205]],LOGO_COLOR_STEP=5,LIGHT_HALO_STRENGTH=.3,HALO_RADIUS_X=6,HALO_RADIUS_Y=3,HALO_LEVELS=32,STAR_ALPHA_LEVELS=8,STAR_FLICKER_LEVELS=3,HINT_FADE=.5,DOT_BITS=[1,8,2,16,4,32,64,128],BRAILLE=Array.from({length:256},(_,bits)=>String.fromCharCode(10240+bits)),LIGHT=normalize([-.45,-.6,.75]),HALF_VECTOR=normalize([LIGHT[0],LIGHT[1],LIGHT[2]+1]);function normalize(v){let length=Math.hypot(v[0],v[1],v[2]);return[v[0]/length,v[1]/length,v[2]/length]}function clamp01(value){return value<0?0:value>1?1:value}function smooth(value){let t=clamp01(value);return t*t*t*(t*(t*6-15)+10)}function easeOut(value){let t=1-clamp01(value);return 1-t*t*t}function mix(a,b,amount){return[a[0]+(b[0]-a[0])*amount,a[1]+(b[1]-a[1])*amount,a[2]+(b[2]-a[2])*amount]}function hash(value){let x=Math.imul(value^2654435769,2246822507);return x^=x>>>13,x=Math.imul(x,3266489909),x^=x>>>16,(x>>>0)/4294967296}function isLight([r,g,b]){return .2126*r+.7152*g+.0722*b>128}function toRgb(color){let{r,g,b}=colorToRgb(color);return[r,g,b]}function glyphInk(text,seed){return text.trim()===""?0:/^[.,:;'`\-_·]$/.test(text)?2:/^[\u2500-\u257f]$/.test(text)?3:4+Math.floor(seed*3)}var segmenter=new Intl.Segmenter;function parseScreen(lines,width,foreground,background){let palette=index=>toRgb(indexedColor(index));return lines.map(line=>{let cells=[],fg,bg,dim=!1,inverse=!1,applySgr=params=>{let codes=params===""?["0"]:params.split(";");for(let i2=0;i2<codes.length;i2++){let parts=codes[i2].split(":").map(part=>Number.parseInt(part,10)),code=parts[0]??0;if(code===38||code===48){let args;if(parts.length>1)args=parts.slice(1).filter(part=>!Number.isNaN(part));else{let kind=Number.parseInt(codes[i2+1]??"",10),count=kind===5?2:kind===2?4:1;args=codes.slice(i2+1,i2+1+count).map(part=>Number.parseInt(part,10)),i2+=count}let color;args[0]===5&&args[1]!==void 0?color=palette(args[1]):args[0]===2&&args.length>=4&&(color=[args[1],args[2],args[3]]),color&&(code===38?fg=color:bg=color)}else code===0?(fg=void 0,bg=void 0,dim=!1,inverse=!1):code===2?dim=!0:code===22?dim=!1:code===7?inverse=!0:code===27?inverse=!1:code>=30&&code<=37?fg=palette(code-30):code>=90&&code<=97?fg=palette(code-90+8):code===39?fg=void 0:code>=40&&code<=47?bg=palette(code-40):code>=100&&code<=107?bg=palette(code-100+8):code===49&&(bg=void 0)}},pushText=text=>{for(let{segment}of segmenter.segment(text)){let glyphWidth=visibleWidth(segment);if(glyphWidth===0||cells.length+glyphWidth>width)continue;let cellFg=fg??foreground,cellBg=bg;inverse&&(cellFg=bg??background,cellBg=fg??foreground),dim&&(cellFg=mix(cellFg,cellBg??background,.4));let cell={text:segment,width:glyphWidth,fg:cellFg,bg:cellBg,delay:0,ink:0,seed:0};cells.push(cell),glyphWidth===2&&cells.push({...cell,text:"",width:0})}},i=0;for(;i<line.length;){let sequenceStart=line.indexOf("\x1B",i);if(sequenceStart===-1){pushText(line.slice(i));break}sequenceStart>i&&pushText(line.slice(i,sequenceStart));let kind=line[sequenceStart+1];if(kind==="["){let end=sequenceStart+2;for(;end<line.length&&(line.charCodeAt(end)<64||line.charCodeAt(end)>126);)end++;line[end]==="m"&&applySgr(line.slice(sequenceStart+2,end)),i=end+1}else if(kind==="]"||kind==="_"||kind==="P"||kind==="^"){let bell=line.indexOf("\x07",sequenceStart+2),st=line.indexOf("\x1B\\",sequenceStart+2);if(bell===-1&&st===-1)break;i=bell!==-1&&(st===-1||bell<st)?bell+1:st+2}else i=sequenceStart+2}return cells})}function rotation(yaw,pitch,roll){let[sy,cy,sx,cx,sz,cz]=[Math.sin(yaw),Math.cos(yaw),Math.sin(pitch),Math.cos(pitch),Math.sin(roll),Math.cos(roll)],ry=[cy,0,sy,0,1,0,-sy,0,cy],rx=[1,0,0,0,cx,-sx,0,sx,cx],rz=[cz,-sz,0,sz,cz,0,0,0,1];return multiply(rz,multiply(rx,ry))}function multiply(a,b){let result=new Array(9);for(let row=0;row<3;row++)for(let column=0;column<3;column++)result[row*3+column]=a[row*3]*b[column]+a[row*3+1]*b[3+column]+a[row*3+2]*b[6+column];return result}var SPIN_RAMP=1.4,SPIN_SPEED=Math.PI*2/PUZZLE_CYCLE,SPIN_LINGER=.6,FIRST_FRONT_VIEW=PUZZLE_START+PUZZLE_STEP*PUZZLE_STEPS+PUZZLE_RETURN+PUZZLE_HOLD/2;function baseSpinPhase(time){let elapsed=time-FLY_START;if(elapsed<=0)return 0;let u=elapsed/SPIN_RAMP;return u<1?SPIN_SPEED*SPIN_RAMP*(u**6-3*u**5+2.5*u**4):SPIN_SPEED*(SPIN_RAMP*.5+elapsed-SPIN_RAMP)}var SPIN_ALIGNMENT=Math.PI*2-baseSpinPhase(FIRST_FRONT_VIEW)%(Math.PI*2);function spinPhase(time){return baseSpinPhase(time)+SPIN_ALIGNMENT*smooth((time-FLY_START)/FLY_DURATION)}function spinAngle(time){let phase=spinPhase(time);return phase-SPIN_LINGER*Math.sin(phase)}var BlockRaster=class{bits=new Uint8Array(0);counts=new Uint8Array(0);rgb=new Float32Array(0);haloAmount=new Float32Array(0);haloRgb=new Float32Array(0);width=0;height=0;depth=new Float32Array(0);faceIds=new Uint16Array(0);dirty;haloDirty;cameraDistance;constructor(cameraDistance){this.cameraDistance=cameraDistance}render(width,height,pose,boxes,background,haloStrength){let dotWidth=width*2,dotHeight=height*4;if(width!==this.width||height!==this.height)this.width=width,this.height=height,this.bits=new Uint8Array(width*height),this.counts=new Uint8Array(width*height),this.rgb=new Float32Array(width*height*3),this.haloAmount=new Float32Array(width*height),this.haloRgb=new Float32Array(width*height*3),this.haloDirty=void 0,this.depth=new Float32Array(dotWidth*dotHeight).fill(1/0),this.faceIds=new Uint16Array(dotWidth*dotHeight),this.dirty=void 0;else if(this.dirty){let{minX:minX2,minY:minY2,maxX:maxX2,maxY:maxY2}=this.dirty;for(let row=minY2;row<=maxY2;row++)this.bits.fill(0,row*width+minX2,row*width+maxX2+1),this.counts.fill(0,row*width+minX2,row*width+maxX2+1),this.rgb.fill(0,(row*width+minX2)*3,(row*width+maxX2+1)*3);this.dirty=void 0}if(this.haloDirty){let{minX:minX2,minY:minY2,maxX:maxX2,maxY:maxY2}=this.haloDirty;for(let row=minY2;row<=maxY2;row++)this.haloAmount.fill(0,row*width+minX2,row*width+maxX2+1),this.haloRgb.fill(0,(row*width+minX2)*3,(row*width+maxX2+1)*3);this.haloDirty=void 0}let m=rotation(pose.yaw,pose.pitch,pose.roll),{centerX,centerY,scale}=pose,cameraDistance=this.cameraDistance,origin=[m[6]*cameraDistance,m[7]*cameraDistance,m[8]*cameraDistance],light=isLight(background),faces=this.visibleFaces(m,origin,pose,boxes,dotWidth,dotHeight,light);if(faces.length===0)return;let minX=dotWidth,minY=dotHeight,maxX=-1,maxY=-1;for(let face of faces)minX=Math.min(minX,face.minX),minY=Math.min(minY,face.minY),maxX=Math.max(maxX,face.maxX),maxY=Math.max(maxY,face.maxY);if(maxX<minX||maxY<minY)return;let depth=this.depth,faceIds=this.faceIds;for(let faceIndex=0;faceIndex<faces.length;faceIndex++){let face=faces[faceIndex],a=face.axis,u=(a+1)%3,v=(a+2)%3,originA=origin[a],originU=origin[u],originV=origin[v],stepA=m[a]/scale,stepU=m[u]/scale,stepV=m[v]/scale,sx=(face.minX+.5-centerX)/scale;for(let dotY=face.minY;dotY<=face.maxY;dotY++){let sy=(dotY+.5-centerY)/scale,directionA=m[a]*sx+m[3+a]*sy-m[6+a]*cameraDistance,directionU=m[u]*sx+m[3+u]*sy-m[6+u]*cameraDistance,directionV=m[v]*sx+m[3+v]*sy-m[6+v]*cameraDistance,index=dotY*dotWidth+face.minX;for(let dotX=face.minX;dotX<=face.maxX;dotX++,index++){let t=(face.plane-originA)/directionA;if(t>0&&t<depth[index]){let hitU=originU+t*directionU,hitV=originV+t*directionV;hitU>=face.uMin&&hitU<=face.uMax&&hitV>=face.vMin&&hitV<=face.vMax&&(depth[index]=t,faceIds[index]=faceIndex+1)}directionA+=stepA,directionU+=stepU,directionV+=stepV}}}let bits=this.bits,counts=this.counts,rgb=this.rgb,cellMinX=width,cellMinY=height,cellMaxX=-1,cellMaxY=-1;for(let dotY=minY;dotY<=maxY;dotY++){let index=dotY*dotWidth+minX;for(let dotX=minX;dotX<=maxX;dotX++,index++){let id=faceIds[index];if(id===0)continue;let face=faces[id-1],fog=clamp01(.15-cameraDistance*(1-depth[index])*.12)*(light?.5:1);faceIds[index]=0,depth[index]=1/0;let cellX=dotX>>1,cellY=dotY>>2,cell=cellY*width+cellX;bits[cell]|=DOT_BITS[(dotY&3)*2+(dotX&1)],counts[cell]++,rgb[cell*3]+=face.red+(background[0]-face.red)*fog,rgb[cell*3+1]+=face.green+(background[1]-face.green)*fog,rgb[cell*3+2]+=face.blue+(background[2]-face.blue)*fog,cellX<cellMinX&&(cellMinX=cellX),cellX>cellMaxX&&(cellMaxX=cellX),cellY<cellMinY&&(cellMinY=cellY),cellY>cellMaxY&&(cellMaxY=cellY)}}cellMaxX>=0&&(this.dirty={minX:cellMinX,minY:cellMinY,maxX:cellMaxX,maxY:cellMaxY}),haloStrength>0&&this.renderHalo(haloStrength)}renderHalo(strength){let cells=this.dirty;if(!cells)return;let{width,height,counts,rgb}=this,minX=Math.max(0,cells.minX-HALO_RADIUS_X),maxX=Math.min(width-1,cells.maxX+HALO_RADIUS_X),minY=Math.max(0,cells.minY-HALO_RADIUS_Y),maxY=Math.min(height-1,cells.maxY+HALO_RADIUS_Y),regionWidth=maxX-minX+1,tent=radius=>{let weights=Array.from({length:radius*2+1},(_,i)=>radius+1-Math.abs(i-radius)),total=weights.reduce((sum,weight)=>sum+weight,0);return weights.map(weight=>weight/total)},weightsX=tent(HALO_RADIUS_X),weightsY=tent(HALO_RADIUS_Y),rows=cells.maxY-cells.minY+1,horizontal=new Float32Array(rows*regionWidth*4);for(let y=cells.minY;y<=cells.maxY;y++)for(let x=minX;x<=maxX;x++){let coverage=0,red=0,green=0,blue=0;for(let dx=-HALO_RADIUS_X;dx<=HALO_RADIUS_X;dx++){let sourceX=x+dx;if(sourceX<cells.minX||sourceX>cells.maxX)continue;let source=y*width+sourceX,count=counts[source];if(count===0)continue;let weight=weightsX[dx+HALO_RADIUS_X]/8;coverage+=count*weight,red+=rgb[source*3]*weight,green+=rgb[source*3+1]*weight,blue+=rgb[source*3+2]*weight}let target=((y-cells.minY)*regionWidth+(x-minX))*4;horizontal[target]=coverage,horizontal[target+1]=red,horizontal[target+2]=green,horizontal[target+3]=blue}for(let y=minY;y<=maxY;y++)for(let x=minX;x<=maxX;x++){let coverage=0,red=0,green=0,blue=0;for(let dy=-HALO_RADIUS_Y;dy<=HALO_RADIUS_Y;dy++){let sourceY=y+dy;if(sourceY<cells.minY||sourceY>cells.maxY)continue;let weight=weightsY[dy+HALO_RADIUS_Y],source=((sourceY-cells.minY)*regionWidth+(x-minX))*4;coverage+=horizontal[source]*weight,red+=horizontal[source+1]*weight,green+=horizontal[source+2]*weight,blue+=horizontal[source+3]*weight}let target=y*width+x,count=counts[target];if(count>0&&count/8>coverage&&(coverage=count/8,red=rgb[target*3]/count*coverage,green=rgb[target*3+1]/count*coverage,blue=rgb[target*3+2]/count*coverage),coverage<=0)continue;let amount=Math.round(strength*Math.min(1,coverage)**.7*HALO_LEVELS)/HALO_LEVELS;amount<=0||(this.haloAmount[target]=amount,this.haloRgb[target*3]=Math.round(red/coverage/LOGO_COLOR_STEP)*LOGO_COLOR_STEP,this.haloRgb[target*3+1]=Math.round(green/coverage/LOGO_COLOR_STEP)*LOGO_COLOR_STEP,this.haloRgb[target*3+2]=Math.round(blue/coverage/LOGO_COLOR_STEP)*LOGO_COLOR_STEP)}this.haloDirty={minX,minY,maxX,maxY}}visibleFaces(m,origin,pose,boxes,dotWidth,dotHeight,lightBackground){let faces=[],cameraDistance=this.cameraDistance;for(let box of boxes)for(let a=0;a<3;a++){let u=(a+1)%3,v=(a+2)%3;for(let side of[-1,1]){let plane=side>0?box.max[a]:box.min[a];if((origin[a]-plane)*side<=0||boxes.some(other=>other!==box&&(side>0?other.min[a]:other.max[a])===plane&&other.min[u]<=box.min[u]&&other.max[u]>=box.max[u]&&other.min[v]<=box.min[v]&&other.max[v]>=box.max[v]))continue;let minX=1/0,minY=1/0,maxX=-1/0,maxY=-1/0,corner=[0,0,0];for(let cornerU of[box.min[u],box.max[u]])for(let cornerV of[box.min[v],box.max[v]]){corner[a]=plane,corner[u]=cornerU,corner[v]=cornerV;let x=m[0]*corner[0]+m[1]*corner[1]+m[2]*corner[2],y=m[3]*corner[0]+m[4]*corner[1]+m[5]*corner[2],z=m[6]*corner[0]+m[7]*corner[1]+m[8]*corner[2],perspective=pose.scale*cameraDistance/(cameraDistance-z),screenX=pose.centerX+x*perspective,screenY=pose.centerY+y*perspective;minX=Math.min(minX,screenX),minY=Math.min(minY,screenY),maxX=Math.max(maxX,screenX),maxY=Math.max(maxY,screenY)}let face={minX:Math.max(0,Math.floor(minX)),minY:Math.max(0,Math.floor(minY)),maxX:Math.min(dotWidth-1,Math.ceil(maxX)),maxY:Math.min(dotHeight-1,Math.ceil(maxY))};if(face.maxX<face.minX||face.maxY<face.minY)continue;let nx=m[a]*side,ny=m[3+a]*side,nz=m[6+a]*side,diffuse=Math.max(0,nx*LIGHT[0]+ny*LIGHT[1]+nz*LIGHT[2]),rim=Math.max(0,nx*.8-nz*.3),specular=lightBackground?0:Math.max(0,nx*HALF_VECTOR[0]+ny*HALF_VECTOR[1]+nz*HALF_VECTOR[2])**24*.6*255,light=lightBackground?Math.min(1,.55+diffuse*.45+rim*.1):.45+diffuse*.78+rim*.25;faces.push({axis:a,plane,uMin:box.min[u],uMax:box.max[u],vMin:box.min[v],vMax:box.max[v],...face,red:Math.min(255,box.color[0]*light+specular),green:Math.min(255,box.color[1]*light+specular),blue:Math.min(255,box.color[2]*light+specular)})}}return faces}},playing=!1;async function playEasterEgg3d(tui,screen,egg){if(playing)return;playing=!0;let reported=await tui.queryTerminalColors({timeoutMs:100}),dark=theme.appearance==="dark",toRgbTuple=(rgb,fallback)=>rgb?[rgb.r,rgb.g,rgb.b]:fallback,colors={foreground:toRgbTuple(reported.foreground,toRgb(theme.colors.text)),background:toRgbTuple(reported.background,dark?[0,0,0]:[255,255,255])};if(tui.hasOverlay()){playing=!1;return}let model=egg.kind==="armin"?arminModel(toRgb(theme.colors.accent)):piLogoModel({column:egg.column,row:egg.row}),animation=new EasterEgg3dAnimation(tui,screen,model,colors,()=>{playing=!1,overlay.hide()}),overlay=tui.showOverlay(animation,{anchor:"top-left",width:"100%",maxHeight:"100%"})}var EasterEgg3dAnimation=class{tui;screen;model;foreground;background;onDone;startTime=performance.now();lastRender=performance.now();timer;exit;shuffle;screenWidth=-1;screenHeight=-1;stars=[];cells=[];ansiCache=new Map;raster;constructor(tui,screen,model,colors,onDone){this.tui=tui,this.screen=screen,this.model=model,this.raster=new BlockRaster(model.cameraDistance),this.foreground=colors.foreground,this.background=colors.background,this.onDone=onDone,this.timer=setInterval(()=>{this.exit&&this.exitProgress()>=1||performance.now()-this.lastRender>1e3?this.finish():this.tui.requestRender()},FRAME_MS),this.timer.unref?.()}close(){if(this.exit){this.finish();return}let time=this.elapsed(),yaw=spinAngle(time),turn=Math.PI*2;this.exit={start:performance.now(),time,yaw,targetYaw:Math.ceil(yaw/turn)*turn,offsets:this.blockOffsets(time)}}handleInput(data){let keybindings=getKeybindings();(keybindings.matches(data,"tui.select.cancel")||keybindings.matches(data,"app.clear"))&&this.close()}handleMouse(event){return event.type==="click"&&this.close(),{handled:!0,render:!1}}invalidate(){this.screenWidth=-1,this.screenHeight=-1,this.ansiCache.clear()}render(width){let height=Math.max(1,this.tui.terminal.rows),foreground=this.foreground,background=this.background;this.lastRender=performance.now(),(width!==this.screenWidth||height!==this.screenHeight)&&(this.screenWidth=width,this.screenHeight=height,this.cells=this.prepareCells(width,foreground),this.stars=this.prepareStars(width,height));let dissolveTime,pose,hintAlpha,starAlpha,offsets;if(this.exit){let progress=this.exitProgress(),landing=clamp01(progress/.8),settle=1-smooth(landing);dissolveTime=Math.min(this.exit.time,DISSOLVE_END)*(1-progress),pose=this.pose(width,height,this.flyProgress(this.exit.time)*settle,this.exit.time),pose.yaw=this.exit.yaw+(this.exit.targetYaw-this.exit.yaw)*easeOut(landing),pose.pitch*=settle,pose.roll*=settle,hintAlpha=this.hintAlpha(this.exit.time)*(1-smooth(progress/.2)),starAlpha=this.starAlpha(this.exit.time)*(1-smooth(progress/.3));let gather=1-smooth(progress/.5);offsets=this.exit.offsets.map(([x,y,z])=>[x*gather,y*gather,z*gather])}else{let time=this.elapsed();dissolveTime=time,pose=this.pose(width,height,this.flyProgress(time),time),hintAlpha=this.hintAlpha(time),starAlpha=this.starAlpha(time),offsets=this.blockOffsets(time)}let{columns,rows}=this.model,boxes=this.model.blocks.map((block,index)=>{let[dx,dy,dz]=offsets[index],x=block.home[0]-columns/2+dx,y=block.home[1]-rows/2+dy;return{min:[x,y,dz-DEPTH/2],max:[x+1,y+1,dz+DEPTH/2],color:block.color}}),raster=this.raster;raster.render(width,height,pose,boxes,background,isLight(background)?LIGHT_HALO_STRENGTH:0);let halo=(index,base)=>{let amount=raster.haloAmount[index];if(amount<=0)return base;let color=raster.haloRgb;return mix(base??background,[color[index*3],color[index*3+1],color[index*3+2]],amount)},backgroundFade=smooth(dissolveTime/BACKGROUND_FADE),textFade=smooth(dissolveTime/.6)*.3,textActive=dissolveTime<DISSOLVE_END||backgroundFade<1,hint=this.hint(width,height,hintAlpha,background),frame=Math.floor(dissolveTime*14),now=this.elapsed(),starLevel=Math.round(starAlpha*STAR_ALPHA_LEVELS)/STAR_ALPHA_LEVELS,starfield=index=>{if(starLevel<=0)return;let star=this.stars[index];if(!star)return;let flicker=Math.round((.5+.5*Math.sin(now*star.speed+star.phase))*STAR_FLICKER_LEVELS)/STAR_FLICKER_LEVELS;return{text:star.glyph,fg:mix(background,mix(foreground,star.tint,.5),star.strength*(.7+.3*flicker)*starLevel)}},lines=[];for(let row=0;row<height;row++){let cells=this.cells[row]??[],line="",currentFg=-1,currentBg=-1,emit=(text,fg,bg)=>{let fgKey=fg?this.pack(fg):-1,bgKey=bg?this.pack(bg):-1;fgKey!==currentFg&&text!==" "&&(line+=fg?this.ansi(fgKey,!1):"\x1B[39m",currentFg=fgKey),bgKey!==currentBg&&(line+=bg?this.ansi(bgKey,!0):"\x1B[49m",currentBg=bgKey),line+=text};for(let column=0;column<width;column++){let index=row*width+column,cell=textActive?cells[column]:void 0,cellBg=halo(index,cell?.bg&&backgroundFade<1?mix(cell.bg,background,backgroundFade):void 0);if(hint&&row===hint.row&&column>=hint.start&&column<hint.start+hint.text.length){let offset=column-hint.start;emit(hint.text[offset],offset<hint.keyLength?hint.keyColor:hint.color,cellBg);continue}let dots=raster.bits[index];if(dots){let step=LOGO_COLOR_STEP*raster.counts[index],rgb=raster.rgb,color=[Math.round(rgb[index*3]/step)*LOGO_COLOR_STEP,Math.round(rgb[index*3+1]/step)*LOGO_COLOR_STEP,Math.round(rgb[index*3+2]/step)*LOGO_COLOR_STEP];emit(BRAILLE[dots],color,cellBg);continue}if(!cell){let star=starfield(index);emit(star?.text??" ",star?.fg,cellBg);continue}let dust=(dissolveTime-cell.delay)/DUST_DURATION;if(dust<0&&cell.width===2&&!raster.bits[index+1]){emit(cell.text,mix(cell.fg,background,textFade),cellBg),column++;continue}if(dust<0&&cell.width===1){emit(cell.text,mix(cell.fg,background,textFade),cellBg);continue}let dotCount=dust<0?cell.ink:Math.round(cell.ink*(1-clamp01(dust)));if(dotCount<=0){let star=starfield(index);emit(star?.text??" ",star?.fg,cellBg);continue}let bits=0,placed=0;for(let attempt=0;placed<dotCount&&attempt<32;attempt++){let bit=DOT_BITS[Math.floor(hash(cell.seed*7919+frame*131+attempt)*8)];bits&bit||(bits|=bit,placed++)}let fade=textFade+(1-textFade)*clamp01(dust)**.8;emit(BRAILLE[bits],mix(cell.fg,background,fade),cellBg)}lines.push(`${line}\x1B[0m`)}return lines}elapsed(){return(performance.now()-this.startTime)/1e3}exitProgress(){return this.exit?clamp01((performance.now()-this.exit.start)/1e3/EXIT_DURATION):0}finish(){this.timer&&(clearInterval(this.timer),this.timer=void 0,this.onDone())}blockOffsets(time){let blocks=this.model.blocks,home=()=>blocks.map(()=>[0,0,0]);if(time<PUZZLE_START)return home();let cycle=Math.floor((time-PUZZLE_START)/PUZZLE_CYCLE),local=time-PUZZLE_START-cycle*PUZZLE_CYCLE;this.shuffle?.cycle!==cycle&&(this.shuffle={cycle,steps:shuffleSteps(this.model,cycle)});let steps=this.shuffle.steps,offset=(position,index)=>{let block=blocks[index].home;return[position[0]-block[0],position[1]-block[1],position[2]-block[2]]},shuffleEnd=PUZZLE_STEP*PUZZLE_STEPS;if(local<shuffleEnd){let step=Math.floor(local/PUZZLE_STEP),progress=smooth((local-step*PUZZLE_STEP)/PUZZLE_STEP);return steps[step].map((from,index)=>{let a=offset(from,index),b=offset(steps[step+1][index],index);return[a[0]+(b[0]-a[0])*progress,a[1]+(b[1]-a[1])*progress,a[2]+(b[2]-a[2])*progress]})}if(local<shuffleEnd+PUZZLE_RETURN){let u=(local-shuffleEnd)/PUZZLE_RETURN,remaining=1-smooth(u),arc=Math.sin(Math.PI*clamp01(u))*.8;return steps[PUZZLE_STEPS].map((position,index)=>{let[x,y,z]=offset(position,index);return[x*remaining,y*remaining,z*remaining+(index%2===0?arc:-arc)]})}return home()}flyProgress(time){return smooth((time-FLY_START)/FLY_DURATION)}starAlpha(time){return smooth((time-STARS_START)/STARS_FADE)}hintAlpha(time){return smooth((time-FLY_START-FLY_DURATION)/HINT_FADE)}pose(width,height,progress,time){let{columns,rows,cameraDistance,radius,widthShare,origin}=this.model,reach=radius*(cameraDistance/(cameraDistance-radius)),startScale=origin?2*(cameraDistance-DEPTH/2)/cameraDistance:START_SCALE,endScale=Math.max(startScale,Math.min(width*2*widthShare,(height*4-8)*.48)/reach),endX=width,endY=height*2-2,startX=origin?origin.column*2+columns:endX,startY=origin?origin.row*4+rows:endY;return{centerX:startX+(endX-startX)*progress,centerY:startY+(endY-startY)*progress,scale:startScale*(endScale/startScale)**progress,yaw:spinAngle(time),pitch:.3*Math.sin(spinPhase(time))*progress,roll:.06*Math.sin(2*spinPhase(time))*progress}}hint(width,height,alpha,background){if(alpha<=0)return;let key=formatKeyText(getKeybindings().getKeys("tui.select.cancel")[0]??"escape"),text=`${key} to return`;if(!(text.length>width))return{row:height-2,start:Math.floor((width-text.length)/2),text,keyLength:key.length,keyColor:mix(background,toRgb(theme.colors.muted),alpha),color:mix(background,toRgb(theme.colors.dim),alpha)}}prepareStars(width,height){let stars=new Array(width*height);for(let index=0;index<width*height;index++){if(hash(index*3+20973)>=STAR_DENSITY)continue;let random=salt=>hash(index*7+salt*40503);stars[index]={glyph:BRAILLE[DOT_BITS[Math.floor(random(1)*8)]],tint:STAR_TINTS[Math.floor(random(2)*STAR_TINTS.length)],strength:.1+random(3)*.12,phase:random(4)*Math.PI*2,speed:.4+random(5)*.8}}return stars}prepareCells(width,foreground){let cells=parseScreen(this.screen,width,foreground,this.background),height=Math.max(1,this.tui.terminal.rows),{columns,rows,origin}=this.model,centerX=origin?origin.column+columns/2:width/2,centerY=origin?origin.row+rows/4:height/2,farthest=Math.hypot(Math.max(centerX,width-centerX),Math.max(centerY,height-centerY)*2);for(let row=0;row<cells.length;row++){let line=cells[row];for(let column=0;column<line.length;column++){let cell=line[column],owner=cell.width===0?line[column-1]:cell,seed=hash(row*65537+column);if(cell.width!==0){let distance=Math.hypot(column-centerX,(row-centerY)*2)/farthest;cell.delay=FLY_START+distance*WAVE_SPREAD+seed*WAVE_JITTER}else cell.delay=owner.delay;cell.seed=row*65537+column,cell.ink=glyphInk(owner.text,seed)}}if(origin)for(let row=origin.row;row<origin.row+Math.ceil(rows/2);row++){let line=cells[row];if(line)for(let column=origin.column;column<origin.column+columns;column++){let cell=line[column];cell&&(cell.text=" ",cell.width=1,cell.ink=0,cell.bg=void 0)}}return cells}pack(color){return Math.round(color[0])<<16|Math.round(color[1])<<8|Math.round(color[2])}ansi(key,isBackground){let cacheKey=key*2+(isBackground?1:0),value=this.ansiCache.get(cacheKey);if(value===void 0){let color=rgbColor(key>>16&255,key>>8&255,key&255),mode=theme.getColorMode();value=isBackground?backgroundAnsi(color,mode):foregroundAnsi(color,mode),this.ansiCache.set(cacheKey,value)}return value}};export{EasterEgg3dAnimation,playEasterEgg3d};
|
|
@@ -1,11 +1,12 @@
|
|
|
1
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-
|
|
2
|
+
import{Bm25Ranker,CODEMODE_DOCS_PATH,CODEMODE_STORE_ENTRY_TYPE,DEFAULT_TOOL_SEARCH_LIMIT,combineUsage,createToolSearchDocument,getCodemodeCallableTools,parseCodemodeSource,renderToolSample,toCodemodeDeclaration,toCodemodeIdentifier}from"./chunk-SYF2TF6W.js";import"./chunk-OYBSLV7Y.js";import{getCodemodeWorkerSpecifier,getQuickJSWasmPath}from"./chunk-6FX7UEPL.js";import"./chunk-S3GGRYIO.js";import"./chunk-4L3WN2XY.js";import{randomBytes}from"node:crypto";import{writeFile}from"node:fs/promises";import{tmpdir}from"node:os";import{join}from"node:path";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}function parseStoreWrites(json){let writes={set:{},delete:[]};for(let[key,value]of JSON.parse(json))value===void 0?writes.delete.push(key):writes.set[key]=JSON.parse(value);return writes}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=>this.handleMessage(message)),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||!isWorkerToHostMessage(message)))switch(message.type){case"output":this.output.push(message.item);break;case"call":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){let parsed=JSON.parse(message.error);this.finish({kind:"script",...parsed});return}this.finish(void 0,message.value===void 0?void 0:JSON.parse(message.value),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===void 0?{set:{},delete:[]}:parseStoreWrites(writes)};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
3
|
"use strict";
|
|
4
4
|
const stringify = JSON.stringify;
|
|
5
5
|
const parse = JSON.parse;
|
|
6
6
|
const promiseThen = Promise.prototype.then;
|
|
7
7
|
const ErrorCtor = Error;
|
|
8
8
|
const TypeErrorCtor = TypeError;
|
|
9
|
+
const RangeErrorCtor = RangeError;
|
|
9
10
|
const pending = new Map();
|
|
10
11
|
let nextId = 1;
|
|
11
12
|
let finished = false;
|
|
@@ -191,6 +192,26 @@ import{Bm25Ranker,CODEMODE_DOCS_PATH,CODEMODE_STORE_ENTRY_TYPE,DEFAULT_TOOL_SEAR
|
|
|
191
192
|
Object.defineProperty(globalThis, "store", { value: store, enumerable: true });
|
|
192
193
|
Object.defineProperty(globalThis, "load", { value: load, enumerable: true });
|
|
193
194
|
|
|
195
|
+
let outputChars = 0;
|
|
196
|
+
let outputItems = 0;
|
|
197
|
+
|
|
198
|
+
// Past the output limits the script fails: done() reports the error, so catching it does not
|
|
199
|
+
// resume output, and the host ends the script.
|
|
200
|
+
function output(kind, data, mimeType) {
|
|
201
|
+
if (finished) return;
|
|
202
|
+
outputChars += data.length;
|
|
203
|
+
outputItems++;
|
|
204
|
+
if (outputChars > 16777216 || outputItems > 100000) {
|
|
205
|
+
const error = new RangeErrorCtor(
|
|
206
|
+
"script output exceeded the limit of 16777216 characters or 100000 text(), image(), and console calls. " +
|
|
207
|
+
"Print a summary instead, or write large data to a file with a tool.",
|
|
208
|
+
);
|
|
209
|
+
done(false, describeError(error));
|
|
210
|
+
throw error;
|
|
211
|
+
}
|
|
212
|
+
bridge("output", kind, data, mimeType);
|
|
213
|
+
}
|
|
214
|
+
|
|
194
215
|
// Primitives become their string form, everything else JSON.
|
|
195
216
|
function outputText(value) {
|
|
196
217
|
if (value === undefined || value === null || typeof value !== "object" && typeof value !== "function") {
|
|
@@ -207,7 +228,7 @@ import{Bm25Ranker,CODEMODE_DOCS_PATH,CODEMODE_STORE_ENTRY_TYPE,DEFAULT_TOOL_SEAR
|
|
|
207
228
|
} catch (error) {
|
|
208
229
|
throw new TypeErrorCtor(error instanceof ErrorCtor ? error.message : String(error));
|
|
209
230
|
}
|
|
210
|
-
|
|
231
|
+
output("text", rendered);
|
|
211
232
|
}
|
|
212
233
|
|
|
213
234
|
function imageUrl(value) {
|
|
@@ -262,7 +283,7 @@ import{Bm25Ranker,CODEMODE_DOCS_PATH,CODEMODE_STORE_ENTRY_TYPE,DEFAULT_TOOL_SEAR
|
|
|
262
283
|
if (!signature) {
|
|
263
284
|
throw new TypeErrorCtor("invalid image output. The image data is not a PNG, JPEG, GIF, or WebP image");
|
|
264
285
|
}
|
|
265
|
-
|
|
286
|
+
output("image", data, signature[0]);
|
|
266
287
|
}
|
|
267
288
|
|
|
268
289
|
function exit() {
|
|
@@ -280,7 +301,7 @@ import{Bm25Ranker,CODEMODE_DOCS_PATH,CODEMODE_STORE_ENTRY_TYPE,DEFAULT_TOOL_SEAR
|
|
|
280
301
|
const console = {};
|
|
281
302
|
for (const level of ["log", "info", "warn", "error", "debug"]) {
|
|
282
303
|
console[level] = (...args) => {
|
|
283
|
-
|
|
304
|
+
output("text", args.map(format).join(" "));
|
|
284
305
|
};
|
|
285
306
|
}
|
|
286
307
|
Object.freeze(console);
|
package/dist/bundle/chunks/{google-generative-ai-APTPZOQL.js → google-generative-ai-ZOK6CV7D.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-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{calculateCost,clampThinkingLevel,collapseSystemMessages,getCurrentTools,getInitialSystemMessage,getSystemMessageText}from"./chunk-7JGR3GZN.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-3LH3ZQKY.js";import{formatProviderError,normalizeProviderError}from"./chunk-TEPMHNKQ.js";import"./chunk-LD2P6SFZ.js";import{buildBaseOptions,getPiUserAgent}from"./chunk-6D7LHLKG.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-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};
|
package/dist/bundle/chunks/{mistral-conversations-DKVFNQL6.js → mistral-conversations-7DAUEE4N.js}
RENAMED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{shortHash}from"./chunk-PJACZCIR.js";import{buildBaseOptions,getJsonSchemaToolParameters,getPiUserAgent,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-
|
|
2
|
+
import{shortHash}from"./chunk-PJACZCIR.js";import{buildBaseOptions,getJsonSchemaToolParameters,getPiUserAgent,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-IKZJX7ZT.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{headersToRecord}from"./chunk-UTB4DTYQ.js";import{parseStreamingJson}from"./chunk-TRDNDS6A.js";import{calculateCost,clampThinkingLevel,getCurrentTools,getSystemMessageText,renderSystemMessageUpdate,resolveTranscript}from"./chunk-7JGR3GZN.js";import{AssistantMessageEventStream}from"./chunk-A3JYRWB6.js";import"./chunk-4L3WN2XY.js";var MISTRAL_TOOL_CALL_ID_LENGTH=9,MAX_MISTRAL_ERROR_BODY_CHARS=4e3,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=resolveTranscript(context,model.compat?.supportsMidConvoSystemMessages);return(async()=>{let output=createOutput(model);try{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let normalizeMistralToolCallId=createMistralToolCallIdNormalizer(),transformedMessages=transformMessages(normalizedContext.messages,model,id=>normalizeMistralToolCallId(id)),payload=buildChatPayload(model,normalizedContext,transformedMessages,options),nextPayload=await options?.onPayload?.(payload,model);nextPayload!==void 0&&(payload=nextPayload);let mistralStream=await requestMistralStream(model,payload,apiKey,options);if(stream2.push({type:"start",partial:output}),await consumeChatStream(model,output,stream2,mistralStream,options?.onProviderStreamEvent),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Mistral stream ended without a finish reason");if(output.stopReason==="aborted"||output.stopReason==="error")throw new Error(output.errorMessage||"An unknown error occurred");stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)delete block.partialArgs;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatMistralError(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},clampedReasoning=options?.reasoning?clampThinkingLevel(model,options.reasoning):void 0,reasoning=clampedReasoning==="off"?void 0:clampedReasoning,effortMap=model.reasoning?model.thinkingLevelMap:void 0,reasoningEffort=effortMap?reasoning?effortMap[reasoning]??"high":effortMap.off??void 0:void 0;return stream(model,context,{...base,promptMode:model.reasoning&&!effortMap&&reasoning?"reasoning":void 0,reasoningEffort})};function createOutput(model){return{role:"assistant",content:[],api:model.api,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()}}function createMistralToolCallIdNormalizer(){let idMap=new Map,reverseMap=new Map;return id=>{let existing=idMap.get(id);if(existing)return existing;let attempt=0;for(;;){let candidate=deriveMistralToolCallId(id,attempt),owner=reverseMap.get(candidate);if(!owner||owner===id)return idMap.set(id,candidate),reverseMap.set(candidate,id),candidate;attempt++}}}function deriveMistralToolCallId(id,attempt){let normalized=id.replace(/[^a-zA-Z0-9]/g,"");if(attempt===0&&normalized.length===MISTRAL_TOOL_CALL_ID_LENGTH)return normalized;let seedBase=normalized||id,seed=attempt===0?seedBase:`${seedBase}:${attempt}`;return shortHash(seed).replace(/[^a-zA-Z0-9]/g,"").slice(0,MISTRAL_TOOL_CALL_ID_LENGTH)}function formatMistralError(error){if(error instanceof Error){let httpError=error,statusCode=typeof httpError.statusCode=="number"?httpError.statusCode:void 0,bodyText=typeof httpError.body=="string"?httpError.body.trim():void 0;return statusCode!==void 0&&bodyText?`Mistral API error (${statusCode}): ${truncateErrorText(bodyText,MAX_MISTRAL_ERROR_BODY_CHARS)}`:statusCode!==void 0?`Mistral API error (${statusCode}): ${error.message}`:error.message}return safeJsonStringify(error)}function truncateErrorText(text,maxChars){return text.length<=maxChars?text:`${text.slice(0,maxChars)}... [truncated ${text.length-maxChars} chars]`}function safeJsonStringify(value){try{let serialized=JSON.stringify(value);return serialized===void 0?String(value):serialized}catch{return String(value)}}async function requestMistralStream(model,payload,apiKey,options){let baseUrl=new URL(model.baseUrl);baseUrl.pathname=`${baseUrl.pathname.replace(/\/+$/u,"")}/`;let url=new URL("v1/chat/completions",baseUrl),headers=buildMistralHeaders(model,apiKey,options),timeoutSignal=AbortSignal.timeout(options?.timeoutMs??6e4),signal=options?.signal?AbortSignal.any([options.signal,timeoutSignal]):timeoutSignal,response=await(options?.fetch??globalThis.fetch)(url,{method:"POST",headers,body:JSON.stringify(toMistralWirePayload(payload)),signal});if(await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),!response.ok){let body=await response.text();throw new MistralHttpError(response.status,body,response.statusText)}if(!response.body)throw new Error("Mistral response has no body");return readMistralEvents(response.body,signal)}var MistralHttpError=class extends Error{statusCode;body;constructor(statusCode,body,statusText){super(statusText||`Request failed with status ${statusCode}`),this.name="MistralHttpError",this.statusCode=statusCode,this.body=body}};function buildMistralHeaders(model,apiKey,options){let headers=new Headers({"User-Agent":getPiUserAgent(),accept:"text/event-stream",authorization:`Bearer ${apiKey}`,"content-type":"application/json"});applyMistralHeaderOverrides(headers,model.headers),applyMistralHeaderOverrides(headers,options?.headers);let hasExplicitAffinity=hasMistralHeaderOverride(model.headers,"x-affinity")||hasMistralHeaderOverride(options?.headers,"x-affinity");return shouldUsePromptCaching(options)&&!hasExplicitAffinity&&headers.set("x-affinity",options.sessionId),headers}function applyMistralHeaderOverrides(headers,overrides){if(overrides)for(let[name,value]of Object.entries(overrides))value===null?headers.delete(name):headers.set(name,value)}function hasMistralHeaderOverride(overrides,target){return!!overrides&&Object.keys(overrides).some(name=>name.toLowerCase()===target)}function toMistralWirePayload(payload){let wirePayload={...payload};for(let[source,target]of[["topP","top_p"],["maxTokens","max_tokens"],["randomSeed","random_seed"],["responseFormat","response_format"],["toolChoice","tool_choice"],["presencePenalty","presence_penalty"],["frequencyPenalty","frequency_penalty"],["parallelToolCalls","parallel_tool_calls"],["reasoningEffort","reasoning_effort"],["promptMode","prompt_mode"],["promptCacheKey","prompt_cache_key"],["safePrompt","safe_prompt"]])remapMistralProperty(wirePayload,source,target);wirePayload.messages=payload.messages.map(message=>toMistralWireMessage(message));let responseFormat=wirePayload.response_format;if(isMistralRecord(responseFormat)){let wireResponseFormat={...responseFormat};remapMistralProperty(wireResponseFormat,"jsonSchema","json_schema");let jsonSchema=wireResponseFormat.json_schema;if(isMistralRecord(jsonSchema)){let wireJsonSchema={...jsonSchema};remapMistralProperty(wireJsonSchema,"schemaDefinition","schema"),wireResponseFormat.json_schema=wireJsonSchema}wirePayload.response_format=wireResponseFormat}return wirePayload}function toMistralWireMessage(message){let wireMessage={...message};return remapMistralProperty(wireMessage,"toolCalls","tool_calls"),remapMistralProperty(wireMessage,"toolCallId","tool_call_id"),Array.isArray(message.content)&&(wireMessage.content=message.content.map(chunk=>toMistralWireContentChunk(chunk))),wireMessage}function toMistralWireContentChunk(chunk){let wireChunk={...chunk};for(let[source,target]of[["imageUrl","image_url"],["documentUrl","document_url"],["documentName","document_name"],["fileId","file_id"],["referenceIds","reference_ids"],["inputAudio","input_audio"]])remapMistralProperty(wireChunk,source,target);return wireChunk}function remapMistralProperty(record,source,target){source in record&&(record[target]=record[source],delete record[source])}function isMistralRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var MISTRAL_STREAM_DONE=Symbol("mistral-stream-done");async function*readMistralEvents(body,signal){let reader=body.getReader(),decoder=new TextDecoder,buffer="",onAbort=()=>{reader.cancel().catch(()=>{})};signal.addEventListener("abort",onAbort,{once:!0});try{for(;;){if(signal.aborted)throw signal.reason;let{done,value}=await reader.read();if(signal.aborted)throw signal.reason;buffer+=done?decoder.decode():decoder.decode(value,{stream:!0});let boundary=findMistralEventBoundary(buffer);for(;boundary;){let event=parseMistralEvent(buffer.slice(0,boundary.index));if(buffer=buffer.slice(boundary.index+boundary.length),event===MISTRAL_STREAM_DONE)return;event&&(yield event),boundary=findMistralEventBoundary(buffer)}if(done)break}if(buffer.trim()){let event=parseMistralEvent(buffer);event!==MISTRAL_STREAM_DONE&&event&&(yield event)}}finally{signal.removeEventListener("abort",onAbort);try{await reader.cancel()}catch{}try{reader.releaseLock()}catch{}}}function findMistralEventBoundary(buffer){let match=/\r\n\r\n|\r\n\r|\r\n\n|\r\r\n|\n\r\n|\r\r|\n\r|\n\n/u.exec(buffer);return match?.index===void 0?void 0:{index:match.index,length:match[0].length}}function parseMistralEvent(raw){let data=raw.split(/\r\n|\r|\n/u).filter(line=>line.startsWith("data:")).map(line=>line.slice(5).trimStart()).join(`
|
|
3
3
|
`).trim();if(!data)return;if(data==="[DONE]")return MISTRAL_STREAM_DONE;let parsed=JSON.parse(data);if(!isMistralRecord(parsed)||!Array.isArray(parsed.choices))throw new Error("Invalid Mistral streaming event");return{data:parsed}}function buildChatPayload(model,context,messages,options){let payload={model:model.id,stream:!0,messages:toChatMessages(messages,model.input.includes("image"))},currentTools=getCurrentTools(context.messages);return currentTools.length>0&&(payload.tools=toFunctionTools(currentTools)),options?.temperature!==void 0&&(payload.temperature=options.temperature),options?.maxTokens!==void 0&&(payload.maxTokens=options.maxTokens),options?.toolChoice&&(payload.toolChoice=mapToolChoice(options.toolChoice)),options?.promptMode&&(payload.promptMode=options.promptMode),options?.reasoningEffort&&(payload.reasoningEffort=options.reasoningEffort),shouldUsePromptCaching(options)&&(payload.promptCacheKey=options.sessionId),payload}function shouldUsePromptCaching(options){return options?.cacheRetention!=="none"&&!!options?.sessionId}function getMistralCachedPromptTokens(usage,promptTokens){let rawUsage=usage,rawCachedTokens=rawUsage.promptTokensDetails?.cachedTokens??rawUsage.prompt_tokens_details?.cached_tokens??rawUsage.promptTokenDetails?.cachedTokens??rawUsage.prompt_token_details?.cached_tokens??rawUsage.numCachedTokens??rawUsage.num_cached_tokens??0,cachedTokens=typeof rawCachedTokens=="number"&&Number.isFinite(rawCachedTokens)?rawCachedTokens:0;return Math.min(promptTokens,Math.max(0,cachedTokens))}async function consumeChatStream(model,output,stream2,mistralStream,onProviderStreamEvent){let currentBlock=null,blocks=output.content,blockIndex=()=>blocks.length-1,toolBlocksByKey=new Map,finishCurrentBlock=block=>{if(block){if(block.type==="text"){stream2.push({type:"text_end",contentIndex:blockIndex(),content:block.text,partial:output});return}block.type==="thinking"&&stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:block.thinking,partial:output})}};for await(let event of mistralStream){let chunk=event.data;if(await onProviderStreamEvent?.(chunk,model),output.responseId||=chunk.id,chunk.usage){let promptTokens=chunk.usage.prompt_tokens||0,cachedPromptTokens=getMistralCachedPromptTokens(chunk.usage,promptTokens);output.usage.input=Math.max(0,promptTokens-cachedPromptTokens),output.usage.output=chunk.usage.completion_tokens||0,output.usage.cacheRead=cachedPromptTokens,output.usage.cacheWrite=0,output.usage.totalTokens=chunk.usage.total_tokens||output.usage.input+output.usage.output+output.usage.cacheRead+output.usage.cacheWrite,calculateCost(model,output.usage)}let choice=chunk.choices[0];if(!choice)continue;if(choice.finish_reason){output.rawStopReason=choice.finish_reason;let stopReasonResult=mapChatStopReason(choice.finish_reason);output.stopReason=stopReasonResult.stopReason,stopReasonResult.errorMessage&&(output.errorMessage=stopReasonResult.errorMessage)}let delta=choice.delta;if(delta.content!==null&&delta.content!==void 0){let contentItems=typeof delta.content=="string"?[delta.content]:delta.content;for(let item of contentItems){if(typeof item=="string"){let textDelta=sanitizeSurrogates(item);if(!textDelta)continue;(!currentBlock||currentBlock.type!=="text")&&(finishCurrentBlock(currentBlock),currentBlock={type:"text",text:""},output.content.push(currentBlock),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output})),currentBlock.text+=textDelta,stream2.push({type:"text_delta",contentIndex:blockIndex(),delta:textDelta,partial:output});continue}if(item.type==="thinking"){let deltaText=(item.thinking??[]).map(part=>part.text??"").filter(text=>text.length>0).join(""),thinkingDelta=sanitizeSurrogates(deltaText);if(!thinkingDelta)continue;(!currentBlock||currentBlock.type!=="thinking")&&(finishCurrentBlock(currentBlock),currentBlock={type:"thinking",thinking:""},output.content.push(currentBlock),stream2.push({type:"thinking_start",contentIndex:blockIndex(),partial:output})),currentBlock.thinking+=thinkingDelta,stream2.push({type:"thinking_delta",contentIndex:blockIndex(),delta:thinkingDelta,partial:output});continue}if(item.type==="text"){let textDelta=sanitizeSurrogates(item.text??"");if(!textDelta)continue;(!currentBlock||currentBlock.type!=="text")&&(finishCurrentBlock(currentBlock),currentBlock={type:"text",text:""},output.content.push(currentBlock),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output})),currentBlock.text+=textDelta,stream2.push({type:"text_delta",contentIndex:blockIndex(),delta:textDelta,partial:output})}}}let toolCalls=delta.tool_calls||[];for(let toolCall of toolCalls){currentBlock&&(finishCurrentBlock(currentBlock),currentBlock=null);let callId=toolCall.id&&toolCall.id!=="null"?toolCall.id:deriveMistralToolCallId(`toolcall:${toolCall.index??0}`,0),key=toolCall.index??callId,existingIndex=toolBlocksByKey.get(key),block;if(existingIndex!==void 0){let existing=output.content[existingIndex];existing?.type==="toolCall"&&(block=existing)}block||(block={type:"toolCall",id:callId,name:toolCall.function.name,arguments:{},partialArgs:""},output.content.push(block),toolBlocksByKey.set(key,output.content.length-1),stream2.push({type:"toolcall_start",contentIndex:output.content.length-1,partial:output}));let argsDelta=typeof toolCall.function.arguments=="string"?toolCall.function.arguments:JSON.stringify(toolCall.function.arguments||{});block.partialArgs=(block.partialArgs||"")+argsDelta,block.arguments=parseStreamingJson(block.partialArgs),stream2.push({type:"toolcall_delta",contentIndex:toolBlocksByKey.get(key),delta:argsDelta,partial:output})}}finishCurrentBlock(currentBlock);for(let index of toolBlocksByKey.values()){let block=output.content[index];if(block.type!=="toolCall")continue;let toolBlock=block;toolBlock.arguments=parseStreamingJson(toolBlock.partialArgs),delete toolBlock.partialArgs,stream2.push({type:"toolcall_end",contentIndex:index,toolCall:toolBlock,partial:output})}}function toFunctionTools(tools){return tools.map(tool=>{let strict=resolveJsonSchemaStrictSampling(tool,!0);return{type:"function",function:{name:tool.name,description:tool.description,parameters:stripSymbolKeys(getJsonSchemaToolParameters(tool,strict)),strict:strict??!1}}})}function stripSymbolKeys(value){if(Array.isArray(value))return value.map(item=>stripSymbolKeys(item));if(value&&typeof value=="object"){let result={};for(let[key,entry]of Object.entries(value))result[key]=stripSymbolKeys(entry);return result}return value}function toChatMessages(messages,supportsImages){let result=[];for(let[index,msg]of messages.entries()){if(msg.role==="system"){let text=index===0?getSystemMessageText(msg):renderSystemMessageUpdate(msg);text.length>0&&result.push({role:"system",content:sanitizeSurrogates(text)});continue}if(msg.role==="user"){if(typeof msg.content=="string"){result.push({role:"user",content:sanitizeSurrogates(msg.content)});continue}let hadImages=msg.content.some(item=>item.type==="image"),content=msg.content.filter(item=>item.type==="text"||supportsImages).map(item=>item.type==="text"?{type:"text",text:sanitizeSurrogates(item.text)}:{type:"image_url",imageUrl:`data:${item.mimeType};base64,${item.data}`});if(content.length>0){result.push({role:"user",content});continue}hadImages&&!supportsImages&&result.push({role:"user",content:"(image omitted: model does not support images)"});continue}if(msg.role==="assistant"){let contentParts=[],toolCalls=[];for(let block of msg.content){if(block.type==="text"){block.text.trim().length>0&&contentParts.push({type:"text",text:sanitizeSurrogates(block.text)});continue}if(block.type==="thinking"){block.thinking.trim().length>0&&contentParts.push({type:"thinking",thinking:[{type:"text",text:sanitizeSurrogates(block.thinking)}]});continue}toolCalls.push({id:block.id,type:"function",function:{name:block.name,arguments:JSON.stringify(block.arguments||{})},index:0})}let assistantMessage={role:"assistant",prefix:!1};contentParts.length>0&&(assistantMessage.content=contentParts),toolCalls.length>0&&(assistantMessage.toolCalls=toolCalls),(contentParts.length>0||toolCalls.length>0)&&result.push(assistantMessage);continue}let toolContent=[],textResult=msg.content.filter(part=>part.type==="text").map(part=>part.type==="text"?sanitizeSurrogates(part.text):"").join(`
|
|
4
4
|
`),hasImages=msg.content.some(part=>part.type==="image"),toolText=buildToolResultText(textResult,hasImages,supportsImages,msg.isError);toolContent.push({type:"text",text:toolText});for(let part of msg.content)supportsImages&&part.type==="image"&&toolContent.push({type:"image_url",imageUrl:`data:${part.mimeType};base64,${part.data}`});result.push({role:"tool",toolCallId:msg.toolCallId,name:msg.toolName,content:toolContent})}return result}function buildToolResultText(text,hasImages,supportsImages,isError){let trimmed=text.trim(),errorPrefix=isError?"[tool error] ":"";return trimmed.length>0?`${errorPrefix}${trimmed}${hasImages&&!supportsImages?`
|
|
5
5
|
[tool image omitted: model does not support images]`:""}`:hasImages?supportsImages?isError?"[tool error] (see attached image)":"(see attached image)":isError?"[tool error] (image omitted: model does not support images)":"(image omitted: model does not support images)":isError?"[tool error] (no tool output)":"(no tool output)"}function mapToolChoice(choice){if(choice)return choice==="auto"||choice==="none"||choice==="any"||choice==="required"?choice:{type:"function",function:{name:choice.function.name}}}function mapChatStopReason(reason){if(reason===null)return{stopReason:"stop"};switch(reason){case"stop":return{stopReason:"stop"};case"length":case"model_length":return{stopReason:"length"};case"tool_calls":return{stopReason:"toolUse"};case"error":return{stopReason:"error",errorMessage:"Provider stopped with: error"};default:return{stopReason:"error",errorMessage:`Provider stopped with: ${reason}`}}}export{stream,streamSimple};
|