@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,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{isOpenAIResponsesPromptCacheModel}from"./chunk-
|
|
2
|
+
import{isOpenAIResponsesPromptCacheModel}from"./chunk-VLW22GHJ.js";import{Build,Clean,Convert,Create,Decode,Default,DisableParseErrors,EnableParseErrors,Encode,Errors,HasCodec,IsArray,IsBoolean,IsInteger,IsNumber,IsObject,IsString,ParseError,Parser,arguments_exports,settings_exports,typebox_exports,value_exports}from"./chunk-RBCQOIAD.js";import{SERVER_FALLBACK_ABORTED_DIAGNOSTIC,parseServerFallbackReceipt}from"./chunk-X4Q5YSTE.js";import{isAnthropicApiBaseUrl}from"./chunk-BJICJY47.js";import{InMemoryCredentialStore,ModelsError,createProvider,defaultProviderAuthContext,resolveProviderAuth}from"./chunk-Z2N5372Y.js";import{getProviderEnvValue}from"./chunk-5ROMKDLK.js";import{parseStreamingJson}from"./chunk-3W47LTXQ.js";import{AssistantMessageEventStream,createAssistantMessageEventStream}from"./chunk-DMI55M2N.js";import{providerHeadersToRecord}from"./chunk-BQVVQ2LQ.js";import{__commonJS,__export,__require,__toESM}from"./chunk-IKOFCODM.js";var require_identity=__commonJS({"node_modules/yaml/dist/nodes/identity.js"(exports){"use strict";var ALIAS=Symbol.for("yaml.alias"),DOC=Symbol.for("yaml.document"),MAP=Symbol.for("yaml.map"),PAIR=Symbol.for("yaml.pair"),SCALAR=Symbol.for("yaml.scalar"),SEQ=Symbol.for("yaml.seq"),NODE_TYPE=Symbol.for("yaml.node.type"),isAlias=node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===ALIAS,isDocument=node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===DOC,isMap=node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===MAP,isPair=node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===PAIR,isScalar=node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===SCALAR,isSeq=node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===SEQ;function isCollection(node){if(node&&typeof node=="object")switch(node[NODE_TYPE]){case MAP:case SEQ:return!0}return!1}function isNode(node){if(node&&typeof node=="object")switch(node[NODE_TYPE]){case ALIAS:case MAP:case SCALAR:case SEQ:return!0}return!1}var hasAnchor=node=>(isScalar(node)||isCollection(node))&&!!node.anchor;exports.ALIAS=ALIAS;exports.DOC=DOC;exports.MAP=MAP;exports.NODE_TYPE=NODE_TYPE;exports.PAIR=PAIR;exports.SCALAR=SCALAR;exports.SEQ=SEQ;exports.hasAnchor=hasAnchor;exports.isAlias=isAlias;exports.isCollection=isCollection;exports.isDocument=isDocument;exports.isMap=isMap;exports.isNode=isNode;exports.isPair=isPair;exports.isScalar=isScalar;exports.isSeq=isSeq}});var require_visit=__commonJS({"node_modules/yaml/dist/visit.js"(exports){"use strict";var identity=require_identity(),BREAK=Symbol("break visit"),SKIP=Symbol("skip children"),REMOVE=Symbol("remove node");function visit(node,visitor){let visitor_=initVisitor(visitor);identity.isDocument(node)?visit_(null,node.contents,visitor_,Object.freeze([node]))===REMOVE&&(node.contents=null):visit_(null,node,visitor_,Object.freeze([]))}visit.BREAK=BREAK;visit.SKIP=SKIP;visit.REMOVE=REMOVE;function visit_(key,node,visitor,path){let ctrl=callVisitor(key,node,visitor,path);if(identity.isNode(ctrl)||identity.isPair(ctrl))return replaceNode(key,path,ctrl),visit_(key,ctrl,visitor,path);if(typeof ctrl!="symbol"){if(identity.isCollection(node)){path=Object.freeze(path.concat(node));for(let i=0;i<node.items.length;++i){let ci=visit_(i,node.items[i],visitor,path);if(typeof ci=="number")i=ci-1;else{if(ci===BREAK)return BREAK;ci===REMOVE&&(node.items.splice(i,1),i-=1)}}}else if(identity.isPair(node)){path=Object.freeze(path.concat(node));let ck=visit_("key",node.key,visitor,path);if(ck===BREAK)return BREAK;ck===REMOVE&&(node.key=null);let cv=visit_("value",node.value,visitor,path);if(cv===BREAK)return BREAK;cv===REMOVE&&(node.value=null)}}return ctrl}async function visitAsync(node,visitor){let visitor_=initVisitor(visitor);identity.isDocument(node)?await visitAsync_(null,node.contents,visitor_,Object.freeze([node]))===REMOVE&&(node.contents=null):await visitAsync_(null,node,visitor_,Object.freeze([]))}visitAsync.BREAK=BREAK;visitAsync.SKIP=SKIP;visitAsync.REMOVE=REMOVE;async function visitAsync_(key,node,visitor,path){let ctrl=await callVisitor(key,node,visitor,path);if(identity.isNode(ctrl)||identity.isPair(ctrl))return replaceNode(key,path,ctrl),visitAsync_(key,ctrl,visitor,path);if(typeof ctrl!="symbol"){if(identity.isCollection(node)){path=Object.freeze(path.concat(node));for(let i=0;i<node.items.length;++i){let ci=await visitAsync_(i,node.items[i],visitor,path);if(typeof ci=="number")i=ci-1;else{if(ci===BREAK)return BREAK;ci===REMOVE&&(node.items.splice(i,1),i-=1)}}}else if(identity.isPair(node)){path=Object.freeze(path.concat(node));let ck=await visitAsync_("key",node.key,visitor,path);if(ck===BREAK)return BREAK;ck===REMOVE&&(node.key=null);let cv=await visitAsync_("value",node.value,visitor,path);if(cv===BREAK)return BREAK;cv===REMOVE&&(node.value=null)}}return ctrl}function initVisitor(visitor){return typeof visitor=="object"&&(visitor.Collection||visitor.Node||visitor.Value)?Object.assign({Alias:visitor.Node,Map:visitor.Node,Scalar:visitor.Node,Seq:visitor.Node},visitor.Value&&{Map:visitor.Value,Scalar:visitor.Value,Seq:visitor.Value},visitor.Collection&&{Map:visitor.Collection,Seq:visitor.Collection},visitor):visitor}function callVisitor(key,node,visitor,path){if(typeof visitor=="function")return visitor(key,node,path);if(identity.isMap(node))return visitor.Map?.(key,node,path);if(identity.isSeq(node))return visitor.Seq?.(key,node,path);if(identity.isPair(node))return visitor.Pair?.(key,node,path);if(identity.isScalar(node))return visitor.Scalar?.(key,node,path);if(identity.isAlias(node))return visitor.Alias?.(key,node,path)}function replaceNode(key,path,node){let parent=path[path.length-1];if(identity.isCollection(parent))parent.items[key]=node;else if(identity.isPair(parent))key==="key"?parent.key=node:parent.value=node;else if(identity.isDocument(parent))parent.contents=node;else{let pt=identity.isAlias(parent)?"alias":"scalar";throw new Error(`Cannot replace node with ${pt} parent`)}}exports.visit=visit;exports.visitAsync=visitAsync}});var require_directives=__commonJS({"node_modules/yaml/dist/doc/directives.js"(exports){"use strict";var identity=require_identity(),visit=require_visit(),escapeChars={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},escapeTagName=tn=>tn.replace(/[!,[\]{}]/g,ch=>escapeChars[ch]),Directives=class _Directives{constructor(yaml,tags){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},_Directives.defaultYaml,yaml),this.tags=Object.assign({},_Directives.defaultTags,tags)}clone(){let copy=new _Directives(this.yaml,this.tags);return copy.docStart=this.docStart,copy}atDocument(){let res=new _Directives(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:_Directives.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},_Directives.defaultTags);break}return res}add(line,onError){this.atNextDocument&&(this.yaml={explicit:_Directives.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},_Directives.defaultTags),this.atNextDocument=!1);let parts=line.trim().split(/[ \t]+/),name=parts.shift();switch(name){case"%TAG":{if(parts.length!==2&&(onError(0,"%TAG directive should contain exactly two parts"),parts.length<2))return!1;let[handle,prefix]=parts;return this.tags[handle]=prefix,!0}case"%YAML":{if(this.yaml.explicit=!0,parts.length!==1)return onError(0,"%YAML directive should contain exactly one part"),!1;let[version]=parts;if(version==="1.1"||version==="1.2")return this.yaml.version=version,!0;{let isValid=/^\d+\.\d+$/.test(version);return onError(6,`Unsupported YAML version ${version}`,isValid),!1}}default:return onError(0,`Unknown directive ${name}`,!0),!1}}tagName(source,onError){if(source==="!")return"!";if(source[0]!=="!")return onError(`Not a valid tag: ${source}`),null;if(source[1]==="<"){let verbatim=source.slice(2,-1);return verbatim==="!"||verbatim==="!!"?(onError(`Verbatim tags aren't resolved, so ${source} is invalid.`),null):(source[source.length-1]!==">"&&onError("Verbatim tags must end with a >"),verbatim)}let[,handle,suffix]=source.match(/^(.*!)([^!]*)$/s);suffix||onError(`The ${source} tag has no suffix`);let prefix=this.tags[handle];if(prefix)try{return prefix+decodeURIComponent(suffix)}catch(error){return onError(String(error)),null}return handle==="!"?source:(onError(`Could not resolve tag: ${source}`),null)}tagString(tag){for(let[handle,prefix]of Object.entries(this.tags))if(tag.startsWith(prefix))return handle+escapeTagName(tag.substring(prefix.length));return tag[0]==="!"?tag:`!<${tag}>`}toString(doc){let lines=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],tagEntries=Object.entries(this.tags),tagNames;if(doc&&tagEntries.length>0&&identity.isNode(doc.contents)){let tags={};visit.visit(doc.contents,(_key,node)=>{identity.isNode(node)&&node.tag&&(tags[node.tag]=!0)}),tagNames=Object.keys(tags)}else tagNames=[];for(let[handle,prefix]of tagEntries)handle==="!!"&&prefix==="tag:yaml.org,2002:"||(!doc||tagNames.some(tn=>tn.startsWith(prefix)))&&lines.push(`%TAG ${handle} ${prefix}`);return lines.join(`
|
|
3
3
|
`)}};Directives.defaultYaml={explicit:!1,version:"1.2"};Directives.defaultTags={"!!":"tag:yaml.org,2002:"};exports.Directives=Directives}});var require_anchors=__commonJS({"node_modules/yaml/dist/doc/anchors.js"(exports){"use strict";var identity=require_identity(),visit=require_visit();function anchorIsValid(anchor){if(/[\x00-\x19\s,[\]{}]/.test(anchor)){let msg=`Anchor must not contain whitespace or control characters: ${JSON.stringify(anchor)}`;throw new Error(msg)}return!0}function anchorNames(root){let anchors=new Set;return visit.visit(root,{Value(_key,node){node.anchor&&anchors.add(node.anchor)}}),anchors}function findNewAnchor(prefix,exclude){for(let i=1;;++i){let name=`${prefix}${i}`;if(!exclude.has(name))return name}}function createNodeAnchors(doc,prefix){let aliasObjects=[],sourceObjects=new Map,prevAnchors=null;return{onAnchor:source=>{aliasObjects.push(source),prevAnchors??(prevAnchors=anchorNames(doc));let anchor=findNewAnchor(prefix,prevAnchors);return prevAnchors.add(anchor),anchor},setAnchors:()=>{for(let source of aliasObjects){let ref=sourceObjects.get(source);if(typeof ref=="object"&&ref.anchor&&(identity.isScalar(ref.node)||identity.isCollection(ref.node)))ref.node.anchor=ref.anchor;else{let error=new Error("Failed to resolve repeated object (this should not happen)");throw error.source=source,error}}},sourceObjects}}exports.anchorIsValid=anchorIsValid;exports.anchorNames=anchorNames;exports.createNodeAnchors=createNodeAnchors;exports.findNewAnchor=findNewAnchor}});var require_applyReviver=__commonJS({"node_modules/yaml/dist/doc/applyReviver.js"(exports){"use strict";function applyReviver(reviver,obj,key,val){if(val&&typeof val=="object")if(Array.isArray(val))for(let i=0,len=val.length;i<len;++i){let v0=val[i],v1=applyReviver(reviver,val,String(i),v0);v1===void 0?delete val[i]:v1!==v0&&(val[i]=v1)}else if(val instanceof Map)for(let k of Array.from(val.keys())){let v0=val.get(k),v1=applyReviver(reviver,val,k,v0);v1===void 0?val.delete(k):v1!==v0&&val.set(k,v1)}else if(val instanceof Set)for(let v0 of Array.from(val)){let v1=applyReviver(reviver,val,v0,v0);v1===void 0?val.delete(v0):v1!==v0&&(val.delete(v0),val.add(v1))}else for(let[k,v0]of Object.entries(val)){let v1=applyReviver(reviver,val,k,v0);v1===void 0?delete val[k]:v1!==v0&&(val[k]=v1)}return reviver.call(obj,key,val)}exports.applyReviver=applyReviver}});var require_toJS=__commonJS({"node_modules/yaml/dist/nodes/toJS.js"(exports){"use strict";var identity=require_identity();function toJS(value,arg,ctx){if(Array.isArray(value))return value.map((v,i)=>toJS(v,String(i),ctx));if(value&&typeof value.toJSON=="function"){if(!ctx||!identity.hasAnchor(value))return value.toJSON(arg,ctx);let data={aliasCount:0,count:1,res:void 0};ctx.anchors.set(value,data),ctx.onCreate=res2=>{data.res=res2,delete ctx.onCreate};let res=value.toJSON(arg,ctx);return ctx.onCreate&&ctx.onCreate(res),res}return typeof value=="bigint"&&!ctx?.keep?Number(value):value}exports.toJS=toJS}});var require_Node=__commonJS({"node_modules/yaml/dist/nodes/Node.js"(exports){"use strict";var applyReviver=require_applyReviver(),identity=require_identity(),toJS=require_toJS(),NodeBase=class{constructor(type){Object.defineProperty(this,identity.NODE_TYPE,{value:type})}clone(){let copy=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(copy.range=this.range.slice()),copy}toJS(doc,{mapAsMap,maxAliasCount,onAnchor,reviver}={}){if(!identity.isDocument(doc))throw new TypeError("A document argument is required");let ctx={anchors:new Map,doc,keep:!0,mapAsMap:mapAsMap===!0,mapKeyWarned:!1,maxAliasCount:typeof maxAliasCount=="number"?maxAliasCount:100},res=toJS.toJS(this,"",ctx);if(typeof onAnchor=="function")for(let{count,res:res2}of ctx.anchors.values())onAnchor(res2,count);return typeof reviver=="function"?applyReviver.applyReviver(reviver,{"":res},"",res):res}};exports.NodeBase=NodeBase}});var require_Alias=__commonJS({"node_modules/yaml/dist/nodes/Alias.js"(exports){"use strict";var anchors=require_anchors(),visit=require_visit(),identity=require_identity(),Node=require_Node(),toJS=require_toJS(),Alias=class extends Node.NodeBase{constructor(source){super(identity.ALIAS),this.source=source,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(doc,ctx){if(ctx?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let nodes;ctx?.aliasResolveCache?nodes=ctx.aliasResolveCache:(nodes=[],visit.visit(doc,{Node:(_key,node)=>{(identity.isAlias(node)||identity.hasAnchor(node))&&nodes.push(node)}}),ctx&&(ctx.aliasResolveCache=nodes));let found;for(let node of nodes){if(node===this)break;node.anchor===this.source&&(found=node)}if(found&&ctx){let{anchors:anchors2,doc:doc2,maxAliasCount}=ctx,data=anchors2.get(found);if(data||(toJS.toJS(found,null,ctx),data=anchors2.get(found)),data?.res===void 0){let msg="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(msg)}if(maxAliasCount>=0&&(data.count+=1,data.aliasCount===0&&(data.aliasCount=getAliasCount(doc2,found,anchors2)),data.count*data.aliasCount>maxAliasCount)){let msg="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(msg)}}return found}toJSON(_arg,ctx){if(!ctx)return{source:this.source};let source=this.resolve(ctx.doc,ctx);if(!source){let msg=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(msg)}return ctx.anchors.get(source).res}toString(ctx,_onComment,_onChompKeep){let src=`*${this.source}`;if(ctx){if(anchors.anchorIsValid(this.source),ctx.options.verifyAliasOrder&&!ctx.anchors.has(this.source)){let msg=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(msg)}if(ctx.implicitKey)return`${src} `}return src}};function getAliasCount(doc,node,anchors2){if(identity.isAlias(node)){let source=node.resolve(doc),anchor=anchors2&&source&&anchors2.get(source);return anchor?anchor.count*anchor.aliasCount:0}else if(identity.isCollection(node)){let count=0;for(let item of node.items){let c=getAliasCount(doc,item,anchors2);c>count&&(count=c)}return count}else if(identity.isPair(node)){let kc=getAliasCount(doc,node.key,anchors2),vc=getAliasCount(doc,node.value,anchors2);return Math.max(kc,vc)}return 1}exports.Alias=Alias}});var require_Scalar=__commonJS({"node_modules/yaml/dist/nodes/Scalar.js"(exports){"use strict";var identity=require_identity(),Node=require_Node(),toJS=require_toJS(),isScalarValue=value=>!value||typeof value!="function"&&typeof value!="object",Scalar=class extends Node.NodeBase{constructor(value){super(identity.SCALAR),this.value=value}toJSON(arg,ctx){return ctx?.keep?this.value:toJS.toJS(this.value,arg,ctx)}toString(){return String(this.value)}};Scalar.BLOCK_FOLDED="BLOCK_FOLDED";Scalar.BLOCK_LITERAL="BLOCK_LITERAL";Scalar.PLAIN="PLAIN";Scalar.QUOTE_DOUBLE="QUOTE_DOUBLE";Scalar.QUOTE_SINGLE="QUOTE_SINGLE";exports.Scalar=Scalar;exports.isScalarValue=isScalarValue}});var require_createNode=__commonJS({"node_modules/yaml/dist/doc/createNode.js"(exports){"use strict";var Alias=require_Alias(),identity=require_identity(),Scalar=require_Scalar(),defaultTagPrefix="tag:yaml.org,2002:";function findTagObject(value,tagName,tags){if(tagName){let match=tags.filter(t=>t.tag===tagName),tagObj=match.find(t=>!t.format)??match[0];if(!tagObj)throw new Error(`Tag ${tagName} not found`);return tagObj}return tags.find(t=>t.identify?.(value)&&!t.format)}function createNode(value,tagName,ctx){if(identity.isDocument(value)&&(value=value.contents),identity.isNode(value))return value;if(identity.isPair(value)){let map=ctx.schema[identity.MAP].createNode?.(ctx.schema,null,ctx);return map.items.push(value),map}(value instanceof String||value instanceof Number||value instanceof Boolean||typeof BigInt<"u"&&value instanceof BigInt)&&(value=value.valueOf());let{aliasDuplicateObjects,onAnchor,onTagObj,schema,sourceObjects}=ctx,ref;if(aliasDuplicateObjects&&value&&typeof value=="object"){if(ref=sourceObjects.get(value),ref)return ref.anchor??(ref.anchor=onAnchor(value)),new Alias.Alias(ref.anchor);ref={anchor:null,node:null},sourceObjects.set(value,ref)}tagName?.startsWith("!!")&&(tagName=defaultTagPrefix+tagName.slice(2));let tagObj=findTagObject(value,tagName,schema.tags);if(!tagObj){if(value&&typeof value.toJSON=="function"&&(value=value.toJSON()),!value||typeof value!="object"){let node2=new Scalar.Scalar(value);return ref&&(ref.node=node2),node2}tagObj=value instanceof Map?schema[identity.MAP]:Symbol.iterator in Object(value)?schema[identity.SEQ]:schema[identity.MAP]}onTagObj&&(onTagObj(tagObj),delete ctx.onTagObj);let node=tagObj?.createNode?tagObj.createNode(ctx.schema,value,ctx):typeof tagObj?.nodeClass?.from=="function"?tagObj.nodeClass.from(ctx.schema,value,ctx):new Scalar.Scalar(value);return tagName?node.tag=tagName:tagObj.default||(node.tag=tagObj.tag),ref&&(ref.node=node),node}exports.createNode=createNode}});var require_Collection=__commonJS({"node_modules/yaml/dist/nodes/Collection.js"(exports){"use strict";var createNode=require_createNode(),identity=require_identity(),Node=require_Node();function collectionFromPath(schema,path,value){let v=value;for(let i=path.length-1;i>=0;--i){let k=path[i];if(typeof k=="number"&&Number.isInteger(k)&&k>=0){let a=[];a[k]=v,v=a}else v=new Map([[k,v]])}return createNode.createNode(v,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema,sourceObjects:new Map})}var isEmptyPath=path=>path==null||typeof path=="object"&&!!path[Symbol.iterator]().next().done,Collection=class extends Node.NodeBase{constructor(type,schema){super(type),Object.defineProperty(this,"schema",{value:schema,configurable:!0,enumerable:!1,writable:!0})}clone(schema){let copy=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return schema&&(copy.schema=schema),copy.items=copy.items.map(it=>identity.isNode(it)||identity.isPair(it)?it.clone(schema):it),this.range&&(copy.range=this.range.slice()),copy}addIn(path,value){if(isEmptyPath(path))this.add(value);else{let[key,...rest]=path,node=this.get(key,!0);if(identity.isCollection(node))node.addIn(rest,value);else if(node===void 0&&this.schema)this.set(key,collectionFromPath(this.schema,rest,value));else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`)}}deleteIn(path){let[key,...rest]=path;if(rest.length===0)return this.delete(key);let node=this.get(key,!0);if(identity.isCollection(node))return node.deleteIn(rest);throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`)}getIn(path,keepScalar){let[key,...rest]=path,node=this.get(key,!0);return rest.length===0?!keepScalar&&identity.isScalar(node)?node.value:node:identity.isCollection(node)?node.getIn(rest,keepScalar):void 0}hasAllNullValues(allowScalar){return this.items.every(node=>{if(!identity.isPair(node))return!1;let n=node.value;return n==null||allowScalar&&identity.isScalar(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(path){let[key,...rest]=path;if(rest.length===0)return this.has(key);let node=this.get(key,!0);return identity.isCollection(node)?node.hasIn(rest):!1}setIn(path,value){let[key,...rest]=path;if(rest.length===0)this.set(key,value);else{let node=this.get(key,!0);if(identity.isCollection(node))node.setIn(rest,value);else if(node===void 0&&this.schema)this.set(key,collectionFromPath(this.schema,rest,value));else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`)}}};exports.Collection=Collection;exports.collectionFromPath=collectionFromPath;exports.isEmptyPath=isEmptyPath}});var require_stringifyComment=__commonJS({"node_modules/yaml/dist/stringify/stringifyComment.js"(exports){"use strict";var stringifyComment=str=>str.replace(/^(?!$)(?: $)?/gm,"#");function indentComment(comment,indent){return/^\n+$/.test(comment)?comment.substring(1):indent?comment.replace(/^(?! *$)/gm,indent):comment}var lineComment=(str,indent,comment)=>str.endsWith(`
|
|
4
4
|
`)?indentComment(comment,indent):comment.includes(`
|
|
5
5
|
`)?`
|
|
@@ -141,7 +141,7 @@ ${end.comment}`:end.comment}this.doc.range[2]=end.offset;break}default:this.erro
|
|
|
141
141
|
`)}function extractUserMessageText(msg){if(msg.role!=="user")return"";let content=msg.content;return typeof content=="string"?content.trim():content.filter(c=>c.type==="text").map(c=>c.text).join(`
|
|
142
142
|
`).trim()}function hasUserMessageImages(msg){return msg.role==="user"&&Array.isArray(msg.content)&&msg.content.some(item=>item.type==="image")}function buildCursorRootPromptContent(content){if(typeof content=="string"){let text=content.trim();return text?[{type:"text",text}]:[]}let parts=[];for(let item of content)if(item.type==="text"){let text=item.text.trim();text&&parts.push({type:"text",text})}else parts.push({type:"image",image:`data:${item.mimeType};base64,${item.data}`,mediaType:item.mimeType});return parts}function cursorUserContentKey(content){if(typeof content=="string")return content.trim();let hash=createHash("sha256");for(let item of content)hash.update(item.type),item.type==="text"?hash.update(item.text):(hash.update(item.mimeType),hash.update(item.data));return hash.digest("hex")}function buildCursorAssistantContent(msg){let content=[];for(let item of msg.content)item.type==="text"?item.text&&content.push({type:"text",text:item.text}):item.type==="toolCall"&&content.push({type:"tool-call",toolCallId:item.id,toolName:item.name,args:item.arguments});return content}function findLastUserMessageIndex(messages){for(let i=messages.length-1;i>=0;i--)if(messages[i].role==="user")return i;return-1}function buildRootPromptMessagesJson(messages,systemPromptIds,blobStore,activeUserMessageIndex=findLastUserMessageIndex(messages)){let entries=[...systemPromptIds],pushJson=obj=>{let bytes=new TextEncoder().encode(JSON.stringify(obj));entries.push(storeCursorBlob(blobStore,bytes))};for(let i=0;i<messages.length&&i!==activeUserMessageIndex;i++){let msg=messages[i];if(msg.role==="user"){let content=buildCursorRootPromptContent(msg.content);if(content.length===0)continue;pushJson({role:"user",content})}else if(msg.role==="assistant"){let content=buildCursorAssistantContent(msg);if(content.length===0)continue;pushJson({role:"assistant",content})}else msg.role==="toolResult"&&pushJson({role:"tool",id:msg.toolCallId,content:[{type:"tool-result",toolName:msg.toolName,toolCallId:msg.toolCallId,result:toolResultToText(msg),...msg.isError?{isError:!0}:{}}]})}return entries}function isPlainRecord(value){if(value===null||typeof value!="object"||Array.isArray(value))return!1;let prototype=Object.getPrototypeOf(value);return prototype===Object.prototype||prototype===null}function isJsonValue(value){if(value===null||typeof value=="string"||typeof value=="boolean")return!0;if(typeof value=="number")return Number.isFinite(value);if(Array.isArray(value))return value.every(isJsonValue);if(!isPlainRecord(value))return!1;for(let key in value)if(!isJsonValue(value[key]))return!1;return!0}function encodeCursorMcpArguments(toolCall){let encoded={};for(let name in toolCall.arguments){let value=toolCall.arguments[name];if(value!==void 0){if(!isJsonValue(value))throw new Error(`Cursor tool argument ${toolCall.name}.${name} is not JSON-serializable`);encoded[name]=toBinary(ValueSchema,fromJson(ValueSchema,value))}}return encoded}function createCursorMcpResult(result){return result.isError?create(McpToolResultSchema,{result:{case:"error",value:create(McpToolErrorSchema,{error:toolResultToText(result)})}}):create(McpToolResultSchema,{result:{case:"success",value:create(McpSuccessSchema,{content:result.content.map(item=>item.type==="text"?create(McpToolResultContentItemSchema,{content:{case:"text",value:create(McpTextContentSchema,{text:item.text})}}):create(McpToolResultContentItemSchema,{content:{case:"image",value:create(McpImageContentSchema,{data:Uint8Array.from(Uint8Array.from(atob(item.data),c=>c.charCodeAt(0))),mimeType:item.mimeType})}}))})}})}function createCursorToolCallStep(toolCall,result){let mcpCall=create(McpToolCallSchema,{args:create(McpArgsSchema,{name:toolCall.name,args:encodeCursorMcpArguments(toolCall),toolCallId:toolCall.id,providerIdentifier:"pi-agent",toolName:toolCall.name}),...result?{result:createCursorMcpResult(result)}:{}});return create(ConversationStepSchema,{message:{case:"toolCall",value:create(ToolCallSchema,{tool:{case:"mcpToolCall",value:mcpCall},toolCallId:toolCall.id})}})}function buildConversationTurns(messages,blobStore,activeUserMessageIndex=findLastUserMessageIndex(messages)){let turns=[],historyEnd=activeUserMessageIndex>=0?activeUserMessageIndex:messages.length,toolResults=new Map,pairedToolCallIds=new Set;for(let index=0;index<historyEnd;index++){let message=messages[index];if(message.role==="toolResult")toolResults.set(message.toolCallId,message);else if(message.role==="assistant")for(let item of message.content)item.type==="toolCall"&&pairedToolCallIds.add(item.id)}let i=0;for(;i<messages.length;){let msg=messages[i];if(msg.role!=="user"){i++;continue}if(i===activeUserMessageIndex)break;let userText=extractUserMessageText(msg);if(userText.length===0&&!hasUserMessageImages(msg)){i++;continue}let userMessage=createCursorUserMessage(msg.content,userText,deterministicUuid(`u:${turns.length}:${cursorUserContentKey(msg.content)}`)),userMessageBlobId=storeCursorBlob(blobStore,toBinary(UserMessageSchema,userMessage)),stepBlobIds=[];for(i++;i<messages.length&&messages[i].role!=="user";){let stepMsg=messages[i];if(stepMsg.role==="assistant")for(let item of stepMsg.content){let step;if(item.type==="text"){if(!item.text)continue;step=create(ConversationStepSchema,{message:{case:"assistantMessage",value:create(AssistantMessageSchema,{text:item.text})}})}else{if(item.type==="thinking")continue;if(item.type==="toolCall")step=createCursorToolCallStep(item,toolResults.get(item.id));else continue}stepBlobIds.push(storeCursorBlob(blobStore,toBinary(ConversationStepSchema,step)))}else if(stepMsg.role==="toolResult"&&!pairedToolCallIds.has(stepMsg.toolCallId)){let text=toolResultToText(stepMsg);if(text){let prefix=stepMsg.isError?"[Tool Error]":"[Tool Result]",step=create(ConversationStepSchema,{message:{case:"assistantMessage",value:create(AssistantMessageSchema,{text:`${prefix}
|
|
143
143
|
${text}`})}});stepBlobIds.push(storeCursorBlob(blobStore,toBinary(ConversationStepSchema,step)))}}i++}let agentTurn=create(AgentConversationTurnStructureSchema,{userMessage:userMessageBlobId,steps:stepBlobIds}),turn=create(ConversationTurnStructureSchema,{turn:{case:"agentConversationTurn",value:agentTurn}});turns.push(storeCursorBlob(blobStore,toBinary(ConversationTurnStructureSchema,turn)))}return turns}function createCursorUserMessage(content,text,messageId=randomUUID()){let images=typeof content=="string"?[]:extractImages(content);return create(UserMessageSchema,{text,messageId,...images.length>0?{selectedContext:create(SelectedContextSchema,{selectedImages:images})}:{}})}function extractImages(content){return content.filter(item=>item.type==="image").map(image=>create(SelectedImageSchema,{uuid:randomUUID(),mimeType:image.mimeType,dataOrBlobId:{case:"data",value:Uint8Array.from(atob(image.data),c=>c.charCodeAt(0))}}))}function measureCursorModelInputSerializedBytes(messages,activeUserMessageIndex=findLastUserMessageIndex(messages)){let blobStore=new Map,total=0;for(let blobId of buildRootPromptMessagesJson(messages,[],blobStore,activeUserMessageIndex))total+=readCursorBlob(blobStore,blobId).byteLength;return total}function measureCursorHistorySerializedBytes(messages,activeUserMessageIndex=findLastUserMessageIndex(messages)){return buildCursorHistoryWireBytesForTest(messages,activeUserMessageIndex).reduce((total,bytes)=>total+bytes.byteLength,0)}function buildCursorHistoryWireBytesForTest(messages,activeUserMessageIndex=findLastUserMessageIndex(messages)){let blobStore=new Map;return buildRootPromptMessagesJson(messages,[],blobStore,activeUserMessageIndex),buildConversationTurns(messages,blobStore,activeUserMessageIndex),[...blobStore.values()]}function piReadArgs(path,offset,limit){return limit!==void 0&&Math.floor(limit)<=0?null:{path,offset:offset!==void 0?Math.max(1,Math.floor(offset)):void 0,limit:limit!==void 0?Math.floor(limit):void 0}}function piLsPath(basePath){return basePath||"."}function piLimit(limit){return limit===void 0?void 0:Math.max(1,Math.floor(limit))}function piTimeout(timeout){return timeout!==void 0&&timeout>=0?timeout:void 0}function composeShellCommand(command,workingDirectory){return workingDirectory?`cd ${`'${workingDirectory.replace(/'/g,"'\\''")}'`} && { ${command}
|
|
144
|
-
}`:command}function omitUndefinedArgs(args){let out={};for(let key of Object.keys(args)){let value=args[key];value!==void 0&&(out[key]=value)}return out}var warmers=new Map;function registerPromptCacheWarmer(api,warmer){warmers.set(api,warmer)}function getPromptCacheWarmer(api){return warmers.get(api)}async function warmPromptCache(model,context,options={}){if(isOpenAIResponsesPromptCacheModel(model)){if((options.cacheRetention??model.cacheRetention)==="none")return{supported:!1};let warmer=getPromptCacheWarmer(model.api);if(warmer===void 0)return{supported:!1};let{usage,usageRaw:usageRaw2}=await warmer(model,context,options);return{supported:!0,usage:{input:usage.input,output:usage.output,cacheRead:usage.cacheRead,cacheWrite:usage.cacheWrite,cost:usage.cost},usageRaw:usageRaw2}}if(model.api!=="anthropic-messages"||!isAnthropicApiBaseUrl(model.baseUrl))return{supported:!1};let anthropicModel=model,[{default:Anthropic},{buildAnthropicWarmPromptCacheParams}]=await Promise.all([import("./sdk-2OVOFKEU.js"),import("./anthropic-messages-
|
|
144
|
+
}`:command}function omitUndefinedArgs(args){let out={};for(let key of Object.keys(args)){let value=args[key];value!==void 0&&(out[key]=value)}return out}var warmers=new Map;function registerPromptCacheWarmer(api,warmer){warmers.set(api,warmer)}function getPromptCacheWarmer(api){return warmers.get(api)}async function warmPromptCache(model,context,options={}){if(isOpenAIResponsesPromptCacheModel(model)){if((options.cacheRetention??model.cacheRetention)==="none")return{supported:!1};let warmer=getPromptCacheWarmer(model.api);if(warmer===void 0)return{supported:!1};let{usage,usageRaw:usageRaw2}=await warmer(model,context,options);return{supported:!0,usage:{input:usage.input,output:usage.output,cacheRead:usage.cacheRead,cacheWrite:usage.cacheWrite,cost:usage.cost},usageRaw:usageRaw2}}if(model.api!=="anthropic-messages"||!isAnthropicApiBaseUrl(model.baseUrl))return{supported:!1};let anthropicModel=model,[{default:Anthropic},{buildAnthropicWarmPromptCacheParams}]=await Promise.all([import("./sdk-2OVOFKEU.js"),import("./anthropic-messages-HEVKB3PL.js")]),headers=providerHeadersToRecord(options.headers),client=new Anthropic({apiKey:options.apiKey??null,baseURL:anthropicModel.baseUrl,dangerouslyAllowBrowser:!0,fetch:options.fetch,defaultHeaders:{...anthropicModel.headers,...headers}}),params=buildAnthropicWarmPromptCacheParams(anthropicModel,context,options),transformed=await options.onPayload?.(params,anthropicModel,{model:anthropicModel,headers});transformed!==void 0&&(params=transformed);let sanitized={...params};delete sanitized.stream,delete sanitized.thinking,delete sanitized.output_config,delete sanitized.tool_choice,sanitized.max_tokens=0;let usageRaw=(await client.beta.messages.create(sanitized,{maxRetries:0,...options.signal?{signal:options.signal}:{},...options.timeoutMs!==void 0?{timeout:options.timeoutMs}:{}})).usage;return{supported:!0,usage:{input:usageRaw.input_tokens,output:usageRaw.output_tokens,cacheRead:usageRaw.cache_read_input_tokens??0,cacheWrite:usageRaw.cache_creation_input_tokens??0},usageRaw}}var DEFAULT_API="faux",DEFAULT_PROVIDER="faux",DEFAULT_MODEL_ID="faux-1",DEFAULT_MODEL_NAME="Faux Model",DEFAULT_BASE_URL="http://localhost:0",DEFAULT_MIN_TOKEN_SIZE=3,DEFAULT_MAX_TOKEN_SIZE=5,DEFAULT_USAGE={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function fauxText(text){return{type:"text",text}}function fauxThinking(thinking){return{type:"thinking",thinking}}function fauxToolCall(name,arguments_,options={}){return{type:"toolCall",id:options.id??randomId("tool"),name,arguments:arguments_}}function normalizeFauxAssistantContent(content){return typeof content=="string"?[fauxText(content)]:Array.isArray(content)?content:[content]}function fauxAssistantMessage(content,options={}){return{role:"assistant",content:normalizeFauxAssistantContent(content),api:DEFAULT_API,provider:DEFAULT_PROVIDER,model:DEFAULT_MODEL_ID,usage:DEFAULT_USAGE,stopReason:options.stopReason??"stop",...options.stopDetails===void 0?{}:{stopDetails:options.stopDetails},...options.deferred===void 0?{}:{deferred:options.deferred},...options.errorMessage===void 0?{}:{errorMessage:options.errorMessage},...options.abortSource===void 0?{}:{abortSource:options.abortSource},...options.responseId===void 0?{}:{responseId:options.responseId},timestamp:options.timestamp??Date.now()}}function estimateTokens(text){return Math.ceil(text.length/4)}function randomId(prefix){return`${prefix}:${Date.now()}:${Math.random().toString(36).slice(2)}`}function cloneStreamOptionsForLog(options){if(options)return{...options}}function cloneContextForLog(context){return{...context,messages:structuredClone(context.messages),tools:context.tools?.map(tool=>({name:tool.name,description:tool.description,parameters:structuredClone(tool.parameters),...tool.freeform?{freeform:structuredClone(tool.freeform)}:{}}))}}function contentToText(content){return typeof content=="string"?content:content.map(block=>block.type==="text"?block.text:`[image:${block.mimeType}:${block.data.length}]`).join(`
|
|
145
145
|
`)}function assistantContentToText(content){return content.map(block=>block.type==="text"?block.text:block.type==="thinking"?block.thinking:block.type==="providerNative"?"":`${block.name}:${JSON.stringify(block.arguments)}`).join(`
|
|
146
146
|
`)}function toolResultToText2(message){return[message.toolName,...message.content.map(block=>contentToText([block]))].join(`
|
|
147
147
|
`)}function messageToText(message){return message.role==="user"?contentToText(message.content):message.role==="assistant"?assistantContentToText(message.content):message.role==="configurationUpdate"?"":toolResultToText2(message)}function serializeContext(context){let parts=[];context.systemPrompt&&parts.push(`system:${context.systemPrompt}`);for(let message of context.messages)parts.push(`${message.role}:${messageToText(message)}`);return context.tools?.length&&parts.push(`tools:${JSON.stringify(context.tools)}`),parts.join(`
|
|
@@ -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{source_default}from"./chunk-26UBFF6N.js";import{APP_NAME,CONFIG_DIR_NAME,ENV_AGENT_DIR,ENV_SESSION_DIR,envValue}from"./chunk-WCAKUCN3.js";import{legacyProviderIdRejection}from"./chunk-
|
|
2
|
+
import{source_default}from"./chunk-26UBFF6N.js";import{APP_NAME,CONFIG_DIR_NAME,ENV_AGENT_DIR,ENV_SESSION_DIR,envValue}from"./chunk-WCAKUCN3.js";import{legacyProviderIdRejection}from"./chunk-Z2N5372Y.js";function isGrokNeoEnabled(env=process.env){let value=envValue("ENABLE_GROK_NEO",env);if(value===void 0)return!1;let normalized=value.trim().toLowerCase();return normalized==="1"||normalized==="true"||normalized==="yes"}var SESSION_RUNTIMES=["in-process","worker"];function isSessionRuntimeKind(value){return SESSION_RUNTIMES.includes(value)}function resolveSessionRuntime(parsed){return parsed.sessionRuntime?parsed.sessionRuntime:parsed.listen!==void 0&&parsed.listen!=="stdio://"?"in-process":"worker"}var VALID_THINKING_LEVELS=["off","minimal","low","medium","high","xhigh","max"];function isValidThinkingLevel(level){return VALID_THINKING_LEVELS.includes(level)}function normalizeSessionName(value){let name=value.trim();return name.length>0?name:void 0}function parseArgs(args,options={}){let grokNeoEnabled=options.grokNeoEnabled??isGrokNeoEnabled(),result={messages:[],fileArgs:[],unknownFlags:new Map,diagnostics:[]};for(let i=0;i<args.length;i++){let arg=args[i];if(arg==="--"){for(let positionalArg of args.slice(i+1))positionalArg.startsWith("@")?result.fileArgs.push(positionalArg.slice(1)):result.messages.push(positionalArg);break}else if(arg==="--help"||arg==="-h")result.help=!0;else if(arg==="--version"||arg==="-v")result.version=!0;else if(arg==="--mode"&&i+1<args.length){let mode=args[++i];(mode==="text"||mode==="json"||mode==="rpc")&&(result.mode=mode)}else if(arg==="--continue"||arg==="-c")result.continue=!0;else if(arg==="--resume"||arg==="-r")result.resume=!0;else if(arg==="--provider"&&i+1<args.length){let typedProvider=args[++i],rejection=typedProvider===void 0?void 0:legacyProviderIdRejection(typedProvider);if(rejection)throw new Error(rejection);result.provider=typedProvider}else if(arg==="--model"&&i+1<args.length)result.model=args[++i];else if(arg==="--api-key"&&i+1<args.length)result.apiKey=args[++i];else if(arg==="--system-prompt"&&i+1<args.length)result.systemPrompt=args[++i];else if(arg==="--append-system-prompt"&&i+1<args.length)result.appendSystemPrompt=result.appendSystemPrompt??[],result.appendSystemPrompt.push(args[++i]);else if(arg==="--name"||arg==="-n")i+1<args.length?result.name=args[++i]:result.diagnostics.push({type:"error",message:"--name requires a value"});else if(arg==="--no-session")result.noSession=!0;else if(arg==="--session"&&i+1<args.length)result.session=args[++i];else if(arg==="--session-id"&&i+1<args.length)result.sessionId=args[++i];else if(arg==="--fork"&&i+1<args.length)result.fork=args[++i];else if(arg==="--rebind"&&i+1<args.length)result.rebind=args[++i];else if(arg==="--session-dir"&&i+1<args.length)result.sessionDir=args[++i];else if(arg==="--models"&&i+1<args.length)result.models=args[++i].split(",").map(s=>s.trim());else if(arg==="--no-tools"||arg==="-nt")result.noTools=!0;else if(arg==="--no-builtin-tools"||arg==="-nbt")result.noBuiltinTools=!0;else if((arg==="--tools"||arg==="-t")&&i+1<args.length)result.tools=args[++i].split(",").map(s=>s.trim()).filter(name=>name.length>0);else if((arg==="--exclude-tools"||arg==="-xt")&&i+1<args.length)result.excludeTools=args[++i].split(",").map(s=>s.trim()).filter(name=>name.length>0);else if(arg==="--thinking"&&i+1<args.length){let level=args[++i];isValidThinkingLevel(level)?result.thinking=level:result.diagnostics.push({type:"warning",message:`Invalid thinking level "${level}". Valid values: ${VALID_THINKING_LEVELS.join(", ")}`})}else if(arg==="--print"||arg==="-p"){result.print=!0;let next=args[i+1];next!==void 0&&!next.startsWith("@")&&(!next.startsWith("-")||next.startsWith("---"))&&(result.messages.push(next),i++)}else if(arg==="--export"&&i+1<args.length)result.export=args[++i];else if((arg==="--extension"||arg==="-e")&&i+1<args.length)result.extensions=result.extensions??[],result.extensions.push(args[++i]);else if(arg==="--no-extensions"||arg==="-ne")result.noExtensions=!0;else if(arg==="--skill"&&i+1<args.length)result.skills=result.skills??[],result.skills.push(args[++i]);else if(arg==="--prompt-template"&&i+1<args.length)result.promptTemplates=result.promptTemplates??[],result.promptTemplates.push(args[++i]);else if(arg==="--theme"&&i+1<args.length)result.themes=result.themes??[],result.themes.push(args[++i]);else if(arg==="--use-theme"){let themeName=args[i+1];themeName===void 0||themeName.startsWith("-")?result.diagnostics.push({type:"error",message:"--use-theme requires a theme name"}):(result.useTheme=themeName,i++)}else if(arg==="--no-skills"||arg==="-ns")result.noSkills=!0;else if(arg==="--no-prompt-templates"||arg==="-np")result.noPromptTemplates=!0;else if(arg==="--no-themes")result.noThemes=!0;else if(arg==="--no-context-files"||arg==="-nc")result.noContextFiles=!0;else if(arg==="--list-models")i+1<args.length&&!args[i+1].startsWith("-")&&!args[i+1].startsWith("@")?result.listModels=args[++i]:result.listModels=!0;else if(arg==="--list-tips")result.listTips=!0;else if(arg==="--tui-mode"){let mode=args[i+1];mode==="regular"||mode==="fullscreen"?(result.tuiMode=mode,i++):mode===void 0||mode.startsWith("-")?result.diagnostics.push({type:"error",message:"--tui-mode requires regular or fullscreen"}):(i++,result.diagnostics.push({type:"error",message:`Invalid TUI mode "${mode}". Valid values: regular, fullscreen`}))}else if(arg==="--verbose")result.verbose=!0;else if(arg==="--approve"||arg==="-a")result.projectTrustOverride=!0;else if(arg==="--no-approve"||arg==="-na")result.projectTrustOverride=!1;else if(arg==="--offline")result.offline=!0;else if(grokNeoEnabled&&arg==="--grok-neo")result.grokNeo=!0;else if(arg==="--multi-session")result.multiSession=!0;else if(arg==="--auto-title-sessions")result.autoTitleSessions=!0;else if(arg==="--session-runtime"){let value=args[i+1];value!==void 0&&!value.startsWith("--")&&i++,value!==void 0&&isSessionRuntimeKind(value)?result.sessionRuntime=value:result.diagnostics.push({type:"error",message:"--session-runtime must be in-process or worker"})}else if(arg==="--listen"&&result.mode==="rpc"){let value=args[i+1];value===void 0||value.startsWith("--")?result.diagnostics.push({type:"error",message:"--listen requires a value"}):(result.listen=value,result.multiSession=!0,i++)}else if(arg.startsWith("@"))result.fileArgs.push(arg.slice(1));else if(arg.startsWith("--")){let eqIndex=arg.indexOf("=");if(eqIndex!==-1)result.unknownFlags.set(arg.slice(2,eqIndex),arg.slice(eqIndex+1));else{let flagName=arg.slice(2),next=args[i+1];next!==void 0&&!next.startsWith("-")&&!next.startsWith("@")?(result.unknownFlags.set(flagName,next),i++):result.unknownFlags.set(flagName,!0)}}else arg.startsWith("-")&&!arg.startsWith("--")?result.diagnostics.push({type:"error",message:`Unknown option: ${arg}`}):arg.startsWith("-")||result.messages.push(arg)}return result}function printHelp(extensionFlags,grokNeoEnabled=isGrokNeoEnabled()){let extensionFlagsText=extensionFlags&&extensionFlags.length>0?`
|
|
3
3
|
${source_default.bold("Extension CLI Flags:")}
|
|
4
4
|
${extensionFlags.map(flag=>{let value=flag.type==="string"?" <value>":"",description=flag.description??`Registered by ${flag.extensionPath}`;return` --${flag.name}${value}`.padEnd(30)+description}).join(`
|
|
5
5
|
`)}
|
|
@@ -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{estimateContextTokens}from"./chunk-
|
|
2
|
+
import{estimateContextTokens}from"./chunk-Z2N5372Y.js";var CONTEXT_SAFETY_TOKENS=4096,MIN_ANSWER_TOKENS=1024,MIN_MAX_TOKENS=1,CONTEXT_GUARD_MIN_WINDOW=CONTEXT_SAFETY_TOKENS+MIN_ANSWER_TOKENS,ContextWindowExhaustedError=class extends Error{constructor(estimatedTokens,contextWindow){super(`Context window exhausted: the conversation is estimated at ${estimatedTokens} of ${contextWindow} tokens, leaving fewer than ${MIN_ANSWER_TOKENS} tokens for a response. Compact the conversation, enable auto-compaction, or start a new session before retrying.`),this.name="ContextWindowExhaustedError",this.estimatedTokens=estimatedTokens,this.contextWindow=contextWindow}};function clampMaxTokensToContext(model,context,maxTokens){if(model.contextWindow<=0)return Number.isFinite(maxTokens)&&maxTokens>0?Math.max(MIN_MAX_TOKENS,Math.floor(maxTokens)):MIN_MAX_TOKENS;let estimatedTokens=estimateContextTokens(context).tokens,available=model.contextWindow-estimatedTokens-CONTEXT_SAFETY_TOKENS;if(model.contextWindow>=CONTEXT_GUARD_MIN_WINDOW&&available<MIN_ANSWER_TOKENS)throw new ContextWindowExhaustedError(estimatedTokens,model.contextWindow);let safeAvailable=Math.max(MIN_MAX_TOKENS,available),requested=Number.isFinite(maxTokens)&&maxTokens>0?Math.floor(maxTokens):safeAvailable;return Math.min(requested,safeAvailable)}function applyExtraBody(target,extraBody,reservedKeys){if(extraBody)for(let[key,value]of Object.entries(extraBody))reservedKeys.has(key)||Reflect.set(target,key,value)}var OPENAI_COMPLETIONS_RESERVED_BODY_KEYS=new Set(["model","messages","stream","stream_options","tools","tool_choice","store","temperature","max_tokens","max_completion_tokens","reasoning_effort","reasoning","thinking","enable_thinking","chat_template_kwargs","tool_stream","provider","providerOptions"]),OPENAI_RESPONSES_RESERVED_BODY_KEYS=new Set(["model","input","instructions","stream","tools","tool_choice","parallel_tool_calls","reasoning","max_output_tokens","temperature","text","store","include","prompt_cache_key","prompt_cache_retention","service_tier"]),GOOGLE_RESERVED_BODY_KEYS=new Set(["systemInstruction","tools","toolConfig","temperature","maxOutputTokens","thinkingConfig","responseMimeType","responseSchema","cachedContent","abortSignal","httpOptions"]),ANTHROPIC_RESERVED_BODY_KEYS=new Set(["model","messages","system","stream","tools","tool_choice","temperature","max_tokens","thinking","output_config","metadata"]),MISTRAL_RESERVED_BODY_KEYS=new Set(["model","messages","stream","tools","toolChoice","temperature","maxTokens","promptMode"]);function buildBaseOptions(model,context,options,apiKey){let samplingParams=model.samplingParams||options?.samplingParams?{...model.samplingParams,...options?.samplingParams}:void 0;return{temperature:options?.temperature,samplingParams,maxTokens:clampMaxTokensToContext(model,context,options?.maxTokens??model.maxTokens),signal:options?.signal,abortServerSideFallback:options?.abortServerSideFallback,telemetryContext:options?.telemetryContext,apiKey:apiKey||options?.apiKey,fetch:options?.fetch,transport:options?.transport,cacheRetention:options?.cacheRetention??model.cacheRetention,sessionId:options?.sessionId,headers:options?.headers,extraBody:options?.extraBody,onPayload:options?.onPayload,onResponse:options?.onResponse,timeoutMs:options?.timeoutMs,websocketConnectTimeoutMs:options?.websocketConnectTimeoutMs,maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,metadata:options?.metadata,env:options?.env}}var DEFAULT_THINKING_BUDGETS={minimal:1024,low:2048,medium:8192,high:16384};function clampReasoning(effort){return effort==="xhigh"||effort==="max"?"high":effort}function clampMaxForOpenAI(effort,xhighSupported){return effort==="max"?xhighSupported?"xhigh":"high":effort}function thinkingBudgetForLevel(reasoningLevel,customBudgets){let budgets={...DEFAULT_THINKING_BUDGETS,...customBudgets},level=clampReasoning(reasoningLevel);return budgets[level]}function clampThinkingBudgetToAnswerRoom(thinkingBudget,ceiling){return Math.min(thinkingBudget,Math.max(0,ceiling-MIN_ANSWER_TOKENS))}function adjustMaxTokensForThinking(baseMaxTokens,modelMaxTokens,reasoningLevel,customBudgets){let level=clampReasoning(reasoningLevel);if(!level)return{maxTokens:baseMaxTokens??modelMaxTokens,thinkingBudget:0};let thinkingBudget=thinkingBudgetForLevel(level,customBudgets),maxTokens=baseMaxTokens===void 0?modelMaxTokens:Math.min(baseMaxTokens+thinkingBudget,modelMaxTokens);return maxTokens<=thinkingBudget&&(thinkingBudget=clampThinkingBudgetToAnswerRoom(thinkingBudget,maxTokens)),{maxTokens,thinkingBudget}}export{clampMaxTokensToContext,applyExtraBody,OPENAI_COMPLETIONS_RESERVED_BODY_KEYS,OPENAI_RESPONSES_RESERVED_BODY_KEYS,GOOGLE_RESERVED_BODY_KEYS,ANTHROPIC_RESERVED_BODY_KEYS,MISTRAL_RESERVED_BODY_KEYS,buildBaseOptions,clampMaxForOpenAI,thinkingBudgetForLevel,clampThinkingBudgetToAnswerRoom,adjustMaxTokensForThinking};
|
|
@@ -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{HOST_GENERATION_ENV,HOST_INSTANCE_ID_ENV}from"./chunk-CIRZTP7W.js";import{engineBuildIdentity}from"./chunk-AGVPQLIU.js";import{parseArgs,resolveSessionRuntime}from"./chunk-
|
|
2
|
+
import{HOST_GENERATION_ENV,HOST_INSTANCE_ID_ENV}from"./chunk-CIRZTP7W.js";import{engineBuildIdentity}from"./chunk-AGVPQLIU.js";import{parseArgs,resolveSessionRuntime}from"./chunk-7CQX3QFV.js";import*as crypto from"node:crypto";var CUSTOM_UNSUPPORTED_CAPABILITY="custom_unsupported",EXTENSION_EVENTS_CAPABILITY="extension_events",AUTO_TITLE_SESSIONS_CAPABILITY="auto_title_sessions",MEDIA_PLACEHOLDERS_CAPABILITY="media_placeholders",QUESTION_CAPABILITY="question",RETAIN_ON_DISCONNECT_CAPABILITY="retain_on_disconnect",SESSION_CONTEXT_CAPABILITY="session_context",SESSION_KIND_CAPABILITY="session_kind",AUTO_TITLE_PER_SESSION_CAPABILITY="auto_title_per_session",WARM_CAPABILITY="warm",DURABLE_SESSION_ID_CAPABILITY="durable_session_id",PROMPT_SURFACE_CAPABILITY="prompt_surface",RPC_CLIENT_CAPABILITIES_ENV="SENPI_RPC_CLIENT_CAPABILITIES";function parseClientCapabilities(value){return value?value.split(",").map(part=>part.trim()).filter(part=>part.length>0):[]}var DEFAULT_CUSTOM_EXTENSION_LABEL="custom UI component";function buildCustomUnsupportedRequest(capabilities,extensionName){if(!capabilities?.includes(CUSTOM_UNSUPPORTED_CAPABILITY))return;let name=extensionName.trim()||DEFAULT_CUSTOM_EXTENSION_LABEL;return{type:"extension_ui_request",id:crypto.randomUUID(),method:"custom_unsupported",extensionName:name}}import{createHash,randomUUID as randomUUID2}from"node:crypto";import{resolve}from"node:path";var INSTANCE_ID=resolveInstanceId(process.env[HOST_INSTANCE_ID_ENV]);function resolveInstanceId(value){return value!==void 0&&value.trim()!==""?value:randomUUID2()}function hostInstanceId(){return INSTANCE_ID}var cachedProfile;function hostGeneration(env){let value=env[HOST_GENERATION_ENV];return value!==void 0&&/^\d+$/.test(value)?Number(value):0}function hostLaunchProfile(argv,cwd){let parsed=parseArgs([...argv],{grokNeoEnabled:!1}),core={extensions:[...new Set((parsed.extensions??[]).map(path=>resolve(cwd,path)))].sort(),multi_session:parsed.multiSession===!0,session_runtime:resolveSessionRuntime(parsed)},canonical=JSON.stringify({extensions:core.extensions,multi_session:core.multi_session,session_runtime:core.session_runtime});return{profile_id:createHash("sha256").update(canonical).digest("hex"),core}}function protocolIdentity(){cachedProfile??=hostLaunchProfile(process.argv.slice(2),process.cwd());let build=engineBuildIdentity();return{instanceId:INSTANCE_ID,generation:hostGeneration(process.env),engineVersion:build.text,engineOrdinal:build.ordinal,launch_profile:cachedProfile}}export{CUSTOM_UNSUPPORTED_CAPABILITY,EXTENSION_EVENTS_CAPABILITY,AUTO_TITLE_SESSIONS_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,QUESTION_CAPABILITY,RETAIN_ON_DISCONNECT_CAPABILITY,SESSION_CONTEXT_CAPABILITY,SESSION_KIND_CAPABILITY,AUTO_TITLE_PER_SESSION_CAPABILITY,WARM_CAPABILITY,DURABLE_SESSION_ID_CAPABILITY,PROMPT_SURFACE_CAPABILITY,RPC_CLIENT_CAPABILITIES_ENV,parseClientCapabilities,DEFAULT_CUSTOM_EXTENSION_LABEL,buildCustomUnsupportedRequest,hostInstanceId,hostGeneration,hostLaunchProfile,protocolIdentity};
|
|
@@ -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{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunk-OUG6SDT7.js";import{parseArgs,printHelp}from"./chunk-
|
|
2
|
+
import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunk-OUG6SDT7.js";import{parseArgs,printHelp}from"./chunk-7CQX3QFV.js";import{CONFIG_DIR_NAME,DISPLAY_VERSION,getAgentDir}from"./chunk-WCAKUCN3.js";import{createHash}from"node:crypto";import{existsSync,mkdirSync,readFileSync,renameSync,rmSync,statSync,writeFileSync}from"node:fs";import{dirname,isAbsolute,join}from"node:path";var CACHE_FILE_VERSION=1,MAX_CACHED_SCOPES=8;function cachePath(agentDir){return join(agentDir,"cache","help-flags.json")}function scopeKey(scope){let material=[scope.cwd,scope.noExtensions?"no-extensions":"extensions",scope.projectTrusted?"trusted":"untrusted",...scope.cliExtensionPaths].join("\0");return createHash("sha256").update(material).digest("hex").slice(0,32)}function stamp(path){try{let stats=statSync(path);return stats.isDirectory()?`d:${stats.mtimeMs}`:`f:${stats.mtimeMs}:${stats.size}`}catch{return"absent"}}function discoveryInputs(scope,extensionPaths){let paths=new Set([join(scope.agentDir,"settings.json"),join(scope.agentDir,"extensions"),join(scope.agentDir,"trust.json"),join(scope.cwd,CONFIG_DIR_NAME,"settings.json"),join(scope.cwd,CONFIG_DIR_NAME,"extensions")]);for(let path of extensionPaths)isAbsolute(path)&&(paths.add(path),paths.add(dirname(path)));for(let path of scope.cliExtensionPaths)isAbsolute(path)&&paths.add(path);return[...paths].sort()}function readCacheFile(agentDir){try{let parsed=JSON.parse(readFileSync(cachePath(agentDir),"utf8"));return parsed.version!==CACHE_FILE_VERSION||typeof parsed.scopes!="object"||parsed.scopes===null?void 0:parsed}catch{return}}function readHelpFlagsCache(scope){let cached=readCacheFile(scope.agentDir)?.scopes[scopeKey(scope)];if(!(!cached||cached.appVersion!==DISPLAY_VERSION||!Array.isArray(cached.inputs))){for(let input of cached.inputs)if(stamp(input.path)!==input.state)return;return[...cached.flags]}}function writeHelpFlagsCache(options){let{scope,flags,extensionPaths}=options;try{let scopes={...readCacheFile(scope.agentDir)?.scopes??{}};scopes[scopeKey(scope)]={writtenAt:Date.now(),appVersion:DISPLAY_VERSION,inputs:discoveryInputs(scope,extensionPaths).map(path=>({path,state:stamp(path)})),flags:[...flags]};let keptEntries=Object.entries(scopes).sort(([,left],[,right])=>right.writtenAt-left.writtenAt).slice(0,MAX_CACHED_SCOPES),file={version:CACHE_FILE_VERSION,scopes:Object.fromEntries(keptEntries)},target=cachePath(scope.agentDir);mkdirSync(dirname(target),{recursive:!0});let temporary=`${target}.${process.pid}.tmp`;writeFileSync(temporary,JSON.stringify(file),{mode:384});try{renameSync(temporary,target)}catch(error){throw existsSync(temporary)&&rmSync(temporary,{force:!0}),error}}catch{return}}function isPlainHelpRequest(parsed){return parsed.help===!0&&parsed.print!==!0&&parsed.mode===void 0}function resolveHelpProjectTrust(parsed,cwd,agentDir){return parsed.projectTrustOverride!==void 0?parsed.projectTrustOverride:hasTrustRequiringProjectResources(cwd)?new ProjectTrustStore(agentDir).get(cwd)===!0:!0}function helpFlagsScope(parsed,cwd,agentDir,projectTrusted){return{cwd,agentDir,cliExtensionPaths:[...parsed.extensions??[]],noExtensions:parsed.noExtensions===!0,projectTrusted}}function tryPrintHelpWithoutEngine(argv){let parsed;try{parsed=parseArgs([...argv])}catch{return!1}if(!isPlainHelpRequest(parsed)||parsed.diagnostics.length>0)return!1;if(parsed.noExtensions===!0)return printHelp([]),!0;let flags;try{let cwd=process.cwd(),agentDir=getAgentDir();flags=readHelpFlagsCache(helpFlagsScope(parsed,cwd,agentDir,resolveHelpProjectTrust(parsed,cwd,agentDir)))}catch{return!1}return flags?(printHelp(flags),!0):!1}export{writeHelpFlagsCache,isPlainHelpRequest,resolveHelpProjectTrust,helpFlagsScope,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{getShellConfig}from"./chunk-SH6VUPE4.js";import{getOverflowPatterns}from"./chunk-H2U7247O.js";import{normalizeProviderError}from"./chunk-BBK6SSYT.js";import{extract429RetryAfterMs}from"./chunk-BPX6QWPD.js";import{PROVIDER_NOT_CONFIGURED_PREFIX}from"./chunk-NUS5JXND.js";import{spawn}from"child_process";function sleep(ms,signal){return new Promise((resolve,reject)=>{if(signal?.aborted){reject(new Error("Aborted"));return}let timeout=setTimeout(resolve,ms);signal?.addEventListener("abort",()=>{clearTimeout(timeout),reject(new Error("Aborted"))})})}var COMMAND_EXECUTION_MAX_ATTEMPTS=3,COMMAND_EXECUTION_BACKOFF_MS=[250,1e3],COMMAND_TIMEOUT_MS=1e4,COMMAND_MAX_OUTPUT_BYTES=1024*1024;function runCommandProcess(file,args,options){return new Promise(resolveOutcome=>{let spawnOptions={shell:options.shell,windowsHide:!0,...options.env===void 0?{}:{env:{...process.env,...options.env}}},child=options.stdin===void 0?spawn(file,[...args],{...spawnOptions,stdio:["ignore","pipe","ignore"]}):spawn(file,[...args],{...spawnOptions,stdio:["pipe","pipe","ignore"]}),stdout="",settled=!1,finish=outcome=>{settled||(settled=!0,clearTimeout(timer),resolveOutcome(outcome))},timer=setTimeout(()=>{child.kill("SIGTERM"),child.unref(),finish({executed:!0,value:void 0})},COMMAND_TIMEOUT_MS);child.stdout.setEncoding("utf-8"),child.stdout.on("data",chunk=>{stdout+=chunk,!(stdout.length<=COMMAND_MAX_OUTPUT_BYTES)&&(child.kill("SIGTERM"),finish({executed:!0,value:void 0}))}),child.on("error",error=>finish({executed:error.code!=="ENOENT",value:void 0})),child.on("close",code=>{let value=stdout.trim();finish({executed:!0,value:code===0&&value?value:void 0})}),child.stdin?.end(options.stdin)})}async function executeWithConfiguredShell(command,env){try{let{shell,args,commandTransport}=getShellConfig(),commandFromStdin=commandTransport==="stdin";return await runCommandProcess(shell,commandFromStdin?args:[...args,command],{shell:!1,...commandFromStdin?{stdin:command}:{},...env===void 0?{}:{env}})}catch{return{executed:!1,value:void 0}}}async function executeCommandOnce(command,env){if(process.platform==="win32"){let configured=await executeWithConfiguredShell(command,env);if(configured.executed)return configured.value}return(await runCommandProcess(command,[],{shell:!0,...env===void 0?{}:{env}})).value}async function runConfigCommand(commandConfig,env){let command=commandConfig.slice(1);for(let attempt=0;attempt<COMMAND_EXECUTION_MAX_ATTEMPTS;attempt++){let value=await executeCommandOnce(command,env);if(value!==void 0)return value;let backoffMs=COMMAND_EXECUTION_BACKOFF_MS[attempt];backoffMs!==void 0&&await sleep(backoffMs)}}var commandResultCache=new Map,ENV_VAR_NAME_RE=/^[A-Za-z_][A-Za-z0-9_]*$/,ENV_VAR_NAME_PREFIX_RE=/^[A-Za-z_][A-Za-z0-9_]*/;function appendLiteral(parts,value){if(!value)return;let previousPart=parts[parts.length-1];if(previousPart?.type==="literal"){previousPart.value+=value;return}parts.push({type:"literal",value})}function parseConfigValueTemplate(config){let parts=[],index=0;for(;index<config.length;){let dollarIndex=config.indexOf("$",index);if(dollarIndex<0){appendLiteral(parts,config.slice(index));break}appendLiteral(parts,config.slice(index,dollarIndex));let nextChar=config[dollarIndex+1];if(nextChar==="$"||nextChar==="!"){appendLiteral(parts,nextChar),index=dollarIndex+2;continue}if(nextChar==="{"){let endIndex=config.indexOf("}",dollarIndex+2);if(endIndex<0){appendLiteral(parts,"$"),index=dollarIndex+1;continue}let name=config.slice(dollarIndex+2,endIndex);ENV_VAR_NAME_RE.test(name)?parts.push({type:"env",name}):appendLiteral(parts,config.slice(dollarIndex,endIndex+1)),index=endIndex+1;continue}let match=config.slice(dollarIndex+1).match(ENV_VAR_NAME_PREFIX_RE);if(match){parts.push({type:"env",name:match[0]}),index=dollarIndex+1+match[0].length;continue}appendLiteral(parts,"$"),index=dollarIndex+1}return parts}function parseConfigValueReference(config){return config.startsWith("!")?{type:"command",config}:{type:"template",parts:parseConfigValueTemplate(config)}}function resolveEnvConfigValue(name,env){return env?.[name]||process.env[name]||void 0}function getTemplateEnvVarNames(parts){let names=[];for(let part of parts)part.type!=="env"||names.includes(part.name)||names.push(part.name);return names}function resolveTemplate(parts,env){let resolved="";for(let part of parts){if(part.type==="literal"){resolved+=part.value;continue}let envValue=resolveEnvConfigValue(part.name,env);if(envValue===void 0)return;resolved+=envValue}return resolved}function getConfigValueEnvVarNames(config){let reference=parseConfigValueReference(config);return reference.type==="template"?getTemplateEnvVarNames(reference.parts):[]}function getMissingConfigValueEnvVarNames(config,env){return getConfigValueEnvVarNames(config).filter(name=>resolveEnvConfigValue(name,env)===void 0)}function isCommandConfigValue(config){return parseConfigValueReference(config).type==="command"}function isConfigValueConfigured(config,env){return getMissingConfigValueEnvVarNames(config,env).length===0}function resolveConfigValue(config,env){let reference=parseConfigValueReference(config);return reference.type==="command"?env===void 0?executeCommand(reference.config):runConfigCommand(reference.config,env):Promise.resolve(resolveTemplate(reference.parts,env))}function executeCommand(commandConfig){let cached=commandResultCache.get(commandConfig);if(cached)return cached;let result=runConfigCommand(commandConfig);return commandResultCache.set(commandConfig,result),result}function resolveConfigValueUncached(config,env){let reference=parseConfigValueReference(config);return reference.type==="command"?runConfigCommand(reference.config,env):Promise.resolve(resolveTemplate(reference.parts,env))}async function resolveConfigValueOrThrow(config,description,env){let resolvedValue=await resolveConfigValueUncached(config,env);if(resolvedValue!==void 0)return resolvedValue;let reference=parseConfigValueReference(config);if(reference.type==="command")throw new Error(`Failed to resolve ${description} from shell command: ${reference.config.slice(1)}`);if(reference.type==="template"){let missingEnvVars=getMissingConfigValueEnvVarNames(config,env);if(missingEnvVars.length===1)throw new Error(`Failed to resolve ${description} from environment variable: ${missingEnvVars[0]}`);if(missingEnvVars.length>1)throw new Error(`Failed to resolve ${description} from environment variables: ${missingEnvVars.join(", ")}`)}throw new Error(`Failed to resolve ${description}`)}async function resolveHeadersOrThrow(headers,description,env){if(!headers)return;let resolved={};for(let[key,value]of Object.entries(headers))resolved[key]=await resolveConfigValueOrThrow(value,`${description} header "${key}"`,env);return Object.keys(resolved).length>0?resolved:void 0}var PRE_COMMIT_EVENT_TYPES=new Set(["start","text_start","thinking_start","toolcall_start"]);function isCommittedRotationOutput(event){return!PRE_COMMIT_EVENT_TYPES.has(event.type)}function isRotationStreamStart(event){return event.type==="start"}function rotationErrorFromEvent(event){if(event.type!=="error")return;let failure=new Error(event.error.errorMessage??"provider stream error"),status=event.error.providerDiagnostic?.httpStatus;return status===void 0?failure:Object.assign(failure,{status})}function rendezvousOrder(key,slots,hasher){return[...slots].map(slot=>({slot,score:hasher(`${key}\0${slot.name}`)})).sort((left,right)=>right.score>left.score?1:right.score<left.score?-1:0).map(({slot})=>slot)}var DEFAULT_SLOT_BLOCK_MS=6e4,MAX_SLOT_BLOCK_MS=2880*60*1e3;var COOLDOWN_BASE_MS=DEFAULT_SLOT_BLOCK_MS,COOLDOWN_CAP_MS=MAX_SLOT_BLOCK_MS,RETRY_SAME_MAX_ATTEMPTS=2;function rateLimitCooldown(failureCount,serverHintMs,policy={}){let cap=policy.capMs??COOLDOWN_CAP_MS,base=policy.baseMs??COOLDOWN_BASE_MS,backoff=Math.min(cap,base*2**Math.max(0,failureCount)),floored=serverHintMs===void 0?backoff:Math.max(backoff,serverHintMs);return{cooldownMs:Math.min(cap,floored),retryAfterWasCapped:floored>cap}}var INVALID_KEY_TEXT=/invalid[ _-]?(?:api[ _-]?)?key|authentication[_ ]?error|invalid x-api-key|unauthorized/i,ACCOUNT_SCOPED_403_TEXT=/account|credential|token|api[ _-]?key|organization|subscription/i,RATE_LIMIT_TEXT=/rate[ _-]?limit|too many requests|resource_exhausted/i,BILLING_TEXT=/billing|credits?[ _-]?(?:required|exhausted|balance)|insufficient[ _-]?(?:funds|quota|credit)|payment[ _-]?required|quota[ _-]?exhausted/i,OVERLOAD_TEXT=/overloaded/i,NETWORK_TEXT=/econnreset|econnrefused|etimedout|enotfound|socket hang up|fetch failed|network error|request timed out/i,WEBSOCKET_REQUEST_FAULT_TEXT=/websocket closed 100[89]\b/i,WEBSOCKET_TRANSPORT_FAULT_TEXT=/websocket (?:closed|error|connect timeout|liveness timeout)/i,FAIL_FAST_TEXT=/context[ _-]?(?:length|window)|maximum context|invalid[ _-]?model|model[ _-]?not[ _-]?found|malformed[ _-]?stream|premature[ _-]?(?:close|stream)/i,ABORT_TEXT=/\baborted?\b/i;function isAbort(error,message){return error instanceof Error&&error.name==="AbortError"?!0:ABORT_TEXT.test(message)}function isOverflowText(text){return getOverflowPatterns().some(pattern=>pattern.test(text))}function classifyCredentialFailure(error,context={}){let normalized=normalizeProviderError(error),text=normalized.messageCarriesBody?normalized.message:`${normalized.message} ${normalized.body??""}`,status=normalized.status,failureCount=context.failureCount??0;if(isAbort(error,text))return{kind:"fail_request"};if(text.includes(PROVIDER_NOT_CONFIGURED_PREFIX))return{kind:"failover",block:{reason:"auth_error"}};if(status===401||INVALID_KEY_TEXT.test(text))return{kind:"failover",block:{reason:"auth_error"}};if(status===403)return ACCOUNT_SCOPED_403_TEXT.test(text)?{kind:"failover",block:{reason:"auth_error"}}:{kind:"fail_request"};if(status===402||BILLING_TEXT.test(text))return{kind:"failover",block:{reason:"account_disabled"}};if(status===429||RATE_LIMIT_TEXT.test(text)){let hint=extract429RetryAfterMs({status:status??429,bodyText:text});return{kind:"failover",block:{reason:"rate_limit",...rateLimitCooldown(failureCount,hint,{baseMs:context.cooldownBaseMs,capMs:context.cooldownCapMs})}}}return isOverflowText(text)||status===400||status===404||FAIL_FAST_TEXT.test(text)?{kind:"fail_request"}:WEBSOCKET_REQUEST_FAULT_TEXT.test(text)?{kind:"fail_request"}:WEBSOCKET_TRANSPORT_FAULT_TEXT.test(text)?{kind:"retry_same",maxAttempts:RETRY_SAME_MAX_ATTEMPTS}:status===529||OVERLOAD_TEXT.test(text)||status!==void 0&&status>=500&&status<600?{kind:"retry_same",maxAttempts:RETRY_SAME_MAX_ATTEMPTS}:status===408||NETWORK_TEXT.test(text)?{kind:"retry_same",maxAttempts:RETRY_SAME_MAX_ATTEMPTS}:{kind:"fail_request"}}var CredentialFailoverError=class extends Error{constructor(action,original,options={}){let detail=original instanceof Error?original.message:String(original);super(detail,{cause:original}),this.name="CredentialFailoverError",this.action=action,this.original=original,this.retryAt=options.retryAt}};function isAvailable(slot,now){return!(slot.blockReason==="auth_error"||slot.blockReason==="account_disabled"||slot.blockedUntil!==void 0&&slot.blockedUntil>now)}function soonestRetryAt(slots,now){let deadlines=slots.map(slot=>slot.blockedUntil).filter(value=>value!==void 0&&value>now);return deadlines.length===0?void 0:Math.min(...deadlines)}async function settle(stream){let iterator=stream[Symbol.asyncIterator]();try{await iterator.return?.(void 0)}catch{}}async function*runCredentialFailover(options){let now=options.now??Date.now,classify=options.classify??classifyCredentialFailure,attempted=new Set,retriesBySlot=new Map,lastError,lastOriginal,lastTerminalEvent,startAnnounced=!1;for(;;){let slots=await options.listSlots(),candidates=slots.filter(slot2=>!attempted.has(slot2.name)&&isAvailable(slot2,now()));if(candidates.length===0){if(lastTerminalEvent!==void 0){yield lastTerminalEvent;return}let retryAt=soonestRetryAt(slots,now());throw lastError!==void 0&&lastOriginal!==void 0?new CredentialFailoverError(lastError.action,lastOriginal,retryAt===void 0?{}:{retryAt}):new CredentialFailoverError({kind:"fail_request"},new Error("No credential slots available"),retryAt===void 0?{}:{retryAt})}let slot=options.select(candidates),committedOutput=!1,terminalEvent,attemptStream;try{attemptStream=await options.runAttempt(slot);for await(let event of attemptStream){let failure=options.errorFromEvent?.(event);if(failure!==void 0)throw terminalEvent=event,failure;if(options.isStreamStart?.(event)){if(startAnnounced)continue;startAnnounced=!0}committedOutput||=options.isCommittedOutput(event),yield event}await options.onSuccess?.(slot);return}catch(error){attemptStream&&await settle(attemptStream);let failureCount=(slot.failureCount??0)+(retriesBySlot.get(slot.name)??0),action=classify(error,{failureCount});if(lastOriginal=error,lastTerminalEvent=terminalEvent,action.kind==="retry_same"&&!committedOutput){let used=(retriesBySlot.get(slot.name)??0)+1;if(retriesBySlot.set(slot.name,used),used<action.maxAttempts)continue;if(terminalEvent!==void 0){yield terminalEvent;return}throw new CredentialFailoverError(action,error)}if(action.kind!=="failover"){if(terminalEvent!==void 0){yield terminalEvent;return}throw new CredentialFailoverError(action,error)}await options.persistBlock(slot,action.block),attempted.add(slot.name);let failure=new CredentialFailoverError(action,error);if(lastError=failure,await options.onRotate?.({slot,block:action.block,attempt:attempted.size,committedOutput}),committedOutput){if(terminalEvent!==void 0){yield terminalEvent;return}throw failure}}}}export{sleep,getConfigValueEnvVarNames,isCommandConfigValue,isConfigValueConfigured,resolveConfigValue,resolveConfigValueOrThrow,resolveHeadersOrThrow,isCommittedRotationOutput,isRotationStreamStart,rotationErrorFromEvent,rendezvousOrder,classifyCredentialFailure,CredentialFailoverError,runCredentialFailover};
|
|
2
|
+
import{getShellConfig}from"./chunk-SH6VUPE4.js";import{getOverflowPatterns}from"./chunk-77AUUH3Z.js";import{normalizeProviderError}from"./chunk-BBK6SSYT.js";import{extract429RetryAfterMs}from"./chunk-BPX6QWPD.js";import{PROVIDER_NOT_CONFIGURED_PREFIX}from"./chunk-Z2N5372Y.js";import{spawn}from"child_process";function sleep(ms,signal){return new Promise((resolve,reject)=>{if(signal?.aborted){reject(new Error("Aborted"));return}let timeout=setTimeout(resolve,ms);signal?.addEventListener("abort",()=>{clearTimeout(timeout),reject(new Error("Aborted"))})})}var COMMAND_EXECUTION_MAX_ATTEMPTS=3,COMMAND_EXECUTION_BACKOFF_MS=[250,1e3],COMMAND_TIMEOUT_MS=1e4,COMMAND_MAX_OUTPUT_BYTES=1024*1024;function runCommandProcess(file,args,options){return new Promise(resolveOutcome=>{let spawnOptions={shell:options.shell,windowsHide:!0,...options.env===void 0?{}:{env:{...process.env,...options.env}}},child=options.stdin===void 0?spawn(file,[...args],{...spawnOptions,stdio:["ignore","pipe","ignore"]}):spawn(file,[...args],{...spawnOptions,stdio:["pipe","pipe","ignore"]}),stdout="",settled=!1,finish=outcome=>{settled||(settled=!0,clearTimeout(timer),resolveOutcome(outcome))},timer=setTimeout(()=>{child.kill("SIGTERM"),child.unref(),finish({executed:!0,value:void 0})},COMMAND_TIMEOUT_MS);child.stdout.setEncoding("utf-8"),child.stdout.on("data",chunk=>{stdout+=chunk,!(stdout.length<=COMMAND_MAX_OUTPUT_BYTES)&&(child.kill("SIGTERM"),finish({executed:!0,value:void 0}))}),child.on("error",error=>finish({executed:error.code!=="ENOENT",value:void 0})),child.on("close",code=>{let value=stdout.trim();finish({executed:!0,value:code===0&&value?value:void 0})}),child.stdin?.end(options.stdin)})}async function executeWithConfiguredShell(command,env){try{let{shell,args,commandTransport}=getShellConfig(),commandFromStdin=commandTransport==="stdin";return await runCommandProcess(shell,commandFromStdin?args:[...args,command],{shell:!1,...commandFromStdin?{stdin:command}:{},...env===void 0?{}:{env}})}catch{return{executed:!1,value:void 0}}}async function executeCommandOnce(command,env){if(process.platform==="win32"){let configured=await executeWithConfiguredShell(command,env);if(configured.executed)return configured.value}return(await runCommandProcess(command,[],{shell:!0,...env===void 0?{}:{env}})).value}async function runConfigCommand(commandConfig,env){let command=commandConfig.slice(1);for(let attempt=0;attempt<COMMAND_EXECUTION_MAX_ATTEMPTS;attempt++){let value=await executeCommandOnce(command,env);if(value!==void 0)return value;let backoffMs=COMMAND_EXECUTION_BACKOFF_MS[attempt];backoffMs!==void 0&&await sleep(backoffMs)}}var commandResultCache=new Map,ENV_VAR_NAME_RE=/^[A-Za-z_][A-Za-z0-9_]*$/,ENV_VAR_NAME_PREFIX_RE=/^[A-Za-z_][A-Za-z0-9_]*/;function appendLiteral(parts,value){if(!value)return;let previousPart=parts[parts.length-1];if(previousPart?.type==="literal"){previousPart.value+=value;return}parts.push({type:"literal",value})}function parseConfigValueTemplate(config){let parts=[],index=0;for(;index<config.length;){let dollarIndex=config.indexOf("$",index);if(dollarIndex<0){appendLiteral(parts,config.slice(index));break}appendLiteral(parts,config.slice(index,dollarIndex));let nextChar=config[dollarIndex+1];if(nextChar==="$"||nextChar==="!"){appendLiteral(parts,nextChar),index=dollarIndex+2;continue}if(nextChar==="{"){let endIndex=config.indexOf("}",dollarIndex+2);if(endIndex<0){appendLiteral(parts,"$"),index=dollarIndex+1;continue}let name=config.slice(dollarIndex+2,endIndex);ENV_VAR_NAME_RE.test(name)?parts.push({type:"env",name}):appendLiteral(parts,config.slice(dollarIndex,endIndex+1)),index=endIndex+1;continue}let match=config.slice(dollarIndex+1).match(ENV_VAR_NAME_PREFIX_RE);if(match){parts.push({type:"env",name:match[0]}),index=dollarIndex+1+match[0].length;continue}appendLiteral(parts,"$"),index=dollarIndex+1}return parts}function parseConfigValueReference(config){return config.startsWith("!")?{type:"command",config}:{type:"template",parts:parseConfigValueTemplate(config)}}function resolveEnvConfigValue(name,env){return env?.[name]||process.env[name]||void 0}function getTemplateEnvVarNames(parts){let names=[];for(let part of parts)part.type!=="env"||names.includes(part.name)||names.push(part.name);return names}function resolveTemplate(parts,env){let resolved="";for(let part of parts){if(part.type==="literal"){resolved+=part.value;continue}let envValue=resolveEnvConfigValue(part.name,env);if(envValue===void 0)return;resolved+=envValue}return resolved}function getConfigValueEnvVarNames(config){let reference=parseConfigValueReference(config);return reference.type==="template"?getTemplateEnvVarNames(reference.parts):[]}function getMissingConfigValueEnvVarNames(config,env){return getConfigValueEnvVarNames(config).filter(name=>resolveEnvConfigValue(name,env)===void 0)}function isCommandConfigValue(config){return parseConfigValueReference(config).type==="command"}function isConfigValueConfigured(config,env){return getMissingConfigValueEnvVarNames(config,env).length===0}function resolveConfigValue(config,env){let reference=parseConfigValueReference(config);return reference.type==="command"?env===void 0?executeCommand(reference.config):runConfigCommand(reference.config,env):Promise.resolve(resolveTemplate(reference.parts,env))}function executeCommand(commandConfig){let cached=commandResultCache.get(commandConfig);if(cached)return cached;let result=runConfigCommand(commandConfig);return commandResultCache.set(commandConfig,result),result}function resolveConfigValueUncached(config,env){let reference=parseConfigValueReference(config);return reference.type==="command"?runConfigCommand(reference.config,env):Promise.resolve(resolveTemplate(reference.parts,env))}async function resolveConfigValueOrThrow(config,description,env){let resolvedValue=await resolveConfigValueUncached(config,env);if(resolvedValue!==void 0)return resolvedValue;let reference=parseConfigValueReference(config);if(reference.type==="command")throw new Error(`Failed to resolve ${description} from shell command: ${reference.config.slice(1)}`);if(reference.type==="template"){let missingEnvVars=getMissingConfigValueEnvVarNames(config,env);if(missingEnvVars.length===1)throw new Error(`Failed to resolve ${description} from environment variable: ${missingEnvVars[0]}`);if(missingEnvVars.length>1)throw new Error(`Failed to resolve ${description} from environment variables: ${missingEnvVars.join(", ")}`)}throw new Error(`Failed to resolve ${description}`)}async function resolveHeadersOrThrow(headers,description,env){if(!headers)return;let resolved={};for(let[key,value]of Object.entries(headers))resolved[key]=await resolveConfigValueOrThrow(value,`${description} header "${key}"`,env);return Object.keys(resolved).length>0?resolved:void 0}var PRE_COMMIT_EVENT_TYPES=new Set(["start","text_start","thinking_start","toolcall_start"]);function isCommittedRotationOutput(event){return!PRE_COMMIT_EVENT_TYPES.has(event.type)}function isRotationStreamStart(event){return event.type==="start"}function rotationErrorFromEvent(event){if(event.type!=="error")return;let failure=new Error(event.error.errorMessage??"provider stream error"),status=event.error.providerDiagnostic?.httpStatus;return status===void 0?failure:Object.assign(failure,{status})}function rendezvousOrder(key,slots,hasher){return[...slots].map(slot=>({slot,score:hasher(`${key}\0${slot.name}`)})).sort((left,right)=>right.score>left.score?1:right.score<left.score?-1:0).map(({slot})=>slot)}var DEFAULT_SLOT_BLOCK_MS=6e4,MAX_SLOT_BLOCK_MS=2880*60*1e3;var COOLDOWN_BASE_MS=DEFAULT_SLOT_BLOCK_MS,COOLDOWN_CAP_MS=MAX_SLOT_BLOCK_MS,RETRY_SAME_MAX_ATTEMPTS=2;function rateLimitCooldown(failureCount,serverHintMs,policy={}){let cap=policy.capMs??COOLDOWN_CAP_MS,base=policy.baseMs??COOLDOWN_BASE_MS,backoff=Math.min(cap,base*2**Math.max(0,failureCount)),floored=serverHintMs===void 0?backoff:Math.max(backoff,serverHintMs);return{cooldownMs:Math.min(cap,floored),retryAfterWasCapped:floored>cap}}var INVALID_KEY_TEXT=/invalid[ _-]?(?:api[ _-]?)?key|authentication[_ ]?error|invalid x-api-key|unauthorized/i,ACCOUNT_SCOPED_403_TEXT=/account|credential|token|api[ _-]?key|organization|subscription/i,RATE_LIMIT_TEXT=/rate[ _-]?limit|too many requests|resource_exhausted/i,BILLING_TEXT=/billing|credits?[ _-]?(?:required|exhausted|balance)|insufficient[ _-]?(?:funds|quota|credit)|payment[ _-]?required|quota[ _-]?exhausted/i,OVERLOAD_TEXT=/overloaded/i,NETWORK_TEXT=/econnreset|econnrefused|etimedout|enotfound|socket hang up|fetch failed|network error|request timed out/i,WEBSOCKET_REQUEST_FAULT_TEXT=/websocket closed 100[89]\b/i,WEBSOCKET_TRANSPORT_FAULT_TEXT=/websocket (?:closed|error|connect timeout|liveness timeout)/i,FAIL_FAST_TEXT=/context[ _-]?(?:length|window)|maximum context|invalid[ _-]?model|model[ _-]?not[ _-]?found|malformed[ _-]?stream|premature[ _-]?(?:close|stream)/i,ABORT_TEXT=/\baborted?\b/i;function isAbort(error,message){return error instanceof Error&&error.name==="AbortError"?!0:ABORT_TEXT.test(message)}function isOverflowText(text){return getOverflowPatterns().some(pattern=>pattern.test(text))}function classifyCredentialFailure(error,context={}){let normalized=normalizeProviderError(error),text=normalized.messageCarriesBody?normalized.message:`${normalized.message} ${normalized.body??""}`,status=normalized.status,failureCount=context.failureCount??0;if(isAbort(error,text))return{kind:"fail_request"};if(text.includes(PROVIDER_NOT_CONFIGURED_PREFIX))return{kind:"failover",block:{reason:"auth_error"}};if(status===401||INVALID_KEY_TEXT.test(text))return{kind:"failover",block:{reason:"auth_error"}};if(status===403)return ACCOUNT_SCOPED_403_TEXT.test(text)?{kind:"failover",block:{reason:"auth_error"}}:{kind:"fail_request"};if(status===402||BILLING_TEXT.test(text))return{kind:"failover",block:{reason:"account_disabled"}};if(status===429||RATE_LIMIT_TEXT.test(text)){let hint=extract429RetryAfterMs({status:status??429,bodyText:text});return{kind:"failover",block:{reason:"rate_limit",...rateLimitCooldown(failureCount,hint,{baseMs:context.cooldownBaseMs,capMs:context.cooldownCapMs})}}}return isOverflowText(text)||status===400||status===404||FAIL_FAST_TEXT.test(text)?{kind:"fail_request"}:WEBSOCKET_REQUEST_FAULT_TEXT.test(text)?{kind:"fail_request"}:WEBSOCKET_TRANSPORT_FAULT_TEXT.test(text)?{kind:"retry_same",maxAttempts:RETRY_SAME_MAX_ATTEMPTS}:status===529||OVERLOAD_TEXT.test(text)||status!==void 0&&status>=500&&status<600?{kind:"retry_same",maxAttempts:RETRY_SAME_MAX_ATTEMPTS}:status===408||NETWORK_TEXT.test(text)?{kind:"retry_same",maxAttempts:RETRY_SAME_MAX_ATTEMPTS}:{kind:"fail_request"}}var CredentialFailoverError=class extends Error{constructor(action,original,options={}){let detail=original instanceof Error?original.message:String(original);super(detail,{cause:original}),this.name="CredentialFailoverError",this.action=action,this.original=original,this.retryAt=options.retryAt}};function isAvailable(slot,now){return!(slot.blockReason==="auth_error"||slot.blockReason==="account_disabled"||slot.blockedUntil!==void 0&&slot.blockedUntil>now)}function soonestRetryAt(slots,now){let deadlines=slots.map(slot=>slot.blockedUntil).filter(value=>value!==void 0&&value>now);return deadlines.length===0?void 0:Math.min(...deadlines)}async function settle(stream){let iterator=stream[Symbol.asyncIterator]();try{await iterator.return?.(void 0)}catch{}}async function*runCredentialFailover(options){let now=options.now??Date.now,classify=options.classify??classifyCredentialFailure,attempted=new Set,retriesBySlot=new Map,lastError,lastOriginal,lastTerminalEvent,startAnnounced=!1;for(;;){let slots=await options.listSlots(),candidates=slots.filter(slot2=>!attempted.has(slot2.name)&&isAvailable(slot2,now()));if(candidates.length===0){if(lastTerminalEvent!==void 0){yield lastTerminalEvent;return}let retryAt=soonestRetryAt(slots,now());throw lastError!==void 0&&lastOriginal!==void 0?new CredentialFailoverError(lastError.action,lastOriginal,retryAt===void 0?{}:{retryAt}):new CredentialFailoverError({kind:"fail_request"},new Error("No credential slots available"),retryAt===void 0?{}:{retryAt})}let slot=options.select(candidates),committedOutput=!1,terminalEvent,attemptStream;try{attemptStream=await options.runAttempt(slot);for await(let event of attemptStream){let failure=options.errorFromEvent?.(event);if(failure!==void 0)throw terminalEvent=event,failure;if(options.isStreamStart?.(event)){if(startAnnounced)continue;startAnnounced=!0}committedOutput||=options.isCommittedOutput(event),yield event}await options.onSuccess?.(slot);return}catch(error){attemptStream&&await settle(attemptStream);let failureCount=(slot.failureCount??0)+(retriesBySlot.get(slot.name)??0),action=classify(error,{failureCount});if(lastOriginal=error,lastTerminalEvent=terminalEvent,action.kind==="retry_same"&&!committedOutput){let used=(retriesBySlot.get(slot.name)??0)+1;if(retriesBySlot.set(slot.name,used),used<action.maxAttempts)continue;if(terminalEvent!==void 0){yield terminalEvent;return}throw new CredentialFailoverError(action,error)}if(action.kind!=="failover"){if(terminalEvent!==void 0){yield terminalEvent;return}throw new CredentialFailoverError(action,error)}await options.persistBlock(slot,action.block),attempted.add(slot.name);let failure=new CredentialFailoverError(action,error);if(lastError=failure,await options.onRotate?.({slot,block:action.block,attempt:attempted.size,committedOutput}),committedOutput){if(terminalEvent!==void 0){yield terminalEvent;return}throw failure}}}}export{sleep,getConfigValueEnvVarNames,isCommandConfigValue,isConfigValueConfigured,resolveConfigValue,resolveConfigValueOrThrow,resolveHeadersOrThrow,isCommittedRotationOutput,isRotationStreamStart,rotationErrorFromEvent,rendezvousOrder,classifyCredentialFailure,CredentialFailoverError,runCredentialFailover};
|
|
@@ -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{appendGrammarToolInputJsonDelta,calculateCost,getGrammarToolInput,getJsonSchemaToolParameters,resolveGrammarConstrainedSampling,resolveJsonSchemaStrictSampling,shortHash,supportsConfigurationUpdate,transformMessages}from"./chunk-
|
|
2
|
+
import{appendGrammarToolInputJsonDelta,calculateCost,getGrammarToolInput,getJsonSchemaToolParameters,resolveGrammarConstrainedSampling,resolveJsonSchemaStrictSampling,shortHash,supportsConfigurationUpdate,transformMessages}from"./chunk-Z2N5372Y.js";import{sanitizeSurrogates}from"./chunk-WDTJ6JKE.js";import{parseStreamingJson}from"./chunk-3W47LTXQ.js";function isOpenAIResponsesPromptCacheModel(model){if(model.api!=="openai-responses"||model.compat?.supportsExplicitPromptCacheMode!==!0)return!1;try{return new URL(model.baseUrl||"https://api.openai.com/v1").hostname==="api.openai.com"}catch{return!1}}function findPromptCacheComparisonResponseId(model,messages){for(let index=messages.length-1;index>=0;index-=1){let message=messages[index];if(message?.role==="assistant"&&!(message.api!==model.api||message.provider!==model.provider||message.model!==model.id)&&!(message.stopReason==="error"||message.stopReason==="aborted")&&typeof message.responseId=="string"&&message.responseId.length>0)return message.responseId.startsWith("resp")?message.responseId:void 0}}function withPromptCacheComparison(options,comparisonResponseId){return comparisonResponseId===void 0?options:{...options,comparison_response_id:comparisonResponseId}}function finiteCount(value){return typeof value=="number"&&Number.isFinite(value)&&value>=0?value:void 0}function parsePromptCacheDiagnostics(raw){if(typeof raw!="object"||raw===null)return;let record=raw;if(typeof record.type!="string"||record.type.length===0)return;let diagnostics={type:record.type};typeof record.reason=="string"&&(diagnostics.reason=record.reason);let cacheMissedTokens=finiteCount(record.cache_missed_tokens);cacheMissedTokens!==void 0&&(diagnostics.cacheMissedTokens=cacheMissedTokens);let comparisonReusableTokens=finiteCount(record.comparison_reusable_tokens);return comparisonReusableTokens!==void 0&&(diagnostics.comparisonReusableTokens=comparisonReusableTokens),diagnostics}var CONTEXT_PROVENANCE_FIELD="__piContextProvenance";function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function getContextProvenance(value){if(!isRecord(value))return;let provenance=value[CONTEXT_PROVENANCE_FIELD];return isRecord(provenance)?provenance:void 0}function copyContextProvenance(source,target){let provenance=getContextProvenance(source);return provenance?Object.assign(target,{[CONTEXT_PROVENANCE_FIELD]:provenance}):target}function contextProvenanceFingerprint(value){if(!isRecord(value))return;let clone={...value};return delete clone[CONTEXT_PROVENANCE_FIELD],JSON.stringify(clone)}function formatResponsesCompletionStall(graceMs){return`Provider stream stalled after the last output item: response.completed timed out after ${graceMs}ms`}var ResponsesCompletionStallError=class extends Error{constructor(graceMs){super(formatResponsesCompletionStall(graceMs)),this.name="ResponsesCompletionStallError",this.graceMs=graceMs}},GRACE_EXPIRED=Symbol("responses-completion-grace-expired");function withResponsesCompletionGrace(source,graceMs=6e4){return{[Symbol.asyncIterator](){let iterator=source[Symbol.asyncIterator](),openItems=0,sawItemDone=!1,finished=!1,observe=event=>{event.type==="response.output_item.added"?openItems++:event.type==="response.output_item.done"&&(openItems=Math.max(0,openItems-1),sawItemDone=!0)},boundedNext=async()=>{let next=iterator.next();if(!sawItemDone||openItems>0||graceMs<=0)return next;let timer,deadline=new Promise(resolve=>{timer=setTimeout(()=>resolve(GRACE_EXPIRED),graceMs)});try{let winner=await Promise.race([next,deadline]);if(winner===GRACE_EXPIRED)throw finished=!0,iterator.return?.().catch(()=>{}),new ResponsesCompletionStallError(graceMs);return winner}finally{timer!==void 0&&clearTimeout(timer)}};return{async next(){if(finished)return{done:!0,value:void 0};let result=await boundedNext();return result.done?finished=!0:observe(result.value),result},async return(value){return finished=!0,await iterator.return?.(value),{done:!0,value:void 0}},async throw(error){if(finished=!0,iterator.throw)return iterator.throw(error);throw error}}}}}function encodeTextSignatureV1(id,phase){let payload={v:1,id};return phase&&(payload.phase=phase),JSON.stringify(payload)}function parseTextSignature(signature){if(signature){if(signature.startsWith("{"))try{let parsed=JSON.parse(signature);if(parsed.v===1&&typeof parsed.id=="string")return parsed.phase==="commentary"||parsed.phase==="final_answer"?{id:parsed.id,phase:parsed.phase}:{id:parsed.id}}catch{}return{id:signature}}}function parseReasoningSignature(signature){if(signature)try{let parsed=JSON.parse(signature);return parsed?.type==="reasoning"?parsed:void 0}catch{return}}function convertToolResultOutput(model,content){let textResult=content.filter(c=>c.type==="text").map(c=>c.text).join(`
|
|
3
3
|
`),images=content.filter(c=>c.type==="image"),hasText=textResult.length>0;if(images.length===0||!model.input.includes("image"))return sanitizeSurrogates(hasText?textResult:images.length>0?"(see attached image)":"(no tool output)");let output=[];hasText&&output.push({type:"input_text",text:sanitizeSurrogates(textResult)});for(let image of images)output.push({type:"input_image",detail:"auto",image_url:`data:${image.mimeType};base64,${image.data}`});return output}var CUSTOM_TOOL_CALL_ITEM_ID_SENTINEL="custom";function isResponseCustomToolCallItem(item){return item.type==="custom_tool_call"}function isFreeformTool(tool){return tool.freeform!==void 0}function isFreeformToolName(toolName,tools){return tools?.some(tool=>tool.name===toolName&&isFreeformTool(tool))??!1}function getFreeformToolInput(argumentsValue){return typeof argumentsValue.input=="string"?argumentsValue.input:JSON.stringify(argumentsValue)}function contextProvenanceForInput(message,seal){let provenance=getContextProvenance(message);if(!provenance)return;let fingerprint=contextProvenanceFingerprint(message);if(fingerprint===void 0)return;let stored=provenance.integrity;return stored===void 0&&seal?(provenance.integrity=fingerprint,provenance):stored===fingerprint?provenance:void 0}function withContextProvenance(item,message,seal){let provenance=contextProvenanceForInput(message,seal);return provenance&&Object.defineProperty(item,CONTEXT_PROVENANCE_FIELD,{value:provenance,enumerable:!1}),item}function convertResponsesMessages(model,context,allowedToolCallProviders,options){let messages=[],loadedToolNames=new Set,normalizeIdPart=part=>{let sanitized=part.replace(/[^a-zA-Z0-9_-]/g,"_");return(sanitized.length>64?sanitized.slice(0,64):sanitized).replace(/_+$/,"")},buildForeignResponsesItemId=itemId=>{let normalized=`fc_${shortHash(itemId)}`;return normalized.length>64?normalized.slice(0,64):normalized},normalizeToolCallId=(id,_targetModel,source)=>{if(!id.includes("|"))return normalizeIdPart(id);let[callId,itemId]=id.split("|"),normalizedCallId=normalizeIdPart(callId);if(itemId===CUSTOM_TOOL_CALL_ITEM_ID_SENTINEL)return`${normalizedCallId}|${CUSTOM_TOOL_CALL_ITEM_ID_SENTINEL}`;if(!allowedToolCallProviders.has(model.provider))return normalizeIdPart(id);let normalizedItemId=source.provider!==model.provider||source.api!==model.api?buildForeignResponsesItemId(itemId):normalizeIdPart(itemId);return normalizedItemId.startsWith("fc_")||(normalizedItemId=normalizeIdPart(`fc_${normalizedItemId}`)),`${normalizedCallId}|${normalizedItemId}`},transformedMessages=transformMessages(context.messages,model,normalizeToolCallId,{preserveThinking:options?.preserveThinking,preserveTextSignatures:options?.preserveTextSignatures});if((options?.includeSystemPrompt??!0)&&context.systemPrompt){let compat=model.compat,role=model.reasoning&&compat?.supportsDeveloperRole!==!1?"developer":"system",text=sanitizeSurrogates(context.systemPrompt);if(options?.systemPromptCacheBreakpoint===!0){let block={type:"input_text",text,prompt_cache_breakpoint:{mode:"explicit"}};messages.push({role,content:[block]})}else messages.push({role,content:text})}let msgIndex=0;for(let msg of transformedMessages){if(msg.role==="configurationUpdate"){if(!supportsConfigurationUpdate(model))continue;messages[messages.length-1]?.type==="configuration_update"?messages[messages.length-1]={type:"configuration_update",reasoning:{effort:msg.effort}}:messages.push({type:"configuration_update",reasoning:{effort:msg.effort}});continue}if(msg.role==="user")if(typeof msg.content=="string")messages.push(withContextProvenance({role:"user",content:[{type:"input_text",text:sanitizeSurrogates(msg.content)}]},msg,options?.sealContextProvenance));else{let content=msg.content.map(item=>item.type==="text"?{type:"input_text",text:sanitizeSurrogates(item.text)}:{type:"input_image",detail:"auto",image_url:`data:${item.mimeType};base64,${item.data}`});if(content.length===0)continue;messages.push(withContextProvenance({role:"user",content},msg,options?.sealContextProvenance))}else if(msg.role==="assistant"){let output=[],assistantMsg=msg,isSameProviderAndApi=assistantMsg.provider===model.provider&&assistantMsg.api===model.api,isSameModel=isSameProviderAndApi&&assistantMsg.model===model.id,isDifferentModel=isSameProviderAndApi&&assistantMsg.model!==model.id,textBlockIndex=0,pushAssistantText=(text,textSignature)=>{let parsedSignature=parseTextSignature(textSignature),fallbackMessageId=textBlockIndex===0?`msg_pi_${msgIndex}`:`msg_pi_${msgIndex}_${textBlockIndex}`;textBlockIndex++;let msgId=parsedSignature?.id;msgId?msgId.length>64&&(msgId=`msg_${shortHash(msgId)}`):msgId=fallbackMessageId,output.push({type:"message",role:"assistant",content:[{type:"output_text",text:sanitizeSurrogates(text),annotations:[]}],status:"completed",id:msgId,phase:parsedSignature?.phase})};for(let block of msg.content)if(block.type==="thinking"){let reasoningItem=parseReasoningSignature(block.thinkingSignature);reasoningItem?output.push(reasoningItem):block.thinkingSignature&&block.thinking.trim()!==""&&pushAssistantText(block.thinking)}else if(block.type!=="providerNative"){if(block.type==="text"){let textBlock=block;pushAssistantText(textBlock.text,textBlock.textSignature)}else if(block.type==="toolCall"){let toolCall=block,[callId,itemIdRaw]=toolCall.id.split("|"),customInputProperty=options?.grammarToolInputProperties?.get(toolCall.name),isPersistedFreeform=itemIdRaw===CUSTOM_TOOL_CALL_ITEM_ID_SENTINEL,isFreeform=isFreeformToolName(toolCall.name,context.tools)||isPersistedFreeform,itemId=isPersistedFreeform?void 0:itemIdRaw;(isDifferentModel&&itemId?.startsWith("fc_")||!isFreeform&&customInputProperty===void 0&&!itemId?.startsWith("fc_"))&&(itemId=void 0);let canReplayNamespace=isSameModel||options?.deferredTools?.has(toolCall.name)===!0;customInputProperty!==void 0?output.push({type:"custom_tool_call",...itemId!==void 0?{id:itemId}:{},call_id:callId,name:toolCall.name,input:sanitizeSurrogates(getGrammarToolInput(toolCall.name,toolCall.arguments,customInputProperty)),...canReplayNamespace&&toolCall.namespace!==void 0?{namespace:toolCall.namespace}:{}}):isFreeform?output.push({type:"custom_tool_call",call_id:callId,name:toolCall.name,input:getFreeformToolInput(toolCall.arguments),...canReplayNamespace&&toolCall.namespace!==void 0?{namespace:toolCall.namespace}:{}}):output.push({type:"function_call",...itemId?.startsWith("fc_")?{id:itemId}:{},call_id:callId,name:toolCall.name,arguments:JSON.stringify(toolCall.arguments),...canReplayNamespace&&toolCall.namespace!==void 0?{namespace:toolCall.namespace}:{}})}}if(output.length===0)continue;messages.push(...output.map(item=>withContextProvenance(item,msg,options?.sealContextProvenance)))}else if(msg.role==="toolResult"){let[callId,itemIdRaw]=msg.toolCallId.split("|"),output=convertToolResultOutput(model,msg.content),customInputProperty=options?.grammarToolInputProperties?.get(msg.toolName),isPersistedFreeform=itemIdRaw===CUSTOM_TOOL_CALL_ITEM_ID_SENTINEL;customInputProperty!==void 0?messages.push(withContextProvenance({type:"custom_tool_call_output",call_id:callId,output},msg,options?.sealContextProvenance)):isFreeformToolName(msg.toolName,context.tools)||isPersistedFreeform?messages.push(withContextProvenance({type:"custom_tool_call_output",call_id:callId,name:msg.toolName,output},msg,options?.sealContextProvenance)):messages.push(withContextProvenance({type:"function_call_output",call_id:callId,output},msg,options?.sealContextProvenance));let deferredTools=[];for(let name of msg.addedToolNames??[]){let tool=options?.deferredTools?.get(name);!tool||loadedToolNames.has(name)||(loadedToolNames.add(name),deferredTools.push(tool))}if(deferredTools.length>0&&options?.deferredToolsMode==="additional-tools")messages.push(withContextProvenance({type:"additional_tools",role:"developer",tools:convertResponsesTools(deferredTools,options.toolOptions)},msg,options.sealContextProvenance));else if(deferredTools.length>0&&options?.deferredToolsMode==="tool-search"){let names=deferredTools.map(tool=>tool.name),searchCallId=`pi_tool_load_${shortHash(`${msg.toolCallId}:${names.join(",")}`)}`;messages.push(withContextProvenance({type:"tool_search_call",call_id:searchCallId,execution:"client",status:"completed",arguments:{query:names.join(" "),limit:names.length}},msg,options?.sealContextProvenance)),messages.push(withContextProvenance({type:"tool_search_output",call_id:searchCallId,execution:"client",status:"completed",tools:convertResponsesTools(deferredTools,{...options?.toolOptions,deferLoading:!0})},msg,options?.sealContextProvenance))}}msgIndex++}return messages}function convertResponsesTools(tools,options){let defaultStrict=options?.strict===void 0?!1:options.strict,supportsStrictMode=options?.supportsStrictMode??!0,supportsOpenAIGrammarTools=options?.supportsOpenAIGrammarTools??!1;return tools.map(tool=>{let grammar=resolveGrammarConstrainedSampling(tool,supportsOpenAIGrammarTools);if(grammar)return{type:"custom",name:tool.name,description:tool.description,format:{type:"grammar",syntax:grammar.format,definition:grammar.definition},...options?.deferLoading?{defer_loading:!0}:{}};if(tool.freeform)return{type:"custom",name:tool.name,description:tool.description,format:tool.freeform,...options?.deferLoading?{defer_loading:!0}:{}};let strict=resolveJsonSchemaStrictSampling(tool,supportsStrictMode)??defaultStrict,functionTool={type:"function",name:tool.name,description:tool.description,parameters:getJsonSchemaToolParameters(tool,strict===!0),...options?.deferLoading?{defer_loading:!0}:{}};return supportsStrictMode&&(functionTool.strict=strict),functionTool})}function getCustomToolCallInput(block){let property=block.customInput?.property;if(property===void 0)return"";let value=block.arguments[property];return typeof value=="string"?value:""}function appendCustomToolCallInput(block,nextInput,close){let customInput=block.customInput;if(!customInput)return;let delta=appendGrammarToolInputJsonDelta(customInput.jsonBuffer,customInput.property,nextInput,close);return block.arguments={[customInput.property]:nextInput},delta}var MAX_NATIVE_IMAGE_BASE64_CHARS=24*1024*1024;function readNativeImageGenerationCall(value){if(!(typeof value!="object"||value===null||!("type"in value)||!("status"in value))&&!(value.type!=="image_generation_call"||typeof value.status!="string"))return{type:"image_generation_call",..."id"in value&&typeof value.id=="string"?{id:value.id}:{},status:value.status,..."result"in value&&(typeof value.result=="string"||value.result===null)?{result:value.result}:{},..."revised_prompt"in value&&typeof value.revised_prompt=="string"?{revised_prompt:value.revised_prompt}:{}}}function isValidBase64(value){return value.length>0&&value.length%4===0&&/^[A-Za-z0-9+/]*={0,2}$/.test(value)}function reconcileNativeImageGenerationCall(item){return item.status!=="completed"?{type:"image_generation_call",...item.id!==void 0?{id:item.id}:{},status:item.status}:typeof item.result!="string"||!isValidBase64(item.result)?{type:"image_generation_call",...item.id!==void 0?{id:item.id}:{},status:"malformed"}:{type:"image_generation_call",...item.id!==void 0?{id:item.id}:{},status:"completed",result:item.result,...item.revised_prompt?.trim()?{revised_prompt:item.revised_prompt}:{}}}async function processResponsesStream(openaiStream,output,stream,model,options){let sawTerminalResponseEvent=!1,nativeImageBase64Chars=0,outputSlots=new Map,reasoningBlocksById=new Map,nativeImageCharsByOutputIndex=new Map,finalizedNativeImageOutputIndexes=new Set,applyMessagePhaseStopReason=item=>{item.type==="message"&&item.phase==="final_answer"&&(output.stopReason="stop")},getSlot=(outputIndex,type)=>{let slot=outputSlots.get(outputIndex);return slot?.type===type?slot:void 0},pushToolCallDelta=(slot,delta)=>{delta!==void 0&&stream.push({type:"toolcall_delta",contentIndex:slot.contentIndex,delta,partial:output})},createSlot=(outputIndex,item)=>{if(item.type==="reasoning"){let block2={type:"thinking",thinking:""};output.content.push(block2);let slot2={type:"thinking",block:block2,contentIndex:output.content.length-1};return outputSlots.set(outputIndex,slot2),stream.push({type:"thinking_start",contentIndex:slot2.contentIndex,partial:output}),slot2}if(item.type==="message"){applyMessagePhaseStopReason(item);let block2={type:"text",text:""};output.content.push(block2);let slot2={type:"text",block:block2,contentIndex:output.content.length-1};return outputSlots.set(outputIndex,slot2),stream.push({type:"text_start",contentIndex:slot2.contentIndex,partial:output}),slot2}if(item.type==="function_call"){let block2={type:"toolCall",id:`${item.call_id}|${item.id}`,name:item.name,arguments:{},...item.namespace!==void 0?{namespace:item.namespace}:{},partialJson:item.arguments||""};output.content.push(block2);let slot2={type:"toolCall",block:block2,contentIndex:output.content.length-1};return outputSlots.set(outputIndex,slot2),stream.push({type:"toolcall_start",contentIndex:slot2.contentIndex,partial:output}),slot2}if(isResponseCustomToolCallItem(item)){let inputProperty=options?.grammarToolInputProperties?.get(item.name)??"input",input=item.input||"",block2={type:"toolCall",id:`${item.call_id}|${item.id??CUSTOM_TOOL_CALL_ITEM_ID_SENTINEL}`,name:item.name,arguments:{[inputProperty]:input},...item.namespace!==void 0?{namespace:item.namespace}:{},customInput:{property:inputProperty,jsonBuffer:{input:"",started:!1,closed:!1}}};output.content.push(block2);let slot2={type:"toolCall",block:block2,contentIndex:output.content.length-1};return outputSlots.set(outputIndex,slot2),stream.push({type:"toolcall_start",contentIndex:slot2.contentIndex,partial:output}),slot2}let imageItem=readNativeImageGenerationCall(item),block={type:"providerNative",subtype:item.type,raw:imageItem?reconcileNativeImageGenerationCall(imageItem):item},slot={type:"providerNative",block,contentIndex:output.content.length};return imageItem&&reconcileNativeImageSlot(outputIndex,slot,imageItem),output.content.push(block),outputSlots.set(outputIndex,slot),slot},getOrCreateSlot=(outputIndex,item)=>outputSlots.get(outputIndex)??createSlot(outputIndex,item);function scrubNativeImageResults(){for(let block of output.content){if(block.type!=="providerNative"||block.subtype!=="image_generation_call")continue;let item=readNativeImageGenerationCall(block.raw);typeof item?.result=="string"&&(block.raw={type:"image_generation_call",...item.id!==void 0?{id:item.id}:{},status:"malformed"})}nativeImageBase64Chars=0,nativeImageCharsByOutputIndex.clear()}function reconcileNativeImageSlot(outputIndex,slot,item){let reconciled=reconcileNativeImageGenerationCall(item),previousChars=nativeImageCharsByOutputIndex.get(outputIndex)??0,nextChars=typeof reconciled.result=="string"?reconciled.result.length:0,nextTotal=nativeImageBase64Chars-previousChars+nextChars;if(nextTotal>MAX_NATIVE_IMAGE_BASE64_CHARS)throw scrubNativeImageResults(),new Error("Native image generation results exceed the 24 MiB base64 limit");nativeImageBase64Chars=nextTotal,nextChars>0?nativeImageCharsByOutputIndex.set(outputIndex,nextChars):nativeImageCharsByOutputIndex.delete(outputIndex),slot.block.subtype="image_generation_call",slot.block.raw=reconciled}let backfillNativeImageGenerationCalls=responseOutput=>{for(let[outputIndex,outputItem]of responseOutput.entries()){if(finalizedNativeImageOutputIndexes.has(outputIndex))continue;let imageItem=readNativeImageGenerationCall(outputItem);if(!imageItem)continue;let existingSlot=getSlot(outputIndex,"providerNative");existingSlot?reconcileNativeImageSlot(outputIndex,existingSlot,imageItem):createSlot(outputIndex,outputItem),outputSlots.delete(outputIndex)}},backfillReasoningSignatures=responseOutput=>{for(let item of responseOutput){if(item.type!=="reasoning"||!item.encrypted_content)continue;let block=reasoningBlocksById.get(item.id);if(!block?.thinkingSignature)continue;let storedItem=parseReasoningSignature(block.thinkingSignature);!storedItem||storedItem.encrypted_content||(block.thinkingSignature=JSON.stringify({...storedItem,encrypted_content:item.encrypted_content}))}},finalizeResponse=response=>{sawTerminalResponseEvent=!0,backfillReasoningSignatures(response.output??[]),backfillNativeImageGenerationCalls(response.output??[]),response?.id&&(output.responseId=response.id);let promptCacheDiagnostics=parsePromptCacheDiagnostics(response?.prompt_cache_diagnostics);if(promptCacheDiagnostics&&(output.promptCacheDiagnostics=promptCacheDiagnostics),response?.usage){let inputDetails=response.usage.input_tokens_details,cachedTokens=inputDetails?.cached_tokens||0,cacheWriteTokens=inputDetails?.cache_write_tokens??inputDetails?.cache_creation_tokens??0;output.usage={input:Math.max(0,(response.usage.input_tokens||0)-cachedTokens-cacheWriteTokens),output:response.usage.output_tokens||0,cacheRead:cachedTokens,cacheWrite:cacheWriteTokens,reasoning:response.usage.output_tokens_details?.reasoning_tokens||0,totalTokens:response.usage.total_tokens||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}if(calculateCost(model,output.usage),options?.applyServiceTierPricing){let serviceTier=options.resolveServiceTier?options.resolveServiceTier(response?.service_tier,options.serviceTier):response?.service_tier??options.serviceTier;options.applyServiceTierPricing(output.usage,serviceTier)}let status=response?.status,incompleteDetails=response?.incomplete_details,incompleteReason=typeof incompleteDetails?.reason=="string"?incompleteDetails.reason:void 0;output.rawStopReason=incompleteReason?`${status}.${incompleteReason}`:status;let mappedStop=mapStopReason(status,incompleteReason);output.stopReason=mappedStop.stopReason,mappedStop.errorMessage===void 0?delete output.errorMessage:output.errorMessage=mappedStop.errorMessage,output.content.some(b=>b.type==="toolCall")&&output.stopReason==="stop"&&(output.stopReason="toolUse")};for await(let event of withResponsesCompletionGrace(openaiStream))if(event.type==="response.created")output.responseId=event.response.id;else if(event.type==="response.output_item.added")createSlot(event.output_index,event.item);else if(event.type==="response.reasoning_summary_text.delta"){let slot=getSlot(event.output_index,"thinking");if(!slot)continue;slot.block.thinking+=event.delta,stream.push({type:"thinking_delta",contentIndex:slot.contentIndex,delta:event.delta,partial:output})}else if(event.type==="response.reasoning_summary_part.done"){let slot=getSlot(event.output_index,"thinking");if(!slot)continue;slot.block.thinking+=`
|
|
4
4
|
|
|
5
5
|
`,stream.push({type:"thinking_delta",contentIndex:slot.contentIndex,delta:`
|
|
@@ -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{import_websocket}from"./chunk-YBZDAABT.js";import{normalizeToolCallId}from"./chunk-U5LXY7UD.js";import{retryProviderRequest}from"./chunk-KLBKUBDV.js";import{getJsonSchemaToolParameters,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-NUS5JXND.js";import{sanitizeSurrogates}from"./chunk-WDTJ6JKE.js";import{__commonJS,__require,__toESM}from"./chunk-IKOFCODM.js";var require_retry_operation=__commonJS({"node_modules/retry/lib/retry_operation.js"(exports,module){function RetryOperation(timeouts,options){typeof options=="boolean"&&(options={forever:options}),this._originalTimeouts=JSON.parse(JSON.stringify(timeouts)),this._timeouts=timeouts,this._options=options||{},this._maxRetryTime=options&&options.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}module.exports=RetryOperation;RetryOperation.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};RetryOperation.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};RetryOperation.prototype.retry=function(err){if(this._timeout&&clearTimeout(this._timeout),!err)return!1;var currentTime=new Date().getTime();if(err&¤tTime-this._operationStart>=this._maxRetryTime)return this._errors.push(err),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(err);var timeout=this._timeouts.shift();if(timeout===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),timeout=this._cachedTimeouts.slice(-1);else return!1;var self2=this;return this._timer=setTimeout(function(){self2._attempts++,self2._operationTimeoutCb&&(self2._timeout=setTimeout(function(){self2._operationTimeoutCb(self2._attempts)},self2._operationTimeout),self2._options.unref&&self2._timeout.unref()),self2._fn(self2._attempts)},timeout),this._options.unref&&this._timer.unref(),!0};RetryOperation.prototype.attempt=function(fn,timeoutOps){this._fn=fn,timeoutOps&&(timeoutOps.timeout&&(this._operationTimeout=timeoutOps.timeout),timeoutOps.cb&&(this._operationTimeoutCb=timeoutOps.cb));var self2=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){self2._operationTimeoutCb()},self2._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};RetryOperation.prototype.try=function(fn){console.log("Using RetryOperation.try() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=function(fn){console.log("Using RetryOperation.start() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=RetryOperation.prototype.try;RetryOperation.prototype.errors=function(){return this._errors};RetryOperation.prototype.attempts=function(){return this._attempts};RetryOperation.prototype.mainError=function(){if(this._errors.length===0)return null;for(var counts={},mainError=null,mainErrorCount=0,i=0;i<this._errors.length;i++){var error=this._errors[i],message=error.message,count=(counts[message]||0)+1;counts[message]=count,count>=mainErrorCount&&(mainError=error,mainErrorCount=count)}return mainError}}});var require_retry=__commonJS({"node_modules/retry/lib/retry.js"(exports){var RetryOperation=require_retry_operation();exports.operation=function(options){var timeouts=exports.timeouts(options);return new RetryOperation(timeouts,{forever:options&&(options.forever||options.retries===1/0),unref:options&&options.unref,maxRetryTime:options&&options.maxRetryTime})};exports.timeouts=function(options){if(options instanceof Array)return[].concat(options);var opts={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var key in options)opts[key]=options[key];if(opts.minTimeout>opts.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var timeouts=[],i=0;i<opts.retries;i++)timeouts.push(this.createTimeout(i,opts));return options&&options.forever&&!timeouts.length&&timeouts.push(this.createTimeout(i,opts)),timeouts.sort(function(a,b){return a-b}),timeouts};exports.createTimeout=function(attempt,opts){var random=opts.randomize?Math.random()+1:1,timeout=Math.round(random*Math.max(opts.minTimeout,1)*Math.pow(opts.factor,attempt));return timeout=Math.min(timeout,opts.maxTimeout),timeout};exports.wrap=function(obj,options,methods){if(options instanceof Array&&(methods=options,options=null),!methods){methods=[];for(var key in obj)typeof obj[key]=="function"&&methods.push(key)}for(var i=0;i<methods.length;i++){var method=methods[i],original=obj[method];obj[method]=function(original2){var op=exports.operation(options),args=Array.prototype.slice.call(arguments,1),callback=args.pop();args.push(function(err){op.retry(err)||(err&&(arguments[0]=op.mainError()),callback.apply(this,arguments))}),op.attempt(function(){original2.apply(obj,args)})}.bind(obj,original),obj[method].options=options}}}});var require_retry2=__commonJS({"node_modules/retry/index.js"(exports,module){module.exports=require_retry()}});var require_p_retry=__commonJS({"node_modules/p-retry/index.js"(exports,module){"use strict";var retry2=require_retry2(),networkErrorMsgs=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"],AbortError=class extends Error{constructor(message){super(),message instanceof Error?(this.originalError=message,{message}=message):(this.originalError=new Error(message),this.originalError.stack=this.stack),this.name="AbortError",this.message=message}},decorateErrorWithCounts=(error,attemptNumber,options)=>{let retriesLeft=options.retries-(attemptNumber-1);return error.attemptNumber=attemptNumber,error.retriesLeft=retriesLeft,error},isNetworkError=errorMessage=>networkErrorMsgs.includes(errorMessage),pRetry2=(input,options)=>new Promise((resolve,reject)=>{options={onFailedAttempt:()=>{},retries:10,...options};let operation=retry2.operation(options);operation.attempt(async attemptNumber=>{try{resolve(await input(attemptNumber))}catch(error){if(!(error instanceof Error)){reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`));return}if(error instanceof AbortError)operation.stop(),reject(error.originalError);else if(error instanceof TypeError&&!isNetworkError(error.message))operation.stop(),reject(error);else{decorateErrorWithCounts(error,attemptNumber,options);try{await options.onFailedAttempt(error)}catch(error2){reject(error2);return}operation.retry(error)||reject(operation.mainError())}}})});module.exports=pRetry2;module.exports.default=pRetry2;module.exports.AbortError=AbortError}});var require_extend=__commonJS({"node_modules/extend/index.js"(exports,module){"use strict";var hasOwn2=Object.prototype.hasOwnProperty,toStr=Object.prototype.toString,defineProperty=Object.defineProperty,gOPD=Object.getOwnPropertyDescriptor,isArray=function(arr){return typeof Array.isArray=="function"?Array.isArray(arr):toStr.call(arr)==="[object Array]"},isPlainObject2=function(obj){if(!obj||toStr.call(obj)!=="[object Object]")return!1;var hasOwnConstructor=hasOwn2.call(obj,"constructor"),hasIsPrototypeOf=obj.constructor&&obj.constructor.prototype&&hasOwn2.call(obj.constructor.prototype,"isPrototypeOf");if(obj.constructor&&!hasOwnConstructor&&!hasIsPrototypeOf)return!1;var key;for(key in obj);return typeof key>"u"||hasOwn2.call(obj,key)},setProperty=function(target,options){defineProperty&&options.name==="__proto__"?defineProperty(target,options.name,{enumerable:!0,configurable:!0,value:options.newValue,writable:!0}):target[options.name]=options.newValue},getProperty=function(obj,name){if(name==="__proto__")if(hasOwn2.call(obj,name)){if(gOPD)return gOPD(obj,name).value}else return;return obj[name]};module.exports=function extend(){var options,name,src,copy,copyIsArray,clone,target=arguments[0],i=1,length=arguments.length,deep=!1;for(typeof target=="boolean"&&(deep=target,target=arguments[1]||{},i=2),(target==null||typeof target!="object"&&typeof target!="function")&&(target={});i<length;++i)if(options=arguments[i],options!=null)for(name in options)src=getProperty(target,name),copy=getProperty(options,name),target!==copy&&(deep&©&&(isPlainObject2(copy)||(copyIsArray=isArray(copy)))?(copyIsArray?(copyIsArray=!1,clone=src&&isArray(src)?src:[]):clone=src&&isPlainObject2(src)?src:{},setProperty(target,{name,newValue:extend(deep,clone,copy)})):typeof copy<"u"&&setProperty(target,{name,newValue:copy}));return target}}});var require_package=__commonJS({"node_modules/gaxios/package.json"(exports,module){module.exports={name:"gaxios",version:"7.1.4",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","docs-test":"linkinator docs","predocs-test":"npm run docs","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"packages/gaxios",url:"https://github.com/googleapis/google-cloud-node-core.git"},keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^22.13.1","@types/sinon":"^17.0.3","@types/tmp":"^0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.1.3",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",linkinator:"^6.1.2",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.1","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","stream-browserify":"^3.0.0",tmp:"0.2.5","ts-loader":"^9.5.2",typescript:"5.8.3",webpack:"^5.97.1","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"},homepage:"https://github.com/googleapis/google-cloud-node-core/tree/main/packages/gaxios"}}});var require_util=__commonJS({"node_modules/gaxios/build/cjs/src/util.cjs"(exports,module){"use strict";var pkg=require_package();module.exports={pkg}}});var require_common=__commonJS({"node_modules/gaxios/build/cjs/src/common.js"(exports){"use strict";var __importDefault=exports&&exports.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0});exports.GaxiosError=exports.GAXIOS_ERROR_SYMBOL=void 0;exports.defaultErrorRedactor=defaultErrorRedactor;var extend_1=__importDefault(require_extend()),util_cjs_1=__importDefault(require_util()),pkg=util_cjs_1.default.pkg;exports.GAXIOS_ERROR_SYMBOL=Symbol.for(`${pkg.name}-gaxios-error`);var GaxiosError=class _GaxiosError extends Error{config;response;code;status;error;[exports.GAXIOS_ERROR_SYMBOL]=pkg.version;static[Symbol.hasInstance](instance){return instance&&typeof instance=="object"&&exports.GAXIOS_ERROR_SYMBOL in instance&&instance[exports.GAXIOS_ERROR_SYMBOL]===pkg.version?!0:Function.prototype[Symbol.hasInstance].call(_GaxiosError,instance)}constructor(message,config,response,cause){if(super(message,{cause}),this.config=config,this.response=response,this.error=cause instanceof Error?cause:void 0,this.config=(0,extend_1.default)(!0,{},config),this.response&&(this.response.config=(0,extend_1.default)(!0,{},this.response.config)),this.response){try{this.response.data=translateData(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}cause instanceof DOMException?this.code=cause.name:cause&&typeof cause=="object"&&"code"in cause&&(typeof cause.code=="string"||typeof cause.code=="number")&&(this.code=cause.code)}static extractAPIErrorFromResponse(res,defaultErrorMessage="The request failed"){let message=defaultErrorMessage;if(typeof res.data=="string"&&(message=res.data),res.data&&typeof res.data=="object"&&"error"in res.data&&res.data.error&&!res.ok){if(typeof res.data.error=="string")return{message:res.data.error,code:res.status,status:res.statusText};if(typeof res.data.error=="object"){message="message"in res.data.error&&typeof res.data.error.message=="string"?res.data.error.message:message;let status="status"in res.data.error&&typeof res.data.error.status=="string"?res.data.error.status:res.statusText,code="code"in res.data.error&&typeof res.data.error.code=="number"?res.data.error.code:res.status;if("errors"in res.data.error&&Array.isArray(res.data.error.errors)){let errorMessages=[];for(let e of res.data.error.errors)typeof e=="object"&&"message"in e&&typeof e.message=="string"&&errorMessages.push(e.message);return Object.assign({message:errorMessages.join(`
|
|
2
|
+
import{import_websocket}from"./chunk-YBZDAABT.js";import{normalizeToolCallId}from"./chunk-2IHY6ZLW.js";import{retryProviderRequest}from"./chunk-KLBKUBDV.js";import{getJsonSchemaToolParameters,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-Z2N5372Y.js";import{sanitizeSurrogates}from"./chunk-WDTJ6JKE.js";import{__commonJS,__require,__toESM}from"./chunk-IKOFCODM.js";var require_retry_operation=__commonJS({"node_modules/retry/lib/retry_operation.js"(exports,module){function RetryOperation(timeouts,options){typeof options=="boolean"&&(options={forever:options}),this._originalTimeouts=JSON.parse(JSON.stringify(timeouts)),this._timeouts=timeouts,this._options=options||{},this._maxRetryTime=options&&options.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}module.exports=RetryOperation;RetryOperation.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};RetryOperation.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};RetryOperation.prototype.retry=function(err){if(this._timeout&&clearTimeout(this._timeout),!err)return!1;var currentTime=new Date().getTime();if(err&¤tTime-this._operationStart>=this._maxRetryTime)return this._errors.push(err),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(err);var timeout=this._timeouts.shift();if(timeout===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),timeout=this._cachedTimeouts.slice(-1);else return!1;var self2=this;return this._timer=setTimeout(function(){self2._attempts++,self2._operationTimeoutCb&&(self2._timeout=setTimeout(function(){self2._operationTimeoutCb(self2._attempts)},self2._operationTimeout),self2._options.unref&&self2._timeout.unref()),self2._fn(self2._attempts)},timeout),this._options.unref&&this._timer.unref(),!0};RetryOperation.prototype.attempt=function(fn,timeoutOps){this._fn=fn,timeoutOps&&(timeoutOps.timeout&&(this._operationTimeout=timeoutOps.timeout),timeoutOps.cb&&(this._operationTimeoutCb=timeoutOps.cb));var self2=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){self2._operationTimeoutCb()},self2._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};RetryOperation.prototype.try=function(fn){console.log("Using RetryOperation.try() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=function(fn){console.log("Using RetryOperation.start() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=RetryOperation.prototype.try;RetryOperation.prototype.errors=function(){return this._errors};RetryOperation.prototype.attempts=function(){return this._attempts};RetryOperation.prototype.mainError=function(){if(this._errors.length===0)return null;for(var counts={},mainError=null,mainErrorCount=0,i=0;i<this._errors.length;i++){var error=this._errors[i],message=error.message,count=(counts[message]||0)+1;counts[message]=count,count>=mainErrorCount&&(mainError=error,mainErrorCount=count)}return mainError}}});var require_retry=__commonJS({"node_modules/retry/lib/retry.js"(exports){var RetryOperation=require_retry_operation();exports.operation=function(options){var timeouts=exports.timeouts(options);return new RetryOperation(timeouts,{forever:options&&(options.forever||options.retries===1/0),unref:options&&options.unref,maxRetryTime:options&&options.maxRetryTime})};exports.timeouts=function(options){if(options instanceof Array)return[].concat(options);var opts={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var key in options)opts[key]=options[key];if(opts.minTimeout>opts.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var timeouts=[],i=0;i<opts.retries;i++)timeouts.push(this.createTimeout(i,opts));return options&&options.forever&&!timeouts.length&&timeouts.push(this.createTimeout(i,opts)),timeouts.sort(function(a,b){return a-b}),timeouts};exports.createTimeout=function(attempt,opts){var random=opts.randomize?Math.random()+1:1,timeout=Math.round(random*Math.max(opts.minTimeout,1)*Math.pow(opts.factor,attempt));return timeout=Math.min(timeout,opts.maxTimeout),timeout};exports.wrap=function(obj,options,methods){if(options instanceof Array&&(methods=options,options=null),!methods){methods=[];for(var key in obj)typeof obj[key]=="function"&&methods.push(key)}for(var i=0;i<methods.length;i++){var method=methods[i],original=obj[method];obj[method]=function(original2){var op=exports.operation(options),args=Array.prototype.slice.call(arguments,1),callback=args.pop();args.push(function(err){op.retry(err)||(err&&(arguments[0]=op.mainError()),callback.apply(this,arguments))}),op.attempt(function(){original2.apply(obj,args)})}.bind(obj,original),obj[method].options=options}}}});var require_retry2=__commonJS({"node_modules/retry/index.js"(exports,module){module.exports=require_retry()}});var require_p_retry=__commonJS({"node_modules/p-retry/index.js"(exports,module){"use strict";var retry2=require_retry2(),networkErrorMsgs=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"],AbortError=class extends Error{constructor(message){super(),message instanceof Error?(this.originalError=message,{message}=message):(this.originalError=new Error(message),this.originalError.stack=this.stack),this.name="AbortError",this.message=message}},decorateErrorWithCounts=(error,attemptNumber,options)=>{let retriesLeft=options.retries-(attemptNumber-1);return error.attemptNumber=attemptNumber,error.retriesLeft=retriesLeft,error},isNetworkError=errorMessage=>networkErrorMsgs.includes(errorMessage),pRetry2=(input,options)=>new Promise((resolve,reject)=>{options={onFailedAttempt:()=>{},retries:10,...options};let operation=retry2.operation(options);operation.attempt(async attemptNumber=>{try{resolve(await input(attemptNumber))}catch(error){if(!(error instanceof Error)){reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`));return}if(error instanceof AbortError)operation.stop(),reject(error.originalError);else if(error instanceof TypeError&&!isNetworkError(error.message))operation.stop(),reject(error);else{decorateErrorWithCounts(error,attemptNumber,options);try{await options.onFailedAttempt(error)}catch(error2){reject(error2);return}operation.retry(error)||reject(operation.mainError())}}})});module.exports=pRetry2;module.exports.default=pRetry2;module.exports.AbortError=AbortError}});var require_extend=__commonJS({"node_modules/extend/index.js"(exports,module){"use strict";var hasOwn2=Object.prototype.hasOwnProperty,toStr=Object.prototype.toString,defineProperty=Object.defineProperty,gOPD=Object.getOwnPropertyDescriptor,isArray=function(arr){return typeof Array.isArray=="function"?Array.isArray(arr):toStr.call(arr)==="[object Array]"},isPlainObject2=function(obj){if(!obj||toStr.call(obj)!=="[object Object]")return!1;var hasOwnConstructor=hasOwn2.call(obj,"constructor"),hasIsPrototypeOf=obj.constructor&&obj.constructor.prototype&&hasOwn2.call(obj.constructor.prototype,"isPrototypeOf");if(obj.constructor&&!hasOwnConstructor&&!hasIsPrototypeOf)return!1;var key;for(key in obj);return typeof key>"u"||hasOwn2.call(obj,key)},setProperty=function(target,options){defineProperty&&options.name==="__proto__"?defineProperty(target,options.name,{enumerable:!0,configurable:!0,value:options.newValue,writable:!0}):target[options.name]=options.newValue},getProperty=function(obj,name){if(name==="__proto__")if(hasOwn2.call(obj,name)){if(gOPD)return gOPD(obj,name).value}else return;return obj[name]};module.exports=function extend(){var options,name,src,copy,copyIsArray,clone,target=arguments[0],i=1,length=arguments.length,deep=!1;for(typeof target=="boolean"&&(deep=target,target=arguments[1]||{},i=2),(target==null||typeof target!="object"&&typeof target!="function")&&(target={});i<length;++i)if(options=arguments[i],options!=null)for(name in options)src=getProperty(target,name),copy=getProperty(options,name),target!==copy&&(deep&©&&(isPlainObject2(copy)||(copyIsArray=isArray(copy)))?(copyIsArray?(copyIsArray=!1,clone=src&&isArray(src)?src:[]):clone=src&&isPlainObject2(src)?src:{},setProperty(target,{name,newValue:extend(deep,clone,copy)})):typeof copy<"u"&&setProperty(target,{name,newValue:copy}));return target}}});var require_package=__commonJS({"node_modules/gaxios/package.json"(exports,module){module.exports={name:"gaxios",version:"7.1.4",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","docs-test":"linkinator docs","predocs-test":"npm run docs","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"packages/gaxios",url:"https://github.com/googleapis/google-cloud-node-core.git"},keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^22.13.1","@types/sinon":"^17.0.3","@types/tmp":"^0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.1.3",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",linkinator:"^6.1.2",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.1","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","stream-browserify":"^3.0.0",tmp:"0.2.5","ts-loader":"^9.5.2",typescript:"5.8.3",webpack:"^5.97.1","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"},homepage:"https://github.com/googleapis/google-cloud-node-core/tree/main/packages/gaxios"}}});var require_util=__commonJS({"node_modules/gaxios/build/cjs/src/util.cjs"(exports,module){"use strict";var pkg=require_package();module.exports={pkg}}});var require_common=__commonJS({"node_modules/gaxios/build/cjs/src/common.js"(exports){"use strict";var __importDefault=exports&&exports.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:!0});exports.GaxiosError=exports.GAXIOS_ERROR_SYMBOL=void 0;exports.defaultErrorRedactor=defaultErrorRedactor;var extend_1=__importDefault(require_extend()),util_cjs_1=__importDefault(require_util()),pkg=util_cjs_1.default.pkg;exports.GAXIOS_ERROR_SYMBOL=Symbol.for(`${pkg.name}-gaxios-error`);var GaxiosError=class _GaxiosError extends Error{config;response;code;status;error;[exports.GAXIOS_ERROR_SYMBOL]=pkg.version;static[Symbol.hasInstance](instance){return instance&&typeof instance=="object"&&exports.GAXIOS_ERROR_SYMBOL in instance&&instance[exports.GAXIOS_ERROR_SYMBOL]===pkg.version?!0:Function.prototype[Symbol.hasInstance].call(_GaxiosError,instance)}constructor(message,config,response,cause){if(super(message,{cause}),this.config=config,this.response=response,this.error=cause instanceof Error?cause:void 0,this.config=(0,extend_1.default)(!0,{},config),this.response&&(this.response.config=(0,extend_1.default)(!0,{},this.response.config)),this.response){try{this.response.data=translateData(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}cause instanceof DOMException?this.code=cause.name:cause&&typeof cause=="object"&&"code"in cause&&(typeof cause.code=="string"||typeof cause.code=="number")&&(this.code=cause.code)}static extractAPIErrorFromResponse(res,defaultErrorMessage="The request failed"){let message=defaultErrorMessage;if(typeof res.data=="string"&&(message=res.data),res.data&&typeof res.data=="object"&&"error"in res.data&&res.data.error&&!res.ok){if(typeof res.data.error=="string")return{message:res.data.error,code:res.status,status:res.statusText};if(typeof res.data.error=="object"){message="message"in res.data.error&&typeof res.data.error.message=="string"?res.data.error.message:message;let status="status"in res.data.error&&typeof res.data.error.status=="string"?res.data.error.status:res.statusText,code="code"in res.data.error&&typeof res.data.error.code=="number"?res.data.error.code:res.status;if("errors"in res.data.error&&Array.isArray(res.data.error.errors)){let errorMessages=[];for(let e of res.data.error.errors)typeof e=="object"&&"message"in e&&typeof e.message=="string"&&errorMessages.push(e.message);return Object.assign({message:errorMessages.join(`
|
|
3
3
|
`)||message,code,status},res.data.error)}return Object.assign({message,code,status},res.data.error)}}return{message,code:res.status,status:res.statusText}}};exports.GaxiosError=GaxiosError;function translateData(responseType,data){switch(responseType){case"stream":return data;case"json":return JSON.parse(JSON.stringify(data));case"arraybuffer":return JSON.parse(Buffer.from(data).toString("utf8"));case"blob":return JSON.parse(data.text());default:return data}}function defaultErrorRedactor(data){let REDACT="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function redactHeaders(headers){headers&&headers.forEach((_,key)=>{(/^authentication$/i.test(key)||/^authorization$/i.test(key)||/secret/i.test(key))&&headers.set(key,REDACT)})}function redactString(obj,key){if(typeof obj=="object"&&obj!==null&&typeof obj[key]=="string"){let text=obj[key];(/grant_type=/i.test(text)||/assertion=/i.test(text)||/secret/i.test(text))&&(obj[key]=REDACT)}}function redactObject(obj){!obj||typeof obj!="object"||(obj instanceof FormData||obj instanceof URLSearchParams||"forEach"in obj&&"set"in obj?obj.forEach((_,key)=>{(["grant_type","assertion"].includes(key)||/secret/.test(key))&&obj.set(key,REDACT)}):("grant_type"in obj&&(obj.grant_type=REDACT),"assertion"in obj&&(obj.assertion=REDACT),"client_secret"in obj&&(obj.client_secret=REDACT)))}return data.config&&(redactHeaders(data.config.headers),redactString(data.config,"data"),redactObject(data.config.data),redactString(data.config,"body"),redactObject(data.config.body),data.config.url.searchParams.has("token")&&data.config.url.searchParams.set("token",REDACT),data.config.url.searchParams.has("client_secret")&&data.config.url.searchParams.set("client_secret",REDACT)),data.response&&(defaultErrorRedactor({config:data.response.config}),redactHeaders(data.response.headers),data.response.bodyUsed&&(redactString(data.response,"data"),redactObject(data.response.data))),data}}});var require_retry3=__commonJS({"node_modules/gaxios/build/cjs/src/retry.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.getRetryConfig=getRetryConfig;async function getRetryConfig(err){let config=getConfig(err);if(!err||!err.config||!config&&!err.config.retry)return{shouldRetry:!1};config=config||{},config.currentRetryAttempt=config.currentRetryAttempt||0,config.retry=config.retry===void 0||config.retry===null?3:config.retry,config.httpMethodsToRetry=config.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],config.noResponseRetries=config.noResponseRetries===void 0||config.noResponseRetries===null?2:config.noResponseRetries,config.retryDelayMultiplier=config.retryDelayMultiplier?config.retryDelayMultiplier:2,config.timeOfFirstRequest=config.timeOfFirstRequest?config.timeOfFirstRequest:Date.now(),config.totalTimeout=config.totalTimeout?config.totalTimeout:Number.MAX_SAFE_INTEGER,config.maxRetryDelay=config.maxRetryDelay?config.maxRetryDelay:Number.MAX_SAFE_INTEGER;let retryRanges=[[100,199],[408,408],[429,429],[500,599]];if(config.statusCodesToRetry=config.statusCodesToRetry||retryRanges,err.config.retryConfig=config,!await(config.shouldRetry||shouldRetryRequest)(err))return{shouldRetry:!1,config:err.config};let delay2=getNextRetryDelay(config);err.config.retryConfig.currentRetryAttempt+=1;let backoff=config.retryBackoff?config.retryBackoff(err,delay2):new Promise(resolve=>{setTimeout(resolve,delay2)});return config.onRetryAttempt&&await config.onRetryAttempt(err),await backoff,{shouldRetry:!0,config:err.config}}function shouldRetryRequest(err){let config=getConfig(err);if(err.config.signal?.aborted&&err.code!=="TimeoutError"||err.code==="AbortError"||!config||config.retry===0||!err.response&&(config.currentRetryAttempt||0)>=config.noResponseRetries||!config.httpMethodsToRetry||!config.httpMethodsToRetry.includes(err.config.method?.toUpperCase()||"GET"))return!1;if(err.response&&err.response.status){let isInRange=!1;for(let[min,max]of config.statusCodesToRetry){let status=err.response.status;if(status>=min&&status<=max){isInRange=!0;break}}if(!isInRange)return!1}return config.currentRetryAttempt=config.currentRetryAttempt||0,!(config.currentRetryAttempt>=config.retry)}function getConfig(err){if(err&&err.config&&err.config.retryConfig)return err.config.retryConfig}function getNextRetryDelay(config){let calculatedDelay=(config.currentRetryAttempt?0:config.retryDelay??100)+(Math.pow(config.retryDelayMultiplier,config.currentRetryAttempt)-1)/2*1e3,maxAllowableDelay=config.totalTimeout-(Date.now()-config.timeOfFirstRequest);return Math.min(calculatedDelay,maxAllowableDelay,config.maxRetryDelay)}}});var require_interceptor=__commonJS({"node_modules/gaxios/build/cjs/src/interceptor.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.GaxiosInterceptorManager=void 0;var GaxiosInterceptorManager=class extends Set{};exports.GaxiosInterceptorManager=GaxiosInterceptorManager}});var require_gaxios=__commonJS({"node_modules/gaxios/build/cjs/src/gaxios.js"(exports){"use strict";var __importDefault=exports&&exports.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}},_a2;Object.defineProperty(exports,"__esModule",{value:!0});exports.Gaxios=void 0;var extend_1=__importDefault(require_extend()),https_1=__require("https"),common_js_1=require_common(),retry_js_1=require_retry3(),stream_1=__require("stream"),interceptor_js_1=require_interceptor(),randomUUID=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),HTTP_STATUS_NO_CONTENT=204,Gaxios=class{agentCache=new Map;defaults;interceptors;constructor(defaults){this.defaults=defaults||{},this.interceptors={request:new interceptor_js_1.GaxiosInterceptorManager,response:new interceptor_js_1.GaxiosInterceptorManager}}fetch(...args){let input=args[0],init=args[1],url,headers=new Headers;return typeof input=="string"?url=new URL(input):input instanceof URL?url=input:input&&input.url&&(url=new URL(input.url)),input&&typeof input=="object"&&"headers"in input&&_a2.mergeHeaders(headers,input.headers),init&&_a2.mergeHeaders(headers,new Headers(init.headers)),typeof input=="object"&&!(input instanceof URL)?this.request({...init,...input,headers,url}):this.request({...init,headers,url})}async request(opts={}){let prepared=await this.#prepareRequest(opts);return prepared=await this.#applyRequestInterceptors(prepared),this.#applyResponseInterceptors(this._request(prepared))}async _defaultAdapter(config){let fetchImpl=config.fetchImplementation||this.defaults.fetchImplementation||await _a2.#getFetch(),preparedOpts={...config};delete preparedOpts.data;let res=await fetchImpl(config.url,preparedOpts),data=await this.getResponseData(config,res);return Object.getOwnPropertyDescriptor(res,"data")?.configurable||Object.defineProperties(res,{data:{configurable:!0,writable:!0,enumerable:!0,value:data}}),Object.assign(res,{config,data})}async _request(opts){try{let translatedResponse;if(opts.adapter?translatedResponse=await opts.adapter(opts,this._defaultAdapter.bind(this)):translatedResponse=await this._defaultAdapter(opts),!opts.validateStatus(translatedResponse.status)){if(opts.responseType==="stream"){let response=[];for await(let chunk of translatedResponse.data)response.push(chunk);translatedResponse.data=response.toString()}let errorInfo=common_js_1.GaxiosError.extractAPIErrorFromResponse(translatedResponse,`Request failed with status code ${translatedResponse.status}`);throw new common_js_1.GaxiosError(errorInfo?.message,opts,translatedResponse,errorInfo)}return translatedResponse}catch(e){let err;e instanceof common_js_1.GaxiosError?err=e:e instanceof Error?err=new common_js_1.GaxiosError(e.message,opts,void 0,e):err=new common_js_1.GaxiosError("Unexpected Gaxios Error",opts,void 0,e);let{shouldRetry,config}=await(0,retry_js_1.getRetryConfig)(err);if(shouldRetry&&config)return err.config.retryConfig.currentRetryAttempt=config.retryConfig.currentRetryAttempt,opts.retryConfig=err.config?.retryConfig,this.#appendTimeoutToSignal(opts),this._request(opts);throw opts.errorRedactor&&opts.errorRedactor(err),err}}async getResponseData(opts,res){if(res.status===HTTP_STATUS_NO_CONTENT)return"";if(opts.maxContentLength&&res.headers.has("content-length")&&opts.maxContentLength<Number.parseInt(res.headers?.get("content-length")||""))throw new common_js_1.GaxiosError("Response's `Content-Length` is over the limit.",opts,Object.assign(res,{config:opts}));switch(opts.responseType){case"stream":return res.body;case"json":{let data=await res.text();try{return JSON.parse(data)}catch{return data}}case"arraybuffer":return res.arrayBuffer();case"blob":return res.blob();case"text":return res.text();default:return this.getResponseDataFromContentType(res)}}#urlMayUseProxy(url,noProxy=[]){let candidate=new URL(url),noProxyList=[...noProxy],noProxyEnvList=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(let rule of noProxyEnvList)noProxyList.push(rule.trim());for(let rule of noProxyList)if(rule instanceof RegExp){if(rule.test(candidate.toString()))return!1}else if(rule instanceof URL){if(rule.origin===candidate.origin)return!1}else if(rule.startsWith("*.")||rule.startsWith(".")){let cleanedRule=rule.replace(/^\*\./,".");if(candidate.hostname.endsWith(cleanedRule))return!1}else if(rule===candidate.origin||rule===candidate.hostname||rule===candidate.href)return!1;return!0}async#applyRequestInterceptors(options){let promiseChain=Promise.resolve(options);for(let interceptor of this.interceptors.request.values())interceptor&&(promiseChain=promiseChain.then(interceptor.resolved,interceptor.rejected));return promiseChain}async#applyResponseInterceptors(response){let promiseChain=Promise.resolve(response);for(let interceptor of this.interceptors.response.values())interceptor&&(promiseChain=promiseChain.then(interceptor.resolved,interceptor.rejected));return promiseChain}async#prepareRequest(options){let preparedHeaders=new Headers(this.defaults.headers);_a2.mergeHeaders(preparedHeaders,options.headers);let opts=(0,extend_1.default)(!0,{},this.defaults,options);if(!opts.url)throw new Error("URL is required.");if(opts.baseURL&&(opts.url=new URL(opts.url,opts.baseURL)),opts.url=new URL(opts.url),opts.params)if(opts.paramsSerializer){let additionalQueryParams=opts.paramsSerializer(opts.params);additionalQueryParams.startsWith("?")&&(additionalQueryParams=additionalQueryParams.slice(1));let prefix=opts.url.toString().includes("?")?"&":"?";opts.url=opts.url+prefix+additionalQueryParams}else{let url=opts.url instanceof URL?opts.url:new URL(opts.url);for(let[key,value]of new URLSearchParams(opts.params))url.searchParams.append(key,value);opts.url=url}typeof options.maxContentLength=="number"&&(opts.size=options.maxContentLength),typeof options.maxRedirects=="number"&&(opts.follow=options.maxRedirects);let shouldDirectlyPassData=typeof opts.data=="string"||opts.data instanceof ArrayBuffer||opts.data instanceof Blob||globalThis.File&&opts.data instanceof File||opts.data instanceof FormData||opts.data instanceof stream_1.Readable||opts.data instanceof ReadableStream||opts.data instanceof String||opts.data instanceof URLSearchParams||ArrayBuffer.isView(opts.data)||["Blob","File","FormData"].includes(opts.data?.constructor?.name||"");if(opts.multipart?.length){let boundary=await randomUUID();preparedHeaders.set("content-type",`multipart/related; boundary=${boundary}`),opts.body=stream_1.Readable.from(this.getMultipartRequest(opts.multipart,boundary))}else shouldDirectlyPassData?opts.body=opts.data:typeof opts.data=="object"?preparedHeaders.get("Content-Type")==="application/x-www-form-urlencoded"?opts.body=opts.paramsSerializer?opts.paramsSerializer(opts.data):new URLSearchParams(opts.data):(preparedHeaders.has("content-type")||preparedHeaders.set("content-type","application/json"),opts.body=JSON.stringify(opts.data)):opts.data&&(opts.body=opts.data);opts.validateStatus=opts.validateStatus||this.validateStatus,opts.responseType=opts.responseType||"unknown",!preparedHeaders.has("accept")&&opts.responseType==="json"&&preparedHeaders.set("accept","application/json");let proxy=opts.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(!opts.agent)if(proxy&&this.#urlMayUseProxy(opts.url,opts.noProxy)){let HttpsProxyAgent=await _a2.#getProxyAgent();this.agentCache.has(proxy)?opts.agent=this.agentCache.get(proxy):(opts.agent=new HttpsProxyAgent(proxy,{cert:opts.cert,key:opts.key}),this.agentCache.set(proxy,opts.agent))}else opts.cert&&opts.key&&(this.agentCache.has(opts.key)?opts.agent=this.agentCache.get(opts.key):(opts.agent=new https_1.Agent({cert:opts.cert,key:opts.key}),this.agentCache.set(opts.key,opts.agent)));return typeof opts.errorRedactor!="function"&&opts.errorRedactor!==!1&&(opts.errorRedactor=common_js_1.defaultErrorRedactor),opts.body&&!("duplex"in opts)&&(opts.duplex="half"),this.#appendTimeoutToSignal(opts),Object.assign(opts,{headers:preparedHeaders,url:opts.url instanceof URL?opts.url:new URL(opts.url)})}#appendTimeoutToSignal(opts){if(opts.timeout){let timeoutSignal=AbortSignal.timeout(opts.timeout);opts.signal&&!opts.signal.aborted?opts.signal=AbortSignal.any([opts.signal,timeoutSignal]):opts.signal=timeoutSignal}}validateStatus(status){return status>=200&&status<300}async getResponseDataFromContentType(response){let contentType=response.headers.get("Content-Type");if(contentType===null)return response.text();if(contentType=contentType.toLowerCase(),contentType.includes("application/json")){let data=await response.text();try{data=JSON.parse(data)}catch{}return data}else return contentType.match(/^text\//)?response.text():response.blob()}async*getMultipartRequest(multipartOptions,boundary){let finale=`--${boundary}--`;for(let currentPart of multipartOptions){let partContentType=currentPart.headers.get("Content-Type")||"application/octet-stream";yield`--${boundary}\r
|
|
4
4
|
Content-Type: ${partContentType}\r
|
|
5
5
|
\r
|
|
@@ -1,3 +1,3 @@
|
|
|
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{classifyProviderFailure}from"./chunk-YOPVJDSU.js";import{attachProviderDiagnostic}from"./chunk-45SZOLCU.js";import{normalizeProviderError}from"./chunk-BBK6SSYT.js";import{formatProviderRequestId}from"./chunk-
|
|
2
|
+
import{classifyProviderFailure}from"./chunk-YOPVJDSU.js";import{attachProviderDiagnostic}from"./chunk-45SZOLCU.js";import{normalizeProviderError}from"./chunk-BBK6SSYT.js";import{formatProviderRequestId}from"./chunk-Z2N5372Y.js";import{appendAssistantMessageDiagnostic}from"./chunk-DMI55M2N.js";var GITHUB_COPILOT_TOOL_LIMIT=128,GITHUB_COPILOT_TOOL_LIMIT_DIAGNOSTIC="github_copilot_tool_limit";function isRecord(value){return typeof value=="object"&&value!==null}function selectedToolName(toolChoice){if(isRecord(toolChoice)){if(toolChoice.type==="function")return isRecord(toolChoice.function)&&typeof toolChoice.function.name=="string"?toolChoice.function.name:typeof toolChoice.name=="string"?toolChoice.name:void 0;if(!(toolChoice.type!=="custom"&&toolChoice.type!=="tool"))return typeof toolChoice.name=="string"?toolChoice.name:void 0}}function toolName(tool){if(isRecord(tool))return tool.type==="function"&&isRecord(tool.function)&&typeof tool.function.name=="string"?tool.function.name:typeof tool.name=="string"?tool.name:void 0}function limitGitHubCopilotTools(provider,tools,toolChoice){if(provider!=="github-copilot"||tools===void 0||tools.length<=GITHUB_COPILOT_TOOL_LIMIT)return{tools,omittedCount:0};let forcedName=selectedToolName(toolChoice),forcedIndex=forcedName===void 0?-1:tools.findIndex(tool=>toolName(tool)===forcedName);if(forcedIndex>=GITHUB_COPILOT_TOOL_LIMIT){let forcedTool=tools[forcedIndex];if(forcedTool!==void 0)return{tools:[...tools.slice(0,GITHUB_COPILOT_TOOL_LIMIT-1),forcedTool],omittedCount:tools.length-GITHUB_COPILOT_TOOL_LIMIT}}return{tools:tools.slice(0,GITHUB_COPILOT_TOOL_LIMIT),omittedCount:tools.length-GITHUB_COPILOT_TOOL_LIMIT}}function recordGitHubCopilotToolLimit(message,omittedCount){omittedCount===0||message.diagnostics?.some(diagnostic=>diagnostic.type===GITHUB_COPILOT_TOOL_LIMIT_DIAGNOSTIC)||appendAssistantMessageDiagnostic(message,{type:GITHUB_COPILOT_TOOL_LIMIT_DIAGNOSTIC,timestamp:Date.now(),details:{limit:GITHUB_COPILOT_TOOL_LIMIT,omittedCount,message:`GitHub Copilot accepts at most ${GITHUB_COPILOT_TOOL_LIMIT} tools on endpoints without tool search; senpi omitted ${omittedCount} excess tool definition${omittedCount===1?"":"s"}.`}})}function formatGitHubCopilotToolLimitError(message,errorMessage){let toolLimitApplied=message.diagnostics?.some(diagnostic=>diagnostic.type===GITHUB_COPILOT_TOOL_LIMIT_DIAGNOSTIC);return message.provider!=="github-copilot"||!toolLimitApplied||message.providerDiagnostic?.httpStatus!==400||!/400 Bad Request$/i.test(errorMessage)?errorMessage:`GitHub Copilot rejected the request after senpi limited its tool list to ${GITHUB_COPILOT_TOOL_LIMIT}. The endpoint may enforce a lower limit or count additional hosted tools. (${errorMessage})`}var SSE_ERROR_ENVELOPE_MAX_BYTES=8192;function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function optionalString(value){if(value!=null)return typeof value=="string"?value:null}function anthropicProviderDiagnosticFromError(error){try{if(!(error instanceof Error))return;let status=Reflect.get(error,"status"),direct=optionalString(Reflect.get(error,"type")),body=Reflect.get(error,"error"),nested=isRecord2(body)&&isRecord2(body.error)?optionalString(body.error.type):void 0;if(direct===null||nested===null||direct!==void 0&&nested!==void 0&&direct!==nested)return;let code=direct??nested;return code===void 0&&status==null?void 0:classifyProviderFailure({status,code})}catch{return}}function anthropicProviderDiagnosticFromSseData(data){try{if(new TextEncoder().encode(data).length>SSE_ERROR_ENVELOPE_MAX_BYTES)return;let parsed=JSON.parse(data);if(!isRecord2(parsed)||parsed.type!=="error"||!isRecord2(parsed.error))return;let code=parsed.error.type;return typeof code!="string"?void 0:classifyProviderFailure({status:void 0,code})}catch{return}}function openAICompatibleProviderDiagnosticFromError(error){try{if(!(error instanceof Error))return;let status=Reflect.get(error,"status"),code=optionalString(Reflect.get(error,"code"));return code===null||code===void 0&&status==null?void 0:classifyProviderFailure({status,code})}catch{return}}async function awaitProviderTransport(request,classify){try{return await request()}catch(error){throw typeof error=="object"&&error!==null&&attachProviderDiagnostic(error,classify(error)),error}}async function*iterateProviderTransport(source,classify){try{yield*source}catch(error){throw typeof error=="object"&&error!==null&&attachProviderDiagnostic(error,classify(error)),error}}var QUOTA_CODES=new Set(["quota_exceeded","free_quota_exceeded","overage_limit_reached","billing_not_configured","additional_spend_limit_reached"]);function headerValue(headers,name){if(headers instanceof Headers)return headers.get(name)??void 0;if(!(typeof headers!="object"||headers===null)){for(let[key,value]of Object.entries(headers))if(key.toLowerCase()===name&&typeof value=="string")return value}}function errorCode(body){if(body!==void 0)try{let parsed=JSON.parse(body);if(typeof parsed!="object"||parsed===null)return;let nested=Reflect.get(parsed,"error"),code=Reflect.get(typeof nested=="object"&&nested!==null?nested:parsed,"code");return typeof code=="string"?code:void 0}catch{return}}function isQuotaFailure(status,body,limitKey){let code=errorCode(body);return code!==void 0&"A_CODES.has(code)||status===402?!0:status===429&&(limitKey?.includes("quota")===!0||/quota exceeded/i.test(body??""))}function describeGitHubCopilotFailure(error){if(!(error instanceof Error))return;let{status,body}=normalizeProviderError(error);if(status===void 0)return;let headers=Reflect.get(error,"headers"),requestId=headerValue(headers,"x-github-request-id"),reference=requestId===void 0?"":` ${formatProviderRequestId("GitHub",requestId)}.`;if(isQuotaFailure(status,body,headerValue(headers,"x-ratelimit-exceeded")))return`GitHub Copilot quota exceeded (HTTP ${status}): the plan's included usage or its additional-usage limit is used up, so premium models are refused until it resets or the limit is raised. Usage is shown at https://github.com/settings/copilot.${reference}`;if(status===421)return`GitHub Copilot sent this account to a different API host (HTTP 421 Misdirected Request): Business and Enterprise accounts are served from their own host, which senpi reads from the Copilot token. Run /login github-copilot so senpi stores the account's endpoint, and report it with the GitHub request id if it persists.${reference}`;if(status===403)return`GitHub Copilot refused the request (HTTP 403${body===void 0?" with an empty body":""}). Copilot checks access per model and per client; if a fresh /login github-copilot does not help, report it with the GitHub request id.${reference}`}function withGitHubCopilotFailureNote(message,provider,error){if(provider!=="github-copilot")return message;let note=describeGitHubCopilotFailure(error);return note===void 0?message:`${message}
|
|
3
3
|
${note}`}export{limitGitHubCopilotTools,recordGitHubCopilotToolLimit,formatGitHubCopilotToolLimitError,anthropicProviderDiagnosticFromError,anthropicProviderDiagnosticFromSseData,openAICompatibleProviderDiagnosticFromError,awaitProviderTransport,iterateProviderTransport,withGitHubCopilotFailureNote};
|