@code-yeongyu/senpi 2026.9.29-4 → 2026.9.29-5
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 +28 -7
- package/dist/bundle/chunks/{anthropic-messages-DZAH73IA.js → anthropic-messages-HEVKB3PL.js} +1 -1
- package/dist/bundle/chunks/{app-server-command-BUIGVCL4.js → app-server-command-32AFWZEH.js} +1 -1
- package/dist/bundle/chunks/{azure-openai-responses-ZJGVMXRJ.js → azure-openai-responses-QVPPCPVL.js} +1 -1
- package/dist/bundle/chunks/{chunk-U5LXY7UD.js → chunk-2IHY6ZLW.js} +1 -1
- package/dist/bundle/chunks/{chunk-ESPYV6XG.js → chunk-2N3BZ5DV.js} +1 -1
- package/dist/bundle/chunks/{chunk-XNR637JQ.js → chunk-2WAKOPNA.js} +1 -1
- package/dist/bundle/chunks/{chunk-SHIPI3FN.js → chunk-63QHOG5A.js} +44 -44
- package/dist/bundle/chunks/{chunk-H2U7247O.js → chunk-77AUUH3Z.js} +2 -2
- package/dist/bundle/chunks/{chunk-T4F7KOR2.js → chunk-7CQX3QFV.js} +1 -1
- package/dist/bundle/chunks/{chunk-WW3YFGEP.js → chunk-7MUTNWPO.js} +1 -1
- package/dist/bundle/chunks/{chunk-6NXC765G.js → chunk-AWEAVBCR.js} +1 -1
- package/dist/bundle/chunks/{chunk-3DISE3EE.js → chunk-BBNWT72C.js} +1 -1
- package/dist/bundle/chunks/{chunk-HKUHLCH7.js → chunk-U7BNOE23.js} +1 -1
- package/dist/bundle/chunks/{chunk-VAKMXHSM.js → chunk-VLW22GHJ.js} +1 -1
- package/dist/bundle/chunks/{chunk-DFRI62DO.js → chunk-W4IEEYWL.js} +1 -1
- package/dist/bundle/chunks/{chunk-Q6X7ES7N.js → chunk-XO7VCMY6.js} +1 -1
- package/dist/bundle/chunks/chunk-YLQTKWEC.js +6 -0
- package/dist/bundle/chunks/{chunk-NUS5JXND.js → chunk-Z2N5372Y.js} +1 -1
- package/dist/bundle/chunks/{chunk-JQNR6OYN.js → chunk-ZDNR3YVJ.js} +1 -1
- package/dist/bundle/chunks/{chunk-DAKIX3RD.js → chunk-ZPMJIPQC.js} +1 -1
- package/dist/bundle/chunks/{cli-main-XCRRH3OR.js → cli-main-ZPMYM3A3.js} +1 -1
- package/dist/bundle/chunks/engine-RCHMSSBT.js +2 -0
- package/dist/bundle/chunks/github-copilot.js +1 -1
- package/dist/bundle/chunks/{google-generative-ai-RYFW7GSR.js → google-generative-ai-E3I6MS7E.js} +1 -1
- package/dist/bundle/chunks/{google-vertex-J64D4U2O.js → google-vertex-KFFI24FU.js} +1 -1
- package/dist/bundle/chunks/{help-fast-path-JJVINW3Y.js → help-fast-path-ZUNFOE53.js} +1 -1
- package/dist/bundle/chunks/{host-command-IZJU2H7Z.js → host-command-V2LDNNXB.js} +1 -1
- package/dist/bundle/chunks/{interactive-mode-KXRPZ2U6.js → interactive-mode-J6KGDRR7.js} +1 -1
- package/dist/bundle/chunks/{mistral-conversations-C7ZTJYKE.js → mistral-conversations-EZ4XNJXU.js} +1 -1
- package/dist/bundle/chunks/{multi-session-host-3XTEXGP4.js → multi-session-host-IBVJ3WN7.js} +1 -1
- package/dist/bundle/chunks/{openai-codex-responses-N5SCEWCY.js → openai-codex-responses-TMUCQW5E.js} +1 -1
- package/dist/bundle/chunks/{openai-completions-T4B2KZ4B.js → openai-completions-SA2UJW7Q.js} +1 -1
- package/dist/bundle/chunks/{openai-responses-N4OK2RIV.js → openai-responses-EHSD4L2M.js} +1 -1
- package/dist/bundle/chunks/{package-manager-cli-ZHWO6FT5.js → package-manager-cli-JJ5R7UWV.js} +1 -1
- package/dist/bundle/chunks/{rotation-stream-5GE3KAHL.js → rotation-stream-EX7PWQ4S.js} +1 -1
- package/dist/bundle/chunks/{rpc-mode-DEVPDAT4.js → rpc-mode-ITND2BVC.js} +1 -1
- package/dist/bundle/chunks/{session-control-endpoint-72A2NRVH.js → session-control-endpoint-UJJGG4WI.js} +1 -1
- package/dist/bundle/chunks/{session-picker-XYMNQ6AZ.js → session-picker-K5FIKV6C.js} +1 -1
- package/dist/bundle/chunks/session-worker.js +42 -42
- package/dist/bundle/cli.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/bundle/runtime-manifest.json +1 -1
- package/dist/core/auth-providers.d.ts +9 -0
- package/dist/core/auth-providers.js +17 -0
- package/dist/core/dynamic-prompt/build.js +1 -1
- package/dist/core/dynamic-prompt/intent-gate.js +1 -1
- package/dist/core/dynamic-prompt/verification.d.ts +9 -1
- package/dist/core/dynamic-prompt/verification.js +11 -2
- package/dist/core/extensions/builtin/prompt-preset/claude-fable-5-1.js +3 -3
- package/dist/core/extensions/builtin/prompt-preset/claude-fable-5.js +3 -3
- package/dist/core/extensions/builtin/prompt-preset/claude-opus-5-5.js +3 -3
- package/dist/core/extensions/builtin/prompt-preset/claude-opus-5.js +3 -3
- package/dist/core/extensions/builtin/prompt-preset/claude-sonnet-5-5.js +3 -3
- package/dist/core/extensions/builtin/prompt-preset/gpt-5.5.js +3 -3
- package/dist/core/extensions/builtin/prompt-preset/gpt-5.6.js +4 -4
- package/dist/core/extensions/builtin/prompt-preset/gpt-6-astra.d.ts +6 -2
- package/dist/core/extensions/builtin/prompt-preset/gpt-6-astra.js +24 -7
- package/dist/core/extensions/builtin/prompt-preset/gpt-surface.d.ts +4 -1
- package/dist/core/extensions/builtin/prompt-preset/gpt-surface.js +4 -1
- package/dist/core/extensions/builtin/prompt-preset/grok-4.5.js +4 -4
- package/dist/core/extensions/builtin/prompt-preset/grok-4.6.js +3 -3
- package/dist/core/extensions/builtin/prompt-preset/grok-4.7.js +3 -3
- package/dist/core/extensions/builtin/prompt-preset/kimi-k3.js +3 -3
- package/dist/core/extensions/builtin/prompt-preset/presets.js +12 -9
- package/dist/core/high-reasoning-warning.js +4 -3
- package/dist/core/model-resolver.js +2 -2
- package/dist/modes/rpc/connection-handler.js +7 -4
- package/package.json +6 -6
- package/dist/bundle/chunks/chunk-TODLHR4S.js +0 -6
- package/dist/bundle/chunks/engine-35QNGFQZ.js +0 -2
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
3
|
-
import{enableStartupCompileCache}from"./chunk-F73COJ7R.js";import{main}from"./chunk-
|
|
3
|
+
import{enableStartupCompileCache}from"./chunk-F73COJ7R.js";import{main}from"./chunk-63QHOG5A.js";import"./chunk-K2SHQNAA.js";import"./chunk-ZPMJIPQC.js";import"./chunk-2POUJCWM.js";import"./chunk-VLTMFAWQ.js";import"./chunk-NZRVAZL2.js";import"./chunk-U5KVIAHJ.js";import"./chunk-YLQTKWEC.js";import{configureHttpDispatcher}from"./chunk-ZDNR3YVJ.js";import"./chunk-HEKLJWA4.js";import"./chunk-XHEMQA2T.js";import"./chunk-JABBHOD5.js";import"./chunk-YU2P3CAR.js";import"./chunk-BMX2U22F.js";import"./chunk-2N3BZ5DV.js";import"./chunk-CNYWF72S.js";import"./chunk-AWEAVBCR.js";import"./chunk-MJQWYN2W.js";import"./chunk-UMLU3I2G.js";import"./chunk-CIRZTP7W.js";import"./chunk-AGVPQLIU.js";import"./chunk-XBGO2JZD.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-U7BNOE23.js";import"./chunk-2WAKOPNA.js";import"./chunk-SH6VUPE4.js";import"./chunk-7RVWDN5Z.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-BBNWT72C.js";import"./chunk-OUG6SDT7.js";import"./chunk-7CQX3QFV.js";import"./chunk-26UBFF6N.js";import"./chunk-77AUUH3Z.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-VLW22GHJ.js";import{installEarlyInspectorVmImportRecovery}from"./chunk-4VWWEMCJ.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import{APP_NAME,scrubBrandFromEnvironment}from"./chunk-WCAKUCN3.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-JRGNL6WM.js";import"./chunk-X4Q5YSTE.js";import"./chunk-CWLCGRUS.js";import"./chunk-BJICJY47.js";import"./chunk-LHYG7TK7.js";import"./chunk-KRNXUTZJ.js";import"./chunk-YOPVJDSU.js";import"./chunk-45SZOLCU.js";import"./chunk-WHPDEDCC.js";import"./chunk-BBK6SSYT.js";import"./chunk-BPX6QWPD.js";import"./chunk-Z2N5372Y.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-IKOFCODM.js";enableStartupCompileCache();installEarlyInspectorVmImportRecovery();process.title=APP_NAME;scrubBrandFromEnvironment();process.env.PI_CODING_AGENT="true";process.emitWarning=(()=>{});configureHttpDispatcher();await main(process.argv.slice(2));
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
+
import{composeFoldResult}from"./chunk-BMX2U22F.js";import"./chunk-IKOFCODM.js";import{existsSync}from"node:fs";import{createRequire}from"node:module";import{join}from"node:path";import{fileURLToPath}from"node:url";var GRAMMAR_FILES=Object.freeze({ts:"typescript.wasm",tsx:"tsx.wasm",js:"javascript.wasm"}),UPSTREAM_FILES=Object.freeze({ts:"tree-sitter-typescript.wasm",tsx:"tree-sitter-tsx.wasm",js:"tree-sitter-javascript.wasm"}),TREE_SITTER_RUNTIME_FILE="web-tree-sitter.wasm",packagedAssetDirectory=fileURLToPath(new URL("../../../../../assets/tree-sitter/",import.meta.url)),embeddedGrammars={js:()=>import("./javascript-ER3DQ367.js")},embeddedRuntime=()=>import("./web-tree-sitter-6VXGLXZD.js");async function embeddedPath(load){if(load)try{let module=await load();return existsSync(module.default)?module.default:void 0}catch{return}}function installedPath(specifier){try{let path=createRequire(import.meta.url).resolve(specifier);return existsSync(path)?path:void 0}catch{return}}async function resolveGrammarPath(language){let packaged=join(packagedAssetDirectory,GRAMMAR_FILES[language]);return existsSync(packaged)?packaged:await embeddedPath(embeddedGrammars[language])??installedPath(`@vscode/tree-sitter-wasm/wasm/${UPSTREAM_FILES[language]}`)}async function resolveRuntimePath(){let packaged=join(packagedAssetDirectory,TREE_SITTER_RUNTIME_FILE);return existsSync(packaged)?packaged:await embeddedPath(embeddedRuntime)??installedPath("web-tree-sitter/web-tree-sitter.wasm")}var bodyKinds=new Set(["statement_block","object","array","switch_body"]),functionKinds=new Set(["function_declaration","function_expression","function","generator_function","generator_function_declaration","arrow_function","method_definition","function_signature","method_signature","abstract_method_signature"]),classKinds=new Set(["class","class_declaration","abstract_class_declaration"]),opaqueKinds=new Set(["type_annotation","type_arguments","type_parameters","type_alias_declaration","interface_declaration","type_predicate_annotation","omitting_type_annotation","opting_type_annotation","asserts_annotation","type_identifier","predefined_type","nested_type_identifier","formal_parameters","class_heritage","extends_clause","extends_type_clause","implements_clause","decorator","import_statement","object_pattern","array_pattern","computed_property_name","ambient_declaration"]);function isOpaque(node){return opaqueKinds.has(node.type)||node.type.endsWith("_type")||node.type.endsWith("_type_annotation")}function childNodes(node){let children=[];for(let child of node.children)child&&children.push(child);return children}function openBrace(node){for(let child of childNodes(node))if(child.type==="{"||child.type==="[")return child}function closeBrace(node){let children=childNodes(node);for(let index=children.length-1;index>=0;index--){let child=children[index];if(child.type==="}"||child.type==="]")return child}}function exportsOnlyBindings(node){for(let child of childNodes(node))if(child.type==="export_clause"||child.type==="*"||child.type==="namespace_export")return!0;return!1}function typeOperator(node){if(!(node.type!=="as_expression"&&node.type!=="satisfies_expression"))return childNodes(node).find(child=>child.type==="as"||child.type==="satisfies")}function assignmentTarget(node){if(node.type!=="assignment_expression"&&node.type!=="for_in_statement")return;let left=node.childForFieldName("left");if(!left)return;let target=left;for(;target.type==="parenthesized_expression";){let inner=childNodes(target).find(child=>child.type!=="("&&child.type!==")");if(!inner)break;target=inner}return target.type==="object"||target.type==="array"?left:void 0}function foldRangesFromSyntax(root,settings){if(root.hasError||root.isMissing)return{status:"parse_failure",reason:"tree_sitter_parse_error"};let candidates=[],guarded=[],protect=(startLine,endLine)=>{endLine>=startLine&&guarded.push({startLine,endLine})},line=row=>row+1,visit=node=>{if(isOpaque(node)||node.type==="export_statement"&&exportsOnlyBindings(node)){protect(line(node.startPosition.row),line(node.endPosition.row));return}if(node.type==="comment"){let lines=node.endPosition.row-node.startPosition.row+1;node.text.startsWith("/**")||node.text.startsWith("/*!")?protect(line(node.startPosition.row),line(node.endPosition.row)):lines>=settings.minCommentLines&&candidates.push({startLine:line(node.startPosition.row)+1,endLine:line(node.endPosition.row)-1});return}let operator=typeOperator(node);if(operator){protect(line(operator.startPosition.row),line(node.endPosition.row));for(let child of childNodes(node)){if(child.id===operator.id)break;visit(child)}return}let target=assignmentTarget(node);if(target){protect(line(target.startPosition.row),line(target.endPosition.row));for(let child of childNodes(node))child.id!==target.id&&visit(child);return}if(functionKinds.has(node.type)){let body=node.childForFieldName("body");if(!body){protect(line(node.startPosition.row),line(node.endPosition.row));return}protect(line(node.startPosition.row),line(body.startPosition.row)),visit(body);return}if(classKinds.has(node.type)){let body=node.childForFieldName("body"),open=body?openBrace(body):void 0;if(!body||!open){protect(line(node.startPosition.row),line(node.endPosition.row));return}protect(line(node.startPosition.row),line(open.startPosition.row));for(let member of childNodes(body))visit(member);return}if(bodyKinds.has(node.type)){let open=openBrace(node),close=closeBrace(node);if(open&&close){let startLine=line(open.startPosition.row)+1,endLine=line(close.startPosition.row)-1;endLine-startLine+1>=settings.minBodyLines&&candidates.push({startLine,endLine})}}for(let child of childNodes(node))visit(child)};return visit(root),{status:"parsed",ranges:candidates.filter(range=>!guarded.some(header=>range.startLine<=header.endLine&&range.endLine>=header.startLine)&&range.endLine>=range.startLine)}}var TREE_SITTER_PARSE_BUDGET_MS=250,TREE_SITTER_FOLDER_ID="tree-sitter-wasm",TREE_SITTER_FOLDER_VERSION="1",runtime,grammars=new Map;async function loadRuntime(resolveRuntime){try{let module=await import("./web-tree-sitter-BA4O6VLR.js"),wasm=await resolveRuntime();return await module.Parser.init(wasm?{locateFile:()=>wasm}:void 0),module}catch{return}}async function loadParser(language,options){let resolveGrammar=options.resolveGrammar??resolveGrammarPath,resolveRuntime=options.resolveRuntime??resolveRuntimePath,grammar=await resolveGrammar(language);if(!grammar)return;if(options.cache===!1){let module2=await loadRuntime(resolveRuntime);return module2&&instantiate(module2,grammar,language)}runtime??=loadRuntime(resolveRuntime);let module=await runtime;return module&&instantiate(module,grammar,language)}async function instantiate(module,grammar,language){try{let loaded=await module.Language.load(grammar),parser=new module.Parser;return parser.setLanguage(loaded),{parser,language}}catch{return}}function foldWith(loaded,budgetMs,input,fallback){let deadline=performance.now()+budgetMs,tree=null;try{if(tree=loaded.parser.parse(input.text,null,{progressCallback:()=>performance.now()>deadline}),!tree)return fallback.fold(input);let scan=foldRangesFromSyntax(tree.rootNode,input.settings);return scan.status==="parse_failure"?fallback.fold(input):composeFoldResult(input.text,scan)}catch{return fallback.fold(input)}finally{tree?.delete(),loaded.parser.reset()}}async function loadTreeSitterFolder(language,options){let load=()=>loadParser(language,options),loaded=await(options.cache===!1?load():grammars.get(language)??(()=>{let pending=load();return grammars.set(language,pending),pending})());if(!loaded)return;let budgetMs=options.parseBudgetMs??TREE_SITTER_PARSE_BUDGET_MS;return Object.freeze({id:TREE_SITTER_FOLDER_ID,version:TREE_SITTER_FOLDER_VERSION,fold:input=>foldWith(loaded,budgetMs,input,options.fallback)})}function resetTreeSitterGrammars(){runtime=void 0,grammars.clear()}export{TREE_SITTER_FOLDER_ID,TREE_SITTER_FOLDER_VERSION,TREE_SITTER_PARSE_BUDGET_MS,loadTreeSitterFolder,resetTreeSitterGrammars};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
var GITHUB_COPILOT_INDIVIDUAL_BASE_URL="https://api.individual.githubcopilot.com";function githubCopilotTokenField(token,key){for(let part of token.split(";")){let separator=part.indexOf("=");if(separator>0&&part.slice(0,separator)===key)return part.slice(separator+1)||void 0}}function githubCopilotBaseUrlFromToken(token){let proxyHost=githubCopilotTokenField(token,"proxy-ep");return proxyHost?`https://${proxyHost.replace(/^proxy\./,"api.")}`:void 0}function parseGitHubCopilotApiEndpoint(value){if(typeof value=="string")try{let url=new URL(value.trim());return url.protocol!=="https:"||!url.hostname||url.username||url.password?void 0:`${url.origin}${url.pathname.replace(/\/+$/,"")}`}catch{return}}function endpointForToken(endpoint,token){if(!token||typeof endpoint!="object"||endpoint===null)return;let tid=Reflect.get(endpoint,"tid"),url=parseGitHubCopilotApiEndpoint(Reflect.get(endpoint,"url"));return typeof tid=="string"&&tid===githubCopilotTokenField(token,"tid")?url:void 0}function resolveGitHubCopilotBaseUrl(input){return endpointForToken(input.apiEndpoint,input.token)??(input.token?githubCopilotBaseUrlFromToken(input.token):void 0)??(input.enterpriseDomain?`https://copilot-api.${input.enterpriseDomain}`:void 0)??GITHUB_COPILOT_INDIVIDUAL_BASE_URL}var GITHUB_COPILOT_REJECTED_TOKEN_STATUSES=[401,403];function sleep(ms,signal){return new Promise((resolve,reject)=>{signal.throwIfAborted();let onAbort=()=>{clearTimeout(timeout),reject(signal.reason)},timeout=setTimeout(()=>{signal.removeEventListener("abort",onAbort),resolve()},ms);signal.addEventListener("abort",onAbort,{once:!0})})}var CANCEL_MESSAGE="Login cancelled",TIMEOUT_MESSAGE="Device flow timed out",SLOW_DOWN_TIMEOUT_MESSAGE="Device flow timed out after one or more slow_down responses. This is often caused by clock drift in WSL or VM environments. Please sync or restart the VM clock and try again.";function abortableSleep(ms,signal,cancelMessage){return new Promise((resolve,reject)=>{if(signal.aborted){reject(new Error(cancelMessage));return}let onAbort=()=>{clearTimeout(timeout),reject(new Error(cancelMessage))},timeout=setTimeout(()=>{signal.removeEventListener("abort",onAbort),resolve()},ms);signal.addEventListener("abort",onAbort,{once:!0})})}async function pollOAuthDeviceCodeFlow(options){let deadline=typeof options.expiresInSeconds=="number"?Date.now()+options.expiresInSeconds*1e3:Number.POSITIVE_INFINITY,intervalMs=Math.max(1e3,Math.floor((options.intervalSeconds??5)*1e3)),slowDownResponses=0;if(options.waitBeforeFirstPoll){let remainingMs=deadline-Date.now();remainingMs>0&&await abortableSleep(Math.min(intervalMs,remainingMs),options.signal,CANCEL_MESSAGE)}for(;Date.now()<deadline;){if(options.signal.aborted)throw new Error(CANCEL_MESSAGE);let result=await options.poll();if(result.status==="complete")return result.value;if(result.status==="failed")throw new Error(result.message);result.status==="slow_down"&&(slowDownResponses+=1,intervalMs=typeof result.intervalSeconds=="number"&&Number.isFinite(result.intervalSeconds)&&result.intervalSeconds>0?Math.max(1e3,Math.floor(result.intervalSeconds*1e3)):Math.max(1e3,intervalMs+5e3));let remainingMs=deadline-Date.now();if(remainingMs<=0)break;await abortableSleep(Math.min(intervalMs,remainingMs),options.signal,CANCEL_MESSAGE)}throw new Error(slowDownResponses>0?SLOW_DOWN_TIMEOUT_MESSAGE:TIMEOUT_MESSAGE)}var github_copilot_default={"anthropic-messages":{"claude-fable-5":{id:"claude-fable-5",name:"Claude Fable 5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:10,output:50,cacheRead:1,cacheWrite:12.5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{xhigh:"xhigh",max:"max"},compat:{supportsDisabledThinking:!1,forceAdaptiveThinking:!0}},"claude-fable-5.1":{id:"claude-fable-5.1",name:"Claude Fable 5.1",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:10,output:50,cacheRead:.25,cacheWrite:12.5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{xhigh:"xhigh",max:"max"},compat:{supportsDisabledThinking:!1,forceAdaptiveThinking:!0}},"claude-haiku-4.5":{id:"claude-haiku-4.5",name:"Claude Haiku 4.5 (latest)",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:1,output:5,cacheRead:.1,cacheWrite:1.25},contextWindow:2e5,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsEagerToolInputStreaming:!1}},"claude-opus-4.7":{id:"claude-opus-4.7",name:"Claude Opus 4.7",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:32e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{xhigh:"xhigh",max:"max",minimal:"low"},compat:{forceAdaptiveThinking:!0,supportsTemperature:!1}},"claude-opus-4.8":{id:"claude-opus-4.8",name:"Claude Opus 4.8",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{xhigh:"xhigh",max:"max",minimal:"low"},compat:{forceAdaptiveThinking:!0,supportsTemperature:!1}},"claude-opus-5":{id:"claude-opus-5",name:"Claude Opus 5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{xhigh:"xhigh",max:"max",minimal:"low"},compat:{forceAdaptiveThinking:!0,supportsTemperature:!1}},"claude-opus-5.5":{id:"claude-opus-5.5",name:"Claude Opus 5.5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:4,output:20,cacheRead:.2,cacheWrite:5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{xhigh:"xhigh",max:"max"},compat:{supportsDisabledThinking:!1,forceAdaptiveThinking:!0,supportsTemperature:!1}},"claude-sonnet-4.6":{id:"claude-sonnet-4.6",name:"Claude Sonnet 4.6",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:1e6,maxTokens:32e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{max:"max",minimal:"low"},compat:{forceAdaptiveThinking:!0}},"claude-sonnet-5":{id:"claude-sonnet-5",name:"Claude Sonnet 5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:10,cacheRead:.2,cacheWrite:2.5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{xhigh:"xhigh",max:"max"},compat:{forceAdaptiveThinking:!0}},"claude-sonnet-5.5":{id:"claude-sonnet-5.5",name:"Claude Sonnet 5.5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:10,cacheRead:.2,cacheWrite:2.5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{xhigh:"xhigh",max:"max"},compat:{supportsDisabledThinking:!1,forceAdaptiveThinking:!0}}},"openai-completions":{"gemini-3.5-flash":{id:"gemini-3.5-flash",name:"Gemini 3.5 Flash",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:1.5,output:9,cacheRead:.15,cacheWrite:0},contextWindow:2e5,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1}},"gemini-3.6-flash":{id:"gemini-3.6-flash",name:"Gemini 3.6 Flash",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.75,output:3.75,cacheRead:.075,cacheWrite:0},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1}},"gemini-3.7-flash":{id:"gemini-3.7-flash",name:"Gemini 3.7 Flash",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.75,output:3.75,cacheRead:.075,cacheWrite:0},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1}},"gemini-3.8-flash":{id:"gemini-3.8-flash",name:"Gemini 3.8 Flash",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.75,output:3.75,cacheRead:.075,cacheWrite:0},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1}},"kimi-k2.7-code":{id:"kimi-k2.7-code",name:"Kimi K2.7 Code",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.95,output:4,cacheRead:.19,cacheWrite:0},contextWindow:256e3,maxTokens:32e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1}},"kimi-k3":{id:"kimi-k3",name:"Kimi K3",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:0},contextWindow:1048576,maxTokens:131072,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1}}},"openai-responses":{"gpt-5-mini":{id:"gpt-5-mini",name:"GPT-5 Mini",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.25,output:2,cacheRead:.025,cacheWrite:0},contextWindow:264e3,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:null,max:null},compat:{supportsOpenAIGrammarTools:!0}},"gpt-5.3-codex":{id:"gpt-5.3-codex",name:"GPT-5.3 Codex",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0}},"gpt-5.4":{id:"gpt-5.4",name:"GPT-5.4",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2.5,output:15,cacheRead:.25,cacheWrite:0,tiers:[{inputTokensAbove:272e3,input:5,output:22.5,cacheRead:.5,cacheWrite:0}]},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0}},"gpt-5.4-mini":{id:"gpt-5.4-mini",name:"GPT-5.4 mini",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.75,output:4.5,cacheRead:.075,cacheWrite:0},contextWindow:272e3,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0}},"gpt-5.4-nano":{id:"gpt-5.4-nano",name:"GPT-5.4 nano",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.2,output:1.25,cacheRead:.02,cacheWrite:0},contextWindow:272e3,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",xhigh:"xhigh"},compat:{supportsOpenAIGrammarTools:!0}},"gpt-5.5":{id:"gpt-5.5",name:"GPT-5.5",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:5,output:30,cacheRead:.5,cacheWrite:0,tiers:[{inputTokensAbove:272e3,input:10,output:45,cacheRead:1,cacheWrite:0}]},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0}},"gpt-5.6-luna":{id:"gpt-5.6-luna",name:"GPT-5.6 Luna",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.2,output:1.2,cacheRead:.02,cacheWrite:.25,tiers:[{inputTokensAbove:2e5,input:.4,output:1.8,cacheRead:.04,cacheWrite:.5}]},contextWindow:922e3,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0}},"gpt-5.6-sol":{id:"gpt-5.6-sol",name:"GPT-5.6 Sol",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:4,output:20,cacheRead:.4,cacheWrite:5,tiers:[{inputTokensAbove:272e3,input:8,output:30,cacheRead:.8,cacheWrite:10}]},contextWindow:922e3,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0}},"gpt-5.6-terra":{id:"gpt-5.6-terra",name:"GPT-5.6 Terra",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:12,cacheRead:.2,cacheWrite:2.5,tiers:[{inputTokensAbove:272e3,input:4,output:18,cacheRead:.4,cacheWrite:5}]},contextWindow:922e3,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0}},"gpt-6-astra":{id:"gpt-6-astra",name:"GPT-6 Astra",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:10,output:50,cacheRead:1,cacheWrite:12.5,tiers:[{inputTokensAbove:272e3,input:20,output:75,cacheRead:2,cacheWrite:25}]},contextWindow:6e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0}},"gpt-6-luna":{id:"gpt-6-luna",name:"GPT-6 Luna",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.1,output:.5,cacheRead:.01,cacheWrite:.125,tiers:[{inputTokensAbove:272e3,input:.2,output:.75,cacheRead:.02,cacheWrite:.25}]},contextWindow:922e3,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:"none",minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0}},"gpt-6-sol":{id:"gpt-6-sol",name:"GPT-6 Sol",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:10,cacheRead:.2,cacheWrite:2.5,tiers:[{inputTokensAbove:272e3,input:4,output:15,cacheRead:.4,cacheWrite:5}]},contextWindow:4e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:"none",minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0}},"grok-4.5":{id:"grok-4.5",name:"Grok 4.5",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:6,cacheRead:.5,cacheWrite:0,tiers:[{inputTokensAbove:2e5,input:4,output:12,cacheRead:1,cacheWrite:0}]},contextWindow:5e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:null,max:null}},"grok-4.6":{id:"grok-4.6",name:"Grok 4.6",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:6,cacheRead:.5,cacheWrite:0,tiers:[{inputTokensAbove:2e5,input:4,output:12,cacheRead:1,cacheWrite:0}]},contextWindow:5e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null}},"grok-4.7":{id:"grok-4.7",name:"Grok 4.7",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:6,cacheRead:.5,cacheWrite:0,tiers:[{inputTokensAbove:2e5,input:4,output:12,cacheRead:1,cacheWrite:0}]},contextWindow:5e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null}},"mai-code-1-flash-picker":{id:"mai-code-1-flash-picker",name:"MAI-Code-1-Flash",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text"],cost:{input:.75,output:4.5,cacheRead:.075,cacheWrite:0},contextWindow:256e3,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:null,max:null}},"mai-code-1.1-flash":{id:"mai-code-1.1-flash",name:"MAI-Code-1.1-Flash",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.2,output:1.2,cacheRead:.02,cacheWrite:0},contextWindow:256e3,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:null,max:null}}}};function flattenModelCatalog(_provider,groups){return Object.assign({},...Object.values(groups))}var GITHUB_COPILOT_MODELS=flattenModelCatalog("github-copilot",github_copilot_default);function asRecord(value){return value&&typeof value=="object"?value:void 0}function positiveInteger(value){return typeof value=="number"&&Number.isInteger(value)&&value>0?value:void 0}function parseGitHubCopilotModelLimit(id,rawLimits){let limits=asRecord(rawLimits);if(!limits)return;let maxContextWindowTokens=positiveInteger(limits.max_context_window_tokens),maxPromptTokens=positiveInteger(limits.max_prompt_tokens),maxOutputTokens=positiveInteger(limits.max_output_tokens);if(!(maxContextWindowTokens===void 0&&maxPromptTokens===void 0&&maxOutputTokens===void 0))return{id,...maxContextWindowTokens!==void 0?{maxContextWindowTokens}:{},...maxPromptTokens!==void 0?{maxPromptTokens}:{},...maxOutputTokens!==void 0?{maxOutputTokens}:{}}}function asRecord2(value){return value&&typeof value=="object"?value:void 0}function parseGitHubCopilotModelCatalog(raw,allowPolicyFallback){let data=asRecord2(raw)?.data;if(!Array.isArray(data))throw new Error("Invalid Copilot models response");let accountModels=data.flatMap(rawItem=>{let item=asRecord2(rawItem),id=item?.id;if(!item||typeof id!="string")return[];let capabilities=asRecord2(item.capabilities);return asRecord2(capabilities?.supports)?.tool_calls===!1?[]:[{id,pickerEnabled:item.model_picker_enabled===!0,policyState:asRecord2(item.policy)?.state,limits:parseGitHubCopilotModelLimit(id,capabilities?.limits)}]}),pickerModelIds=accountModels.filter(model=>model.pickerEnabled&&model.policyState!=="disabled").map(model=>model.id),usePolicyFallback=allowPolicyFallback&&pickerModelIds.length===0,availableModelIds=pickerModelIds.length>0||!allowPolicyFallback?pickerModelIds:accountModels.filter(model=>model.policyState==="enabled").map(model=>model.id),policyModelIds=accountModels.filter(model=>model.policyState==="unconfigured"&&Object.hasOwn(GITHUB_COPILOT_MODELS,model.id)&&(model.pickerEnabled||usePolicyFallback)).map(model=>model.id),modelLimits=accountModels.map(model=>model.limits).filter(limits=>limits!==void 0);return{availableModelIds,policyModelIds,modelLimits}}var decode=s=>atob(s),CLIENT_ID=decode("SXYxLmI1MDdhMDhjODdlY2ZlOTg="),COPILOT_HEADERS={"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},COPILOT_API_VERSION="2026-06-01";function normalizeDomain(input){let trimmed=input.trim();if(!trimmed)return null;try{return(trimmed.includes("://")?new URL(trimmed):new URL(`https://${trimmed}`)).hostname}catch{return null}}function getUrls(domain){return{deviceCodeUrl:`https://${domain}/login/device/code`,accessTokenUrl:`https://${domain}/login/oauth/access_token`,copilotTokenUrl:`https://api.${domain}/copilot_internal/v2/token`}}function getGitHubCopilotBaseUrl(token,enterpriseDomain,apiEndpoint){return resolveGitHubCopilotBaseUrl({token,enterpriseDomain,apiEndpoint})}async function fetchWithRateLimitRetry(url,init,signal,retryPolicy){let retryBudgetSignal=retryPolicy.maxRetries>0&&retryPolicy.maxElapsedMs>0?AbortSignal.timeout(retryPolicy.maxElapsedMs):void 0,requestSignal=retryBudgetSignal?AbortSignal.any([signal,retryBudgetSignal]):signal,retryDeadline=retryBudgetSignal?Date.now()+retryPolicy.maxElapsedMs:void 0;for(let retry=0;;retry++){let response=await fetch(url,{...init,signal:AbortSignal.any([requestSignal,AbortSignal.timeout(5e3)])});if(response.status!==429||retry===retryPolicy.maxRetries)return response;let retryAfter=response.headers.get("retry-after"),delayMs=500*2**retry;if(retryAfter){let seconds=Number.parseFloat(retryAfter);if(delayMs=Number.isNaN(seconds)?Date.parse(retryAfter)-Date.now():seconds*1e3,!Number.isFinite(delayMs))return response}if(delayMs=Math.max(0,delayMs),retryDeadline!==void 0&&delayMs>=retryDeadline-Date.now())return response;await response.body?.cancel(),await sleep(delayMs,requestSignal)}}async function fetchGitHubCopilotModels(copilotToken,enterpriseDomain,signal,retryPolicy,apiEndpoint){let baseUrl=getGitHubCopilotBaseUrl(copilotToken,enterpriseDomain,apiEndpoint),allowPolicyFallback=baseUrl===GITHUB_COPILOT_INDIVIDUAL_BASE_URL,response=await fetchWithRateLimitRetry(`${baseUrl}/models`,{headers:{Accept:"application/json",Authorization:`Bearer ${copilotToken}`,...COPILOT_HEADERS,"X-GitHub-Api-Version":COPILOT_API_VERSION}},signal,retryPolicy);if(!response.ok)throw new Error(`${response.status} ${response.statusText}: ${await response.text()}`);return parseGitHubCopilotModelCatalog(await response.json(),allowPolicyFallback)}async function fetchJson(url,init){let response=await fetch(url,init);if(!response.ok){let text=await response.text();throw new Error(`${response.status} ${response.statusText}: ${text}`)}return response.json()}async function startDeviceFlow(domain,signal){let urls=getUrls(domain),data=await fetchJson(urls.deviceCodeUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","User-Agent":"GitHubCopilotChat/0.35.0"},body:new URLSearchParams({client_id:CLIENT_ID,scope:"read:user"}),signal});if(!data||typeof data!="object")throw new Error("Invalid device code response");let deviceCode=data.device_code,userCode=data.user_code,verificationUri=data.verification_uri,interval=data.interval,expiresIn=data.expires_in;if(typeof deviceCode!="string"||typeof userCode!="string"||typeof verificationUri!="string"||interval!==void 0&&typeof interval!="number"||typeof expiresIn!="number")throw new Error("Invalid device code response fields");let parsedUri;try{parsedUri=new URL(verificationUri)}catch{throw new Error("Untrusted verification_uri in device code response")}if(parsedUri.protocol!=="https:"&&parsedUri.protocol!=="http:")throw new Error("Untrusted verification_uri in device code response");return{device_code:deviceCode,user_code:userCode,verification_uri:parsedUri.href,interval,expires_in:expiresIn}}async function pollForGitHubAccessToken(domain,device,signal){let urls=getUrls(domain);return pollOAuthDeviceCodeFlow({intervalSeconds:device.interval,expiresInSeconds:device.expires_in,waitBeforeFirstPoll:!0,signal,poll:async()=>{let raw=await fetchJson(urls.accessTokenUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","User-Agent":"GitHubCopilotChat/0.35.0"},body:new URLSearchParams({client_id:CLIENT_ID,device_code:device.device_code,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}),signal});if(raw&&typeof raw=="object"&&typeof raw.access_token=="string")return{status:"complete",value:raw.access_token};if(raw&&typeof raw=="object"&&typeof raw.error=="string"){let{error,error_description:description,interval}=raw;if(error==="authorization_pending")return{status:"pending"};if(error==="slow_down")return{status:"slow_down",intervalSeconds:typeof interval=="number"?interval:void 0};let descriptionSuffix=description?`: ${description}`:"";return{status:"failed",message:`Device flow failed: ${error}${descriptionSuffix}`}}return{status:"failed",message:"Invalid device token response"}}})}async function refreshGitHubCopilotAccessToken(refreshToken,enterpriseDomain,signal){let urls=getUrls(enterpriseDomain||"github.com"),raw=await fetchJson(urls.copilotTokenUrl,{headers:{Accept:"application/json",Authorization:`Bearer ${refreshToken}`,...COPILOT_HEADERS},signal});if(!raw||typeof raw!="object")throw new Error("Invalid Copilot token response");let token=raw.token,expiresAt=raw.expires_at;if(typeof token!="string"||typeof expiresAt!="number")throw new Error("Invalid Copilot token response fields");let endpoints=raw.endpoints,apiUrl=parseGitHubCopilotApiEndpoint(typeof endpoints=="object"&&endpoints!==null?Reflect.get(endpoints,"api"):void 0),tid=githubCopilotTokenField(token,"tid");return{type:"oauth",refresh:refreshToken,access:token,expires:expiresAt*1e3-300*1e3,enterpriseUrl:enterpriseDomain,...apiUrl!==void 0&&tid!==void 0?{copilotApiEndpoint:{tid,url:apiUrl}}:{}}}async function refreshGitHubCopilotToken(refreshToken,enterpriseDomain,signal){let credentials=await refreshGitHubCopilotAccessToken(refreshToken,enterpriseDomain,signal),{availableModelIds,modelLimits}=await fetchGitHubCopilotModels(credentials.access,enterpriseDomain,signal,{maxRetries:0,maxElapsedMs:0},credentials.copilotApiEndpoint);return{...credentials,availableModelIds,copilotModelLimits:modelLimits}}async function enableGitHubCopilotModel(token,modelId,enterpriseDomain,signal,apiEndpoint){let url=`${getGitHubCopilotBaseUrl(token,enterpriseDomain,apiEndpoint)}/models/${modelId}/policy`,response;try{response=await fetchWithRateLimitRetry(url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${token}`,...COPILOT_HEADERS,"openai-intent":"chat-policy","x-interaction-type":"chat-policy"},body:JSON.stringify({state:"enabled"})},signal,{maxRetries:2,maxElapsedMs:5e3})}catch(error){if(signal.aborted)throw error;return!1}if(response.status===429)throw new Error(`${response.status} ${response.statusText}: ${await response.text()}`);return response.ok}async function enableGitHubCopilotModels(token,modelIds,enterpriseDomain,signal,apiEndpoint){let enabledModelIds=[];for(let modelId of modelIds)try{await enableGitHubCopilotModel(token,modelId,enterpriseDomain,signal,apiEndpoint)&&enabledModelIds.push(modelId)}catch(error){if(signal.aborted)throw error;break}return enabledModelIds}async function loginGitHubCopilot(interaction){let input=await interaction.prompt({type:"text",message:"GitHub Enterprise URL/domain (blank for github.com)",placeholder:"company.ghe.com"});if(interaction.signal.aborted)throw new Error("Login cancelled");let trimmed=input.trim(),enterpriseDomain=normalizeDomain(input);if(trimmed&&!enterpriseDomain)throw new Error("Invalid GitHub Enterprise URL/domain");let domain=enterpriseDomain||"github.com",device=await startDeviceFlow(domain,interaction.signal);interaction.notify({type:"device_code",userCode:device.user_code,verificationUri:device.verification_uri,intervalSeconds:device.interval,expiresInSeconds:device.expires_in});let githubAccessToken=await pollForGitHubAccessToken(domain,device,interaction.signal),credentials=await refreshGitHubCopilotAccessToken(githubAccessToken,enterpriseDomain??void 0,interaction.signal),models=await fetchGitHubCopilotModels(credentials.access,enterpriseDomain??void 0,interaction.signal,{maxRetries:2,maxElapsedMs:5e3},credentials.copilotApiEndpoint),enabledModelIds=[];return models.policyModelIds.length>0&&(interaction.notify({type:"progress",message:"Enabling models..."}),enabledModelIds=await enableGitHubCopilotModels(credentials.access,models.policyModelIds,enterpriseDomain??void 0,interaction.signal,credentials.copilotApiEndpoint)),{...credentials,availableModelIds:[...new Set([...models.availableModelIds,...enabledModelIds])],copilotModelLimits:models.modelLimits}}function copilotEnterpriseDomain(credential){let enterpriseUrl=credential.enterpriseUrl;if(!(typeof enterpriseUrl!="string"||!enterpriseUrl))return normalizeDomain(enterpriseUrl)??void 0}var githubCopilotOAuth={name:"GitHub Copilot",isSubscription:!0,rejectedTokenStatuses:GITHUB_COPILOT_REJECTED_TOKEN_STATUSES,login:loginGitHubCopilot,refresh:(credential,signal)=>refreshGitHubCopilotToken(credential.refresh,copilotEnterpriseDomain(credential),signal),async toAuth(credential){return{apiKey:credential.access,baseUrl:getGitHubCopilotBaseUrl(credential.access,copilotEnterpriseDomain(credential),credential.copilotApiEndpoint)}}};export{githubCopilotOAuth};
|
|
2
|
+
var GITHUB_COPILOT_INDIVIDUAL_BASE_URL="https://api.individual.githubcopilot.com";function githubCopilotTokenField(token,key){for(let part of token.split(";")){let separator=part.indexOf("=");if(separator>0&&part.slice(0,separator)===key)return part.slice(separator+1)||void 0}}function githubCopilotBaseUrlFromToken(token){let proxyHost=githubCopilotTokenField(token,"proxy-ep");return proxyHost?`https://${proxyHost.replace(/^proxy\./,"api.")}`:void 0}function parseGitHubCopilotApiEndpoint(value){if(typeof value=="string")try{let url=new URL(value.trim());return url.protocol!=="https:"||!url.hostname||url.username||url.password?void 0:`${url.origin}${url.pathname.replace(/\/+$/,"")}`}catch{return}}function endpointForToken(endpoint,token){if(!token||typeof endpoint!="object"||endpoint===null)return;let tid=Reflect.get(endpoint,"tid"),url=parseGitHubCopilotApiEndpoint(Reflect.get(endpoint,"url"));return typeof tid=="string"&&tid===githubCopilotTokenField(token,"tid")?url:void 0}function resolveGitHubCopilotBaseUrl(input){return endpointForToken(input.apiEndpoint,input.token)??(input.token?githubCopilotBaseUrlFromToken(input.token):void 0)??(input.enterpriseDomain?`https://copilot-api.${input.enterpriseDomain}`:void 0)??GITHUB_COPILOT_INDIVIDUAL_BASE_URL}var GITHUB_COPILOT_REJECTED_TOKEN_STATUSES=[401,403];function sleep(ms,signal){return new Promise((resolve,reject)=>{signal.throwIfAborted();let onAbort=()=>{clearTimeout(timeout),reject(signal.reason)},timeout=setTimeout(()=>{signal.removeEventListener("abort",onAbort),resolve()},ms);signal.addEventListener("abort",onAbort,{once:!0})})}var CANCEL_MESSAGE="Login cancelled",TIMEOUT_MESSAGE="Device flow timed out",SLOW_DOWN_TIMEOUT_MESSAGE="Device flow timed out after one or more slow_down responses. This is often caused by clock drift in WSL or VM environments. Please sync or restart the VM clock and try again.";function abortableSleep(ms,signal,cancelMessage){return new Promise((resolve,reject)=>{if(signal.aborted){reject(new Error(cancelMessage));return}let onAbort=()=>{clearTimeout(timeout),reject(new Error(cancelMessage))},timeout=setTimeout(()=>{signal.removeEventListener("abort",onAbort),resolve()},ms);signal.addEventListener("abort",onAbort,{once:!0})})}async function pollOAuthDeviceCodeFlow(options){let deadline=typeof options.expiresInSeconds=="number"?Date.now()+options.expiresInSeconds*1e3:Number.POSITIVE_INFINITY,intervalMs=Math.max(1e3,Math.floor((options.intervalSeconds??5)*1e3)),slowDownResponses=0;if(options.waitBeforeFirstPoll){let remainingMs=deadline-Date.now();remainingMs>0&&await abortableSleep(Math.min(intervalMs,remainingMs),options.signal,CANCEL_MESSAGE)}for(;Date.now()<deadline;){if(options.signal.aborted)throw new Error(CANCEL_MESSAGE);let result=await options.poll();if(result.status==="complete")return result.value;if(result.status==="failed")throw new Error(result.message);result.status==="slow_down"&&(slowDownResponses+=1,intervalMs=typeof result.intervalSeconds=="number"&&Number.isFinite(result.intervalSeconds)&&result.intervalSeconds>0?Math.max(1e3,Math.floor(result.intervalSeconds*1e3)):Math.max(1e3,intervalMs+5e3));let remainingMs=deadline-Date.now();if(remainingMs<=0)break;await abortableSleep(Math.min(intervalMs,remainingMs),options.signal,CANCEL_MESSAGE)}throw new Error(slowDownResponses>0?SLOW_DOWN_TIMEOUT_MESSAGE:TIMEOUT_MESSAGE)}var github_copilot_default={"anthropic-messages":{"claude-fable-5":{id:"claude-fable-5",name:"Claude Fable 5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:10,output:50,cacheRead:1,cacheWrite:12.5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{xhigh:"xhigh",max:"max"},compat:{supportsDisabledThinking:!1,forceAdaptiveThinking:!0}},"claude-fable-5.1":{id:"claude-fable-5.1",name:"Claude Fable 5.1",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:10,output:50,cacheRead:.25,cacheWrite:12.5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{xhigh:"xhigh",max:"max"},compat:{supportsDisabledThinking:!1,forceAdaptiveThinking:!0}},"claude-haiku-4.5":{id:"claude-haiku-4.5",name:"Claude Haiku 4.5 (latest)",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:1,output:5,cacheRead:.1,cacheWrite:1.25},contextWindow:2e5,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsEagerToolInputStreaming:!1}},"claude-opus-4.7":{id:"claude-opus-4.7",name:"Claude Opus 4.7",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:32e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{xhigh:"xhigh",max:"max",minimal:"low"},compat:{forceAdaptiveThinking:!0,supportsTemperature:!1}},"claude-opus-4.8":{id:"claude-opus-4.8",name:"Claude Opus 4.8",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{xhigh:"xhigh",max:"max",minimal:"low"},compat:{forceAdaptiveThinking:!0,supportsTemperature:!1}},"claude-opus-5":{id:"claude-opus-5",name:"Claude Opus 5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{xhigh:"xhigh",max:"max",minimal:"low"},compat:{forceAdaptiveThinking:!0,supportsTemperature:!1}},"claude-opus-5.5":{id:"claude-opus-5.5",name:"Claude Opus 5.5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:4,output:20,cacheRead:.2,cacheWrite:5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{xhigh:"xhigh",max:"max"},compat:{supportsDisabledThinking:!1,forceAdaptiveThinking:!0,supportsTemperature:!1}},"claude-sonnet-4.6":{id:"claude-sonnet-4.6",name:"Claude Sonnet 4.6",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:1e6,maxTokens:32e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{max:"max",minimal:"low"},compat:{forceAdaptiveThinking:!0}},"claude-sonnet-5":{id:"claude-sonnet-5",name:"Claude Sonnet 5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:10,cacheRead:.2,cacheWrite:2.5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{xhigh:"xhigh",max:"max"},compat:{forceAdaptiveThinking:!0}},"claude-sonnet-5.5":{id:"claude-sonnet-5.5",name:"Claude Sonnet 5.5",api:"anthropic-messages",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:10,cacheRead:.2,cacheWrite:2.5},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{xhigh:"xhigh",max:"max"},compat:{supportsDisabledThinking:!1,forceAdaptiveThinking:!0}}},"openai-completions":{"gemini-3.5-flash":{id:"gemini-3.5-flash",name:"Gemini 3.5 Flash",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:1.5,output:9,cacheRead:.15,cacheWrite:0},contextWindow:2e5,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1}},"gemini-3.6-flash":{id:"gemini-3.6-flash",name:"Gemini 3.6 Flash",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.75,output:3.75,cacheRead:.075,cacheWrite:0},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1}},"gemini-3.7-flash":{id:"gemini-3.7-flash",name:"Gemini 3.7 Flash",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.75,output:3.75,cacheRead:.075,cacheWrite:0},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1}},"gemini-3.8-flash":{id:"gemini-3.8-flash",name:"Gemini 3.8 Flash",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.75,output:3.75,cacheRead:.075,cacheWrite:0},contextWindow:1e6,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1}},"kimi-k2.7-code":{id:"kimi-k2.7-code",name:"Kimi K2.7 Code",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.95,output:4,cacheRead:.19,cacheWrite:0},contextWindow:256e3,maxTokens:32e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1}},"kimi-k3":{id:"kimi-k3",name:"Kimi K3",api:"openai-completions",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:0},contextWindow:1048576,maxTokens:131072,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},compat:{supportsStore:!1,supportsDeveloperRole:!1,supportsReasoningEffort:!1}}},"openai-responses":{"gpt-5-mini":{id:"gpt-5-mini",name:"GPT-5 Mini",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.25,output:2,cacheRead:.025,cacheWrite:0},contextWindow:264e3,maxTokens:64e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:null,max:null},compat:{supportsOpenAIGrammarTools:!0}},"gpt-5.3-codex":{id:"gpt-5.3-codex",name:"GPT-5.3 Codex",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0}},"gpt-5.4":{id:"gpt-5.4",name:"GPT-5.4",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2.5,output:15,cacheRead:.25,cacheWrite:0,tiers:[{inputTokensAbove:272e3,input:5,output:22.5,cacheRead:.5,cacheWrite:0}]},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0}},"gpt-5.4-mini":{id:"gpt-5.4-mini",name:"GPT-5.4 mini",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.75,output:4.5,cacheRead:.075,cacheWrite:0},contextWindow:272e3,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0}},"gpt-5.4-nano":{id:"gpt-5.4-nano",name:"GPT-5.4 nano",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.2,output:1.25,cacheRead:.02,cacheWrite:0},contextWindow:272e3,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",xhigh:"xhigh"},compat:{supportsOpenAIGrammarTools:!0}},"gpt-5.5":{id:"gpt-5.5",name:"GPT-5.5",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:5,output:30,cacheRead:.5,cacheWrite:0,tiers:[{inputTokensAbove:272e3,input:10,output:45,cacheRead:1,cacheWrite:0}]},contextWindow:1e6,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null},compat:{supportsOpenAIGrammarTools:!0}},"gpt-5.6-luna":{id:"gpt-5.6-luna",name:"GPT-5.6 Luna",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.2,output:1.2,cacheRead:.02,cacheWrite:.25,tiers:[{inputTokensAbove:2e5,input:.4,output:1.8,cacheRead:.04,cacheWrite:.5}]},contextWindow:922e3,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0}},"gpt-5.6-sol":{id:"gpt-5.6-sol",name:"GPT-5.6 Sol",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:4,output:20,cacheRead:.4,cacheWrite:5,tiers:[{inputTokensAbove:272e3,input:8,output:30,cacheRead:.8,cacheWrite:10}]},contextWindow:922e3,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0}},"gpt-5.6-terra":{id:"gpt-5.6-terra",name:"GPT-5.6 Terra",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:12,cacheRead:.2,cacheWrite:2.5,tiers:[{inputTokensAbove:272e3,input:4,output:18,cacheRead:.4,cacheWrite:5}]},contextWindow:922e3,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0}},"gpt-6-astra":{id:"gpt-6-astra",name:"GPT-6 Astra",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:10,output:50,cacheRead:1,cacheWrite:12.5,tiers:[{inputTokensAbove:272e3,input:20,output:75,cacheRead:2,cacheWrite:25}]},contextWindow:6e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0}},"gpt-6-luna":{id:"gpt-6-luna",name:"GPT-6 Luna",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.1,output:.5,cacheRead:.01,cacheWrite:.125,tiers:[{inputTokensAbove:272e3,input:.2,output:.75,cacheRead:.02,cacheWrite:.25}]},contextWindow:922e3,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:"none",minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0}},"gpt-6-sol":{id:"gpt-6-sol",name:"GPT-6 Sol",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:10,cacheRead:.2,cacheWrite:2.5,tiers:[{inputTokensAbove:272e3,input:4,output:15,cacheRead:.4,cacheWrite:5}]},contextWindow:4e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:"none",minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0}},"gpt-6.1-sol":{id:"gpt-6.1-sol",name:"GPT-6.1 Sol",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:10,cacheRead:.1,cacheWrite:2.5,tiers:[{inputTokensAbove:272e3,input:4,output:15,cacheRead:.2,cacheWrite:5}]},contextWindow:4e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max"},compat:{supportsOpenAIGrammarTools:!0}},"grok-4.5":{id:"grok-4.5",name:"Grok 4.5",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:6,cacheRead:.5,cacheWrite:0,tiers:[{inputTokensAbove:2e5,input:4,output:12,cacheRead:1,cacheWrite:0}]},contextWindow:5e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:null,max:null}},"grok-4.6":{id:"grok-4.6",name:"Grok 4.6",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:6,cacheRead:.5,cacheWrite:0,tiers:[{inputTokensAbove:2e5,input:4,output:12,cacheRead:1,cacheWrite:0}]},contextWindow:5e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null}},"grok-4.7":{id:"grok-4.7",name:"Grok 4.7",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:2,output:6,cacheRead:.5,cacheWrite:0,tiers:[{inputTokensAbove:2e5,input:4,output:12,cacheRead:1,cacheWrite:0}]},contextWindow:5e5,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:null}},"mai-code-1-flash-picker":{id:"mai-code-1-flash-picker",name:"MAI-Code-1-Flash",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text"],cost:{input:.75,output:4.5,cacheRead:.075,cacheWrite:0},contextWindow:256e3,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:null,max:null}},"mai-code-1.1-flash":{id:"mai-code-1.1-flash",name:"MAI-Code-1.1-Flash",api:"openai-responses",provider:"github-copilot",baseUrl:"https://api.individual.githubcopilot.com",reasoning:!0,input:["text","image"],cost:{input:.2,output:1.2,cacheRead:.02,cacheWrite:0},contextWindow:256e3,maxTokens:128e3,headers:{"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},thinkingLevelMap:{off:null,minimal:null,low:"low",medium:"medium",high:"high",xhigh:null,max:null}}}};function flattenModelCatalog(_provider,groups){return Object.assign({},...Object.values(groups))}var GITHUB_COPILOT_MODELS=flattenModelCatalog("github-copilot",github_copilot_default);function asRecord(value){return value&&typeof value=="object"?value:void 0}function positiveInteger(value){return typeof value=="number"&&Number.isInteger(value)&&value>0?value:void 0}function parseGitHubCopilotModelLimit(id,rawLimits){let limits=asRecord(rawLimits);if(!limits)return;let maxContextWindowTokens=positiveInteger(limits.max_context_window_tokens),maxPromptTokens=positiveInteger(limits.max_prompt_tokens),maxOutputTokens=positiveInteger(limits.max_output_tokens);if(!(maxContextWindowTokens===void 0&&maxPromptTokens===void 0&&maxOutputTokens===void 0))return{id,...maxContextWindowTokens!==void 0?{maxContextWindowTokens}:{},...maxPromptTokens!==void 0?{maxPromptTokens}:{},...maxOutputTokens!==void 0?{maxOutputTokens}:{}}}function asRecord2(value){return value&&typeof value=="object"?value:void 0}function parseGitHubCopilotModelCatalog(raw,allowPolicyFallback){let data=asRecord2(raw)?.data;if(!Array.isArray(data))throw new Error("Invalid Copilot models response");let accountModels=data.flatMap(rawItem=>{let item=asRecord2(rawItem),id=item?.id;if(!item||typeof id!="string")return[];let capabilities=asRecord2(item.capabilities);return asRecord2(capabilities?.supports)?.tool_calls===!1?[]:[{id,pickerEnabled:item.model_picker_enabled===!0,policyState:asRecord2(item.policy)?.state,limits:parseGitHubCopilotModelLimit(id,capabilities?.limits)}]}),pickerModelIds=accountModels.filter(model=>model.pickerEnabled&&model.policyState!=="disabled").map(model=>model.id),usePolicyFallback=allowPolicyFallback&&pickerModelIds.length===0,availableModelIds=pickerModelIds.length>0||!allowPolicyFallback?pickerModelIds:accountModels.filter(model=>model.policyState==="enabled").map(model=>model.id),policyModelIds=accountModels.filter(model=>model.policyState==="unconfigured"&&Object.hasOwn(GITHUB_COPILOT_MODELS,model.id)&&(model.pickerEnabled||usePolicyFallback)).map(model=>model.id),modelLimits=accountModels.map(model=>model.limits).filter(limits=>limits!==void 0);return{availableModelIds,policyModelIds,modelLimits}}var decode=s=>atob(s),CLIENT_ID=decode("SXYxLmI1MDdhMDhjODdlY2ZlOTg="),COPILOT_HEADERS={"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},COPILOT_API_VERSION="2026-06-01";function normalizeDomain(input){let trimmed=input.trim();if(!trimmed)return null;try{return(trimmed.includes("://")?new URL(trimmed):new URL(`https://${trimmed}`)).hostname}catch{return null}}function getUrls(domain){return{deviceCodeUrl:`https://${domain}/login/device/code`,accessTokenUrl:`https://${domain}/login/oauth/access_token`,copilotTokenUrl:`https://api.${domain}/copilot_internal/v2/token`}}function getGitHubCopilotBaseUrl(token,enterpriseDomain,apiEndpoint){return resolveGitHubCopilotBaseUrl({token,enterpriseDomain,apiEndpoint})}async function fetchWithRateLimitRetry(url,init,signal,retryPolicy){let retryBudgetSignal=retryPolicy.maxRetries>0&&retryPolicy.maxElapsedMs>0?AbortSignal.timeout(retryPolicy.maxElapsedMs):void 0,requestSignal=retryBudgetSignal?AbortSignal.any([signal,retryBudgetSignal]):signal,retryDeadline=retryBudgetSignal?Date.now()+retryPolicy.maxElapsedMs:void 0;for(let retry=0;;retry++){let response=await fetch(url,{...init,signal:AbortSignal.any([requestSignal,AbortSignal.timeout(5e3)])});if(response.status!==429||retry===retryPolicy.maxRetries)return response;let retryAfter=response.headers.get("retry-after"),delayMs=500*2**retry;if(retryAfter){let seconds=Number.parseFloat(retryAfter);if(delayMs=Number.isNaN(seconds)?Date.parse(retryAfter)-Date.now():seconds*1e3,!Number.isFinite(delayMs))return response}if(delayMs=Math.max(0,delayMs),retryDeadline!==void 0&&delayMs>=retryDeadline-Date.now())return response;await response.body?.cancel(),await sleep(delayMs,requestSignal)}}async function fetchGitHubCopilotModels(copilotToken,enterpriseDomain,signal,retryPolicy,apiEndpoint){let baseUrl=getGitHubCopilotBaseUrl(copilotToken,enterpriseDomain,apiEndpoint),allowPolicyFallback=baseUrl===GITHUB_COPILOT_INDIVIDUAL_BASE_URL,response=await fetchWithRateLimitRetry(`${baseUrl}/models`,{headers:{Accept:"application/json",Authorization:`Bearer ${copilotToken}`,...COPILOT_HEADERS,"X-GitHub-Api-Version":COPILOT_API_VERSION}},signal,retryPolicy);if(!response.ok)throw new Error(`${response.status} ${response.statusText}: ${await response.text()}`);return parseGitHubCopilotModelCatalog(await response.json(),allowPolicyFallback)}async function fetchJson(url,init){let response=await fetch(url,init);if(!response.ok){let text=await response.text();throw new Error(`${response.status} ${response.statusText}: ${text}`)}return response.json()}async function startDeviceFlow(domain,signal){let urls=getUrls(domain),data=await fetchJson(urls.deviceCodeUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","User-Agent":"GitHubCopilotChat/0.35.0"},body:new URLSearchParams({client_id:CLIENT_ID,scope:"read:user"}),signal});if(!data||typeof data!="object")throw new Error("Invalid device code response");let deviceCode=data.device_code,userCode=data.user_code,verificationUri=data.verification_uri,interval=data.interval,expiresIn=data.expires_in;if(typeof deviceCode!="string"||typeof userCode!="string"||typeof verificationUri!="string"||interval!==void 0&&typeof interval!="number"||typeof expiresIn!="number")throw new Error("Invalid device code response fields");let parsedUri;try{parsedUri=new URL(verificationUri)}catch{throw new Error("Untrusted verification_uri in device code response")}if(parsedUri.protocol!=="https:"&&parsedUri.protocol!=="http:")throw new Error("Untrusted verification_uri in device code response");return{device_code:deviceCode,user_code:userCode,verification_uri:parsedUri.href,interval,expires_in:expiresIn}}async function pollForGitHubAccessToken(domain,device,signal){let urls=getUrls(domain);return pollOAuthDeviceCodeFlow({intervalSeconds:device.interval,expiresInSeconds:device.expires_in,waitBeforeFirstPoll:!0,signal,poll:async()=>{let raw=await fetchJson(urls.accessTokenUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","User-Agent":"GitHubCopilotChat/0.35.0"},body:new URLSearchParams({client_id:CLIENT_ID,device_code:device.device_code,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}),signal});if(raw&&typeof raw=="object"&&typeof raw.access_token=="string")return{status:"complete",value:raw.access_token};if(raw&&typeof raw=="object"&&typeof raw.error=="string"){let{error,error_description:description,interval}=raw;if(error==="authorization_pending")return{status:"pending"};if(error==="slow_down")return{status:"slow_down",intervalSeconds:typeof interval=="number"?interval:void 0};let descriptionSuffix=description?`: ${description}`:"";return{status:"failed",message:`Device flow failed: ${error}${descriptionSuffix}`}}return{status:"failed",message:"Invalid device token response"}}})}async function refreshGitHubCopilotAccessToken(refreshToken,enterpriseDomain,signal){let urls=getUrls(enterpriseDomain||"github.com"),raw=await fetchJson(urls.copilotTokenUrl,{headers:{Accept:"application/json",Authorization:`Bearer ${refreshToken}`,...COPILOT_HEADERS},signal});if(!raw||typeof raw!="object")throw new Error("Invalid Copilot token response");let token=raw.token,expiresAt=raw.expires_at;if(typeof token!="string"||typeof expiresAt!="number")throw new Error("Invalid Copilot token response fields");let endpoints=raw.endpoints,apiUrl=parseGitHubCopilotApiEndpoint(typeof endpoints=="object"&&endpoints!==null?Reflect.get(endpoints,"api"):void 0),tid=githubCopilotTokenField(token,"tid");return{type:"oauth",refresh:refreshToken,access:token,expires:expiresAt*1e3-300*1e3,enterpriseUrl:enterpriseDomain,...apiUrl!==void 0&&tid!==void 0?{copilotApiEndpoint:{tid,url:apiUrl}}:{}}}async function refreshGitHubCopilotToken(refreshToken,enterpriseDomain,signal){let credentials=await refreshGitHubCopilotAccessToken(refreshToken,enterpriseDomain,signal),{availableModelIds,modelLimits}=await fetchGitHubCopilotModels(credentials.access,enterpriseDomain,signal,{maxRetries:0,maxElapsedMs:0},credentials.copilotApiEndpoint);return{...credentials,availableModelIds,copilotModelLimits:modelLimits}}async function enableGitHubCopilotModel(token,modelId,enterpriseDomain,signal,apiEndpoint){let url=`${getGitHubCopilotBaseUrl(token,enterpriseDomain,apiEndpoint)}/models/${modelId}/policy`,response;try{response=await fetchWithRateLimitRetry(url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${token}`,...COPILOT_HEADERS,"openai-intent":"chat-policy","x-interaction-type":"chat-policy"},body:JSON.stringify({state:"enabled"})},signal,{maxRetries:2,maxElapsedMs:5e3})}catch(error){if(signal.aborted)throw error;return!1}if(response.status===429)throw new Error(`${response.status} ${response.statusText}: ${await response.text()}`);return response.ok}async function enableGitHubCopilotModels(token,modelIds,enterpriseDomain,signal,apiEndpoint){let enabledModelIds=[];for(let modelId of modelIds)try{await enableGitHubCopilotModel(token,modelId,enterpriseDomain,signal,apiEndpoint)&&enabledModelIds.push(modelId)}catch(error){if(signal.aborted)throw error;break}return enabledModelIds}async function loginGitHubCopilot(interaction){let input=await interaction.prompt({type:"text",message:"GitHub Enterprise URL/domain (blank for github.com)",placeholder:"company.ghe.com"});if(interaction.signal.aborted)throw new Error("Login cancelled");let trimmed=input.trim(),enterpriseDomain=normalizeDomain(input);if(trimmed&&!enterpriseDomain)throw new Error("Invalid GitHub Enterprise URL/domain");let domain=enterpriseDomain||"github.com",device=await startDeviceFlow(domain,interaction.signal);interaction.notify({type:"device_code",userCode:device.user_code,verificationUri:device.verification_uri,intervalSeconds:device.interval,expiresInSeconds:device.expires_in});let githubAccessToken=await pollForGitHubAccessToken(domain,device,interaction.signal),credentials=await refreshGitHubCopilotAccessToken(githubAccessToken,enterpriseDomain??void 0,interaction.signal),models=await fetchGitHubCopilotModels(credentials.access,enterpriseDomain??void 0,interaction.signal,{maxRetries:2,maxElapsedMs:5e3},credentials.copilotApiEndpoint),enabledModelIds=[];return models.policyModelIds.length>0&&(interaction.notify({type:"progress",message:"Enabling models..."}),enabledModelIds=await enableGitHubCopilotModels(credentials.access,models.policyModelIds,enterpriseDomain??void 0,interaction.signal,credentials.copilotApiEndpoint)),{...credentials,availableModelIds:[...new Set([...models.availableModelIds,...enabledModelIds])],copilotModelLimits:models.modelLimits}}function copilotEnterpriseDomain(credential){let enterpriseUrl=credential.enterpriseUrl;if(!(typeof enterpriseUrl!="string"||!enterpriseUrl))return normalizeDomain(enterpriseUrl)??void 0}var githubCopilotOAuth={name:"GitHub Copilot",isSubscription:!0,rejectedTokenStatuses:GITHUB_COPILOT_REJECTED_TOKEN_STATUSES,login:loginGitHubCopilot,refresh:(credential,signal)=>refreshGitHubCopilotToken(credential.refresh,copilotEnterpriseDomain(credential),signal),async toAuth(credential){return{apiKey:credential.access,baseUrl:getGitHubCopilotBaseUrl(credential.access,copilotEnterpriseDomain(credential),credential.copilotApiEndpoint)}}};export{githubCopilotOAuth};
|
package/dist/bundle/chunks/{google-generative-ai-RYFW7GSR.js → google-generative-ai-E3I6MS7E.js}
RENAMED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{GoogleGenAI,ThinkingLevel,convertMessages,convertTools,isThinkingPart,mapStopReason,resolveGoogleFunctionCallingMode,resolveGoogleThinkingLevel,retainThoughtSignature,retryGoogleRequest,supportsGoogleStrictToolSampling,toProviderNativeContent}from"./chunk-DFRI62DO.js";import"./chunk-YBZDAABT.js";import"./chunk-U5LXY7UD.js";import{getPiUserAgent}from"./chunk-QTG7MY2X.js";import"./chunk-KLBKUBDV.js";import{GOOGLE_RESERVED_BODY_KEYS,applyExtraBody,buildBaseOptions}from"./chunk-WW3YFGEP.js";import"./chunk-45SZOLCU.js";import{formatProviderError,normalizeProviderError}from"./chunk-BBK6SSYT.js";import"./chunk-BPX6QWPD.js";import{calculateCost,clampThinkingLevel}from"./chunk-NUS5JXND.js";import{sanitizeSurrogates}from"./chunk-WDTJ6JKE.js";import{AssistantMessageEventStream}from"./chunk-DMI55M2N.js";import{providerHeadersToRecord}from"./chunk-BQVVQ2LQ.js";import"./chunk-IKOFCODM.js";var THINKING_LEVEL_MAP={THINKING_LEVEL_UNSPECIFIED:ThinkingLevel.THINKING_LEVEL_UNSPECIFIED,MINIMAL:ThinkingLevel.MINIMAL,LOW:ThinkingLevel.LOW,MEDIUM:ThinkingLevel.MEDIUM,HIGH:ThinkingLevel.HIGH},toolCallCounter=0,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream;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,providerHeadersToRecord(options?.headers)),params=buildParams(model,context,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,groundingMetadataEmitted=!1,urlContextMetadataEmitted=!1,blocks=output.content,blockIndex=()=>blocks.length-1;for await(let chunk of googleStream){output.responseId||=chunk.responseId;let candidate=chunk.candidates?.[0];if(candidate?.content?.parts)for(let part of candidate.content.parts){let handledAsKnownPart=!1;if(part.text!==void 0){handledAsKnownPart=!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){handledAsKnownPart=!0,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})}handledAsKnownPart||output.content.push(toProviderNativeContent(part))}candidate?.groundingMetadata&&!groundingMetadataEmitted&&(output.content.push({type:"providerNative",subtype:"groundingMetadata",raw:candidate.groundingMetadata}),groundingMetadataEmitted=!0),candidate?.urlContextMetadata&&!urlContextMetadataEmitted&&(output.content.push({type:"providerNative",subtype:"urlContextMetadata",raw:candidate.urlContextMetadata}),urlContextMetadataEmitted=!0),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||options.reasoning==="off")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),googleModel=model;return isGemini3ProModel(googleModel)||isGemini3FlashModel(googleModel)||isGemma4Model(googleModel)?stream(model,context,{...base,thinking:{enabled:!0,level:getThinkingLevel(resolvedLevel,googleModel)}}):stream(model,context,{...base,thinking:{enabled:!0,budgetTokens:getGoogleBudget(googleModel,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,{preserveThinking:options.thinking?.enabled===!0}),generationConfig={};options.temperature!==void 0&&(generationConfig.temperature=options.temperature),options.maxTokens!==void 0&&(generationConfig.maxOutputTokens=options.maxTokens);let supportsStrictMode=supportsGoogleStrictToolSampling(model.id),functionCallingMode=context.tools?.length?resolveGoogleFunctionCallingMode(context.tools,options.toolChoice,supportsStrictMode):void 0,config={...Object.keys(generationConfig).length>0&&generationConfig,...context.systemPrompt&&{systemInstruction:sanitizeSurrogates(context.systemPrompt)},...context.tools&&context.tools.length>0&&{tools:convertTools(context.tools,!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=THINKING_LEVEL_MAP[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=getDisabledThinkingConfig(model));if(options.signal){if(options.signal.aborted)throw new Error("Request aborted");config.abortSignal=options.signal}return applyExtraBody(config,options?.extraBody,GOOGLE_RESERVED_BODY_KEYS),{model:model.id,contents,config}}function isGemma4Model(model){return/gemma-?4/.test(model.id.toLowerCase())}function isGemini3ProModel(model){return/gemini-3(?:\.\d+)?-pro/.test(model.id.toLowerCase())}function isGemini3FlashModel(model){let id=model.id.toLowerCase();return/gemini-3(?:\.\d+)?-flash/.test(id)||id==="gemini-flash-latest"||id==="gemini-flash-lite-latest"}function getDisabledThinkingConfig(model){return isGemini3ProModel(model)?{thinkingLevel:ThinkingLevel.LOW}:isGemini3FlashModel(model)?{thinkingLevel:ThinkingLevel.MINIMAL}:isGemma4Model(model)?{thinkingLevel:ThinkingLevel.MINIMAL}:{thinkingBudget:0}}function getThinkingLevel(effort,model){if(isGemini3ProModel(model))switch(effort){case"minimal":case"low":return"LOW";case"medium":case"high":return"HIGH"}if(isGemma4Model(model))switch(effort){case"minimal":case"low":return"MINIMAL";case"medium":case"high":return"HIGH"}switch(effort){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH"}}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};
|
|
2
|
+
import{GoogleGenAI,ThinkingLevel,convertMessages,convertTools,isThinkingPart,mapStopReason,resolveGoogleFunctionCallingMode,resolveGoogleThinkingLevel,retainThoughtSignature,retryGoogleRequest,supportsGoogleStrictToolSampling,toProviderNativeContent}from"./chunk-W4IEEYWL.js";import"./chunk-YBZDAABT.js";import"./chunk-2IHY6ZLW.js";import{getPiUserAgent}from"./chunk-QTG7MY2X.js";import"./chunk-KLBKUBDV.js";import{GOOGLE_RESERVED_BODY_KEYS,applyExtraBody,buildBaseOptions}from"./chunk-7MUTNWPO.js";import"./chunk-45SZOLCU.js";import{formatProviderError,normalizeProviderError}from"./chunk-BBK6SSYT.js";import"./chunk-BPX6QWPD.js";import{calculateCost,clampThinkingLevel}from"./chunk-Z2N5372Y.js";import{sanitizeSurrogates}from"./chunk-WDTJ6JKE.js";import{AssistantMessageEventStream}from"./chunk-DMI55M2N.js";import{providerHeadersToRecord}from"./chunk-BQVVQ2LQ.js";import"./chunk-IKOFCODM.js";var THINKING_LEVEL_MAP={THINKING_LEVEL_UNSPECIFIED:ThinkingLevel.THINKING_LEVEL_UNSPECIFIED,MINIMAL:ThinkingLevel.MINIMAL,LOW:ThinkingLevel.LOW,MEDIUM:ThinkingLevel.MEDIUM,HIGH:ThinkingLevel.HIGH},toolCallCounter=0,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream;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,providerHeadersToRecord(options?.headers)),params=buildParams(model,context,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,groundingMetadataEmitted=!1,urlContextMetadataEmitted=!1,blocks=output.content,blockIndex=()=>blocks.length-1;for await(let chunk of googleStream){output.responseId||=chunk.responseId;let candidate=chunk.candidates?.[0];if(candidate?.content?.parts)for(let part of candidate.content.parts){let handledAsKnownPart=!1;if(part.text!==void 0){handledAsKnownPart=!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){handledAsKnownPart=!0,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})}handledAsKnownPart||output.content.push(toProviderNativeContent(part))}candidate?.groundingMetadata&&!groundingMetadataEmitted&&(output.content.push({type:"providerNative",subtype:"groundingMetadata",raw:candidate.groundingMetadata}),groundingMetadataEmitted=!0),candidate?.urlContextMetadata&&!urlContextMetadataEmitted&&(output.content.push({type:"providerNative",subtype:"urlContextMetadata",raw:candidate.urlContextMetadata}),urlContextMetadataEmitted=!0),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||options.reasoning==="off")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),googleModel=model;return isGemini3ProModel(googleModel)||isGemini3FlashModel(googleModel)||isGemma4Model(googleModel)?stream(model,context,{...base,thinking:{enabled:!0,level:getThinkingLevel(resolvedLevel,googleModel)}}):stream(model,context,{...base,thinking:{enabled:!0,budgetTokens:getGoogleBudget(googleModel,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,{preserveThinking:options.thinking?.enabled===!0}),generationConfig={};options.temperature!==void 0&&(generationConfig.temperature=options.temperature),options.maxTokens!==void 0&&(generationConfig.maxOutputTokens=options.maxTokens);let supportsStrictMode=supportsGoogleStrictToolSampling(model.id),functionCallingMode=context.tools?.length?resolveGoogleFunctionCallingMode(context.tools,options.toolChoice,supportsStrictMode):void 0,config={...Object.keys(generationConfig).length>0&&generationConfig,...context.systemPrompt&&{systemInstruction:sanitizeSurrogates(context.systemPrompt)},...context.tools&&context.tools.length>0&&{tools:convertTools(context.tools,!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=THINKING_LEVEL_MAP[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=getDisabledThinkingConfig(model));if(options.signal){if(options.signal.aborted)throw new Error("Request aborted");config.abortSignal=options.signal}return applyExtraBody(config,options?.extraBody,GOOGLE_RESERVED_BODY_KEYS),{model:model.id,contents,config}}function isGemma4Model(model){return/gemma-?4/.test(model.id.toLowerCase())}function isGemini3ProModel(model){return/gemini-3(?:\.\d+)?-pro/.test(model.id.toLowerCase())}function isGemini3FlashModel(model){let id=model.id.toLowerCase();return/gemini-3(?:\.\d+)?-flash/.test(id)||id==="gemini-flash-latest"||id==="gemini-flash-lite-latest"}function getDisabledThinkingConfig(model){return isGemini3ProModel(model)?{thinkingLevel:ThinkingLevel.LOW}:isGemini3FlashModel(model)?{thinkingLevel:ThinkingLevel.MINIMAL}:isGemma4Model(model)?{thinkingLevel:ThinkingLevel.MINIMAL}:{thinkingBudget:0}}function getThinkingLevel(effort,model){if(isGemini3ProModel(model))switch(effort){case"minimal":case"low":return"LOW";case"medium":case"high":return"HIGH"}if(isGemma4Model(model))switch(effort){case"minimal":case"low":return"MINIMAL";case"medium":case"high":return"HIGH"}switch(effort){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH"}}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); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{GoogleGenAI,ResourceScope,ThinkingLevel,convertMessages,convertTools,isThinkingPart,mapStopReason,resolveGoogleFunctionCallingMode,resolveGoogleThinkingLevel,retainThoughtSignature,retryGoogleRequest,supportsGoogleStrictToolSampling,toProviderNativeContent}from"./chunk-DFRI62DO.js";import"./chunk-YBZDAABT.js";import"./chunk-U5LXY7UD.js";import{getPiUserAgent}from"./chunk-QTG7MY2X.js";import"./chunk-KLBKUBDV.js";import{GOOGLE_RESERVED_BODY_KEYS,applyExtraBody,buildBaseOptions}from"./chunk-WW3YFGEP.js";import"./chunk-45SZOLCU.js";import{formatProviderError,normalizeProviderError}from"./chunk-BBK6SSYT.js";import"./chunk-BPX6QWPD.js";import{calculateCost,clampThinkingLevel}from"./chunk-NUS5JXND.js";import{sanitizeSurrogates}from"./chunk-WDTJ6JKE.js";import{getProviderEnvValue}from"./chunk-5ROMKDLK.js";import{AssistantMessageEventStream}from"./chunk-DMI55M2N.js";import{providerHeadersToRecord}from"./chunk-BQVVQ2LQ.js";import"./chunk-IKOFCODM.js";var API_VERSION="v1",GCP_VERTEX_CREDENTIALS_MARKER="gcp-vertex-credentials",THINKING_LEVEL_MAP={THINKING_LEVEL_UNSPECIFIED:ThinkingLevel.THINKING_LEVEL_UNSPECIFIED,MINIMAL:ThinkingLevel.MINIMAL,LOW:ThinkingLevel.LOW,MEDIUM:ThinkingLevel.MEDIUM,HIGH:ThinkingLevel.HIGH},toolCallCounter=0,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream;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),headers=providerHeadersToRecord(options?.headers),client=apiKey?createClientWithApiKey(model,apiKey,headers):createClient(model,resolveProject(options),resolveLocation(options),headers,options?.env),params=buildParams(model,context,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,groundingMetadataEmitted=!1,urlContextMetadataEmitted=!1,blocks=output.content,blockIndex=()=>blocks.length-1;for await(let chunk of googleStream){output.responseId||=chunk.responseId;let candidate=chunk.candidates?.[0];if(candidate?.content?.parts)for(let part of candidate.content.parts){let handledAsKnownPart=!1;if(part.text!==void 0){handledAsKnownPart=!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){handledAsKnownPart=!0,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})}handledAsKnownPart||output.content.push(toProviderNativeContent(part))}candidate?.groundingMetadata&&!groundingMetadataEmitted&&(output.content.push({type:"providerNative",subtype:"groundingMetadata",raw:candidate.groundingMetadata}),groundingMetadataEmitted=!0),candidate?.urlContextMetadata&&!urlContextMetadataEmitted&&(output.content.push({type:"providerNative",subtype:"urlContextMetadata",raw:candidate.urlContextMetadata}),urlContextMetadataEmitted=!0),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||options.reasoning==="off")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 isGemini3ProModel(model)||isGemini3FlashModel(model)?stream(model,context,{...base,thinking:{enabled:!0,level:getGemini3ThinkingLevel(resolvedLevel,model)}}):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,{preserveThinking:options.thinking?.enabled===!0}),generationConfig={};options.temperature!==void 0&&(generationConfig.temperature=options.temperature),options.maxTokens!==void 0&&(generationConfig.maxOutputTokens=options.maxTokens);let supportsStrictMode=supportsGoogleStrictToolSampling(model.id),functionCallingMode=context.tools?.length?resolveGoogleFunctionCallingMode(context.tools,options.toolChoice,supportsStrictMode):void 0,config={...Object.keys(generationConfig).length>0&&generationConfig,...context.systemPrompt&&{systemInstruction:sanitizeSurrogates(context.systemPrompt)},...context.tools&&context.tools.length>0&&{tools:convertTools(context.tools,!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=THINKING_LEVEL_MAP[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=getDisabledThinkingConfig(model));if(options.signal){if(options.signal.aborted)throw new Error("Request aborted");config.abortSignal=options.signal}return applyExtraBody(config,options?.extraBody,GOOGLE_RESERVED_BODY_KEYS),{model:model.id,contents,config}}function isGemini3ProModel(model){return/gemini-3(?:\.\d+)?-pro/.test(model.id.toLowerCase())}function isGemini3FlashModel(model){let id=model.id.toLowerCase();return/gemini-3(?:\.\d+)?-flash/.test(id)||id==="gemini-flash-latest"||id==="gemini-flash-lite-latest"}function getDisabledThinkingConfig(model){return isGemini3ProModel(model)?{thinkingLevel:ThinkingLevel.LOW}:isGemini3FlashModel(model)?{thinkingLevel:ThinkingLevel.MINIMAL}:{thinkingBudget:0}}function getGemini3ThinkingLevel(effort,model){if(isGemini3ProModel(model))switch(effort){case"minimal":case"low":return"LOW";case"medium":case"high":return"HIGH"}switch(effort){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH"}}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,ThinkingLevel,convertMessages,convertTools,isThinkingPart,mapStopReason,resolveGoogleFunctionCallingMode,resolveGoogleThinkingLevel,retainThoughtSignature,retryGoogleRequest,supportsGoogleStrictToolSampling,toProviderNativeContent}from"./chunk-W4IEEYWL.js";import"./chunk-YBZDAABT.js";import"./chunk-2IHY6ZLW.js";import{getPiUserAgent}from"./chunk-QTG7MY2X.js";import"./chunk-KLBKUBDV.js";import{GOOGLE_RESERVED_BODY_KEYS,applyExtraBody,buildBaseOptions}from"./chunk-7MUTNWPO.js";import"./chunk-45SZOLCU.js";import{formatProviderError,normalizeProviderError}from"./chunk-BBK6SSYT.js";import"./chunk-BPX6QWPD.js";import{calculateCost,clampThinkingLevel}from"./chunk-Z2N5372Y.js";import{sanitizeSurrogates}from"./chunk-WDTJ6JKE.js";import{getProviderEnvValue}from"./chunk-5ROMKDLK.js";import{AssistantMessageEventStream}from"./chunk-DMI55M2N.js";import{providerHeadersToRecord}from"./chunk-BQVVQ2LQ.js";import"./chunk-IKOFCODM.js";var API_VERSION="v1",GCP_VERTEX_CREDENTIALS_MARKER="gcp-vertex-credentials",THINKING_LEVEL_MAP={THINKING_LEVEL_UNSPECIFIED:ThinkingLevel.THINKING_LEVEL_UNSPECIFIED,MINIMAL:ThinkingLevel.MINIMAL,LOW:ThinkingLevel.LOW,MEDIUM:ThinkingLevel.MEDIUM,HIGH:ThinkingLevel.HIGH},toolCallCounter=0,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream;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),headers=providerHeadersToRecord(options?.headers),client=apiKey?createClientWithApiKey(model,apiKey,headers):createClient(model,resolveProject(options),resolveLocation(options),headers,options?.env),params=buildParams(model,context,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,groundingMetadataEmitted=!1,urlContextMetadataEmitted=!1,blocks=output.content,blockIndex=()=>blocks.length-1;for await(let chunk of googleStream){output.responseId||=chunk.responseId;let candidate=chunk.candidates?.[0];if(candidate?.content?.parts)for(let part of candidate.content.parts){let handledAsKnownPart=!1;if(part.text!==void 0){handledAsKnownPart=!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){handledAsKnownPart=!0,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})}handledAsKnownPart||output.content.push(toProviderNativeContent(part))}candidate?.groundingMetadata&&!groundingMetadataEmitted&&(output.content.push({type:"providerNative",subtype:"groundingMetadata",raw:candidate.groundingMetadata}),groundingMetadataEmitted=!0),candidate?.urlContextMetadata&&!urlContextMetadataEmitted&&(output.content.push({type:"providerNative",subtype:"urlContextMetadata",raw:candidate.urlContextMetadata}),urlContextMetadataEmitted=!0),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||options.reasoning==="off")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 isGemini3ProModel(model)||isGemini3FlashModel(model)?stream(model,context,{...base,thinking:{enabled:!0,level:getGemini3ThinkingLevel(resolvedLevel,model)}}):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,{preserveThinking:options.thinking?.enabled===!0}),generationConfig={};options.temperature!==void 0&&(generationConfig.temperature=options.temperature),options.maxTokens!==void 0&&(generationConfig.maxOutputTokens=options.maxTokens);let supportsStrictMode=supportsGoogleStrictToolSampling(model.id),functionCallingMode=context.tools?.length?resolveGoogleFunctionCallingMode(context.tools,options.toolChoice,supportsStrictMode):void 0,config={...Object.keys(generationConfig).length>0&&generationConfig,...context.systemPrompt&&{systemInstruction:sanitizeSurrogates(context.systemPrompt)},...context.tools&&context.tools.length>0&&{tools:convertTools(context.tools,!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=THINKING_LEVEL_MAP[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=getDisabledThinkingConfig(model));if(options.signal){if(options.signal.aborted)throw new Error("Request aborted");config.abortSignal=options.signal}return applyExtraBody(config,options?.extraBody,GOOGLE_RESERVED_BODY_KEYS),{model:model.id,contents,config}}function isGemini3ProModel(model){return/gemini-3(?:\.\d+)?-pro/.test(model.id.toLowerCase())}function isGemini3FlashModel(model){let id=model.id.toLowerCase();return/gemini-3(?:\.\d+)?-flash/.test(id)||id==="gemini-flash-latest"||id==="gemini-flash-lite-latest"}function getDisabledThinkingConfig(model){return isGemini3ProModel(model)?{thinkingLevel:ThinkingLevel.LOW}:isGemini3FlashModel(model)?{thinkingLevel:ThinkingLevel.MINIMAL}:{thinkingBudget:0}}function getGemini3ThinkingLevel(effort,model){if(isGemini3ProModel(model))switch(effort){case"minimal":case"low":return"LOW";case"medium":case"high":return"HIGH"}switch(effort){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH"}}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};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{helpFlagsScope,isPlainHelpRequest,resolveHelpProjectTrust,tryPrintHelpWithoutEngine}from"./chunk-
|
|
2
|
+
import{helpFlagsScope,isPlainHelpRequest,resolveHelpProjectTrust,tryPrintHelpWithoutEngine}from"./chunk-BBNWT72C.js";import"./chunk-OUG6SDT7.js";import"./chunk-7CQX3QFV.js";import"./chunk-26UBFF6N.js";import"./chunk-77AUUH3Z.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-VLW22GHJ.js";import"./chunk-WCAKUCN3.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-X4Q5YSTE.js";import"./chunk-BJICJY47.js";import"./chunk-YOPVJDSU.js";import"./chunk-45SZOLCU.js";import"./chunk-WHPDEDCC.js";import"./chunk-Z2N5372Y.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-IKOFCODM.js";export{helpFlagsScope,isPlainHelpRequest,resolveHelpProjectTrust,tryPrintHelpWithoutEngine};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{parseHostArgs,runHostCommand}from"./chunk-
|
|
2
|
+
import{parseHostArgs,runHostCommand}from"./chunk-2N3BZ5DV.js";import"./chunk-CNYWF72S.js";import"./chunk-AWEAVBCR.js";import"./chunk-MJQWYN2W.js";import"./chunk-UMLU3I2G.js";import"./chunk-CIRZTP7W.js";import"./chunk-AGVPQLIU.js";import"./chunk-7CQX3QFV.js";import"./chunk-26UBFF6N.js";import"./chunk-77AUUH3Z.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-VLW22GHJ.js";import"./chunk-WCAKUCN3.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-X4Q5YSTE.js";import"./chunk-BJICJY47.js";import"./chunk-YOPVJDSU.js";import"./chunk-45SZOLCU.js";import"./chunk-WHPDEDCC.js";import"./chunk-Z2N5372Y.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-IKOFCODM.js";export{parseHostArgs,runHostCommand};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{InteractiveMode,OptimisticUserEchoController,createInteractiveTui,createInteractiveTuiReference,formatResumeCommand,shouldShowRetryIndicator}from"./chunk-
|
|
2
|
+
import{InteractiveMode,OptimisticUserEchoController,createInteractiveTui,createInteractiveTuiReference,formatResumeCommand,shouldShowRetryIndicator}from"./chunk-63QHOG5A.js";import"./chunk-K2SHQNAA.js";import"./chunk-ZPMJIPQC.js";import"./chunk-2POUJCWM.js";import"./chunk-VLTMFAWQ.js";import"./chunk-NZRVAZL2.js";import"./chunk-U5KVIAHJ.js";import{isApiKeyLoginProvider}from"./chunk-YLQTKWEC.js";import"./chunk-ZDNR3YVJ.js";import"./chunk-HEKLJWA4.js";import"./chunk-XHEMQA2T.js";import"./chunk-JABBHOD5.js";import"./chunk-YU2P3CAR.js";import"./chunk-BMX2U22F.js";import"./chunk-2N3BZ5DV.js";import"./chunk-CNYWF72S.js";import"./chunk-AWEAVBCR.js";import"./chunk-MJQWYN2W.js";import"./chunk-UMLU3I2G.js";import"./chunk-CIRZTP7W.js";import"./chunk-AGVPQLIU.js";import"./chunk-XBGO2JZD.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-U7BNOE23.js";import"./chunk-2WAKOPNA.js";import"./chunk-SH6VUPE4.js";import"./chunk-7RVWDN5Z.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-BBNWT72C.js";import"./chunk-OUG6SDT7.js";import"./chunk-7CQX3QFV.js";import"./chunk-26UBFF6N.js";import"./chunk-77AUUH3Z.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-VLW22GHJ.js";import"./chunk-4VWWEMCJ.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import"./chunk-WCAKUCN3.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-JRGNL6WM.js";import"./chunk-X4Q5YSTE.js";import"./chunk-CWLCGRUS.js";import"./chunk-BJICJY47.js";import"./chunk-LHYG7TK7.js";import"./chunk-KRNXUTZJ.js";import"./chunk-YOPVJDSU.js";import"./chunk-45SZOLCU.js";import"./chunk-WHPDEDCC.js";import"./chunk-BBK6SSYT.js";import"./chunk-BPX6QWPD.js";import"./chunk-Z2N5372Y.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-IKOFCODM.js";export{InteractiveMode,OptimisticUserEchoController,createInteractiveTui,createInteractiveTuiReference,formatResumeCommand,isApiKeyLoginProvider,shouldShowRetryIndicator};
|
package/dist/bundle/chunks/{mistral-conversations-C7ZTJYKE.js → mistral-conversations-EZ4XNJXU.js}
RENAMED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{getPiUserAgent}from"./chunk-QTG7MY2X.js";import{MISTRAL_RESERVED_BODY_KEYS,applyExtraBody,buildBaseOptions}from"./chunk-
|
|
2
|
+
import{getPiUserAgent}from"./chunk-QTG7MY2X.js";import{MISTRAL_RESERVED_BODY_KEYS,applyExtraBody,buildBaseOptions}from"./chunk-7MUTNWPO.js";import{calculateCost,clampThinkingLevel,getJsonSchemaToolParameters,resolveJsonSchemaStrictSampling,shortHash,transformMessages}from"./chunk-Z2N5372Y.js";import{sanitizeSurrogates}from"./chunk-WDTJ6JKE.js";import{parseStreamingJson}from"./chunk-3W47LTXQ.js";import{AssistantMessageEventStream}from"./chunk-DMI55M2N.js";import{headersToRecord}from"./chunk-BQVVQ2LQ.js";import"./chunk-IKOFCODM.js";var MISTRAL_TOOL_CALL_ID_LENGTH=9,MAX_MISTRAL_ERROR_BODY_CHARS=4e3,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream;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(),preserveThinking=options?.promptMode==="reasoning"||options?.reasoningEffort!==void 0,transformedMessages=transformMessages(context.messages,model,id=>normalizeMistralToolCallId(id),{preserveThinking}),payload=buildChatPayload(model,context,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?.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,shouldUseReasoning=model.reasoning&&reasoning!==void 0;return stream(model,context,{...base,promptMode:shouldUseReasoning&&usesPromptModeReasoning(model)?"reasoning":void 0,reasoningEffort:shouldUseReasoning&&usesReasoningEffort(model)?mapReasoningEffort(model,reasoning):void 0})};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{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"))};return context.tools?.length&&(payload.tools=toFunctionTools(context.tools)),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),context.systemPrompt&&payload.messages.unshift({role:"system",content:sanitizeSurrogates(context.systemPrompt)}),applyExtraBody(payload,options?.extraBody,MISTRAL_RESERVED_BODY_KEYS),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){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(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);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?.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??"");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 msg of messages){if(msg.role==="configurationUpdate")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}block.type==="toolCall"&&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 usesReasoningEffort(model){return model.id==="mistral-small-2603"||model.id==="mistral-small-latest"||model.id.startsWith("mistral-medium-")||model.id==="zai-glm-5-2"}function usesPromptModeReasoning(model){return model.reasoning&&!usesReasoningEffort(model)}function mapReasoningEffort(model,level){return model.thinkingLevelMap?.[level]??"high"}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};
|
package/dist/bundle/chunks/{multi-session-host-3XTEXGP4.js → multi-session-host-IBVJ3WN7.js}
RENAMED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{AgentSessionRuntime,EMPTY_SESSION_CONTEXT,HostMcpRegistry,ProviderScope,SessionManager,assertValidSessionId,bindToProviderScope,createAgentSessionRuntime,createWebViewBroker,isSessionBusySnapshot,readOwnFootprint,runWithProviderScope,startHostChildReaper}from"./chunk-
|
|
2
|
+
import{AgentSessionRuntime,EMPTY_SESSION_CONTEXT,HostMcpRegistry,ProviderScope,SessionManager,assertValidSessionId,bindToProviderScope,createAgentSessionRuntime,createWebViewBroker,isSessionBusySnapshot,readOwnFootprint,runWithProviderScope,startHostChildReaper}from"./chunk-63QHOG5A.js";import"./chunk-K2SHQNAA.js";import"./chunk-ZPMJIPQC.js";import"./chunk-2POUJCWM.js";import"./chunk-VLTMFAWQ.js";import"./chunk-NZRVAZL2.js";import"./chunk-U5KVIAHJ.js";import{RPC_ERROR_ATTACHED,RPC_ERROR_HOST_DRAINING,RPC_ERROR_INVALID_LAUNCH_PROFILE,RPC_ERROR_INVALID_PATH,RPC_ERROR_INVALID_RELEASE_REASON,RPC_ERROR_INVALID_SESSION_CONTEXT,RPC_ERROR_INVALID_SESSION_KIND,RPC_ERROR_MISSING_SESSION_ID,RPC_ERROR_OPEN_FAILED,RPC_ERROR_RELEASE_FAILED,RPC_ERROR_RELEASE_UNSUPPORTED,RPC_ERROR_SESSION_BUSY,RPC_ERROR_SESSION_CLOSING,RPC_ERROR_TURN_ACTIVE,RPC_ERROR_UNKNOWN_SESSION,RPC_ERROR_WARM_FAILED,createRpcConnectionHandler}from"./chunk-YLQTKWEC.js";import{flushRawStdout,takeOverStdout,waitForRawStdoutBackpressure,writeRawStdout}from"./chunk-ZDNR3YVJ.js";import"./chunk-HEKLJWA4.js";import{buildRpcSessionState,rpcCommandShapeError,sessionAutoTitleError,sessionContextError,sessionKindError,sessionPromptSurfaceError}from"./chunk-XHEMQA2T.js";import"./chunk-JABBHOD5.js";import"./chunk-YU2P3CAR.js";import"./chunk-BMX2U22F.js";import{GENERATION_HANDOFF_CAPABILITY,runAsHostGenerationProcess}from"./chunk-2N3BZ5DV.js";import"./chunk-CNYWF72S.js";import{AUTO_TITLE_PER_SESSION_CAPABILITY,AUTO_TITLE_SESSIONS_CAPABILITY,DURABLE_SESSION_ID_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,PROMPT_SURFACE_CAPABILITY,RETAIN_ON_DISCONNECT_CAPABILITY,SESSION_CONTEXT_CAPABILITY,SESSION_KIND_CAPABILITY,WARM_CAPABILITY,hostGeneration,hostInstanceId,parseClientCapabilities,protocolIdentity}from"./chunk-AWEAVBCR.js";import{ClientOccupancy,armHostWatchdog,parseIdleExitMs,readHostWatchdogConfigFromBrandEnv}from"./chunk-MJQWYN2W.js";import{PUBLIC_SOCKET_IDENTITY_FILE,SESSION_PATH_RETRY_AFTER_MS,SOCKET_SECRET_FILE_ENV,authenticateSocket,canonicalSessionPath,createEndpointReservations,ensureSocketSecret,readSocketIdentityFile,resolveSocketTransportAddress,sessionDirectoryRemoved,shieldSocketDuringClose,socketEntryReplaced,socketSecretPath,statSocketIdentity,unlinkOwnedSocket,waitForSocketIdentityFile}from"./chunk-UMLU3I2G.js";import"./chunk-CIRZTP7W.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader,serializeJsonLine}from"./chunk-AGVPQLIU.js";import"./chunk-XBGO2JZD.js";import"./chunk-H4QOEVS5.js";import"./chunk-HB35RBP4.js";import"./chunk-U7BNOE23.js";import"./chunk-2WAKOPNA.js";import{killTrackedDetachedChildren}from"./chunk-SH6VUPE4.js";import"./chunk-7RVWDN5Z.js";import"./chunk-7X72IACK.js";import"./chunk-KUPQO7MC.js";import"./chunk-BBNWT72C.js";import"./chunk-OUG6SDT7.js";import"./chunk-7CQX3QFV.js";import"./chunk-26UBFF6N.js";import"./chunk-77AUUH3Z.js";import"./chunk-GZVCRV7I.js";import"./chunk-U3VOXCGP.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-VLW22GHJ.js";import"./chunk-4VWWEMCJ.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import{VERSION,envValue,isBunBinary}from"./chunk-WCAKUCN3.js";import"./chunk-ATQFN5HI.js";import"./chunk-RBCQOIAD.js";import"./chunk-JRGNL6WM.js";import"./chunk-X4Q5YSTE.js";import"./chunk-CWLCGRUS.js";import"./chunk-BJICJY47.js";import"./chunk-LHYG7TK7.js";import"./chunk-KRNXUTZJ.js";import"./chunk-YOPVJDSU.js";import"./chunk-45SZOLCU.js";import"./chunk-WHPDEDCC.js";import"./chunk-BBK6SSYT.js";import"./chunk-BPX6QWPD.js";import"./chunk-Z2N5372Y.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-DMI55M2N.js";import"./chunk-BQVVQ2LQ.js";import"./chunk-IKOFCODM.js";import{access as access2,chmod,mkdir,unlink}from"node:fs/promises";import{createConnection,createServer}from"node:net";import{basename,dirname,join}from"node:path";var RPC_SESSION_IDLE_EVICTION_MS_ENV="SENPI_RPC_SESSION_IDLE_EVICTION_MS",RPC_HOST_EMPTY_EXIT_MS_ENV="SENPI_RPC_HOST_EMPTY_EXIT_MS",RPC_CLOSE_GRACE_MS_ENV="SENPI_RPC_CLOSE_GRACE_MS",DEFAULT_SESSION_IDLE_EVICTION_MS=30*6e4,DEFAULT_HOST_EMPTY_EXIT_MS=15*6e4;function resolveHostIdlePolicy(env,overrides={}){return{now:overrides.now??Date.now,idleEvictionMs:overrides.idleEvictionMs??parseIdleExitMs(env[RPC_SESSION_IDLE_EVICTION_MS_ENV])??DEFAULT_SESSION_IDLE_EVICTION_MS,emptyExitMs:overrides.emptyExitMs??parseIdleExitMs(env[RPC_HOST_EMPTY_EXIT_MS_ENV])??DEFAULT_HOST_EMPTY_EXIT_MS}}var HOST_RSS_WARN_MB_ENV="SENPI_RPC_HOST_RSS_WARN_MB",DEFAULT_HOST_RSS_WARN_MB=4096,HOST_MEMORY_SAMPLE_MS=3e4,HOST_MEMORY_STDERR_INTERVAL_MS=5*6e4,BYTES_PER_MEGABYTE=1024*1024;function parsePositiveInteger(value){if(value===void 0||!/^\d+$/.test(value.trim()))return;let parsed=Number(value.trim());return Number.isFinite(parsed)&&parsed>0?parsed:void 0}var HostMemorySampler=class{constructor(options){this.pressure=!1,this.idleReported=!1;let env=options.env??process.env;this.emit=options.emit,this.sessions=options.sessions,this.onPressure=options.onPressure,options.onIdlePressure&&(this.onIdlePressure=options.onIdlePressure),this.log=options.log??(message=>{process.stderr.write(message)}),this.now=options.now??Date.now,this.readFootprint=options.readFootprint??readOwnFootprint,this.readRssBytes=options.readRssBytes??(()=>process.memoryUsage.rss()),this.warnMb=parsePositiveInteger(env[HOST_RSS_WARN_MB_ENV])??DEFAULT_HOST_RSS_WARN_MB}start(){this.timer===void 0&&(this.timer=setInterval(()=>this.sample(),HOST_MEMORY_SAMPLE_MS),this.timer.unref?.())}stop(){this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0)}sample(){let footprint=this.readFootprint(),reading={footprintMb:Math.round(footprint.bytes/BYTES_PER_MEGABYTE),measure:footprint.measure,rssMb:Math.round(this.readRssBytes()/BYTES_PER_MEGABYTE)};if(reading.footprintMb<=this.warnMb){if(this.idleReported=!1,!this.pressure)return;this.pressure=!1,this.onPressure(!1);return}this.pressure||(this.pressure=!0,this.onPressure(!0));let sessions=this.sessions();sessions>0?this.idleReported=!1:this.idleReported||(this.idleReported=!0,this.onIdlePressure?.(reading));let{footprintMb,measure,rssMb}=reading;this.emit({type:"host_memory_pressure",rssMb,footprintMb,measure,sessions});let now=this.now();this.lastLoggedAt!==void 0&&now-this.lastLoggedAt<HOST_MEMORY_STDERR_INTERVAL_MS||(this.lastLoggedAt=now,this.log(`senpi rpc host memory pressure: footprintMb=${footprintMb} (${measure}) rssMb=${rssMb} sessions=${sessions} (idle parking halved)
|
|
3
3
|
`))}};var blockedMsTotal=0;function recordLoopBlockedMs(driftMs){driftMs>0&&(blockedMsTotal+=driftMs)}function loopBlockedMark(){return blockedMsTotal}function loopBlockedMsSince(mark){return blockedMsTotal-mark}import{AsyncLocalStorage}from"node:async_hooks";var attributionStore=new AsyncLocalStorage,sequence=0,openActivities=new Map,lastFinished;function runWithSessionAttribution(attribution,task){let mark=++sequence;openActivities.set(mark,attribution);let finish=()=>{openActivities.delete(mark)&&(lastFinished={sequence:++sequence,attribution})},awaited=!1;try{let result=attributionStore.run(attribution,task);return isPromiseLike(result)&&(awaited=!0,Promise.resolve(result).then(finish,finish)),result}finally{awaited||finish()}}function isPromiseLike(value){return typeof value=="object"&&value!==null&&"then"in value&&typeof value.then=="function"}function openSessionAttributionSpan(attribution){let ambient=attributionStore.getStore(),merged={sessionId:attribution.sessionId??ambient?.sessionId,tool:attribution.tool},mark=++sequence;return openActivities.set(mark,merged),()=>{openActivities.delete(mark)&&(lastFinished={sequence:++sequence,attribution:merged})}}function sessionActivityMark(){return sequence}function sessionActivitySince(mark){if(lastFinished!==void 0&&lastFinished.sequence>mark)return lastFinished.attribution;let newest;for(let attribution of openActivities.values())newest=attribution;return newest}function toolRecord(record){if(!(!("type"in record)||typeof record.type!="string"))return{type:record.type,toolCallId:"toolCallId"in record&&typeof record.toolCallId=="string"?record.toolCallId:void 0,toolName:"toolName"in record&&typeof record.toolName=="string"?record.toolName:void 0}}function createToolAttributionSpans(sessionId){let spans=new Map,closeAll=()=>{for(let close of spans.values())close();spans.clear()};return{closeAll,observe:record=>{let parsed=toolRecord(record);if(parsed!==void 0){if(parsed.type==="tool_execution_start"&&parsed.toolCallId!==void 0){spans.get(parsed.toolCallId)?.(),spans.set(parsed.toolCallId,openSessionAttributionSpan({sessionId,tool:parsed.toolName}));return}if(parsed.type==="tool_execution_end"&&parsed.toolCallId!==void 0){spans.get(parsed.toolCallId)?.(),spans.delete(parsed.toolCallId);return}(parsed.type==="agent_settled"||parsed.type==="agent_idle")&&closeAll()}}}}var LOOP_LAG_WARN_MS_ENV="SENPI_RPC_LOOP_LAG_WARN_MS",LOOP_LAG_ERROR_MS_ENV="SENPI_RPC_LOOP_LAG_ERROR_MS",DEFAULT_LOOP_LAG_WARN_MS=500,DEFAULT_LOOP_LAG_ERROR_MS=5e3,LOOP_LAG_TICK_MS=200,LOOP_LAG_WARN_INTERVAL_MS=1e4,BYTES_PER_MB=1024*1024;function describeWindow(processCpuMs,heapDeltaMb){return`cpu=${processCpuMs}ms heap=${heapDeltaMb>=0?"+":""}${heapDeltaMb}MB`}function describeAttribution(attribution){return attribution?.sessionId===void 0&&attribution?.tool===void 0?"no attributed session":`sessionId=${attribution.sessionId??"unknown"}${attribution.tool?` tool=${attribution.tool}`:""}`}var LoopLagWatchdog=class{constructor(options){this.activityMark=0,this.cpuMicrosAtTick=0,this.heapBytesAtTick=0;let env=options.env??process.env;this.emit=options.emit,this.log=options.log??(message=>{process.stderr.write(message)}),this.now=options.now??Date.now,this.cpuUsage=options.cpuUsage??(()=>process.cpuUsage()),this.heapUsed=options.heapUsed??(()=>process.memoryUsage().heapUsed),this.warnMs=parseIdleExitMs(env[LOOP_LAG_WARN_MS_ENV])??DEFAULT_LOOP_LAG_WARN_MS,this.errorMs=parseIdleExitMs(env[LOOP_LAG_ERROR_MS_ENV])??DEFAULT_LOOP_LAG_ERROR_MS}start(){if(this.timer!==void 0)return;this.expectedTickAt=this.now()+LOOP_LAG_TICK_MS,this.activityMark=sessionActivityMark();let cpu=this.cpuUsage();this.cpuMicrosAtTick=cpu.user+cpu.system,this.heapBytesAtTick=this.heapUsed(),this.timer=setInterval(()=>this.tick(),LOOP_LAG_TICK_MS),this.timer.unref?.()}stop(){this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0,this.expectedTickAt=void 0)}tick(){let now=this.now(),expectedAt=this.expectedTickAt??now,previousMark=this.activityMark;this.expectedTickAt=now+LOOP_LAG_TICK_MS,this.activityMark=sessionActivityMark();let cpu=this.cpuUsage(),cpuMicros=cpu.user+cpu.system,heapBytes=this.heapUsed(),previousCpuMicros=this.cpuMicrosAtTick,previousHeapBytes=this.heapBytesAtTick;this.cpuMicrosAtTick=cpuMicros,this.heapBytesAtTick=heapBytes;let driftMs=Math.round(now-expectedAt);if(recordLoopBlockedMs(driftMs),driftMs<=this.warnMs)return;let attribution=sessionActivitySince(previousMark),processCpuMs=Math.round((cpuMicros-previousCpuMicros)/1e3),heapDeltaMb=Math.round((heapBytes-previousHeapBytes)/BYTES_PER_MB);driftMs>this.errorMs&&this.emit({type:"host_stalled",driftMs,sessionId:attribution?.sessionId,tool:attribution?.tool,processCpuMs,heapDeltaMb}),!(this.lastWarnAt!==void 0&&now-this.lastWarnAt<LOOP_LAG_WARN_INTERVAL_MS)&&(this.lastWarnAt=now,this.log(`senpi rpc host stall: event loop blocked ${driftMs}ms (${describeAttribution(attribution)}; ${describeWindow(processCpuMs,heapDeltaMb)})
|
|
4
4
|
`))}};import{access}from"node:fs/promises";import{isAbsolute}from"node:path";var MAX_WARM_PROFILES=64;function profileKey(profile){let context=Object.entries(profile.sessionContext??{}).sort(([a],[b])=>a<b?-1:a>b?1:0);return JSON.stringify([profile.cwd,profile.sessionKind??"interactive",context])}var HostWarmer=class{constructor(load){this.warm=new Set,this.loading=new Map,this.load=load}async run(profile){let key=profileKey(profile);if(this.warm.has(key))return"already_warm";let pending=this.loading.get(key);return pending===void 0&&(pending=this.loadOnce(key,profile),this.loading.set(key,pending)),await pending,"warmed"}async loadOnce(key,profile){try{if(await this.load(profile),this.warm.add(key),this.warm.size>MAX_WARM_PROFILES){let oldest=this.warm.values().next().value;oldest!==void 0&&this.warm.delete(oldest)}}finally{this.loading.delete(key)}}};function createRegistryWarm(prepare,host){let warmer=new HostWarmer(async profile=>{await access(profile.cwd);let launchProfile={cwd:profile.cwd,...profile.sessionKind!==void 0?{sessionKind:profile.sessionKind}:{},...profile.sessionContext!==void 0?{sessionContext:Object.freeze({...profile.sessionContext})}:{}},scope=new ProviderScope;try{await runWithProviderScope(scope,()=>prepare({cwd:profile.cwd,agentDir:host.agentDir,launchProfile:Object.freeze(launchProfile),...host.mcpRegistry!==void 0?{mcpRegistry:host.mcpRegistry}:{}}))}finally{scope.close()}});return profile=>warmer.run(profile)}function refusal(command,code){return{id:command.id,type:"response",command:"warm",success:!1,error:code}}async function answerWarm(command,host){if(host.draining)return refusal(command,"host_draining");let kindError=sessionKindError(command.kind);if(kindError)return refusal(command,`${RPC_ERROR_INVALID_SESSION_KIND}: ${kindError}`);let contextError=sessionContextError(command.context);if(contextError)return refusal(command,`${RPC_ERROR_INVALID_SESSION_CONTEXT}: ${contextError}`);if(host.warm===void 0)return{id:command.id,type:"response",command:"warm",success:!0,data:{state:"unsupported"}};let sessionContext=host.hostContext?{...command.context,...host.hostContext}:command.context,cwd=command.cwd??host.cwd;if(!isAbsolute(cwd))return refusal(command,RPC_ERROR_INVALID_PATH);try{let state=await host.warm({cwd,...command.kind!==void 0?{sessionKind:command.kind}:{},...sessionContext!==void 0?{sessionContext}:{}});return{id:command.id,type:"response",command:"warm",success:!0,data:{state}}}catch(cause){return refusal(command,`${RPC_ERROR_WARM_FAILED}: ${cause instanceof Error?cause.message:String(cause)}`)}}async function createRpcSessionBinding(sessionId,entry,writer,requestClose,options={}){if(entry.worker)return entry.worker.bind(sessionId,writer,requestClose,options);if(!entry.runtime)throw new Error("Session runtime was not created");let toolSpans=createToolAttributionSpans(sessionId),enqueueRecords=chunk=>{for(let line of chunk.split(`
|
|
5
5
|
`)){if(!line)continue;let record=JSON.parse(line);toolSpans.observe(record),writer.enqueue(sessionId,record)}},runtimeHost=new Proxy({},{get(_target,property){if(property==="switchSession"&&entry.switchSession)return entry.switchSession;if(property==="setRebindSession")return callback=>{entry.rebindSession=callback,entry.runtime?.setRebindSession(callback)};let runtime=entry.runtime;if(!runtime)throw new Error("Session runtime was not created");let value=Reflect.get(runtime,property,runtime);return typeof value=="function"?value.bind(runtime):value}}),handler=await runWithProviderScope(entry.scope,async()=>{let taggedSink={writeRaw:bindToProviderScope(enqueueRecords),waitForBackpressure:bindToProviderScope(async()=>{})};return createRpcConnectionHandler(runtimeHost,taggedSink,{sessionId,shutdownHandler:bindToProviderScope(requestClose),disposeRuntime:!1,eventFlushScheduler:flush=>flush(),...options})});return await handler.ready,{handle:command=>runWithProviderScope(entry.scope,()=>handler.handleInputLine(JSON.stringify(command))),cancelPendingExtensionUiRequests:()=>runWithProviderScope(entry.scope,()=>handler.cancelPendingExtensionUiRequests()),pendingPrompts:()=>handler.pendingPrompts(),dispose:()=>(toolSpans.closeAll(),runWithProviderScope(entry.scope,()=>handler.dispose()))}}function isHandoffBusy(snapshot){return isSessionBusySnapshot({...snapshot,hasActiveWakeSource:!1})}function selectDrainVerdicts(registry,inFlight,unreadable){let park=[],gone=[];for(let{sessionId,status,sessionPath}of registry.list()){if(status!=="open"||inFlight(sessionId))continue;let entry=registry.peek(sessionId);!entry||handoffBusy(entry,sessionId,unreadable)||(sessionPath!==void 0&&sessionDirectoryRemoved(sessionPath)?gone.push(sessionId):park.push(sessionId))}return{park,gone}}function handoffBusy(entry,sessionId,unreadable){try{let snapshot=entry.runtime?.session.activitySnapshot;return entry.worker?.handoffBusy===!0||snapshot!==void 0&&isHandoffBusy(snapshot)}catch(cause){return unreadable(sessionId,cause),!1}}function readDrainVerdicts(registry,inFlight){try{return selectDrainVerdicts(registry,inFlight,(sessionId,cause)=>{process.stderr.write(`senpi rpc handoff activity of ${sessionId} unreadable, parking: ${String(cause)}
|