@code-yeongyu/senpi 2026.10.26-1 → 2026.10.26-2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +24 -0
- package/dist/bundle/chunks/{anthropic-messages-M235FJQV.js → anthropic-messages-ODSFJCXR.js} +1 -1
- package/dist/bundle/chunks/{args-FBNJOJSR.js → args-SWKJAYQD.js} +1 -1
- package/dist/bundle/chunks/{azure-openai-responses-YQRTQ7H6.js → azure-openai-responses-REGXS4XO.js} +1 -1
- package/dist/bundle/chunks/bedrock-converse-stream.js +1 -1
- package/dist/bundle/chunks/chunk-2XF6W6F6.js +410 -0
- package/dist/bundle/chunks/{chunk-DMFAVE5N.js → chunk-4QVORFQ2.js} +1 -1
- package/dist/bundle/chunks/{chunk-ZXHLH4MW.js → chunk-5W3DTM2J.js} +1 -1
- package/dist/bundle/chunks/{chunk-QREKAXKX.js → chunk-6GAMRAVM.js} +5 -5
- package/dist/bundle/chunks/{chunk-MSHRIZGT.js → chunk-7IZH2KQX.js} +3 -3
- package/dist/bundle/chunks/{chunk-PH3JDRB2.js → chunk-ARSENVDY.js} +1 -1
- package/dist/bundle/chunks/{chunk-5KZH6EYQ.js → chunk-CNDPCYNT.js} +1 -1
- package/dist/bundle/chunks/{chunk-DYWIFF2Q.js → chunk-CYOHFREV.js} +1 -1
- package/dist/bundle/chunks/{chunk-3LPWILUZ.js → chunk-DNDZPKIQ.js} +1 -1
- package/dist/bundle/chunks/{chunk-ZLIVZQDY.js → chunk-EQNUL2WB.js} +1 -1
- package/dist/bundle/chunks/{chunk-5FQMNHXV.js → chunk-ESNSRUW4.js} +1 -1
- package/dist/bundle/chunks/{chunk-LO5MYLGF.js → chunk-FQDARFHT.js} +1 -1
- package/dist/bundle/chunks/{chunk-7KOUQSBX.js → chunk-GPPOPK76.js} +3 -3
- package/dist/bundle/chunks/chunk-I2WFLKZ2.js +5 -0
- package/dist/bundle/chunks/{chunk-I7QWTWVZ.js → chunk-IHKHCWWG.js} +1 -1
- package/dist/bundle/chunks/{chunk-MY4ZD3EW.js → chunk-IY4G44MN.js} +1 -1
- package/dist/bundle/chunks/{chunk-OQ3WDMB3.js → chunk-JH7MVRNJ.js} +1 -1
- package/dist/bundle/chunks/chunk-KBSFTXAT.js +2 -0
- package/dist/bundle/chunks/{chunk-UW6M3EXY.js → chunk-KRO63T4Q.js} +1 -1
- package/dist/bundle/chunks/{chunk-J5FCH7TI.js → chunk-KTDIIF2F.js} +1 -1
- package/dist/bundle/chunks/{chunk-3WP5RFQR.js → chunk-NDNIMC5W.js} +1 -1
- package/dist/bundle/chunks/{chunk-CDQPA4FP.js → chunk-ODRGPC5S.js} +1 -1
- package/dist/bundle/chunks/{chunk-3A3XCLNH.js → chunk-PDG4XWO2.js} +1 -1
- package/dist/bundle/chunks/{chunk-QYFOHFPS.js → chunk-PPECSSWX.js} +1 -1
- package/dist/bundle/chunks/{chunk-5LWUUXMH.js → chunk-PY4ZQHTN.js} +1 -1
- package/dist/bundle/chunks/{chunk-EZP6AYW2.js → chunk-RPW3XQW3.js} +22 -22
- package/dist/bundle/chunks/{chunk-SOXQ42VS.js → chunk-RQ5JTXUC.js} +1 -1
- package/dist/bundle/chunks/{chunk-JFQUWEN7.js → chunk-TQ67PB7U.js} +2 -2
- package/dist/bundle/chunks/{chunk-6U3TBFBA.js → chunk-UJPG4ROT.js} +1 -1
- package/dist/bundle/chunks/{chunk-UDM7VO6O.js → chunk-XM36IFP3.js} +1 -1
- package/dist/bundle/chunks/{chunk-XQ45JMGN.js → chunk-Z6BREXV3.js} +1 -1
- package/dist/bundle/chunks/{chunk-ADQAPDPV.js → chunk-ZP6JJDYV.js} +1 -1
- package/dist/bundle/chunks/{cli-main-55EQA5PS.js → cli-main-Q2GA53XM.js} +1 -1
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-ZJQGIIRC.js → cloudflare-workers-ai-system-one-WDHT7BBV.js} +1 -1
- package/dist/bundle/chunks/cursor-agent.js +1 -1
- package/dist/bundle/chunks/devin-agent.js +1 -1
- package/dist/bundle/chunks/{dispatch-C2IBP5VV.js → dispatch-5R3TYAYB.js} +3 -3
- package/dist/bundle/chunks/{google-generative-ai-5G4RIQA6.js → google-generative-ai-FHYFXKLA.js} +1 -1
- package/dist/bundle/chunks/{google-vertex-ALD4P27O.js → google-vertex-5DWE5U5K.js} +1 -1
- package/dist/bundle/chunks/{help-fast-path-PEIKGCKZ.js → help-fast-path-FETLIF3W.js} +1 -1
- package/dist/bundle/chunks/{host-command-657VCQ34.js → host-command-XEB7SHT3.js} +1 -1
- package/dist/bundle/chunks/{host-session-command-OV5XDOJK.js → host-session-command-FFN52LXJ.js} +1 -1
- package/dist/bundle/chunks/{interactive-mode-MLXSYK2H.js → interactive-mode-5DEKY3YW.js} +1 -1
- package/dist/bundle/chunks/{mistral-conversations-RAE4K2XY.js → mistral-conversations-I2PI7DDF.js} +1 -1
- package/dist/bundle/chunks/{multi-session-host-774MACJU.js → multi-session-host-OPR5VBFO.js} +3 -3
- package/dist/bundle/chunks/{openai-codex-responses-3CW4R7TG.js → openai-codex-responses-WSEX6SH7.js} +1 -1
- package/dist/bundle/chunks/{openai-completions-5UIJXQUF.js → openai-completions-YCBHTBSS.js} +1 -1
- package/dist/bundle/chunks/{openai-responses-2BO44MRW.js → openai-responses-GXNSQF4A.js} +1 -1
- package/dist/bundle/chunks/{package-manager-cli-MZHVCX2S.js → package-manager-cli-W55E3LHP.js} +1 -1
- package/dist/bundle/chunks/{pi-messages-RF6GER4R.js → pi-messages-O6GISIRW.js} +1 -1
- package/dist/bundle/chunks/{role-ETSFSDTS.js → role-SHIZQKK4.js} +1 -1
- package/dist/bundle/chunks/{rotation-stream-ZMQB4GPO.js → rotation-stream-2PCZWNKF.js} +1 -1
- package/dist/bundle/chunks/{rpc-mode-UJXOIZCW.js → rpc-mode-IDUJTSYS.js} +1 -1
- package/dist/bundle/chunks/{schedule-command-KA7LFFNK.js → schedule-command-B7RRSANU.js} +1 -1
- package/dist/bundle/chunks/{session-control-endpoint-MFWXUR7Z.js → session-control-endpoint-LMZH5JLH.js} +1 -1
- package/dist/bundle/chunks/{session-picker-BP33NRSL.js → session-picker-DTGBOXDR.js} +1 -1
- package/dist/bundle/chunks/session-worker.js +41 -41
- package/dist/bundle/chunks/{typesafe-system-one-GNNZ5O5U.js → typesafe-system-one-XGYJJVSE.js} +1 -1
- package/dist/bundle/cli.js +2 -2
- 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/agent-session.d.ts +11 -1
- package/dist/core/agent-session.js +19 -2
- package/dist/core/extensions/builtin/compaction/index.js +7 -1
- package/dist/core/extensions/builtin/herdr/index.js +9 -5
- package/dist/core/extensions/builtin/mcp/auth/oauth-issuer.d.ts +6 -0
- package/dist/core/extensions/builtin/mcp/auth/oauth-issuer.js +25 -0
- package/dist/core/extensions/builtin/mcp/auth/oauth-provider.d.ts +3 -3
- package/dist/core/extensions/builtin/mcp/auth/oauth-provider.js +50 -19
- package/dist/core/extensions/builtin/mcp/auth/oauth-refresh.js +4 -3
- package/dist/core/extensions/builtin/mcp/auth/oauth.js +19 -12
- package/dist/core/extensions/builtin/mcp/modern/dispatch.js +1 -0
- package/dist/core/extensions/builtin/mcp/modern/parameter-headers.d.ts +4 -1
- package/dist/core/extensions/builtin/mcp/modern/parameter-headers.js +33 -35
- package/dist/core/extensions/builtin/mcp/modern/request.js +3 -0
- package/dist/core/extensions/builtin/mcp/modern/transport.d.ts +2 -0
- package/dist/core/extensions/builtin/mcp/modern/transport.js +4 -2
- package/dist/core/extensions/builtin/terminal/extension-state.js +2 -1
- package/dist/core/extensions/builtin/vertex-model-garden/auth.d.ts +9 -0
- package/dist/core/extensions/builtin/vertex-model-garden/auth.js +17 -1
- package/dist/core/extensions/builtin/websearch/websearch/providers/google.d.ts +6 -0
- package/dist/core/extensions/builtin/websearch/websearch/providers/google.js +6 -1
- package/dist/core/extensions/types.d.ts +2 -0
- package/dist/core/lifecycle-children.d.ts +3 -1
- package/dist/core/lifecycle-children.js +79 -15
- package/dist/core/lifecycle-record.js +1 -24
- package/dist/core/lifecycle-session-binding.js +2 -1
- package/dist/core/lifecycle-wait-items.d.ts +17 -0
- package/dist/core/lifecycle-wait-items.js +72 -0
- package/dist/core/model-runtime.js +6 -1
- package/dist/core/provider-api-key-auth.d.ts +6 -1
- package/dist/core/provider-api-key-auth.js +11 -4
- package/dist/core/provider-composer.d.ts +8 -1
- package/dist/core/provider-composer.js +7 -3
- package/dist/core/sdk.js +4 -1
- package/dist/core/session-activity.js +2 -0
- package/dist/core/session-lifecycle-types.d.ts +20 -4
- package/dist/core/session-lifecycle.js +35 -4
- package/dist/core/structured-session-lane.d.ts +33 -0
- package/dist/core/structured-session-lane.js +62 -0
- package/dist/core/work-custody-record.d.ts +2 -1
- package/dist/core/work-custody-record.js +2 -0
- package/dist/core/work-obligations.d.ts +1 -1
- package/dist/core/work-obligations.js +8 -2
- package/dist/modes/json-event.d.ts +79 -1
- package/dist/modes/json-event.js +79 -1
- package/dist/modes/rpc/compact-content-index.d.ts +85 -0
- package/dist/modes/rpc/compact-content-index.js +254 -0
- package/dist/modes/rpc/compact-content-store.d.ts +6 -43
- package/dist/modes/rpc/compact-content-store.js +22 -157
- package/dist/modes/rpc/compact-index-pages.d.ts +12 -0
- package/dist/modes/rpc/compact-index-pages.js +31 -0
- package/dist/modes/rpc/compact-session-state.d.ts +11 -39
- package/dist/modes/rpc/compact-session-state.js +17 -26
- package/dist/modes/rpc/compact-spool-dir.d.ts +4 -1
- package/dist/modes/rpc/compact-spool-dir.js +41 -8
- package/dist/modes/rpc/compact-spool-storage.d.ts +53 -0
- package/dist/modes/rpc/compact-spool-storage.js +162 -0
- package/dist/modes/rpc/compact-storage-io.d.ts +2 -1
- package/dist/modes/rpc/compact-storage-io.js +7 -1
- package/dist/modes/rpc/compact-transition.d.ts +41 -0
- package/dist/modes/rpc/compact-transition.js +12 -0
- package/dist/modes/rpc/connection-handler.d.ts +2 -0
- package/dist/modes/rpc/connection-handler.js +12 -6
- package/dist/modes/rpc/host-ensure-start.js +5 -3
- package/dist/modes/rpc/security-presentations.js +2 -1
- package/dist/modes/rpc/session-binding.js +10 -0
- package/dist/modes/rpc/session-event-writer.d.ts +2 -0
- package/dist/modes/rpc/session-event-writer.js +2 -0
- package/dist/modes/rpc/session-record-stream.d.ts +3 -3
- package/dist/modes/rpc/session-record-stream.js +3 -3
- package/dist/modes/rpc/session-structured-lanes.d.ts +12 -0
- package/dist/modes/rpc/session-structured-lanes.js +24 -0
- package/dist/modes/rpc/session-worker-client.js +6 -5
- package/dist/modes/rpc/structured-session-records.d.ts +12 -0
- package/dist/modes/rpc/structured-session-records.js +88 -0
- package/docs/extensions.md +7 -1
- package/docs/rpc.md +17 -2
- package/package.json +6 -6
- package/dist/bundle/chunks/chunk-GQJYNFMO.js +0 -2
- package/dist/bundle/chunks/chunk-VICDRG3J.js +0 -410
- package/dist/bundle/chunks/chunk-VL7O5PO4.js +0 -5
|
@@ -1,9 +1,9 @@
|
|
|
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{fetchWithinOrigin}from"./chunk-YP72RYUP.js";import{InitializeResultSchema,JSONRPCMessageSchema,LATEST_PROTOCOL_VERSION}from"./chunk-WJOT3DFL.js";import"./chunk-AX72VNRS.js";import{AuthError,ConnectError,configureMcpElicitation,getModernDispatchGuard,installModernRequestAdapter,isMcpNeedsAuthError,legacyMcpFormEligible,loadMcpSdkAuth,loadMcpSdkClient,loadMcpSdkStdioTransport,loadMcpSdkStreamableHttpTransport,mcpClientCapabilities,mcpElapsedClock,modernDispatchGuard,reapProcessTree,safeOn}from"./chunk-JFQUWEN7.js";import{McpMrtrError,isRecord}from"./chunk-JPGT64RV.js";import{external_exports}from"./chunk-KUPQO7MC.js";import"./chunk-DLAY7CIU.js";import"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import"./chunk-IKOFCODM.js";import{Buffer as Buffer2}from"node:buffer";var isRecord2=value=>typeof value=="object"&&value!==null&&!Array.isArray(value);function encodeMcpHeaderValue(value){return/^[\x09\x20-\x7e]*$/.test(value)&&value.trim()===value&&!(value.startsWith("=?base64?")&&value.endsWith("?="))?value:`=?base64?${Buffer2.from(value,"utf8").toString("base64")}?=`}function clearMcpParameterHeaders(headers){for(let name of[...headers.keys()])name.toLowerCase().startsWith("mcp-param-")&&headers.delete(name)}function parseParameterHeaders(schema){let headers=[],names=new Set,visit=(node,path)=>{if(!isRecord2(node))return!0;if(Object.hasOwn(node,"x-mcp-header")){let name=node["x-mcp-header"],type=node.type;if(!path?.length||typeof name!="string"||!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(name)||names.has(name.toLowerCase())||type!=="string"&&type!=="integer"&&type!=="boolean")return!1;names.add(name.toLowerCase()),headers.push({name,path,type})}for(let[keyword,value]of Object.entries(node))if(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"].includes(keyword)){if(!isRecord2(value))continue;for(let[key,child]of Object.entries(value)){let childPath=keyword==="properties"&&path!==void 0?[...path,key]:void 0;if(!visit(child,childPath))return!1}}else if(["items","prefixItems","allOf","anyOf","oneOf","additionalItems","additionalProperties","unevaluatedItems","unevaluatedProperties","contains","propertyNames","not","if","then","else","contentSchema"].includes(keyword)){for(let child of Array.isArray(value)?value:[value])if(!visit(child,void 0))return!1}return!0};return visit(schema,[])?headers:void 0}var ModernParameterHeaders=class{#tools=new Map;filterTools(tools,firstPage){return firstPage&&this.#tools.clear(),tools.filter(tool=>{if(!isRecord2(tool)||typeof tool.name!="string")return!0;let headers=parseParameterHeaders(tool.inputSchema);return headers===void 0?(this.#tools.delete(tool.name),!1):(this.#tools.set(tool.name,headers),!0)})}append(headers,name,args){if(typeof name=="string")for(let parameter of this.#tools.get(name)??[]){let value=args;for(let key of parameter.path)value=isRecord2(value)&&Object.hasOwn(value,key)?value[key]:void 0;(parameter.type==="string"&&typeof value=="string"||parameter.type==="boolean"&&typeof value=="boolean"||parameter.type==="integer"&&typeof value=="number"&&Number.isSafeInteger(value))&&headers.set(`Mcp-Param-${parameter.name}`,encodeMcpHeaderValue(String(value)))}}};var modernCredentialSnapshot=tokens=>tokens===void 0?void 0:JSON.stringify([tokens.access_token,tokens.refresh_token]);function modernHttpFetch(spec,signal,authorizeResend=!0){let fetch=fetchWithinOrigin();return async(url,init)=>{let requestSignal=init?.signal?AbortSignal.any([signal,init.signal]):signal,send=()=>{let headers=new Headers,tokens=spec.authProvider?.tokens(),guard=init?.[modernDispatchGuard];guard?.(modernCredentialSnapshot(tokens)),tokens&&headers.set("Authorization",`Bearer ${tokens.access_token}`),new Headers(spec.requestInit?.headers).forEach((value,key)=>{headers.set(key,value)});for(let key of["Mcp-Session-Id","Mcp-Name","Mcp-Method","MCP-Protocol-Version"])headers.delete(key);return clearMcpParameterHeaders(headers),new Headers(init?.headers).forEach((value,key)=>{headers.set(key,value)}),headers.delete("Mcp-Session-Id"),fetch(url,{...spec.requestInit,...init,headers,signal:requestSignal})},response=await send();if(authorizeResend&&spec.authProvider&&(response.status===401||response.status===403)){let{auth,extractWWWAuthenticateParams,UnauthorizedError}=await loadMcpSdkAuth(),{resourceMetadataUrl,scope,error}=extractWWWAuthenticateParams(response);if(response.status===401||error==="insufficient_scope"){if(await response.body?.cancel(),await auth(spec.authProvider,{serverUrl:spec.url,resourceMetadataUrl,scope,fetchFn:(target,request2)=>fetch(target,{...request2,signal:request2?.signal?AbortSignal.any([requestSignal,request2.signal]):requestSignal})})!=="AUTHORIZED")throw new UnauthorizedError;if(response=await send(),response.status===401)throw await response.body?.cancel(),new UnauthorizedError("Server returned 401 after successful authentication")}}return response}}async function createMcpRequestClient(protocol,uiProvider,readCredential=()=>{},elicitationEnabled=!0){let{Client}=await loadMcpSdkClient();protocol.privateForms=uiProvider?.enforced?.()===!0;let legacyEligible=legacyMcpFormEligible(uiProvider,elicitationEnabled);protocol.legacyFormEligible=legacyEligible;let client=new Client({name:"senpi-mcp-client",version:"0.0.0"},{capabilities:mcpClientCapabilities(legacyEligible)});return await configureMcpElicitation(client,uiProvider,void 0,legacyEligible),installModernRequestAdapter(client,protocol,mcpElapsedClock,readCredential),client}import{PassThrough}from"node:stream";var ProjectStdioTransport=class{#resolve;#create;#current;#epoch;constructor(resolve,create){this.stderr=new PassThrough,this.#epoch=0,this.#resolve=resolve,this.#create=create}get pid(){return this.#current?.pid??null}async start(){let epoch=this.#epoch,spec=await this.#resolve();if(epoch!==this.#epoch)throw new ConnectError("Project MCP spawn was invalidated; retry",{phase:"create",retriable:!0});let transport=this.#create(spec);if(this.#current=transport,transport.onmessage=message=>this.onmessage?.(message),transport.onclose=()=>this.onclose?.(),transport.onerror=error=>this.onerror?.(error),transport.stderr?.pipe(this.stderr,{end:!1}),await transport.start(),epoch!==this.#epoch)throw await transport.close(),new ConnectError("Project MCP spawn was invalidated; retry",{phase:"create",retriable:!0})}async send(message,_options){if(this.#current===void 0)throw new ConnectError("Project MCP transport has not started",{phase:"send",retriable:!0});await this.#current.send(message)}async close(){this.#epoch++,await this.#current?.close()}};async function materializeMcpTransport(options,protocol={}){let client=await createMcpRequestClient(protocol,options.elicitationUiProvider,()=>modernCredentialSnapshot(options.spec.authProvider?.tokens()),options.elicitationEnabled);return options.spec.kind==="stdio"?materializeStdio(options.spec,options,client,protocol):materializeHttp(options.spec,client)}async function materializeStdio(spec,options,client,protocol){let{getDefaultEnvironment,StdioClientTransport}=await loadMcpSdkStdioTransport(),create=current=>new StdioClientTransport({args:current.args,command:current.command,cwd:current.cwd,env:{...current.projectPolicy?{}:getDefaultEnvironment(),...current.env,...oauthAccessTokenEnv(current.authProvider)},stderr:"pipe"}),transport=spec.projectPolicy&&spec.resolveBeforeStart!==void 0?new ProjectStdioTransport(spec.resolveBeforeStart,create):create(spec);return trackStdioStart(transport,options.onStart),pipeStderr(transport,options.logger,options.sink,protocol),dropNullNextCursor(transport),{client,close:()=>closeClientAndTransport(transport,client),readPid:()=>transport.pid,transport}}async function materializeHttp(spec,client){let{StreamableHTTPClientTransport}=await loadMcpSdkStreamableHttpTransport(),transport=new StreamableHTTPClientTransport(spec.url,{authProvider:spec.authProvider,requestInit:spec.requestInit});return dropNullNextCursor(transport),{client,close:()=>closeClientAndTransport(transport,client),readPid:()=>null,transport}}function oauthAccessTokenEnv(authProvider){let accessToken=authProvider?.tokens()?.access_token;return accessToken===void 0||accessToken.length===0?{}:{OAUTH_ACCESS_TOKEN:accessToken}}function dropNullNextCursor(transport){let originalStart=transport.start.bind(transport);transport.start=async()=>{let deliver=transport.onmessage;deliver!==void 0&&(transport.onmessage=(message,extra)=>{if("result"in message&&message.result!==null&&typeof message.result=="object"){let result=message.result;result.nextCursor===null&&delete result.nextCursor}deliver(message,extra)}),await originalStart()}}function trackStdioStart(transport,onStart){let start=transport.start.bind(transport);transport.start=async()=>{await start(),onStart()}}function pipeStderr(transport,logger,sink,protocol){let pending="",undecided="",stderrEnded=!1,stderr=transport.stderr;if(stderr==null)return;let logLine=line=>{let code=protocol.privateForms?line.match(/\b(?:EACCES|ENOENT|EPIPE|ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENOSPC|ENOMEM|EMFILE)\b/)?.[0]:void 0;logger.stderr(protocol.privateForms?`[private MCP stderr redacted]${code?` ${code}`:""}`:line)},append=text=>{pending+=text;let lines=pending.split(/\r?\n/);pending=lines.pop()??"";for(let line of lines)line.length>0&&logLine(line)};protocol.resolveStdioDiagnostics=modern=>{(!modern||protocol.privateForms)&&(append(undecided),stderrEnded&&pending.length>0&&(logLine(pending),pending="")),undecided="",modern&&!protocol.privateForms&&(pending="")},safeOn(stderr,"data","transport.stderr.data",chunk=>{if(protocol.version!==void 0&&!protocol.privateForms){pending="",undecided="";return}if(!Buffer.isBuffer(chunk)&&typeof chunk!="string")return;let text=Buffer.isBuffer(chunk)?chunk.toString("utf8"):chunk;if(!protocol.legacy&&!protocol.privateForms){undecided+=text.slice(0,Math.max(0,512*1024-undecided.length));return}append(text)},sink),safeOn(stderr,"end","transport.stderr.end",()=>{stderrEnded=!0,(protocol.privateForms||protocol.legacy&&protocol.version===void 0)&&pending.length>0&&logLine(pending),pending="",(protocol.legacy||protocol.version!==void 0)&&(undecided="")},sink)}async function closeClientAndTransport(transport,client){isTerminableHttpTransport(transport)&&await transport.terminateSession().catch(()=>{}),await transport.close().catch(()=>{}),await client.close().catch(()=>{})}function isTerminableHttpTransport(transport){return"terminateSession"in transport&&typeof transport.terminateSession=="function"}var MODERN_PROTOCOL_VERSION="2026-07-28",MODERN_ERROR_CODES={HeaderMismatch:-32020,MissingRequiredClientCapabilityError:-32021,UnsupportedProtocolVersionError:-32022};function buildModernRequest(id,method,clientInfo2,clientCapabilities,params={}){return{jsonrpc:"2.0",id,method,params:{...params,_meta:{...params._meta,"io.modelcontextprotocol/protocolVersion":MODERN_PROTOCOL_VERSION,"io.modelcontextprotocol/clientInfo":clientInfo2,"io.modelcontextprotocol/clientCapabilities":clientCapabilities}}}}function modernizeRequest(id,method,clientInfo2,clientCapabilities,version,params){let built=buildModernRequest(id,method,clientInfo2,clientCapabilities,params),capabilities=params?._meta?.["io.modelcontextprotocol/clientCapabilities"];return{...built,params:{...built.params,_meta:{...built.params._meta,"io.modelcontextprotocol/clientCapabilities":isRecord3(capabilities)?capabilities:clientCapabilities,"io.modelcontextprotocol/protocolVersion":version}}}}function deriveModernHeaders(request2){let headers={"MCP-Protocol-Version":request2.params._meta["io.modelcontextprotocol/protocolVersion"],"Mcp-Method":request2.method},name=request2.method==="resources/read"?request2.params.uri:request2.method==="tools/call"||request2.method==="prompts/get"?request2.params.name:void 0;return typeof name=="string"&&(headers["Mcp-Name"]=encodeMcpHeaderValue(name)),headers}function classifyModernError(body2){let response=parseBody(body2);if(!isRecord3(response)||response.jsonrpc!=="2.0"||!isRecord3(response.error))return;let error=response.error;if(typeof error.message!="string")return;let common={message:error.message,..."data"in error?{data:error.data}:{}};switch(error.code){case MODERN_ERROR_CODES.HeaderMismatch:return{...common,kind:"HeaderMismatch",code:error.code};case MODERN_ERROR_CODES.MissingRequiredClientCapabilityError:return{...common,kind:"MissingRequiredClientCapabilityError",code:error.code};case MODERN_ERROR_CODES.UnsupportedProtocolVersionError:{let supported=isRecord3(error.data)?error.data.supported:void 0;return{...common,kind:"UnsupportedProtocolVersionError",code:error.code,...Array.isArray(supported)&&supported.every(version=>typeof version=="string")?{supportedVersions:supported}:{}}}default:return}}function parseBody(body2){if(typeof body2!="string")return body2;try{return JSON.parse(body2)}catch(error){if(error instanceof SyntaxError)return;throw error}}function isRecord3(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var discoverySchema=external_exports.object({resultType:external_exports.literal("complete"),supportedVersions:external_exports.array(external_exports.string()),capabilities:external_exports.record(external_exports.string(),external_exports.unknown()),_meta:external_exports.object({"io.modelcontextprotocol/serverInfo":external_exports.object({name:external_exports.string(),version:external_exports.string()}).passthrough()}).passthrough(),instructions:external_exports.string().optional(),ttlMs:external_exports.number().nonnegative().optional(),cacheScope:external_exports.string().optional()}).passthrough(),modernError=classifyModernError,STDIO_PROBE_ID="senpi-era-probe",StdioProbeSilence=class extends Error{constructor(){super("MCP stdio server did not answer discovery in time"),this.name="StdioProbeSilence"}};function discoveryReply(value,id){return complete(value,id)}function request(options,version,id=1){let built=buildModernRequest(id,"server/discover",options.clientInfo,options.clientCapabilities);return{...built,params:{_meta:{...built.params._meta,"io.modelcontextprotocol/protocolVersion":version}}}}function complete(value,id=1){let parsed=external_exports.object({jsonrpc:external_exports.literal("2.0"),id:external_exports.literal(id),result:discoverySchema}).safeParse(value);return parsed.success?parsed.data.result:void 0}function errorReply(value,id){return external_exports.object({jsonrpc:external_exports.literal("2.0"),id:id===void 0?external_exports.union([external_exports.string(),external_exports.number(),external_exports.null()]):external_exports.literal(id),error:external_exports.object({code:external_exports.number(),message:external_exports.string()})}).safeParse(value).success}function mutualVersion(error,options){if(!(error.kind!=="UnsupportedProtocolVersionError"||!error.supportedVersions))return error.supportedVersions.filter(candidate=>options.supportedVersions.includes(candidate)).sort().at(-1)}function indeterminate(reason,action,details={}){return{kind:"indeterminate",reason,action,...details}}function parseJson(text){try{return JSON.parse(text)}catch(error){if(error instanceof SyntaxError)return;throw error}}async function body(response){let text=await response.text();if(!response.headers.get("Content-Type")?.includes("text/event-stream"))return parseJson(text);for(let event of text.replace(/\r\n/g,`
|
|
2
|
+
import{fetchWithinOrigin}from"./chunk-YP72RYUP.js";import{InitializeResultSchema,JSONRPCMessageSchema,LATEST_PROTOCOL_VERSION}from"./chunk-WJOT3DFL.js";import"./chunk-AX72VNRS.js";import{AuthError,ConnectError,ModernParameterHeaders,ParameterHeaderValidationError,clearMcpParameterHeaders,configureMcpElicitation,encodeMcpHeaderValue,getModernDispatchGuard,installModernRequestAdapter,isMcpNeedsAuthError,legacyMcpFormEligible,loadMcpSdkAuth,loadMcpSdkClient,loadMcpSdkStdioTransport,loadMcpSdkStreamableHttpTransport,mcpClientCapabilities,mcpElapsedClock,modernDispatchGuard,reapProcessTree,safeOn}from"./chunk-TQ67PB7U.js";import{McpMrtrError,isRecord}from"./chunk-JPGT64RV.js";import{external_exports}from"./chunk-KUPQO7MC.js";import"./chunk-DLAY7CIU.js";import"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import"./chunk-IKOFCODM.js";var modernCredentialSnapshot=tokens=>tokens===void 0?void 0:JSON.stringify([tokens.access_token,tokens.refresh_token]);function modernHttpFetch(spec,signal,authorizeResend=!0){let fetch=fetchWithinOrigin();return async(url,init)=>{let requestSignal=init?.signal?AbortSignal.any([signal,init.signal]):signal,send=()=>{let headers=new Headers,tokens=spec.authProvider?.tokens(),guard=init?.[modernDispatchGuard];guard?.(modernCredentialSnapshot(tokens)),tokens&&headers.set("Authorization",`Bearer ${tokens.access_token}`),new Headers(spec.requestInit?.headers).forEach((value,key)=>{headers.set(key,value)});for(let key of["Mcp-Session-Id","Mcp-Name","Mcp-Method","MCP-Protocol-Version"])headers.delete(key);return clearMcpParameterHeaders(headers),new Headers(init?.headers).forEach((value,key)=>{headers.set(key,value)}),headers.delete("Mcp-Session-Id"),fetch(url,{...spec.requestInit,...init,headers,signal:requestSignal})},response=await send();if(authorizeResend&&spec.authProvider&&(response.status===401||response.status===403)){let{auth,extractWWWAuthenticateParams,UnauthorizedError}=await loadMcpSdkAuth(),{resourceMetadataUrl,scope,error}=extractWWWAuthenticateParams(response);if(response.status===401||error==="insufficient_scope"){if(await response.body?.cancel(),await auth(spec.authProvider,{serverUrl:spec.url,resourceMetadataUrl,scope,fetchFn:(target,request2)=>fetch(target,{...request2,signal:request2?.signal?AbortSignal.any([requestSignal,request2.signal]):requestSignal})})!=="AUTHORIZED")throw new UnauthorizedError;if(response=await send(),response.status===401)throw await response.body?.cancel(),new UnauthorizedError("Server returned 401 after successful authentication")}}return response}}async function createMcpRequestClient(protocol,uiProvider,readCredential=()=>{},elicitationEnabled=!0){let{Client}=await loadMcpSdkClient();protocol.privateForms=uiProvider?.enforced?.()===!0;let legacyEligible=legacyMcpFormEligible(uiProvider,elicitationEnabled);protocol.legacyFormEligible=legacyEligible;let client=new Client({name:"senpi-mcp-client",version:"0.0.0"},{capabilities:mcpClientCapabilities(legacyEligible)});return await configureMcpElicitation(client,uiProvider,void 0,legacyEligible),installModernRequestAdapter(client,protocol,mcpElapsedClock,readCredential),client}import{PassThrough}from"node:stream";var ProjectStdioTransport=class{#resolve;#create;#current;#epoch;constructor(resolve,create){this.stderr=new PassThrough,this.#epoch=0,this.#resolve=resolve,this.#create=create}get pid(){return this.#current?.pid??null}async start(){let epoch=this.#epoch,spec=await this.#resolve();if(epoch!==this.#epoch)throw new ConnectError("Project MCP spawn was invalidated; retry",{phase:"create",retriable:!0});let transport=this.#create(spec);if(this.#current=transport,transport.onmessage=message=>this.onmessage?.(message),transport.onclose=()=>this.onclose?.(),transport.onerror=error=>this.onerror?.(error),transport.stderr?.pipe(this.stderr,{end:!1}),await transport.start(),epoch!==this.#epoch)throw await transport.close(),new ConnectError("Project MCP spawn was invalidated; retry",{phase:"create",retriable:!0})}async send(message,_options){if(this.#current===void 0)throw new ConnectError("Project MCP transport has not started",{phase:"send",retriable:!0});await this.#current.send(message)}async close(){this.#epoch++,await this.#current?.close()}};async function materializeMcpTransport(options,protocol={}){let client=await createMcpRequestClient(protocol,options.elicitationUiProvider,()=>modernCredentialSnapshot(options.spec.authProvider?.tokens()),options.elicitationEnabled);return options.spec.kind==="stdio"?materializeStdio(options.spec,options,client,protocol):materializeHttp(options.spec,client)}async function materializeStdio(spec,options,client,protocol){let{getDefaultEnvironment,StdioClientTransport}=await loadMcpSdkStdioTransport(),create=current=>new StdioClientTransport({args:current.args,command:current.command,cwd:current.cwd,env:{...current.projectPolicy?{}:getDefaultEnvironment(),...current.env,...oauthAccessTokenEnv(current.authProvider)},stderr:"pipe"}),transport=spec.projectPolicy&&spec.resolveBeforeStart!==void 0?new ProjectStdioTransport(spec.resolveBeforeStart,create):create(spec);return trackStdioStart(transport,options.onStart),pipeStderr(transport,options.logger,options.sink,protocol),dropNullNextCursor(transport),{client,close:()=>closeClientAndTransport(transport,client),readPid:()=>transport.pid,transport}}async function materializeHttp(spec,client){let{StreamableHTTPClientTransport}=await loadMcpSdkStreamableHttpTransport(),transport=new StreamableHTTPClientTransport(spec.url,{authProvider:spec.authProvider,requestInit:spec.requestInit});return dropNullNextCursor(transport),{client,close:()=>closeClientAndTransport(transport,client),readPid:()=>null,transport}}function oauthAccessTokenEnv(authProvider){let accessToken=authProvider?.tokens()?.access_token;return accessToken===void 0||accessToken.length===0?{}:{OAUTH_ACCESS_TOKEN:accessToken}}function dropNullNextCursor(transport){let originalStart=transport.start.bind(transport);transport.start=async()=>{let deliver=transport.onmessage;deliver!==void 0&&(transport.onmessage=(message,extra)=>{if("result"in message&&message.result!==null&&typeof message.result=="object"){let result=message.result;result.nextCursor===null&&delete result.nextCursor}deliver(message,extra)}),await originalStart()}}function trackStdioStart(transport,onStart){let start=transport.start.bind(transport);transport.start=async()=>{await start(),onStart()}}function pipeStderr(transport,logger,sink,protocol){let pending="",undecided="",stderrEnded=!1,stderr=transport.stderr;if(stderr==null)return;let logLine=line=>{let code=protocol.privateForms?line.match(/\b(?:EACCES|ENOENT|EPIPE|ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENOSPC|ENOMEM|EMFILE)\b/)?.[0]:void 0;logger.stderr(protocol.privateForms?`[private MCP stderr redacted]${code?` ${code}`:""}`:line)},append=text=>{pending+=text;let lines=pending.split(/\r?\n/);pending=lines.pop()??"";for(let line of lines)line.length>0&&logLine(line)};protocol.resolveStdioDiagnostics=modern=>{(!modern||protocol.privateForms)&&(append(undecided),stderrEnded&&pending.length>0&&(logLine(pending),pending="")),undecided="",modern&&!protocol.privateForms&&(pending="")},safeOn(stderr,"data","transport.stderr.data",chunk=>{if(protocol.version!==void 0&&!protocol.privateForms){pending="",undecided="";return}if(!Buffer.isBuffer(chunk)&&typeof chunk!="string")return;let text=Buffer.isBuffer(chunk)?chunk.toString("utf8"):chunk;if(!protocol.legacy&&!protocol.privateForms){undecided+=text.slice(0,Math.max(0,512*1024-undecided.length));return}append(text)},sink),safeOn(stderr,"end","transport.stderr.end",()=>{stderrEnded=!0,(protocol.privateForms||protocol.legacy&&protocol.version===void 0)&&pending.length>0&&logLine(pending),pending="",(protocol.legacy||protocol.version!==void 0)&&(undecided="")},sink)}async function closeClientAndTransport(transport,client){isTerminableHttpTransport(transport)&&await transport.terminateSession().catch(()=>{}),await transport.close().catch(()=>{}),await client.close().catch(()=>{})}function isTerminableHttpTransport(transport){return"terminateSession"in transport&&typeof transport.terminateSession=="function"}var MODERN_PROTOCOL_VERSION="2026-07-28",MODERN_ERROR_CODES={HeaderMismatch:-32020,MissingRequiredClientCapabilityError:-32021,UnsupportedProtocolVersionError:-32022};function buildModernRequest(id,method,clientInfo2,clientCapabilities,params={}){return{jsonrpc:"2.0",id,method,params:{...params,_meta:{...params._meta,"io.modelcontextprotocol/protocolVersion":MODERN_PROTOCOL_VERSION,"io.modelcontextprotocol/clientInfo":clientInfo2,"io.modelcontextprotocol/clientCapabilities":clientCapabilities}}}}function modernizeRequest(id,method,clientInfo2,clientCapabilities,version,params){let built=buildModernRequest(id,method,clientInfo2,clientCapabilities,params),capabilities=params?._meta?.["io.modelcontextprotocol/clientCapabilities"];return{...built,params:{...built.params,_meta:{...built.params._meta,"io.modelcontextprotocol/clientCapabilities":isRecord2(capabilities)?capabilities:clientCapabilities,"io.modelcontextprotocol/protocolVersion":version}}}}function deriveModernHeaders(request2){let headers={"MCP-Protocol-Version":request2.params._meta["io.modelcontextprotocol/protocolVersion"],"Mcp-Method":request2.method},name=request2.method==="resources/read"?request2.params.uri:request2.method==="tools/call"||request2.method==="prompts/get"?request2.params.name:void 0;return typeof name=="string"&&(headers["Mcp-Name"]=encodeMcpHeaderValue(name)),headers}function classifyModernError(body2){let response=parseBody(body2);if(!isRecord2(response)||response.jsonrpc!=="2.0"||!isRecord2(response.error))return;let error=response.error;if(typeof error.message!="string")return;let common={message:error.message,..."data"in error?{data:error.data}:{}};switch(error.code){case MODERN_ERROR_CODES.HeaderMismatch:return{...common,kind:"HeaderMismatch",code:error.code};case MODERN_ERROR_CODES.MissingRequiredClientCapabilityError:return{...common,kind:"MissingRequiredClientCapabilityError",code:error.code};case MODERN_ERROR_CODES.UnsupportedProtocolVersionError:{let supported=isRecord2(error.data)?error.data.supported:void 0;return{...common,kind:"UnsupportedProtocolVersionError",code:error.code,...Array.isArray(supported)&&supported.every(version=>typeof version=="string")?{supportedVersions:supported}:{}}}default:return}}function parseBody(body2){if(typeof body2!="string")return body2;try{return JSON.parse(body2)}catch(error){if(error instanceof SyntaxError)return;throw error}}function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var discoverySchema=external_exports.object({resultType:external_exports.literal("complete"),supportedVersions:external_exports.array(external_exports.string()),capabilities:external_exports.record(external_exports.string(),external_exports.unknown()),_meta:external_exports.object({"io.modelcontextprotocol/serverInfo":external_exports.object({name:external_exports.string(),version:external_exports.string()}).passthrough()}).passthrough(),instructions:external_exports.string().optional(),ttlMs:external_exports.number().nonnegative().optional(),cacheScope:external_exports.string().optional()}).passthrough(),modernError=classifyModernError,STDIO_PROBE_ID="senpi-era-probe",StdioProbeSilence=class extends Error{constructor(){super("MCP stdio server did not answer discovery in time"),this.name="StdioProbeSilence"}};function discoveryReply(value,id){return complete(value,id)}function request(options,version,id=1){let built=buildModernRequest(id,"server/discover",options.clientInfo,options.clientCapabilities);return{...built,params:{_meta:{...built.params._meta,"io.modelcontextprotocol/protocolVersion":version}}}}function complete(value,id=1){let parsed=external_exports.object({jsonrpc:external_exports.literal("2.0"),id:external_exports.literal(id),result:discoverySchema}).safeParse(value);return parsed.success?parsed.data.result:void 0}function errorReply(value,id){return external_exports.object({jsonrpc:external_exports.literal("2.0"),id:id===void 0?external_exports.union([external_exports.string(),external_exports.number(),external_exports.null()]):external_exports.literal(id),error:external_exports.object({code:external_exports.number(),message:external_exports.string()})}).safeParse(value).success}function mutualVersion(error,options){if(!(error.kind!=="UnsupportedProtocolVersionError"||!error.supportedVersions))return error.supportedVersions.filter(candidate=>options.supportedVersions.includes(candidate)).sort().at(-1)}function indeterminate(reason,action,details={}){return{kind:"indeterminate",reason,action,...details}}function parseJson(text){try{return JSON.parse(text)}catch(error){if(error instanceof SyntaxError)return;throw error}}async function body(response){let text=await response.text();if(!response.headers.get("Content-Type")?.includes("text/event-stream"))return parseJson(text);for(let event of text.replace(/\r\n/g,`
|
|
3
3
|
`).split(`
|
|
4
4
|
|
|
5
5
|
`)){let data=event.split(`
|
|
6
6
|
`).filter(line=>line.startsWith("data:")).map(line=>line.slice(5).replace(/^ /,"")).join(`
|
|
7
|
-
`),value=parseJson(data);if(complete(value)||modernError(value))return value}}async function probeHttpEra(url,fetch,options){let version=MODERN_PROTOCOL_VERSION;for(let attempt=0;attempt<2;attempt++){let response,value;try{let discoveryRequest=request(options,version);response=await fetch(url,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream",...deriveModernHeaders(discoveryRequest)},body:JSON.stringify(discoveryRequest)}),value=await body(response)}catch(cause){if(isMcpNeedsAuthError(cause))throw cause;return indeterminate("transport","Check the MCP endpoint connection and retry discovery.",{cause})}let error=modernError(value);if(response.status===400){if(!error)return attempt===0?{kind:"legacy-fallback"}:indeterminate("version-retry-rejected","Check server version negotiation; the modern retry failed.",{era:"modern"});if(error.code!==-32022)return{kind:attempt?"modern-version-retry":"modern-OK",version,error};if(attempt===1)return indeterminate("version-retry-rejected","Update client or server; the single version retry was rejected.",{era:"modern"});let mutual=mutualVersion(error,options);if(!mutual)return indeterminate("no-mutual-version","Update client or server to share a supported protocol version.",{era:"modern"});version=mutual;continue}if(!error&&errorReply(value))return attempt===0?{kind:"legacy-fallback"}:indeterminate("version-retry-rejected","Check server version negotiation; the modern retry failed.",{era:"modern"});if(!response.ok)return indeterminate("http-status","Check endpoint, authentication, or server health before retrying.",{status:response.status});let discovery=complete(value);return discovery?{kind:attempt?"modern-version-retry":"modern-OK",version,discovery}:error?{kind:attempt?"modern-version-retry":"modern-OK",version,error}:indeterminate("invalid-discovery","Check that the server returns a complete server/discover envelope.")}return indeterminate("version-retry-rejected","Update client or server protocol versions.",{era:"modern"})}async function probeStdioEra(send,options){let version=MODERN_PROTOCOL_VERSION,retryRejected=()=>indeterminate("version-retry-rejected","Update client or server; the single version retry was rejected.",{era:"modern"});for(let attempt=0;attempt<2;attempt++){let id=attempt===0?STDIO_PROBE_ID:`${STDIO_PROBE_ID}-${attempt}`,value;try{value=await send(request(options,version,id))}catch(error2){return attempt>0?retryRejected():error2 instanceof StdioProbeSilence?{kind:"legacy-fallback",silent:!0}:{kind:"legacy-fallback",restart:!0}}let kind=attempt===0?"modern-OK":"modern-version-retry",discovery=complete(value,id);if(discovery)return{kind,version,discovery};if(!errorReply(value,id))return attempt>0?retryRejected():{kind:"legacy-fallback",restart:!0};let error=modernError(value);if(!error)return attempt>0?retryRejected():{kind:"legacy-fallback"};let mutual=attempt===0?mutualVersion(error,options):void 0;if(!mutual)return{kind,version,error};version=mutual}return retryRejected()}function sanitizeModernMessage(message){if("error"in message)return{jsonrpc:"2.0",id:message.id,error:{code:message.error.code,message:"MCP server request failed."}};if(!("method"in message))return message;if("id"in message)throw new McpMrtrError("MCP_MRTR_INVALID_RESULT");if(message.method==="notifications/progress"){let params=message.params;return!params||typeof params.progress!="number"||!Number.isFinite(params.progress)||params.total!==void 0&&(typeof params.total!="number"||!Number.isFinite(params.total))?void 0:{jsonrpc:"2.0",method:message.method,params:{progressToken:params.progressToken,progress:params.progress,...params.total===void 0?{}:{total:params.total}}}}return message.method==="notifications/message"?{jsonrpc:"2.0",method:message.method,params:{level:"info",data:"MCP server diagnostic suppressed."}}:message}var ModernTransportError=class extends Error{constructor(message){super(message),this.name="ModernTransportError"}},ModernHttpTransport=class{#options;#abort=new AbortController;#attempts=new Map;#toolLists=new Map;#parameterHeaders=new ModernParameterHeaders;#started=!1;#closed=!1;constructor(options){this.#options=options}async start(){if(this.#started||this.#closed)throw new ModernTransportError("Modern MCP transport cannot be started twice");this.#started=!0}async close(){this.#closed||(this.#closed=!0,this.#abort.abort(),this.onclose?.())}async send(message){if(!this.#started||this.#closed)throw new ModernTransportError("Modern MCP transport is not open");if("method"in message&&message.method==="notifications/cancelled"){let id2=message.params?.requestId;(typeof id2=="string"||typeof id2=="number")&&this.#attempts.get(id2)?.abort();return}let id="method"in message&&"id"in message?message.id:void 0;id!==void 0&&"method"in message&&message.method==="tools/list"&&this.#toolLists.set(id,message.params?.cursor===void 0);let controller=new AbortController;id!==void 0&&this.#attempts.set(id,controller);let signal=AbortSignal.any([this.#abort.signal,controller.signal]);try{let version=this.#options.protocolVersion??MODERN_PROTOCOL_VERSION,headers=new Headers(this.#options.headers);clearMcpParameterHeaders(headers);for(let name of["Mcp-Session-Id","Mcp-Name","Mcp-Method","MCP-Protocol-Version"])headers.delete(name);headers.set("Content-Type","application/json"),headers.set("Accept","application/json, text/event-stream");let body2=message;if("method"in message){let request2=modernizeRequest("id"in message?message.id:0,message.method,this.#options.clientInfo,this.#options.clientCapabilities,version,message.params);for(let[name,value]of Object.entries(deriveModernHeaders(request2)))headers.set(name,value);if(request2.method==="tools/call"&&this.#parameterHeaders.append(headers,request2.params.name,request2.params.arguments),"id"in message)body2=request2;else{let{id:_id,...notification}=request2;body2=notification}}else headers.set("MCP-Protocol-Version",version);let guard="method"in message?getModernDispatchGuard(message.params):void 0;guard?.();let init={method:"POST",headers,body:JSON.stringify(body2),signal,[modernDispatchGuard]:guard},response=await this.#options.fetch(this.#options.url,init);if(signal.throwIfAborted(),response.status===401||response.status===403)throw await response.body?.cancel(),new AuthError("MCP server needs authentication; use /mcp auth-start.",{phase:"auth",retriable:!1});if(response.status===202||response.status===204)return;let mediaType=response.headers.get("Content-Type")?.split(";")[0].trim().toLowerCase();if(mediaType==="application/json"){let incoming=JSONRPCMessageSchema.parse(await response.json());if(!response.ok&&!("error"in incoming))throw new ModernTransportError(`Modern MCP POST failed with HTTP ${response.status}`);signal.throwIfAborted(),this.#deliver(incoming,id)}else if(response.ok&&mediaType==="text/event-stream"&&response.body)await this.#consumeSse(response.body,id,signal);else throw new ModernTransportError(`Modern MCP POST failed with HTTP ${response.status} (${mediaType??"no content type"})`)}catch(error){let failure=error instanceof McpMrtrError||error instanceof AuthError?error:new McpMrtrError("MCP_MRTR_TRANSPORT_FAILED");throw this.onerror?.(failure),failure}finally{id!==void 0&&this.#attempts.delete(id),id!==void 0&&this.#toolLists.delete(id)}}#deliver(incoming,expected){if("id"in incoming&&(expected===void 0||incoming.id!==expected))throw new McpMrtrError("MCP_MRTR_INVALID_RESULT");if("id"in incoming&&"result"in incoming&&this.#toolLists.has(incoming.id)){let result=incoming.result;Array.isArray(result.tools)&&(incoming={...incoming,result:{...result,tools:this.#parameterHeaders.filterTools(result.tools,this.#toolLists.get(incoming.id)===!0)}})}let safe=sanitizeModernMessage(incoming);safe&&this.onmessage?.(safe)}async#consumeSse(stream,requestId,signal){let reader=stream.getReader(),decoder=new TextDecoder,aborted=Promise.withResolvers(),onabort=()=>aborted.reject(signal.reason);signal.addEventListener("abort",onabort,{once:!0}),signal.aborted&&onabort();let buffer="",data=[],event="";try{for(;;){let{value,done}=await Promise.race([reader.read(),aborted.promise]);for(signal.throwIfAborted(),buffer+=done?decoder.decode():decoder.decode(value,{stream:!0});;){let match=/[\r\n]/.exec(buffer);if(match===null)break;let end=match.index;if(!done&&buffer[end]==="\r"&&end+1===buffer.length)break;let line=buffer.slice(0,end);if(buffer=buffer.slice(end+(buffer.slice(end,end+2)===`\r
|
|
7
|
+
`),value=parseJson(data);if(complete(value)||modernError(value))return value}}async function probeHttpEra(url,fetch,options){let version=MODERN_PROTOCOL_VERSION;for(let attempt=0;attempt<2;attempt++){let response,value;try{let discoveryRequest=request(options,version);response=await fetch(url,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream",...deriveModernHeaders(discoveryRequest)},body:JSON.stringify(discoveryRequest)}),value=await body(response)}catch(cause){if(isMcpNeedsAuthError(cause))throw cause;return indeterminate("transport","Check the MCP endpoint connection and retry discovery.",{cause})}let error=modernError(value);if(response.status===400){if(!error)return attempt===0?{kind:"legacy-fallback"}:indeterminate("version-retry-rejected","Check server version negotiation; the modern retry failed.",{era:"modern"});if(error.code!==-32022)return{kind:attempt?"modern-version-retry":"modern-OK",version,error};if(attempt===1)return indeterminate("version-retry-rejected","Update client or server; the single version retry was rejected.",{era:"modern"});let mutual=mutualVersion(error,options);if(!mutual)return indeterminate("no-mutual-version","Update client or server to share a supported protocol version.",{era:"modern"});version=mutual;continue}if(!error&&errorReply(value))return attempt===0?{kind:"legacy-fallback"}:indeterminate("version-retry-rejected","Check server version negotiation; the modern retry failed.",{era:"modern"});if(!response.ok)return indeterminate("http-status","Check endpoint, authentication, or server health before retrying.",{status:response.status});let discovery=complete(value);return discovery?{kind:attempt?"modern-version-retry":"modern-OK",version,discovery}:error?{kind:attempt?"modern-version-retry":"modern-OK",version,error}:indeterminate("invalid-discovery","Check that the server returns a complete server/discover envelope.")}return indeterminate("version-retry-rejected","Update client or server protocol versions.",{era:"modern"})}async function probeStdioEra(send,options){let version=MODERN_PROTOCOL_VERSION,retryRejected=()=>indeterminate("version-retry-rejected","Update client or server; the single version retry was rejected.",{era:"modern"});for(let attempt=0;attempt<2;attempt++){let id=attempt===0?STDIO_PROBE_ID:`${STDIO_PROBE_ID}-${attempt}`,value;try{value=await send(request(options,version,id))}catch(error2){return attempt>0?retryRejected():error2 instanceof StdioProbeSilence?{kind:"legacy-fallback",silent:!0}:{kind:"legacy-fallback",restart:!0}}let kind=attempt===0?"modern-OK":"modern-version-retry",discovery=complete(value,id);if(discovery)return{kind,version,discovery};if(!errorReply(value,id))return attempt>0?retryRejected():{kind:"legacy-fallback",restart:!0};let error=modernError(value);if(!error)return attempt>0?retryRejected():{kind:"legacy-fallback"};let mutual=attempt===0?mutualVersion(error,options):void 0;if(!mutual)return{kind,version,error};version=mutual}return retryRejected()}function sanitizeModernMessage(message){if("error"in message)return{jsonrpc:"2.0",id:message.id,error:{code:message.error.code,message:"MCP server request failed."}};if(!("method"in message))return message;if("id"in message)throw new McpMrtrError("MCP_MRTR_INVALID_RESULT");if(message.method==="notifications/progress"){let params=message.params;return!params||typeof params.progress!="number"||!Number.isFinite(params.progress)||params.total!==void 0&&(typeof params.total!="number"||!Number.isFinite(params.total))?void 0:{jsonrpc:"2.0",method:message.method,params:{progressToken:params.progressToken,progress:params.progress,...params.total===void 0?{}:{total:params.total}}}}return message.method==="notifications/message"?{jsonrpc:"2.0",method:message.method,params:{level:"info",data:"MCP server diagnostic suppressed."}}:message}var ModernTransportError=class extends Error{constructor(message){super(message),this.name="ModernTransportError"}},ModernHttpTransport=class{#options;#abort=new AbortController;#attempts=new Map;#toolLists=new Map;#parameterHeaders=new ModernParameterHeaders;#started=!1;#closed=!1;constructor(options){this.#options=options}async start(){if(this.#started||this.#closed)throw new ModernTransportError("Modern MCP transport cannot be started twice");this.#started=!0}async close(){this.#closed||(this.#closed=!0,this.#abort.abort(),this.onclose?.())}async send(message){if(!this.#started||this.#closed)throw new ModernTransportError("Modern MCP transport is not open");if("method"in message&&message.method==="notifications/cancelled"){let id2=message.params?.requestId;(typeof id2=="string"||typeof id2=="number")&&this.#attempts.get(id2)?.abort();return}let id="method"in message&&"id"in message?message.id:void 0;id!==void 0&&"method"in message&&message.method==="tools/list"&&this.#toolLists.set(id,message.params?.cursor===void 0);let controller=new AbortController;id!==void 0&&this.#attempts.set(id,controller);let signal=AbortSignal.any([this.#abort.signal,controller.signal]);try{let version=this.#options.protocolVersion??MODERN_PROTOCOL_VERSION,headers=new Headers(this.#options.headers);clearMcpParameterHeaders(headers);for(let name of["Mcp-Session-Id","Mcp-Name","Mcp-Method","MCP-Protocol-Version"])headers.delete(name);headers.set("Content-Type","application/json"),headers.set("Accept","application/json, text/event-stream");let body2=message;if("method"in message){let request2=modernizeRequest("id"in message?message.id:0,message.method,this.#options.clientInfo,this.#options.clientCapabilities,version,message.params);for(let[name,value]of Object.entries(deriveModernHeaders(request2)))headers.set(name,value);if(request2.method==="tools/call"&&this.#parameterHeaders.append(headers,request2.params.name,request2.params.arguments),"id"in message)body2=request2;else{let{id:_id,...notification}=request2;body2=notification}}else headers.set("MCP-Protocol-Version",version);let guard="method"in message?getModernDispatchGuard(message.params):void 0;guard?.();let init={method:"POST",headers,body:JSON.stringify(body2),signal,[modernDispatchGuard]:guard},response=await this.#options.fetch(this.#options.url,init);if(signal.throwIfAborted(),response.status===401||response.status===403)throw await response.body?.cancel(),new AuthError("MCP server needs authentication; use /mcp auth-start.",{phase:"auth",retriable:!1});if(response.status===202||response.status===204)return;let mediaType=response.headers.get("Content-Type")?.split(";")[0].trim().toLowerCase();if(mediaType==="application/json"){let incoming=JSONRPCMessageSchema.parse(await response.json());if(!response.ok&&!("error"in incoming))throw new ModernTransportError(`Modern MCP POST failed with HTTP ${response.status}`);signal.throwIfAborted(),this.#deliver(incoming,id)}else if(response.ok&&mediaType==="text/event-stream"&&response.body)await this.#consumeSse(response.body,id,signal);else throw new ModernTransportError(`Modern MCP POST failed with HTTP ${response.status} (${mediaType??"no content type"})`)}catch(error){if(error instanceof ParameterHeaderValidationError)throw error;let failure=error instanceof McpMrtrError||error instanceof AuthError?error:new McpMrtrError("MCP_MRTR_TRANSPORT_FAILED");throw this.onerror?.(failure),failure}finally{id!==void 0&&this.#attempts.delete(id),id!==void 0&&this.#toolLists.delete(id)}}#deliver(incoming,expected){if("id"in incoming&&(expected===void 0||incoming.id!==expected))throw new McpMrtrError("MCP_MRTR_INVALID_RESULT");if("id"in incoming&&"result"in incoming&&this.#toolLists.has(incoming.id)){let result=incoming.result;Array.isArray(result.tools)&&(incoming={...incoming,result:{...result,tools:this.#parameterHeaders.filterTools(result.tools,this.#toolLists.get(incoming.id)===!0,message=>this.#options.logger?.warn(message))}})}let safe=sanitizeModernMessage(incoming);safe&&this.onmessage?.(safe)}async#consumeSse(stream,requestId,signal){let reader=stream.getReader(),decoder=new TextDecoder,aborted=Promise.withResolvers(),onabort=()=>aborted.reject(signal.reason);signal.addEventListener("abort",onabort,{once:!0}),signal.aborted&&onabort();let buffer="",data=[],event="";try{for(;;){let{value,done}=await Promise.race([reader.read(),aborted.promise]);for(signal.throwIfAborted(),buffer+=done?decoder.decode():decoder.decode(value,{stream:!0});;){let match=/[\r\n]/.exec(buffer);if(match===null)break;let end=match.index;if(!done&&buffer[end]==="\r"&&end+1===buffer.length)break;let line=buffer.slice(0,end);if(buffer=buffer.slice(end+(buffer.slice(end,end+2)===`\r
|
|
8
8
|
`?2:1)),line===""){if(data.length>0&&(event===""||event==="message")){let incoming=JSONRPCMessageSchema.parse(JSON.parse(data.join(`
|
|
9
|
-
`)));if(this.#deliver(incoming,requestId),"id"in incoming&&!("method"in incoming)&&incoming.id===requestId)return}data=[],event=""}else if(!line.startsWith(":")){let colon=line.indexOf(":"),field=colon===-1?line:line.slice(0,colon),text=colon===-1?"":line.slice(colon+1).replace(/^ /,"");field==="data"&&data.push(text),field==="event"&&(event=text)}}if(done){if(requestId!==void 0)throw new ModernTransportError("Modern MCP SSE ended before the request response");return}}}finally{signal.removeEventListener("abort",onabort),await reader.cancel(),reader.releaseLock()}}};import{randomUUID}from"node:crypto";var subscriptionKey="io.modelcontextprotocol/subscriptionId",listFilters={"notifications/tools/list_changed":"toolsListChanged","notifications/prompts/list_changed":"promptsListChanged","notifications/resources/list_changed":"resourcesListChanged"},ModernSubscriptions=class{#send;#capabilities;#sendCompletesStream;#filter={};#resourceLists=new Map;#resourceCursors=new Map;#latestSweep;#active;#pending;#timer;#retry=0;#closed=!1;#started=!1;constructor(send,capabilities,sendCompletesStream=!1){this.#send=send,this.#capabilities=capabilities,this.#sendCompletesStream=sendCompletesStream}outgoing(message){if("method"in message){if(message.method==="notifications/cancelled"){let id=message.params?.requestId;(typeof id=="string"||typeof id=="number")&&this.#resourceLists.delete(id)}if("id"in message){if(message.method==="resources/list"&&this.#supports("resources","subscribe")){let cursor=message.params?.cursor;if(cursor===void 0){let sweep={uris:[]};this.#latestSweep=sweep,this.#resourceLists.set(message.id,sweep)}else if(typeof cursor=="string"){let sweep=this.#resourceCursors.get(cursor);this.#resourceCursors.delete(cursor),sweep&&this.#resourceLists.set(message.id,sweep)}}this.#started||!["tools/list","prompts/list","resources/list"].includes(message.method)||(this.#started=!0,this.#supports("tools","listChanged")&&(this.#filter.toolsListChanged=!0),this.#supports("prompts","listChanged")&&(this.#filter.promptsListChanged=!0),this.#supports("resources","listChanged")&&(this.#filter.resourcesListChanged=!0),this.#open())}}}incoming(message){let sweep="id"in message&&message.id!==void 0?this.#resourceLists.get(message.id):void 0;if("id"in message&&message.id!==void 0&&this.#resourceLists.delete(message.id),sweep&&"result"in message){let resources=message.result.resources;if(Array.isArray(resources)){for(let resource2 of resources)isRecord(resource2)&&typeof resource2.uri=="string"&&sweep.uris.push(resource2.uri);if(typeof message.result.nextCursor=="string"&&message.result.nextCursor)this.#resourceCursors.set(message.result.nextCursor,sweep);else if(sweep===this.#latestSweep){let uris=[...new Set(sweep.uris)].sort();JSON.stringify(uris)!==JSON.stringify(this.#filter.resourceSubscriptions??[])&&(this.#filter.resourceSubscriptions=uris,this.#open())}}}if("id"in message){let stream=[this.#active,this.#pending].find(entry=>entry?.id===message.id);return stream?(this.#retire(stream),!1):!0}if(!("method"in message))return!0;if(message.method==="notifications/cancelled"){let stream=[this.#active,this.#pending].find(entry=>entry?.id===message.params?.requestId);if(stream)return this.#retire(stream),!1}let meta=message.params?._meta,id=isRecord(meta)?meta[subscriptionKey]:void 0,acknowledged=message.method==="notifications/subscriptions/acknowledged",list=Object.hasOwn(listFilters,message.method),resource=message.method==="notifications/resources/updated";if(!acknowledged&&!list&&!resource)return!0;let active=[this.#active,this.#pending].find(entry=>entry?.id===id);if(!active)return!1;if(acknowledged){if(active.accepted)return!1;if(!isRecord(message.params?.notifications))return this.#failed(active),this.#cancel(active),!1;let offered=message.params.notifications,accepted={};for(let key of Object.values(listFilters))active.requested[key]&&offered[key]===!0&&(accepted[key]=!0);let uris=offered.resourceSubscriptions;Array.isArray(uris)&&(accepted.resourceSubscriptions=active.requested.resourceSubscriptions?.filter(uri=>uris.includes(uri))),active.accepted=accepted;let previous=this.#active;return this.#pending=void 0,this.#active=active,previous&&previous!==active&&this.#cancel(previous),!Object.values(accepted).some(value=>value===!0)&&!accepted.resourceSubscriptions?.length&&this.#cancel(active),!1}if(active!==this.#active||!active.accepted)return!1;let deliver=resource?typeof message.params?.uri=="string"&&active.accepted.resourceSubscriptions?.includes(message.params.uri)===!0:active.accepted[listFilters[message.method]]===!0;return deliver&&(this.#retry=0),deliver}failedSend(message){"id"in message&&message.id!==void 0&&this.#resourceLists.delete(message.id)}dispose(){this.#closed=!0,this.#timer&&mcpElapsedClock.cancel(this.#timer),this.#timer=void 0,this.#pending&&this.#cancel(this.#pending),this.#active&&this.#cancel(this.#active),this.#resourceLists.clear(),this.#resourceCursors.clear(),this.#latestSweep=void 0}#supports(feature,flag){let capability=this.#capabilities[feature];return isRecord(capability)&&capability[flag]===!0}#retire(active){this.#active===active&&(this.#active=void 0),this.#pending===active&&(this.#pending=void 0)}#cancel(active){this.#retire(active),this.#send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:active.id}}).catch(()=>{})}#open(){if(this.#closed||JSON.stringify((this.#pending??this.#active)?.requested)===JSON.stringify(this.#filter))return;if(this.#timer&&mcpElapsedClock.cancel(this.#timer),this.#timer=void 0,this.#pending&&this.#cancel(this.#pending),!Object.values(this.#filter).some(value=>value===!0)&&!this.#filter.resourceSubscriptions?.length){this.#active&&this.#cancel(this.#active);return}let active={id:`senpi-subscription-${randomUUID()}`,requested:structuredClone(this.#filter)};this.#pending=active,this.#send({jsonrpc:"2.0",id:active.id,method:"subscriptions/listen",params:{notifications:active.requested}}).then(()=>{this.#sendCompletesStream&&this.#failed(active)},()=>this.#failed(active))}#failed(active){this.#closed||this.#active!==active&&this.#pending!==active||(this.#retire(active),!(this.#pending||this.#timer)&&(this.#timer=mcpElapsedClock.schedule(()=>{this.#timer=void 0,this.#open()},Math.min(3e4,1e3*2**Math.min(this.#retry++,5))),this.#timer.unref?.()))}};function modernInitializeResult(discovery,wireVersion){if(!discovery.supportedVersions.includes(wireVersion))throw new ModernTransportError(`Discovery does not support negotiated MCP version ${wireVersion}`);return InitializeResultSchema.parse({protocolVersion:LATEST_PROTOCOL_VERSION,capabilities:discovery.capabilities,serverInfo:discovery._meta["io.modelcontextprotocol/serverInfo"],...discovery.instructions===void 0?{}:{instructions:discovery.instructions}})}function normalizeModernResult(message){return"result"in message&&message.result.nextCursor===null&&delete message.result.nextCursor,message}var ModernSdkBridge=class{#transport;#initializeResult;#subscriptions;#initialized=!1;constructor(transport,discovery,wireVersion){this.#initializeResult=modernInitializeResult(discovery,wireVersion),this.#transport=transport,this.#subscriptions=new ModernSubscriptions(transport.send.bind(transport),discovery.capabilities,!0)}async start(){this.#transport.onmessage=(message,extra)=>{this.#subscriptions.incoming(message)&&this.onmessage?.(normalizeModernResult(message),extra)},this.#transport.onclose=()=>{this.#subscriptions.dispose(),this.onclose?.()},this.#transport.onerror=error=>this.onerror?.(error),await this.#transport.start()}async send(message,options){if("method"in message&&message.method==="initialize"){if(!("id"in message)||this.#initialized)throw new ModernTransportError("Modern MCP bridge has already initialized");this.#initialized=!0,this.onmessage?.({jsonrpc:"2.0",id:message.id,result:this.#initializeResult});return}if(!("method"in message&&message.method==="notifications/initialized"&&!("id"in message))){this.#subscriptions.outgoing(message);try{await this.#transport.send(message,options)}catch(error){throw this.#subscriptions.failedSend(message),error}}}close(){return this.#subscriptions.dispose(),this.#transport.close()}};var STDIO_PROBE_MS=2e3;function probeStdioTransport(transport,options,logger,timeoutMs,serverName,onModern,probeMs=STDIO_PROBE_MS,onLegacy){let start=transport.start.bind(transport),close=transport.close.bind(transport),send=transport.send.bind(transport),abort=new AbortController;transport.close=async()=>{abort.abort(),await close()},transport.start=async()=>{await start();let outcome=await probeStdioEra(exchange,options);if(abort.signal.throwIfAborted(),outcome.kind==="legacy-fallback"){outcome.restart?await restart():outcome.silent&&awaitLateDiscovery(),outcome.silent||onLegacy?.();return}if(outcome.kind==="indeterminate"||!outcome.discovery){let reason=outcome.kind==="indeterminate"?outcome.reason:outcome.error?.message,message=`MCP server ${serverName} modern discovery failed: ${reason}`;throw logger.error(message),new ConnectError(message,{phase:"modern-stdio",serverName})}speakModern(outcome.discovery,outcome.version),onModern?.(outcome.version)};async function exchange(request2){let reply=Promise.withResolvers(),signal=AbortSignal.any([abort.signal,AbortSignal.timeout(Math.min(probeMs,Math.floor(timeoutMs/4)))]),onabort=()=>reply.reject(abort.signal.aborted?abort.signal.reason:new StdioProbeSilence),{onmessage,onclose,onerror}=transport;signal.addEventListener("abort",onabort,{once:!0}),transport.onmessage=(message,extra)=>{"id"in message&&!("method"in message)&&message.id===request2.id?reply.resolve(message):onmessage?.(message,extra)},transport.onclose=()=>reply.reject(new ModernTransportError("MCP stdio closed during discovery")),transport.onerror=error=>reply.reject(error);try{return signal.throwIfAborted(),send(request2).catch(reply.reject),await reply.promise}finally{signal.removeEventListener("abort",onabort),transport.onmessage=onmessage,transport.onclose=onclose,transport.onerror=onerror}}async function restart(){logger.info(`MCP server ${serverName}: no clean discovery answer; restarting it for the legacy handshake`);let pid=transport.pid,stale=pid==null?0:1,onclose=transport.onclose;transport.onclose=()=>{stale>0?stale--:onclose?.()},pid!=null&&await reapProcessTree(pid,{termWaitMs:200,killWaitMs:200}),await close(),stale=0,abort.signal.throwIfAborted(),await start(),abort.signal.aborted&&(await close(),abort.signal.throwIfAborted())}function awaitLateDiscovery(){let{onmessage:deliver,onclose,onerror}=transport,late,initialize,initializeId,restarting,settle=()=>{transport.onmessage=deliver,transport.onclose=onclose,transport.onerror=onerror,transport.send=send},unclean=report=>{if(restarting)return report();let replay=initialize;restarting=(async()=>{try{await restart(),replay&&await send(replay)}catch(error){abort.signal.aborted||onerror?.(error instanceof Error?error:new Error(String(error))),onclose?.()}})()};transport.onclose=()=>unclean(()=>onclose?.()),transport.onerror=error=>unclean(()=>onerror?.(error)),transport.onmessage=(message,extra)=>{if("id"in message&&!("method"in message)&&typeof message.id=="string"&&message.id.startsWith(STDIO_PROBE_ID)){late??=discoveryReply(message,message.id);return}let isInitializeReply=initializeId!==void 0&&"id"in message&&message.id===initializeId;if(isInitializeReply&&late&&"error"in message&&late.supportedVersions.includes(MODERN_PROTOCOL_VERSION)){let discovery=late;logger.info(`MCP server ${serverName}: late discovery reply; switching to modern`),settle(),speakModern(discovery,MODERN_PROTOCOL_VERSION),onModern?.(MODERN_PROTOCOL_VERSION),deliver?.({jsonrpc:"2.0",id:initializeId,result:modernInitializeResult(discovery,MODERN_PROTOCOL_VERSION)},extra);return}isInitializeReply&&(settle(),onLegacy?.()),deliver?.(message,extra)},transport.send=async(message,sendOptions)=>("method"in message&&message.method==="initialize"&&"id"in message&&(initialize=message,initializeId=message.id),restarting&&await restarting,send(message,sendOptions))}function speakModern(discovery,version){let initializeResult=modernInitializeResult(discovery,version),deliver=transport.onmessage,live=new Set,subscriptions=new ModernSubscriptions((message,options2)=>transport.send(message,options2),discovery.capabilities),end=transport.close.bind(transport);transport.close=async()=>{subscriptions.dispose(),await end()};let onclose=transport.onclose;transport.onclose=()=>{subscriptions.dispose(),onclose?.()};let initialized=!1;transport.onerror=()=>{let failure=new McpMrtrError("MCP_MRTR_TRANSPORT_FAILED");logger.warn(failure.message),transport.close()},transport.onmessage=(message,extra)=>{if("id"in message&&"method"in message){send({jsonrpc:"2.0",id:message.id,error:{code:-32601,message:"Unsupported MCP method."}}).catch(()=>{});return}if("id"in message&&message.id!==void 0&&!live.delete(message.id))return;if(!subscriptions.incoming(message)){let id="method"in message&&message.method==="notifications/cancelled"?message.params?.requestId:void 0;(typeof id=="string"||typeof id=="number")&&live.delete(id);return}if("method"in message&&message.method==="notifications/progress"){let token=message.params?.progressToken;if(typeof token!="string"&&typeof token!="number"||!live.has(token))return}let safe=sanitizeModernMessage(message);safe&&deliver?.(normalizeModernResult(safe),extra)},transport.send=async(message,sendOptions)=>{if(!("method"in message))return send(message,sendOptions);if(message.method==="initialize"){if(!("id"in message)||initialized)throw new ModernTransportError("Modern MCP stdio has already initialized");initialized=!0,deliver?.({jsonrpc:"2.0",id:message.id,result:initializeResult});return}if(message.method==="notifications/initialized"&&!("id"in message))return;if(message.method==="notifications/cancelled"&&!("id"in message)){subscriptions.outgoing(message);let id=message.params?.requestId;return typeof id!="string"&&typeof id!="number"||!live.delete(id)?void 0:send({jsonrpc:"2.0",method:message.method,params:{requestId:id,reason:"MCP request canceled"}},sendOptions)}getModernDispatchGuard(message.params)?.(),subscriptions.outgoing(message);let request2=modernizeRequest("id"in message?message.id:0,message.method,options.clientInfo,options.clientCapabilities,version,message.params);if("id"in message){live.add(message.id);try{return await send(request2,sendOptions)}catch{throw live.delete(message.id),subscriptions.failedSend(message),new McpMrtrError("MCP_MRTR_TRANSPORT_FAILED")}}let{id:_id,...notification}=request2;return send(notification,sendOptions)}}}var clientInfo={name:"senpi-mcp-client",version:"0.0.0"},probeOptions={clientInfo,clientCapabilities:{},supportedVersions:[MODERN_PROTOCOL_VERSION]};async function materializeNegotiatedTransport(options,serverName,timeoutMs,signal){signal.throwIfAborted();let{spec,logger}=options,protocol={},outcome={kind:"legacy-fallback"};if(spec.kind==="http"){let fetch=modernHttpFetch(spec,signal),timeout=AbortSignal.timeout(timeoutMs);if(outcome=await probeHttpEra(spec.url,(url,init)=>fetch(url,{...init,signal:timeout}),probeOptions),signal.throwIfAborted(),timeout.throwIfAborted(),outcome.kind==="modern-OK"||outcome.kind==="modern-version-retry"){if(!outcome.discovery)throw new ConnectError(`MCP server ${serverName} modern discovery failed: ${outcome.error?.message}`,{phase:"connect",serverName});protocol.version=outcome.version;let client=await createMcpRequestClient(protocol,options.elicitationUiProvider,()=>modernCredentialSnapshot(spec.authProvider?.tokens()),options.elicitationEnabled),transport=new ModernSdkBridge(new ModernHttpTransport({url:spec.url,fetch:modernHttpFetch(spec,signal,!1),clientInfo,clientCapabilities:{},protocolVersion:outcome.version}),outcome.discovery,outcome.version),version=outcome.version;return logVersion(transport,()=>version),{client,transport,readPid:()=>null,close:async()=>{await transport.close(),await client.close()}}}if(outcome.kind==="indeterminate"&&(outcome.era==="modern"||outcome.reason==="invalid-discovery"))throw new ConnectError(`MCP server ${serverName}: ${outcome.reason}. ${outcome.action}`,{phase:"connect",serverName,cause:outcome.cause})}spec.kind==="http"&&(protocol.legacy=!0);let legacy=await materializeMcpTransport(options,protocol),stdioModernVersion;return spec.kind==="stdio"&&probeStdioTransport(legacy.transport,probeOptions,logger,timeoutMs,serverName,version=>{stdioModernVersion=version,protocol.version=version,protocol.activateRequests?.(),protocol.resolveStdioDiagnostics?.(!0)},void 0,()=>{protocol.legacy=!0,protocol.resolveStdioDiagnostics?.(!1)}),logVersion(legacy.transport,()=>stdioModernVersion),legacy;function logVersion(transport,readModernVersion){let setVersion=transport.setProtocolVersion?.bind(transport);transport.setProtocolVersion=sdkVersion=>{setVersion?.(sdkVersion);let modernVersion=readModernVersion();logger.info(`MCP server ${serverName} negotiated: era=${modernVersion?"modern":"legacy"} version=${modernVersion??sdkVersion}`)}}}export{materializeNegotiatedTransport};
|
|
9
|
+
`)));if(this.#deliver(incoming,requestId),"id"in incoming&&!("method"in incoming)&&incoming.id===requestId)return}data=[],event=""}else if(!line.startsWith(":")){let colon=line.indexOf(":"),field=colon===-1?line:line.slice(0,colon),text=colon===-1?"":line.slice(colon+1).replace(/^ /,"");field==="data"&&data.push(text),field==="event"&&(event=text)}}if(done){if(requestId!==void 0)throw new ModernTransportError("Modern MCP SSE ended before the request response");return}}}finally{signal.removeEventListener("abort",onabort),await reader.cancel(),reader.releaseLock()}}};import{randomUUID}from"node:crypto";var subscriptionKey="io.modelcontextprotocol/subscriptionId",listFilters={"notifications/tools/list_changed":"toolsListChanged","notifications/prompts/list_changed":"promptsListChanged","notifications/resources/list_changed":"resourcesListChanged"},ModernSubscriptions=class{#send;#capabilities;#sendCompletesStream;#filter={};#resourceLists=new Map;#resourceCursors=new Map;#latestSweep;#active;#pending;#timer;#retry=0;#closed=!1;#started=!1;constructor(send,capabilities,sendCompletesStream=!1){this.#send=send,this.#capabilities=capabilities,this.#sendCompletesStream=sendCompletesStream}outgoing(message){if("method"in message){if(message.method==="notifications/cancelled"){let id=message.params?.requestId;(typeof id=="string"||typeof id=="number")&&this.#resourceLists.delete(id)}if("id"in message){if(message.method==="resources/list"&&this.#supports("resources","subscribe")){let cursor=message.params?.cursor;if(cursor===void 0){let sweep={uris:[]};this.#latestSweep=sweep,this.#resourceLists.set(message.id,sweep)}else if(typeof cursor=="string"){let sweep=this.#resourceCursors.get(cursor);this.#resourceCursors.delete(cursor),sweep&&this.#resourceLists.set(message.id,sweep)}}this.#started||!["tools/list","prompts/list","resources/list"].includes(message.method)||(this.#started=!0,this.#supports("tools","listChanged")&&(this.#filter.toolsListChanged=!0),this.#supports("prompts","listChanged")&&(this.#filter.promptsListChanged=!0),this.#supports("resources","listChanged")&&(this.#filter.resourcesListChanged=!0),this.#open())}}}incoming(message){let sweep="id"in message&&message.id!==void 0?this.#resourceLists.get(message.id):void 0;if("id"in message&&message.id!==void 0&&this.#resourceLists.delete(message.id),sweep&&"result"in message){let resources=message.result.resources;if(Array.isArray(resources)){for(let resource2 of resources)isRecord(resource2)&&typeof resource2.uri=="string"&&sweep.uris.push(resource2.uri);if(typeof message.result.nextCursor=="string"&&message.result.nextCursor)this.#resourceCursors.set(message.result.nextCursor,sweep);else if(sweep===this.#latestSweep){let uris=[...new Set(sweep.uris)].sort();JSON.stringify(uris)!==JSON.stringify(this.#filter.resourceSubscriptions??[])&&(this.#filter.resourceSubscriptions=uris,this.#open())}}}if("id"in message){let stream=[this.#active,this.#pending].find(entry=>entry?.id===message.id);return stream?(this.#retire(stream),!1):!0}if(!("method"in message))return!0;if(message.method==="notifications/cancelled"){let stream=[this.#active,this.#pending].find(entry=>entry?.id===message.params?.requestId);if(stream)return this.#retire(stream),!1}let meta=message.params?._meta,id=isRecord(meta)?meta[subscriptionKey]:void 0,acknowledged=message.method==="notifications/subscriptions/acknowledged",list=Object.hasOwn(listFilters,message.method),resource=message.method==="notifications/resources/updated";if(!acknowledged&&!list&&!resource)return!0;let active=[this.#active,this.#pending].find(entry=>entry?.id===id);if(!active)return!1;if(acknowledged){if(active.accepted)return!1;if(!isRecord(message.params?.notifications))return this.#failed(active),this.#cancel(active),!1;let offered=message.params.notifications,accepted={};for(let key of Object.values(listFilters))active.requested[key]&&offered[key]===!0&&(accepted[key]=!0);let uris=offered.resourceSubscriptions;Array.isArray(uris)&&(accepted.resourceSubscriptions=active.requested.resourceSubscriptions?.filter(uri=>uris.includes(uri))),active.accepted=accepted;let previous=this.#active;return this.#pending=void 0,this.#active=active,previous&&previous!==active&&this.#cancel(previous),!Object.values(accepted).some(value=>value===!0)&&!accepted.resourceSubscriptions?.length&&this.#cancel(active),!1}if(active!==this.#active||!active.accepted)return!1;let deliver=resource?typeof message.params?.uri=="string"&&active.accepted.resourceSubscriptions?.includes(message.params.uri)===!0:active.accepted[listFilters[message.method]]===!0;return deliver&&(this.#retry=0),deliver}failedSend(message){"id"in message&&message.id!==void 0&&this.#resourceLists.delete(message.id)}dispose(){this.#closed=!0,this.#timer&&mcpElapsedClock.cancel(this.#timer),this.#timer=void 0,this.#pending&&this.#cancel(this.#pending),this.#active&&this.#cancel(this.#active),this.#resourceLists.clear(),this.#resourceCursors.clear(),this.#latestSweep=void 0}#supports(feature,flag){let capability=this.#capabilities[feature];return isRecord(capability)&&capability[flag]===!0}#retire(active){this.#active===active&&(this.#active=void 0),this.#pending===active&&(this.#pending=void 0)}#cancel(active){this.#retire(active),this.#send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:active.id}}).catch(()=>{})}#open(){if(this.#closed||JSON.stringify((this.#pending??this.#active)?.requested)===JSON.stringify(this.#filter))return;if(this.#timer&&mcpElapsedClock.cancel(this.#timer),this.#timer=void 0,this.#pending&&this.#cancel(this.#pending),!Object.values(this.#filter).some(value=>value===!0)&&!this.#filter.resourceSubscriptions?.length){this.#active&&this.#cancel(this.#active);return}let active={id:`senpi-subscription-${randomUUID()}`,requested:structuredClone(this.#filter)};this.#pending=active,this.#send({jsonrpc:"2.0",id:active.id,method:"subscriptions/listen",params:{notifications:active.requested}}).then(()=>{this.#sendCompletesStream&&this.#failed(active)},()=>this.#failed(active))}#failed(active){this.#closed||this.#active!==active&&this.#pending!==active||(this.#retire(active),!(this.#pending||this.#timer)&&(this.#timer=mcpElapsedClock.schedule(()=>{this.#timer=void 0,this.#open()},Math.min(3e4,1e3*2**Math.min(this.#retry++,5))),this.#timer.unref?.()))}};function modernInitializeResult(discovery,wireVersion){if(!discovery.supportedVersions.includes(wireVersion))throw new ModernTransportError(`Discovery does not support negotiated MCP version ${wireVersion}`);return InitializeResultSchema.parse({protocolVersion:LATEST_PROTOCOL_VERSION,capabilities:discovery.capabilities,serverInfo:discovery._meta["io.modelcontextprotocol/serverInfo"],...discovery.instructions===void 0?{}:{instructions:discovery.instructions}})}function normalizeModernResult(message){return"result"in message&&message.result.nextCursor===null&&delete message.result.nextCursor,message}var ModernSdkBridge=class{#transport;#initializeResult;#subscriptions;#initialized=!1;constructor(transport,discovery,wireVersion){this.#initializeResult=modernInitializeResult(discovery,wireVersion),this.#transport=transport,this.#subscriptions=new ModernSubscriptions(transport.send.bind(transport),discovery.capabilities,!0)}async start(){this.#transport.onmessage=(message,extra)=>{this.#subscriptions.incoming(message)&&this.onmessage?.(normalizeModernResult(message),extra)},this.#transport.onclose=()=>{this.#subscriptions.dispose(),this.onclose?.()},this.#transport.onerror=error=>this.onerror?.(error),await this.#transport.start()}async send(message,options){if("method"in message&&message.method==="initialize"){if(!("id"in message)||this.#initialized)throw new ModernTransportError("Modern MCP bridge has already initialized");this.#initialized=!0,this.onmessage?.({jsonrpc:"2.0",id:message.id,result:this.#initializeResult});return}if(!("method"in message&&message.method==="notifications/initialized"&&!("id"in message))){this.#subscriptions.outgoing(message);try{await this.#transport.send(message,options)}catch(error){throw this.#subscriptions.failedSend(message),error}}}close(){return this.#subscriptions.dispose(),this.#transport.close()}};var STDIO_PROBE_MS=2e3;function probeStdioTransport(transport,options,logger,timeoutMs,serverName,onModern,probeMs=STDIO_PROBE_MS,onLegacy){let start=transport.start.bind(transport),close=transport.close.bind(transport),send=transport.send.bind(transport),abort=new AbortController;transport.close=async()=>{abort.abort(),await close()},transport.start=async()=>{await start();let outcome=await probeStdioEra(exchange,options);if(abort.signal.throwIfAborted(),outcome.kind==="legacy-fallback"){outcome.restart?await restart():outcome.silent&&awaitLateDiscovery(),outcome.silent||onLegacy?.();return}if(outcome.kind==="indeterminate"||!outcome.discovery){let reason=outcome.kind==="indeterminate"?outcome.reason:outcome.error?.message,message=`MCP server ${serverName} modern discovery failed: ${reason}`;throw logger.error(message),new ConnectError(message,{phase:"modern-stdio",serverName})}speakModern(outcome.discovery,outcome.version),onModern?.(outcome.version)};async function exchange(request2){let reply=Promise.withResolvers(),signal=AbortSignal.any([abort.signal,AbortSignal.timeout(Math.min(probeMs,Math.floor(timeoutMs/4)))]),onabort=()=>reply.reject(abort.signal.aborted?abort.signal.reason:new StdioProbeSilence),{onmessage,onclose,onerror}=transport;signal.addEventListener("abort",onabort,{once:!0}),transport.onmessage=(message,extra)=>{"id"in message&&!("method"in message)&&message.id===request2.id?reply.resolve(message):onmessage?.(message,extra)},transport.onclose=()=>reply.reject(new ModernTransportError("MCP stdio closed during discovery")),transport.onerror=error=>reply.reject(error);try{return signal.throwIfAborted(),send(request2).catch(reply.reject),await reply.promise}finally{signal.removeEventListener("abort",onabort),transport.onmessage=onmessage,transport.onclose=onclose,transport.onerror=onerror}}async function restart(){logger.info(`MCP server ${serverName}: no clean discovery answer; restarting it for the legacy handshake`);let pid=transport.pid,stale=pid==null?0:1,onclose=transport.onclose;transport.onclose=()=>{stale>0?stale--:onclose?.()},pid!=null&&await reapProcessTree(pid,{termWaitMs:200,killWaitMs:200}),await close(),stale=0,abort.signal.throwIfAborted(),await start(),abort.signal.aborted&&(await close(),abort.signal.throwIfAborted())}function awaitLateDiscovery(){let{onmessage:deliver,onclose,onerror}=transport,late,initialize,initializeId,restarting,settle=()=>{transport.onmessage=deliver,transport.onclose=onclose,transport.onerror=onerror,transport.send=send},unclean=report=>{if(restarting)return report();let replay=initialize;restarting=(async()=>{try{await restart(),replay&&await send(replay)}catch(error){abort.signal.aborted||onerror?.(error instanceof Error?error:new Error(String(error))),onclose?.()}})()};transport.onclose=()=>unclean(()=>onclose?.()),transport.onerror=error=>unclean(()=>onerror?.(error)),transport.onmessage=(message,extra)=>{if("id"in message&&!("method"in message)&&typeof message.id=="string"&&message.id.startsWith(STDIO_PROBE_ID)){late??=discoveryReply(message,message.id);return}let isInitializeReply=initializeId!==void 0&&"id"in message&&message.id===initializeId;if(isInitializeReply&&late&&"error"in message&&late.supportedVersions.includes(MODERN_PROTOCOL_VERSION)){let discovery=late;logger.info(`MCP server ${serverName}: late discovery reply; switching to modern`),settle(),speakModern(discovery,MODERN_PROTOCOL_VERSION),onModern?.(MODERN_PROTOCOL_VERSION),deliver?.({jsonrpc:"2.0",id:initializeId,result:modernInitializeResult(discovery,MODERN_PROTOCOL_VERSION)},extra);return}isInitializeReply&&(settle(),onLegacy?.()),deliver?.(message,extra)},transport.send=async(message,sendOptions)=>("method"in message&&message.method==="initialize"&&"id"in message&&(initialize=message,initializeId=message.id),restarting&&await restarting,send(message,sendOptions))}function speakModern(discovery,version){let initializeResult=modernInitializeResult(discovery,version),deliver=transport.onmessage,live=new Set,subscriptions=new ModernSubscriptions((message,options2)=>transport.send(message,options2),discovery.capabilities),end=transport.close.bind(transport);transport.close=async()=>{subscriptions.dispose(),await end()};let onclose=transport.onclose;transport.onclose=()=>{subscriptions.dispose(),onclose?.()};let initialized=!1;transport.onerror=()=>{let failure=new McpMrtrError("MCP_MRTR_TRANSPORT_FAILED");logger.warn(failure.message),transport.close()},transport.onmessage=(message,extra)=>{if("id"in message&&"method"in message){send({jsonrpc:"2.0",id:message.id,error:{code:-32601,message:"Unsupported MCP method."}}).catch(()=>{});return}if("id"in message&&message.id!==void 0&&!live.delete(message.id))return;if(!subscriptions.incoming(message)){let id="method"in message&&message.method==="notifications/cancelled"?message.params?.requestId:void 0;(typeof id=="string"||typeof id=="number")&&live.delete(id);return}if("method"in message&&message.method==="notifications/progress"){let token=message.params?.progressToken;if(typeof token!="string"&&typeof token!="number"||!live.has(token))return}let safe=sanitizeModernMessage(message);safe&&deliver?.(normalizeModernResult(safe),extra)},transport.send=async(message,sendOptions)=>{if(!("method"in message))return send(message,sendOptions);if(message.method==="initialize"){if(!("id"in message)||initialized)throw new ModernTransportError("Modern MCP stdio has already initialized");initialized=!0,deliver?.({jsonrpc:"2.0",id:message.id,result:initializeResult});return}if(message.method==="notifications/initialized"&&!("id"in message))return;if(message.method==="notifications/cancelled"&&!("id"in message)){subscriptions.outgoing(message);let id=message.params?.requestId;return typeof id!="string"&&typeof id!="number"||!live.delete(id)?void 0:send({jsonrpc:"2.0",method:message.method,params:{requestId:id,reason:"MCP request canceled"}},sendOptions)}getModernDispatchGuard(message.params)?.(),subscriptions.outgoing(message);let request2=modernizeRequest("id"in message?message.id:0,message.method,options.clientInfo,options.clientCapabilities,version,message.params);if("id"in message){live.add(message.id);try{return await send(request2,sendOptions)}catch{throw live.delete(message.id),subscriptions.failedSend(message),new McpMrtrError("MCP_MRTR_TRANSPORT_FAILED")}}let{id:_id,...notification}=request2;return send(notification,sendOptions)}}}var clientInfo={name:"senpi-mcp-client",version:"0.0.0"},probeOptions={clientInfo,clientCapabilities:{},supportedVersions:[MODERN_PROTOCOL_VERSION]};async function materializeNegotiatedTransport(options,serverName,timeoutMs,signal){signal.throwIfAborted();let{spec,logger}=options,protocol={},outcome={kind:"legacy-fallback"};if(spec.kind==="http"){let fetch=modernHttpFetch(spec,signal),timeout=AbortSignal.timeout(timeoutMs);if(outcome=await probeHttpEra(spec.url,(url,init)=>fetch(url,{...init,signal:timeout}),probeOptions),signal.throwIfAborted(),timeout.throwIfAborted(),outcome.kind==="modern-OK"||outcome.kind==="modern-version-retry"){if(!outcome.discovery)throw new ConnectError(`MCP server ${serverName} modern discovery failed: ${outcome.error?.message}`,{phase:"connect",serverName});protocol.version=outcome.version;let client=await createMcpRequestClient(protocol,options.elicitationUiProvider,()=>modernCredentialSnapshot(spec.authProvider?.tokens()),options.elicitationEnabled),transport=new ModernSdkBridge(new ModernHttpTransport({url:spec.url,fetch:modernHttpFetch(spec,signal,!1),clientInfo,clientCapabilities:{},protocolVersion:outcome.version,logger}),outcome.discovery,outcome.version),version=outcome.version;return logVersion(transport,()=>version),{client,transport,readPid:()=>null,close:async()=>{await transport.close(),await client.close()}}}if(outcome.kind==="indeterminate"&&(outcome.era==="modern"||outcome.reason==="invalid-discovery"))throw new ConnectError(`MCP server ${serverName}: ${outcome.reason}. ${outcome.action}`,{phase:"connect",serverName,cause:outcome.cause})}spec.kind==="http"&&(protocol.legacy=!0);let legacy=await materializeMcpTransport(options,protocol),stdioModernVersion;return spec.kind==="stdio"&&probeStdioTransport(legacy.transport,probeOptions,logger,timeoutMs,serverName,version=>{stdioModernVersion=version,protocol.version=version,protocol.activateRequests?.(),protocol.resolveStdioDiagnostics?.(!0)},void 0,()=>{protocol.legacy=!0,protocol.resolveStdioDiagnostics?.(!1)}),logVersion(legacy.transport,()=>stdioModernVersion),legacy;function logVersion(transport,readModernVersion){let setVersion=transport.setProtocolVersion?.bind(transport);transport.setProtocolVersion=sdkVersion=>{setVersion?.(sdkVersion);let modernVersion=readModernVersion();logger.info(`MCP server ${serverName} negotiated: era=${modernVersion?"modern":"legacy"} version=${modernVersion??sdkVersion}`)}}}export{materializeNegotiatedTransport};
|
package/dist/bundle/chunks/{google-generative-ai-5G4RIQA6.js → google-generative-ai-FHYFXKLA.js}
RENAMED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{GoogleGenAI,convertMessages,convertTools,getDisabledGoogleThinkingConfig,isThinkingPart,mapStopReason,resolveGoogleFunctionCallingMode,resolveGoogleThinkingLevel,retainThoughtSignature,retryGoogleRequest,supportsGoogleStrictToolSampling,toGoogleSdkThinkingLevel,toGoogleThinkingLevel,toProviderNativeContent,usesGoogleThinkingLevel}from"./chunk-CDQPA4FP.js";import"./chunk-K2EVQGGT.js";import"./chunk-DMFAVE5N.js";import{getPiUserAgent}from"./chunk-QTG7MY2X.js";import{GOOGLE_RESERVED_BODY_KEYS,applyExtraBody,buildBaseOptions}from"./chunk-XQ45JMGN.js";import"./chunk-EDOW5W5H.js";import{formatProviderError,normalizeProviderError}from"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import{reportedCount}from"./chunk-GVSBCJFI.js";import"./chunk-5LWUUXMH.js";import{sanitizeSurrogates}from"./chunk-WDTJ6JKE.js";import{calculateCost,clampThinkingLevel,collapseSystemMessages,getCurrentTools,getInitialSystemMessage,getSystemMessageText}from"./chunk-ZXHLH4MW.js";import"./chunk-45SZOLCU.js";import{AssistantMessageEventStream,pushAssistantCompleteBlock,pushAssistantSignature}from"./chunk-GQJYNFMO.js";import{providerHeadersToRecord}from"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";var toolCallCounter=0,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream({captureBlocks:!0}),normalizedContext=collapseSystemMessages(context);return(async()=>{let output={role:"assistant",content:[],api:"google-generative-ai",provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{if(options?.fetch&&options.fetch!==globalThis.fetch)throw new Error("Custom fetch is not supported by the Google Generative AI adapter");let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let client=createClient(model,apiKey,providerHeadersToRecord(options?.headers)),params=buildParams(model,normalizedContext,options),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let googleStream=await retryGoogleRequest(()=>client.models.generateContentStream(params),options);stream2.push({type:"start",partial:output});let currentBlock=null,currentIndex=0,groundingMetadataEmitted=!1,urlContextMetadataEmitted=!1,blocks=output.content,blockIndex=()=>blocks.length-1,pushOpen=event=>stream2.push(event,{contentIndex:currentIndex});for await(let chunk of googleStream){await options?.onProviderStreamEvent?.(chunk,model),output.responseId||=chunk.responseId;let candidate=chunk.candidates?.[0];if(candidate?.content?.parts)for(let part of candidate.content.parts){let handledAsKnownPart=!1;if(part.text!==void 0){handledAsKnownPart=!0;let isThinking=isThinkingPart(part);(!currentBlock||isThinking&¤tBlock.type!=="thinking"||!isThinking&¤tBlock.type!=="text")&&(currentBlock&&(currentBlock.type==="text"?pushOpen({type:"text_end",contentIndex:blocks.length-1,content:currentBlock.text,partial:output}):pushOpen({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),isThinking?(currentBlock={type:"thinking",thinking:"",thinkingSignature:void 0},output.content.push(currentBlock),currentIndex=blockIndex(),stream2.push({type:"thinking_start",contentIndex:blockIndex(),partial:output})):(currentBlock={type:"text",text:""},output.content.push(currentBlock),currentIndex=blockIndex(),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output}))),currentBlock.type==="thinking"?(currentBlock.thinking+=part.text,pushAssistantSignature(stream2,currentIndex,currentBlock,part.thoughtSignature),currentBlock.thinkingSignature=retainThoughtSignature(currentBlock.thinkingSignature,part.thoughtSignature),pushOpen({type:"thinking_delta",contentIndex:blockIndex(),delta:part.text,partial:output})):(currentBlock.text+=part.text,pushAssistantSignature(stream2,currentIndex,currentBlock,part.thoughtSignature),currentBlock.textSignature=retainThoughtSignature(currentBlock.textSignature,part.thoughtSignature),pushOpen({type:"text_delta",contentIndex:blockIndex(),delta:part.text,partial:output}))}if(part.functionCall){handledAsKnownPart=!0,currentBlock&&(currentBlock.type==="text"?pushOpen({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):pushOpen({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output}),currentBlock=null);let providedId=part.functionCall.id,toolCall={type:"toolCall",id:!providedId||output.content.some(b=>b.type==="toolCall"&&b.id===providedId)?`${part.functionCall.name}_${Date.now()}_${++toolCallCounter}`:providedId,name:part.functionCall.name||"",arguments:part.functionCall.args??{},...part.thoughtSignature&&{thoughtSignature:part.thoughtSignature}};output.content.push(toolCall),stream2.push({type:"toolcall_start",contentIndex:blockIndex(),partial:output}),stream2.push({type:"toolcall_delta",contentIndex:blockIndex(),delta:JSON.stringify(toolCall.arguments),partial:output},{parsedThrough:0}),stream2.push({type:"toolcall_end",contentIndex:blockIndex(),toolCall,partial:output})}handledAsKnownPart||(output.content.push(toProviderNativeContent(part)),pushAssistantCompleteBlock(stream2,blockIndex(),blocks[blockIndex()]))}if(candidate?.groundingMetadata&&!groundingMetadataEmitted&&(output.content.push({type:"providerNative",subtype:"groundingMetadata",raw:candidate.groundingMetadata}),pushAssistantCompleteBlock(stream2,blockIndex(),blocks[blockIndex()]),groundingMetadataEmitted=!0),candidate?.urlContextMetadata&&!urlContextMetadataEmitted&&(output.content.push({type:"providerNative",subtype:"urlContextMetadata",raw:candidate.urlContextMetadata}),pushAssistantCompleteBlock(stream2,blockIndex(),blocks[blockIndex()]),urlContextMetadataEmitted=!0),candidate?.finishReason&&(output.rawStopReason=candidate.finishReason,output.stopReason=mapStopReason(candidate.finishReason),output.content.some(b=>b.type==="toolCall")&&output.stopReason==="stop"&&(output.stopReason="toolUse")),chunk.usageMetadata){let reasoning=reportedCount(chunk.usageMetadata.thoughtsTokenCount);output.usage={input:(chunk.usageMetadata.promptTokenCount||0)-(chunk.usageMetadata.cachedContentTokenCount||0),output:(chunk.usageMetadata.candidatesTokenCount||0)+(chunk.usageMetadata.thoughtsTokenCount||0),cacheRead:chunk.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,...reasoning===void 0?{}:{reasoning},totalTokens:chunk.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},calculateCost(model,output.usage)}}if(currentBlock&&(currentBlock.type==="text"?pushOpen({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):pushOpen({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Google stream ended without a finish reason");if(output.stopReason==="aborted"||output.stopReason==="error"){let errorMessage=output.rawStopReason?`Provider stopped with: ${output.rawStopReason}`:"An unknown error occurred";throw new Error(errorMessage)}stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)"index"in block&&delete block.index;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error)),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let base={...buildBaseOptions(model,context,options,apiKey),toolChoice:options?.toolChoice};if(!options?.reasoning||options.reasoning==="off")return stream(model,context,{...base,thinking:{enabled:!1}});let clampedReasoning=clampThinkingLevel(model,options.reasoning);if(clampedReasoning==="off")return stream(model,context,{...base,thinking:{enabled:!1}});let resolvedLevel=resolveGoogleThinkingLevel(model,clampedReasoning);return usesGoogleThinkingLevel(model)?stream(model,context,{...base,thinking:{enabled:!0,level:toGoogleThinkingLevel(resolvedLevel)}}):stream(model,context,{...base,thinking:{enabled:!0,budgetTokens:getGoogleBudget(model,resolvedLevel,options.thinkingBudgets)}})};function createClient(model,apiKey,optionsHeaders){let httpOptions={};model.baseUrl&&(httpOptions.baseUrl=model.baseUrl,httpOptions.apiVersion="");let headers=providerHeadersToRecord({"User-Agent":getPiUserAgent(),...model.headers,...optionsHeaders});return headers&&(httpOptions.headers=headers),new GoogleGenAI({apiKey,httpOptions:Object.keys(httpOptions).length>0?httpOptions:void 0})}function buildParams(model,context,options={}){let contents=convertMessages(model,context,{preserveThinking:options.thinking?.enabled===!0}),initialSystemMessage=getInitialSystemMessage(context.messages),currentTools=getCurrentTools(context.messages),generationConfig={};options.temperature!==void 0&&(generationConfig.temperature=options.temperature),options.maxTokens!==void 0&&(generationConfig.maxOutputTokens=options.maxTokens);let supportsStrictMode=supportsGoogleStrictToolSampling(model.id),functionCallingMode=currentTools.length>0?resolveGoogleFunctionCallingMode(currentTools,options.toolChoice,supportsStrictMode):void 0,systemInstruction=initialSystemMessage?getSystemMessageText(initialSystemMessage):"",config={...Object.keys(generationConfig).length>0&&generationConfig,...systemInstruction&&{systemInstruction:sanitizeSurrogates(systemInstruction)},...currentTools.length>0&&{tools:convertTools(currentTools,!1,supportsStrictMode)},...functionCallingMode!==void 0&&{toolConfig:{functionCallingConfig:{mode:functionCallingMode}}}};if(options.thinking?.enabled&&model.reasoning){let thinkingConfig={includeThoughts:!0};options.thinking.level!==void 0?thinkingConfig.thinkingLevel=toGoogleSdkThinkingLevel(options.thinking.level):options.thinking.budgetTokens!==void 0&&(thinkingConfig.thinkingBudget=options.thinking.budgetTokens),config.thinkingConfig=thinkingConfig}else model.reasoning&&options.thinking&&!options.thinking.enabled&&(config.thinkingConfig=getDisabledGoogleThinkingConfig(model));if(options.signal){if(options.signal.aborted)throw new Error("Request aborted");config.abortSignal=options.signal}return applyExtraBody(config,options?.extraBody,GOOGLE_RESERVED_BODY_KEYS),{model:model.id,contents,config}}function getGoogleBudget(model,level,customBudgets){return customBudgets?.[level]!==void 0?customBudgets[level]:model.id.includes("2.5-pro")?{minimal:128,low:2048,medium:8192,high:32768}[level]:model.id.includes("2.5-flash-lite")?{minimal:512,low:2048,medium:8192,high:24576}[level]:model.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[level]:-1}export{stream,streamSimple};
|
|
2
|
+
import{GoogleGenAI,convertMessages,convertTools,getDisabledGoogleThinkingConfig,isThinkingPart,mapStopReason,resolveGoogleFunctionCallingMode,resolveGoogleThinkingLevel,retainThoughtSignature,retryGoogleRequest,supportsGoogleStrictToolSampling,toGoogleSdkThinkingLevel,toGoogleThinkingLevel,toProviderNativeContent,usesGoogleThinkingLevel}from"./chunk-ODRGPC5S.js";import"./chunk-K2EVQGGT.js";import"./chunk-4QVORFQ2.js";import{getPiUserAgent}from"./chunk-QTG7MY2X.js";import{GOOGLE_RESERVED_BODY_KEYS,applyExtraBody,buildBaseOptions}from"./chunk-Z6BREXV3.js";import"./chunk-EDOW5W5H.js";import{formatProviderError,normalizeProviderError}from"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import{reportedCount}from"./chunk-GVSBCJFI.js";import"./chunk-PY4ZQHTN.js";import{sanitizeSurrogates}from"./chunk-WDTJ6JKE.js";import{calculateCost,clampThinkingLevel,collapseSystemMessages,getCurrentTools,getInitialSystemMessage,getSystemMessageText}from"./chunk-5W3DTM2J.js";import"./chunk-45SZOLCU.js";import{AssistantMessageEventStream,pushAssistantCompleteBlock,pushAssistantSignature}from"./chunk-KBSFTXAT.js";import{providerHeadersToRecord}from"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";var toolCallCounter=0,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream({captureBlocks:!0}),normalizedContext=collapseSystemMessages(context);return(async()=>{let output={role:"assistant",content:[],api:"google-generative-ai",provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{if(options?.fetch&&options.fetch!==globalThis.fetch)throw new Error("Custom fetch is not supported by the Google Generative AI adapter");let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let client=createClient(model,apiKey,providerHeadersToRecord(options?.headers)),params=buildParams(model,normalizedContext,options),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let googleStream=await retryGoogleRequest(()=>client.models.generateContentStream(params),options);stream2.push({type:"start",partial:output});let currentBlock=null,currentIndex=0,groundingMetadataEmitted=!1,urlContextMetadataEmitted=!1,blocks=output.content,blockIndex=()=>blocks.length-1,pushOpen=event=>stream2.push(event,{contentIndex:currentIndex});for await(let chunk of googleStream){await options?.onProviderStreamEvent?.(chunk,model),output.responseId||=chunk.responseId;let candidate=chunk.candidates?.[0];if(candidate?.content?.parts)for(let part of candidate.content.parts){let handledAsKnownPart=!1;if(part.text!==void 0){handledAsKnownPart=!0;let isThinking=isThinkingPart(part);(!currentBlock||isThinking&¤tBlock.type!=="thinking"||!isThinking&¤tBlock.type!=="text")&&(currentBlock&&(currentBlock.type==="text"?pushOpen({type:"text_end",contentIndex:blocks.length-1,content:currentBlock.text,partial:output}):pushOpen({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),isThinking?(currentBlock={type:"thinking",thinking:"",thinkingSignature:void 0},output.content.push(currentBlock),currentIndex=blockIndex(),stream2.push({type:"thinking_start",contentIndex:blockIndex(),partial:output})):(currentBlock={type:"text",text:""},output.content.push(currentBlock),currentIndex=blockIndex(),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output}))),currentBlock.type==="thinking"?(currentBlock.thinking+=part.text,pushAssistantSignature(stream2,currentIndex,currentBlock,part.thoughtSignature),currentBlock.thinkingSignature=retainThoughtSignature(currentBlock.thinkingSignature,part.thoughtSignature),pushOpen({type:"thinking_delta",contentIndex:blockIndex(),delta:part.text,partial:output})):(currentBlock.text+=part.text,pushAssistantSignature(stream2,currentIndex,currentBlock,part.thoughtSignature),currentBlock.textSignature=retainThoughtSignature(currentBlock.textSignature,part.thoughtSignature),pushOpen({type:"text_delta",contentIndex:blockIndex(),delta:part.text,partial:output}))}if(part.functionCall){handledAsKnownPart=!0,currentBlock&&(currentBlock.type==="text"?pushOpen({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):pushOpen({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output}),currentBlock=null);let providedId=part.functionCall.id,toolCall={type:"toolCall",id:!providedId||output.content.some(b=>b.type==="toolCall"&&b.id===providedId)?`${part.functionCall.name}_${Date.now()}_${++toolCallCounter}`:providedId,name:part.functionCall.name||"",arguments:part.functionCall.args??{},...part.thoughtSignature&&{thoughtSignature:part.thoughtSignature}};output.content.push(toolCall),stream2.push({type:"toolcall_start",contentIndex:blockIndex(),partial:output}),stream2.push({type:"toolcall_delta",contentIndex:blockIndex(),delta:JSON.stringify(toolCall.arguments),partial:output},{parsedThrough:0}),stream2.push({type:"toolcall_end",contentIndex:blockIndex(),toolCall,partial:output})}handledAsKnownPart||(output.content.push(toProviderNativeContent(part)),pushAssistantCompleteBlock(stream2,blockIndex(),blocks[blockIndex()]))}if(candidate?.groundingMetadata&&!groundingMetadataEmitted&&(output.content.push({type:"providerNative",subtype:"groundingMetadata",raw:candidate.groundingMetadata}),pushAssistantCompleteBlock(stream2,blockIndex(),blocks[blockIndex()]),groundingMetadataEmitted=!0),candidate?.urlContextMetadata&&!urlContextMetadataEmitted&&(output.content.push({type:"providerNative",subtype:"urlContextMetadata",raw:candidate.urlContextMetadata}),pushAssistantCompleteBlock(stream2,blockIndex(),blocks[blockIndex()]),urlContextMetadataEmitted=!0),candidate?.finishReason&&(output.rawStopReason=candidate.finishReason,output.stopReason=mapStopReason(candidate.finishReason),output.content.some(b=>b.type==="toolCall")&&output.stopReason==="stop"&&(output.stopReason="toolUse")),chunk.usageMetadata){let reasoning=reportedCount(chunk.usageMetadata.thoughtsTokenCount);output.usage={input:(chunk.usageMetadata.promptTokenCount||0)-(chunk.usageMetadata.cachedContentTokenCount||0),output:(chunk.usageMetadata.candidatesTokenCount||0)+(chunk.usageMetadata.thoughtsTokenCount||0),cacheRead:chunk.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,...reasoning===void 0?{}:{reasoning},totalTokens:chunk.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},calculateCost(model,output.usage)}}if(currentBlock&&(currentBlock.type==="text"?pushOpen({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):pushOpen({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Google stream ended without a finish reason");if(output.stopReason==="aborted"||output.stopReason==="error"){let errorMessage=output.rawStopReason?`Provider stopped with: ${output.rawStopReason}`:"An unknown error occurred";throw new Error(errorMessage)}stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)"index"in block&&delete block.index;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error)),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let base={...buildBaseOptions(model,context,options,apiKey),toolChoice:options?.toolChoice};if(!options?.reasoning||options.reasoning==="off")return stream(model,context,{...base,thinking:{enabled:!1}});let clampedReasoning=clampThinkingLevel(model,options.reasoning);if(clampedReasoning==="off")return stream(model,context,{...base,thinking:{enabled:!1}});let resolvedLevel=resolveGoogleThinkingLevel(model,clampedReasoning);return usesGoogleThinkingLevel(model)?stream(model,context,{...base,thinking:{enabled:!0,level:toGoogleThinkingLevel(resolvedLevel)}}):stream(model,context,{...base,thinking:{enabled:!0,budgetTokens:getGoogleBudget(model,resolvedLevel,options.thinkingBudgets)}})};function createClient(model,apiKey,optionsHeaders){let httpOptions={};model.baseUrl&&(httpOptions.baseUrl=model.baseUrl,httpOptions.apiVersion="");let headers=providerHeadersToRecord({"User-Agent":getPiUserAgent(),...model.headers,...optionsHeaders});return headers&&(httpOptions.headers=headers),new GoogleGenAI({apiKey,httpOptions:Object.keys(httpOptions).length>0?httpOptions:void 0})}function buildParams(model,context,options={}){let contents=convertMessages(model,context,{preserveThinking:options.thinking?.enabled===!0}),initialSystemMessage=getInitialSystemMessage(context.messages),currentTools=getCurrentTools(context.messages),generationConfig={};options.temperature!==void 0&&(generationConfig.temperature=options.temperature),options.maxTokens!==void 0&&(generationConfig.maxOutputTokens=options.maxTokens);let supportsStrictMode=supportsGoogleStrictToolSampling(model.id),functionCallingMode=currentTools.length>0?resolveGoogleFunctionCallingMode(currentTools,options.toolChoice,supportsStrictMode):void 0,systemInstruction=initialSystemMessage?getSystemMessageText(initialSystemMessage):"",config={...Object.keys(generationConfig).length>0&&generationConfig,...systemInstruction&&{systemInstruction:sanitizeSurrogates(systemInstruction)},...currentTools.length>0&&{tools:convertTools(currentTools,!1,supportsStrictMode)},...functionCallingMode!==void 0&&{toolConfig:{functionCallingConfig:{mode:functionCallingMode}}}};if(options.thinking?.enabled&&model.reasoning){let thinkingConfig={includeThoughts:!0};options.thinking.level!==void 0?thinkingConfig.thinkingLevel=toGoogleSdkThinkingLevel(options.thinking.level):options.thinking.budgetTokens!==void 0&&(thinkingConfig.thinkingBudget=options.thinking.budgetTokens),config.thinkingConfig=thinkingConfig}else model.reasoning&&options.thinking&&!options.thinking.enabled&&(config.thinkingConfig=getDisabledGoogleThinkingConfig(model));if(options.signal){if(options.signal.aborted)throw new Error("Request aborted");config.abortSignal=options.signal}return applyExtraBody(config,options?.extraBody,GOOGLE_RESERVED_BODY_KEYS),{model:model.id,contents,config}}function getGoogleBudget(model,level,customBudgets){return customBudgets?.[level]!==void 0?customBudgets[level]:model.id.includes("2.5-pro")?{minimal:128,low:2048,medium:8192,high:32768}[level]:model.id.includes("2.5-flash-lite")?{minimal:512,low:2048,medium:8192,high:24576}[level]:model.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[level]:-1}export{stream,streamSimple};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{buildGoogleAuthOptions,resolveVertexProjectFromEnv}from"./chunk-74YFRVGQ.js";import{GoogleGenAI,ResourceScope,convertMessages,convertTools,getDisabledGoogleThinkingConfig,isThinkingPart,mapStopReason,resolveGoogleFunctionCallingMode,resolveGoogleThinkingLevel,retainThoughtSignature,retryGoogleRequest,supportsGoogleStrictToolSampling,toGoogleSdkThinkingLevel,toGoogleThinkingLevel,toProviderNativeContent,usesGoogleThinkingLevel}from"./chunk-CDQPA4FP.js";import"./chunk-K2EVQGGT.js";import"./chunk-DMFAVE5N.js";import{getPiUserAgent}from"./chunk-QTG7MY2X.js";import{GOOGLE_RESERVED_BODY_KEYS,applyExtraBody,buildBaseOptions}from"./chunk-XQ45JMGN.js";import"./chunk-EDOW5W5H.js";import{formatProviderError,normalizeProviderError}from"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import{reportedCount}from"./chunk-GVSBCJFI.js";import"./chunk-5LWUUXMH.js";import{sanitizeSurrogates}from"./chunk-WDTJ6JKE.js";import{getProviderEnvValue}from"./chunk-5ROMKDLK.js";import{calculateCost,clampThinkingLevel,collapseSystemMessages,getCurrentTools,getInitialSystemMessage,getSystemMessageText}from"./chunk-ZXHLH4MW.js";import"./chunk-45SZOLCU.js";import{AssistantMessageEventStream,pushAssistantCompleteBlock,pushAssistantSignature}from"./chunk-GQJYNFMO.js";import{providerHeadersToRecord}from"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";var API_VERSION="v1",GCP_VERTEX_CREDENTIALS_MARKER="gcp-vertex-credentials",toolCallCounter=0,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream({captureBlocks:!0}),normalizedContext=collapseSystemMessages(context);return(async()=>{let output={role:"assistant",content:[],api:"google-vertex",provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{if(options?.fetch&&options.fetch!==globalThis.fetch)throw new Error("Custom fetch is not supported by the Google Vertex adapter");let apiKey=resolveApiKey(options),headers=providerHeadersToRecord(options?.headers),client=apiKey?createClientWithApiKey(model,apiKey,headers):createClient(model,resolveProject(options),resolveLocation(options),headers,options?.env),params=buildParams(model,normalizedContext,options),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let googleStream=await retryGoogleRequest(()=>client.models.generateContentStream(params),options);stream2.push({type:"start",partial:output});let currentBlock=null,currentIndex=0,groundingMetadataEmitted=!1,urlContextMetadataEmitted=!1,blocks=output.content,blockIndex=()=>blocks.length-1,pushOpen=event=>stream2.push(event,{contentIndex:currentIndex});for await(let chunk of googleStream){await options?.onProviderStreamEvent?.(chunk,model),output.responseId||=chunk.responseId;let candidate=chunk.candidates?.[0];if(candidate?.content?.parts)for(let part of candidate.content.parts){let handledAsKnownPart=!1;if(part.text!==void 0){handledAsKnownPart=!0;let isThinking=isThinkingPart(part);(!currentBlock||isThinking&¤tBlock.type!=="thinking"||!isThinking&¤tBlock.type!=="text")&&(currentBlock&&(currentBlock.type==="text"?pushOpen({type:"text_end",contentIndex:blocks.length-1,content:currentBlock.text,partial:output}):pushOpen({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),isThinking?(currentBlock={type:"thinking",thinking:"",thinkingSignature:void 0},output.content.push(currentBlock),currentIndex=blockIndex(),stream2.push({type:"thinking_start",contentIndex:blockIndex(),partial:output})):(currentBlock={type:"text",text:""},output.content.push(currentBlock),currentIndex=blockIndex(),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output}))),currentBlock.type==="thinking"?(currentBlock.thinking+=part.text,pushAssistantSignature(stream2,currentIndex,currentBlock,part.thoughtSignature),currentBlock.thinkingSignature=retainThoughtSignature(currentBlock.thinkingSignature,part.thoughtSignature),pushOpen({type:"thinking_delta",contentIndex:blockIndex(),delta:part.text,partial:output})):(currentBlock.text+=part.text,pushAssistantSignature(stream2,currentIndex,currentBlock,part.thoughtSignature),currentBlock.textSignature=retainThoughtSignature(currentBlock.textSignature,part.thoughtSignature),pushOpen({type:"text_delta",contentIndex:blockIndex(),delta:part.text,partial:output}))}if(part.functionCall){handledAsKnownPart=!0,currentBlock&&(currentBlock.type==="text"?pushOpen({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):pushOpen({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output}),currentBlock=null);let providedId=part.functionCall.id,toolCall={type:"toolCall",id:!providedId||output.content.some(b=>b.type==="toolCall"&&b.id===providedId)?`${part.functionCall.name}_${Date.now()}_${++toolCallCounter}`:providedId,name:part.functionCall.name||"",arguments:part.functionCall.args??{},...part.thoughtSignature&&{thoughtSignature:part.thoughtSignature}};output.content.push(toolCall),stream2.push({type:"toolcall_start",contentIndex:blockIndex(),partial:output}),stream2.push({type:"toolcall_delta",contentIndex:blockIndex(),delta:JSON.stringify(toolCall.arguments),partial:output},{parsedThrough:0}),stream2.push({type:"toolcall_end",contentIndex:blockIndex(),toolCall,partial:output})}handledAsKnownPart||(output.content.push(toProviderNativeContent(part)),pushAssistantCompleteBlock(stream2,blockIndex(),blocks[blockIndex()]))}if(candidate?.groundingMetadata&&!groundingMetadataEmitted&&(output.content.push({type:"providerNative",subtype:"groundingMetadata",raw:candidate.groundingMetadata}),pushAssistantCompleteBlock(stream2,blockIndex(),blocks[blockIndex()]),groundingMetadataEmitted=!0),candidate?.urlContextMetadata&&!urlContextMetadataEmitted&&(output.content.push({type:"providerNative",subtype:"urlContextMetadata",raw:candidate.urlContextMetadata}),pushAssistantCompleteBlock(stream2,blockIndex(),blocks[blockIndex()]),urlContextMetadataEmitted=!0),candidate?.finishReason&&(output.rawStopReason=candidate.finishReason,output.stopReason=mapStopReason(candidate.finishReason),output.content.some(b=>b.type==="toolCall")&&output.stopReason==="stop"&&(output.stopReason="toolUse")),chunk.usageMetadata){let reasoning=reportedCount(chunk.usageMetadata.thoughtsTokenCount);output.usage={input:(chunk.usageMetadata.promptTokenCount||0)-(chunk.usageMetadata.cachedContentTokenCount||0),output:(chunk.usageMetadata.candidatesTokenCount||0)+(chunk.usageMetadata.thoughtsTokenCount||0),cacheRead:chunk.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,...reasoning===void 0?{}:{reasoning},totalTokens:chunk.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},calculateCost(model,output.usage)}}if(currentBlock&&(currentBlock.type==="text"?pushOpen({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):pushOpen({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Google Vertex stream ended without a finish reason");if(output.stopReason==="aborted"||output.stopReason==="error"){let errorMessage=output.rawStopReason?`Provider stopped with: ${output.rawStopReason}`:"An unknown error occurred";throw new Error(errorMessage)}stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)"index"in block&&delete block.index;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error)),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let base={...buildBaseOptions(model,context,options,void 0),toolChoice:options?.toolChoice};if(!options?.reasoning||options.reasoning==="off")return stream(model,context,{...base,thinking:{enabled:!1}});let clampedReasoning=clampThinkingLevel(model,options.reasoning);if(clampedReasoning==="off")return stream(model,context,{...base,thinking:{enabled:!1}});let resolvedLevel=resolveGoogleThinkingLevel(model,clampedReasoning);return usesGoogleThinkingLevel(model)?stream(model,context,{...base,thinking:{enabled:!0,level:toGoogleThinkingLevel(resolvedLevel)}}):stream(model,context,{...base,thinking:{enabled:!0,budgetTokens:getGoogleBudget(model,resolvedLevel,options.thinkingBudgets)}})};function createClient(model,project,location,optionsHeaders,env){let googleAuthOptions=buildGoogleAuthOptions(env);return new GoogleGenAI({vertexai:!0,project,location,apiVersion:API_VERSION,...googleAuthOptions?{googleAuthOptions}:{},httpOptions:buildHttpOptions(model,optionsHeaders)})}function createClientWithApiKey(model,apiKey,optionsHeaders){return new GoogleGenAI({vertexai:!0,apiKey,apiVersion:API_VERSION,httpOptions:buildHttpOptions(model,optionsHeaders)})}function buildHttpOptions(model,optionsHeaders){let httpOptions={},baseUrl=resolveCustomBaseUrl(model.baseUrl);baseUrl&&(httpOptions.baseUrl=baseUrl,httpOptions.baseUrlResourceScope=ResourceScope.COLLECTION,baseUrlIncludesApiVersion(baseUrl)&&(httpOptions.apiVersion=""));let headers=providerHeadersToRecord({"User-Agent":getPiUserAgent(),...model.headers,...optionsHeaders});return headers&&(httpOptions.headers=headers),Object.keys(httpOptions).length>0?httpOptions:void 0}function resolveCustomBaseUrl(baseUrl){let trimmed=baseUrl.trim();if(!(!trimmed||trimmed.includes("{location}")))return trimmed}function baseUrlIncludesApiVersion(baseUrl){try{return new URL(baseUrl).pathname.split("/").some(part=>/^v\d+(?:beta\d*)?$/.test(part))}catch{return/(?:^|\/)v\d+(?:beta\d*)?(?:\/|$)/.test(baseUrl)}}function resolveApiKey(options){let apiKey=options?.apiKey?.trim();if(!(!apiKey||apiKey===GCP_VERTEX_CREDENTIALS_MARKER||isPlaceholderApiKey(apiKey)))return apiKey}function isPlaceholderApiKey(apiKey){return/^<[^>]+>$/.test(apiKey)}function resolveProject(options){let project=resolveVertexProjectFromEnv(options);if(!project)throw new Error("Vertex AI requires a project ID. Set GOOGLE_CLOUD_PROJECT/GCLOUD_PROJECT or pass project in options.");return project}function resolveLocation(options){let location=options?.location||getProviderEnvValue("GOOGLE_CLOUD_LOCATION",options?.env);if(!location)throw new Error("Vertex AI requires a location. Set GOOGLE_CLOUD_LOCATION or pass location in options.");return location}function buildParams(model,context,options={}){let contents=convertMessages(model,context,{preserveThinking:options.thinking?.enabled===!0}),initialSystemMessage=getInitialSystemMessage(context.messages),currentTools=getCurrentTools(context.messages),generationConfig={};options.temperature!==void 0&&(generationConfig.temperature=options.temperature),options.maxTokens!==void 0&&(generationConfig.maxOutputTokens=options.maxTokens);let supportsStrictMode=supportsGoogleStrictToolSampling(model.id),functionCallingMode=currentTools.length>0?resolveGoogleFunctionCallingMode(currentTools,options.toolChoice,supportsStrictMode):void 0,systemInstruction=initialSystemMessage?getSystemMessageText(initialSystemMessage):"",config={...Object.keys(generationConfig).length>0&&generationConfig,...systemInstruction&&{systemInstruction:sanitizeSurrogates(systemInstruction)},...currentTools.length>0&&{tools:convertTools(currentTools,!1,supportsStrictMode)},...functionCallingMode!==void 0&&{toolConfig:{functionCallingConfig:{mode:functionCallingMode}}}};if(options.thinking?.enabled&&model.reasoning){let thinkingConfig={includeThoughts:!0};options.thinking.level!==void 0?thinkingConfig.thinkingLevel=toGoogleSdkThinkingLevel(options.thinking.level):options.thinking.budgetTokens!==void 0&&(thinkingConfig.thinkingBudget=options.thinking.budgetTokens),config.thinkingConfig=thinkingConfig}else model.reasoning&&options.thinking&&!options.thinking.enabled&&(config.thinkingConfig=getDisabledGoogleThinkingConfig(model));if(options.signal){if(options.signal.aborted)throw new Error("Request aborted");config.abortSignal=options.signal}return applyExtraBody(config,options?.extraBody,GOOGLE_RESERVED_BODY_KEYS),{model:model.id,contents,config}}function getGoogleBudget(model,level,customBudgets){return customBudgets?.[level]!==void 0?customBudgets[level]:model.id.includes("2.5-pro")?{minimal:128,low:2048,medium:8192,high:32768}[level]:model.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[level]:-1}export{stream,streamSimple};
|
|
2
|
+
import{buildGoogleAuthOptions,resolveVertexProjectFromEnv}from"./chunk-74YFRVGQ.js";import{GoogleGenAI,ResourceScope,convertMessages,convertTools,getDisabledGoogleThinkingConfig,isThinkingPart,mapStopReason,resolveGoogleFunctionCallingMode,resolveGoogleThinkingLevel,retainThoughtSignature,retryGoogleRequest,supportsGoogleStrictToolSampling,toGoogleSdkThinkingLevel,toGoogleThinkingLevel,toProviderNativeContent,usesGoogleThinkingLevel}from"./chunk-ODRGPC5S.js";import"./chunk-K2EVQGGT.js";import"./chunk-4QVORFQ2.js";import{getPiUserAgent}from"./chunk-QTG7MY2X.js";import{GOOGLE_RESERVED_BODY_KEYS,applyExtraBody,buildBaseOptions}from"./chunk-Z6BREXV3.js";import"./chunk-EDOW5W5H.js";import{formatProviderError,normalizeProviderError}from"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import{reportedCount}from"./chunk-GVSBCJFI.js";import"./chunk-PY4ZQHTN.js";import{sanitizeSurrogates}from"./chunk-WDTJ6JKE.js";import{getProviderEnvValue}from"./chunk-5ROMKDLK.js";import{calculateCost,clampThinkingLevel,collapseSystemMessages,getCurrentTools,getInitialSystemMessage,getSystemMessageText}from"./chunk-5W3DTM2J.js";import"./chunk-45SZOLCU.js";import{AssistantMessageEventStream,pushAssistantCompleteBlock,pushAssistantSignature}from"./chunk-KBSFTXAT.js";import{providerHeadersToRecord}from"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";var API_VERSION="v1",GCP_VERTEX_CREDENTIALS_MARKER="gcp-vertex-credentials",toolCallCounter=0,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream({captureBlocks:!0}),normalizedContext=collapseSystemMessages(context);return(async()=>{let output={role:"assistant",content:[],api:"google-vertex",provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{if(options?.fetch&&options.fetch!==globalThis.fetch)throw new Error("Custom fetch is not supported by the Google Vertex adapter");let apiKey=resolveApiKey(options),headers=providerHeadersToRecord(options?.headers),client=apiKey?createClientWithApiKey(model,apiKey,headers):createClient(model,resolveProject(options),resolveLocation(options),headers,options?.env),params=buildParams(model,normalizedContext,options),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let googleStream=await retryGoogleRequest(()=>client.models.generateContentStream(params),options);stream2.push({type:"start",partial:output});let currentBlock=null,currentIndex=0,groundingMetadataEmitted=!1,urlContextMetadataEmitted=!1,blocks=output.content,blockIndex=()=>blocks.length-1,pushOpen=event=>stream2.push(event,{contentIndex:currentIndex});for await(let chunk of googleStream){await options?.onProviderStreamEvent?.(chunk,model),output.responseId||=chunk.responseId;let candidate=chunk.candidates?.[0];if(candidate?.content?.parts)for(let part of candidate.content.parts){let handledAsKnownPart=!1;if(part.text!==void 0){handledAsKnownPart=!0;let isThinking=isThinkingPart(part);(!currentBlock||isThinking&¤tBlock.type!=="thinking"||!isThinking&¤tBlock.type!=="text")&&(currentBlock&&(currentBlock.type==="text"?pushOpen({type:"text_end",contentIndex:blocks.length-1,content:currentBlock.text,partial:output}):pushOpen({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),isThinking?(currentBlock={type:"thinking",thinking:"",thinkingSignature:void 0},output.content.push(currentBlock),currentIndex=blockIndex(),stream2.push({type:"thinking_start",contentIndex:blockIndex(),partial:output})):(currentBlock={type:"text",text:""},output.content.push(currentBlock),currentIndex=blockIndex(),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output}))),currentBlock.type==="thinking"?(currentBlock.thinking+=part.text,pushAssistantSignature(stream2,currentIndex,currentBlock,part.thoughtSignature),currentBlock.thinkingSignature=retainThoughtSignature(currentBlock.thinkingSignature,part.thoughtSignature),pushOpen({type:"thinking_delta",contentIndex:blockIndex(),delta:part.text,partial:output})):(currentBlock.text+=part.text,pushAssistantSignature(stream2,currentIndex,currentBlock,part.thoughtSignature),currentBlock.textSignature=retainThoughtSignature(currentBlock.textSignature,part.thoughtSignature),pushOpen({type:"text_delta",contentIndex:blockIndex(),delta:part.text,partial:output}))}if(part.functionCall){handledAsKnownPart=!0,currentBlock&&(currentBlock.type==="text"?pushOpen({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):pushOpen({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output}),currentBlock=null);let providedId=part.functionCall.id,toolCall={type:"toolCall",id:!providedId||output.content.some(b=>b.type==="toolCall"&&b.id===providedId)?`${part.functionCall.name}_${Date.now()}_${++toolCallCounter}`:providedId,name:part.functionCall.name||"",arguments:part.functionCall.args??{},...part.thoughtSignature&&{thoughtSignature:part.thoughtSignature}};output.content.push(toolCall),stream2.push({type:"toolcall_start",contentIndex:blockIndex(),partial:output}),stream2.push({type:"toolcall_delta",contentIndex:blockIndex(),delta:JSON.stringify(toolCall.arguments),partial:output},{parsedThrough:0}),stream2.push({type:"toolcall_end",contentIndex:blockIndex(),toolCall,partial:output})}handledAsKnownPart||(output.content.push(toProviderNativeContent(part)),pushAssistantCompleteBlock(stream2,blockIndex(),blocks[blockIndex()]))}if(candidate?.groundingMetadata&&!groundingMetadataEmitted&&(output.content.push({type:"providerNative",subtype:"groundingMetadata",raw:candidate.groundingMetadata}),pushAssistantCompleteBlock(stream2,blockIndex(),blocks[blockIndex()]),groundingMetadataEmitted=!0),candidate?.urlContextMetadata&&!urlContextMetadataEmitted&&(output.content.push({type:"providerNative",subtype:"urlContextMetadata",raw:candidate.urlContextMetadata}),pushAssistantCompleteBlock(stream2,blockIndex(),blocks[blockIndex()]),urlContextMetadataEmitted=!0),candidate?.finishReason&&(output.rawStopReason=candidate.finishReason,output.stopReason=mapStopReason(candidate.finishReason),output.content.some(b=>b.type==="toolCall")&&output.stopReason==="stop"&&(output.stopReason="toolUse")),chunk.usageMetadata){let reasoning=reportedCount(chunk.usageMetadata.thoughtsTokenCount);output.usage={input:(chunk.usageMetadata.promptTokenCount||0)-(chunk.usageMetadata.cachedContentTokenCount||0),output:(chunk.usageMetadata.candidatesTokenCount||0)+(chunk.usageMetadata.thoughtsTokenCount||0),cacheRead:chunk.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,...reasoning===void 0?{}:{reasoning},totalTokens:chunk.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},calculateCost(model,output.usage)}}if(currentBlock&&(currentBlock.type==="text"?pushOpen({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):pushOpen({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Google Vertex stream ended without a finish reason");if(output.stopReason==="aborted"||output.stopReason==="error"){let errorMessage=output.rawStopReason?`Provider stopped with: ${output.rawStopReason}`:"An unknown error occurred";throw new Error(errorMessage)}stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)"index"in block&&delete block.index;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error)),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let base={...buildBaseOptions(model,context,options,void 0),toolChoice:options?.toolChoice};if(!options?.reasoning||options.reasoning==="off")return stream(model,context,{...base,thinking:{enabled:!1}});let clampedReasoning=clampThinkingLevel(model,options.reasoning);if(clampedReasoning==="off")return stream(model,context,{...base,thinking:{enabled:!1}});let resolvedLevel=resolveGoogleThinkingLevel(model,clampedReasoning);return usesGoogleThinkingLevel(model)?stream(model,context,{...base,thinking:{enabled:!0,level:toGoogleThinkingLevel(resolvedLevel)}}):stream(model,context,{...base,thinking:{enabled:!0,budgetTokens:getGoogleBudget(model,resolvedLevel,options.thinkingBudgets)}})};function createClient(model,project,location,optionsHeaders,env){let googleAuthOptions=buildGoogleAuthOptions(env);return new GoogleGenAI({vertexai:!0,project,location,apiVersion:API_VERSION,...googleAuthOptions?{googleAuthOptions}:{},httpOptions:buildHttpOptions(model,optionsHeaders)})}function createClientWithApiKey(model,apiKey,optionsHeaders){return new GoogleGenAI({vertexai:!0,apiKey,apiVersion:API_VERSION,httpOptions:buildHttpOptions(model,optionsHeaders)})}function buildHttpOptions(model,optionsHeaders){let httpOptions={},baseUrl=resolveCustomBaseUrl(model.baseUrl);baseUrl&&(httpOptions.baseUrl=baseUrl,httpOptions.baseUrlResourceScope=ResourceScope.COLLECTION,baseUrlIncludesApiVersion(baseUrl)&&(httpOptions.apiVersion=""));let headers=providerHeadersToRecord({"User-Agent":getPiUserAgent(),...model.headers,...optionsHeaders});return headers&&(httpOptions.headers=headers),Object.keys(httpOptions).length>0?httpOptions:void 0}function resolveCustomBaseUrl(baseUrl){let trimmed=baseUrl.trim();if(!(!trimmed||trimmed.includes("{location}")))return trimmed}function baseUrlIncludesApiVersion(baseUrl){try{return new URL(baseUrl).pathname.split("/").some(part=>/^v\d+(?:beta\d*)?$/.test(part))}catch{return/(?:^|\/)v\d+(?:beta\d*)?(?:\/|$)/.test(baseUrl)}}function resolveApiKey(options){let apiKey=options?.apiKey?.trim();if(!(!apiKey||apiKey===GCP_VERTEX_CREDENTIALS_MARKER||isPlaceholderApiKey(apiKey)))return apiKey}function isPlaceholderApiKey(apiKey){return/^<[^>]+>$/.test(apiKey)}function resolveProject(options){let project=resolveVertexProjectFromEnv(options);if(!project)throw new Error("Vertex AI requires a project ID. Set GOOGLE_CLOUD_PROJECT/GCLOUD_PROJECT or pass project in options.");return project}function resolveLocation(options){let location=options?.location||getProviderEnvValue("GOOGLE_CLOUD_LOCATION",options?.env);if(!location)throw new Error("Vertex AI requires a location. Set GOOGLE_CLOUD_LOCATION or pass location in options.");return location}function buildParams(model,context,options={}){let contents=convertMessages(model,context,{preserveThinking:options.thinking?.enabled===!0}),initialSystemMessage=getInitialSystemMessage(context.messages),currentTools=getCurrentTools(context.messages),generationConfig={};options.temperature!==void 0&&(generationConfig.temperature=options.temperature),options.maxTokens!==void 0&&(generationConfig.maxOutputTokens=options.maxTokens);let supportsStrictMode=supportsGoogleStrictToolSampling(model.id),functionCallingMode=currentTools.length>0?resolveGoogleFunctionCallingMode(currentTools,options.toolChoice,supportsStrictMode):void 0,systemInstruction=initialSystemMessage?getSystemMessageText(initialSystemMessage):"",config={...Object.keys(generationConfig).length>0&&generationConfig,...systemInstruction&&{systemInstruction:sanitizeSurrogates(systemInstruction)},...currentTools.length>0&&{tools:convertTools(currentTools,!1,supportsStrictMode)},...functionCallingMode!==void 0&&{toolConfig:{functionCallingConfig:{mode:functionCallingMode}}}};if(options.thinking?.enabled&&model.reasoning){let thinkingConfig={includeThoughts:!0};options.thinking.level!==void 0?thinkingConfig.thinkingLevel=toGoogleSdkThinkingLevel(options.thinking.level):options.thinking.budgetTokens!==void 0&&(thinkingConfig.thinkingBudget=options.thinking.budgetTokens),config.thinkingConfig=thinkingConfig}else model.reasoning&&options.thinking&&!options.thinking.enabled&&(config.thinkingConfig=getDisabledGoogleThinkingConfig(model));if(options.signal){if(options.signal.aborted)throw new Error("Request aborted");config.abortSignal=options.signal}return applyExtraBody(config,options?.extraBody,GOOGLE_RESERVED_BODY_KEYS),{model:model.id,contents,config}}function getGoogleBudget(model,level,customBudgets){return customBudgets?.[level]!==void 0?customBudgets[level]:model.id.includes("2.5-pro")?{minimal:128,low:2048,medium:8192,high:32768}[level]:model.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[level]:-1}export{stream,streamSimple};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{helpFlagsScope,isPlainHelpRequest,resolveHelpProjectTrust,tryPrintHelpWithoutEngine}from"./chunk-
|
|
2
|
+
import{helpFlagsScope,isPlainHelpRequest,resolveHelpProjectTrust,tryPrintHelpWithoutEngine}from"./chunk-ZP6JJDYV.js";import"./chunk-MLVIYDHK.js";import"./chunk-GZVCRV7I.js";import"./chunk-IHKHCWWG.js";import"./chunk-26UBFF6N.js";import"./chunk-U3VOXCGP.js";import"./chunk-6GAMRAVM.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-EQNUL2WB.js";import"./chunk-GVSBCJFI.js";import"./chunk-IY4G44MN.js";import"./chunk-QGJLZ6BI.js";import"./chunk-WHPDEDCC.js";import"./chunk-AA2L2RHH.js";import"./chunk-HK46JMSC.js";import"./chunk-PY4ZQHTN.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-5W3DTM2J.js";import"./chunk-45SZOLCU.js";import"./chunk-KBSFTXAT.js";import"./chunk-PJ34QVL5.js";import"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-IKOFCODM.js";export{helpFlagsScope,isPlainHelpRequest,resolveHelpProjectTrust,tryPrintHelpWithoutEngine};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{parseHostArgs,resolveHostSocket,runHostCommand}from"./chunk-
|
|
2
|
+
import{parseHostArgs,resolveHostSocket,runHostCommand}from"./chunk-7IZH2KQX.js";import"./chunk-CNDPCYNT.js";import"./chunk-QMRJYMNH.js";import"./chunk-XMNPK472.js";import"./chunk-FQDARFHT.js";import"./chunk-KUPQO7MC.js";import"./chunk-IHKHCWWG.js";import"./chunk-26UBFF6N.js";import"./chunk-L2O6K3SJ.js";import"./chunk-H4WJ4LY3.js";import"./chunk-Z6SAQ5O3.js";import"./chunk-ZAUVY6ZC.js";import"./chunk-J2YAYTB2.js";import"./chunk-4WZRVZNX.js";import"./chunk-U3VOXCGP.js";import"./chunk-GWGNVYPB.js";import"./chunk-YI7SPFDN.js";import"./chunk-6GAMRAVM.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-EQNUL2WB.js";import"./chunk-GVSBCJFI.js";import"./chunk-IY4G44MN.js";import"./chunk-QGJLZ6BI.js";import"./chunk-WHPDEDCC.js";import"./chunk-AA2L2RHH.js";import"./chunk-HK46JMSC.js";import"./chunk-PY4ZQHTN.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-5W3DTM2J.js";import"./chunk-45SZOLCU.js";import"./chunk-KBSFTXAT.js";import"./chunk-PJ34QVL5.js";import"./chunk-VRDU425E.js";import"./chunk-ZGAB7WQA.js";import"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-O5RYI3IW.js";import"./chunk-IKOFCODM.js";export{parseHostArgs,resolveHostSocket,runHostCommand};
|
package/dist/bundle/chunks/{host-session-command-OV5XDOJK.js → host-session-command-FFN52LXJ.js}
RENAMED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{RpcClient,RpcCommandError,RpcRequestTimeoutError,RpcTransportGoneError,isTransportGoneError}from"./chunk-6U3TBFBA.js";import"./chunk-GY5MR5KR.js";import{SessionManager,assertValidSessionId}from"./chunk-DYWIFF2Q.js";import"./chunk-CNPDUC4D.js";import{DEFAULT_HOST_LAUNCH_SPEC,HOST_EXIT_ERROR,HOST_EXIT_OK,HOST_EXIT_REFUSED,HOST_EXIT_USAGE,HostLaunchSpecError,STOP_WAIT_BUDGET_MS,daemonEnvKeys,daemonEnvOverrides,emit,ensureHost,loadHostLaunchSpec,refusal,resolveHostSocket,writeDaemonEnvKeys}from"./chunk-MSHRIZGT.js";import{HostEnsureRefusedError}from"./chunk-5KZH6EYQ.js";import"./chunk-QMRJYMNH.js";import{endpointKindOfSocket}from"./chunk-XMNPK472.js";import"./chunk-LO5MYLGF.js";import"./chunk-KLAX467B.js";import"./chunk-KUPQO7MC.js";import"./chunk-SOMFLLPD.js";import"./chunk-I7QWTWVZ.js";import"./chunk-26UBFF6N.js";import"./chunk-L2O6K3SJ.js";import{withRpcKeyRoot}from"./chunk-H4WJ4LY3.js";import"./chunk-Z6SAQ5O3.js";import"./chunk-ZAUVY6ZC.js";import"./chunk-J2YAYTB2.js";import{canonicalSessionPath,createHostDaemonPaths}from"./chunk-4WZRVZNX.js";import"./chunk-U3VOXCGP.js";import"./chunk-GWGNVYPB.js";import"./chunk-YI7SPFDN.js";import"./chunk-FDL4CF6F.js";import"./chunk-QREKAXKX.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-ZLIVZQDY.js";import"./chunk-GVSBCJFI.js";import"./chunk-MY4ZD3EW.js";import"./chunk-QGJLZ6BI.js";import"./chunk-WHPDEDCC.js";import"./chunk-AA2L2RHH.js";import"./chunk-HK46JMSC.js";import"./chunk-5LWUUXMH.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-ZXHLH4MW.js";import"./chunk-45SZOLCU.js";import"./chunk-GQJYNFMO.js";import"./chunk-PJ34QVL5.js";import"./chunk-VRDU425E.js";import"./chunk-ZGAB7WQA.js";import{APP_NAME,getAgentDir}from"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-O5RYI3IW.js";import"./chunk-IKOFCODM.js";import{readFileSync}from"node:fs";import{resolve}from"node:path";var DETACH_ACK_TIMEOUT_MS=5e3;async function detachBeforeClose(client,report,timeoutMs=DETACH_ACK_TIMEOUT_MS){let timer,late=new Promise(resolve2=>{timer=setTimeout(()=>resolve2("late"),timeoutMs)});try{await Promise.race([client.detachConnection(),late])==="late"&&report(`the host did not confirm the detach within ${timeoutMs} ms; closing the connection anyway`)}catch(error){if(error instanceof RpcTransportGoneError)return;report(`the host refused the detach (${error instanceof Error?error.message:String(error)}); closing the connection anyway`)}finally{clearTimeout(timer)}}var USAGE_CODES=new Set(["missing_session_id","invalid_path","invalid_session_context","invalid_session_kind","invalid_launch_profile","invalid_session_id","invalid_release_reason","empty","unknown_command"]),FAILURE_CODES=new Set(["open_failed","warm_failed","release_failed"]),REASON_FOR_CODE={streaming:"busy",not_found:"unknown_cursor"},BARE_CODE=/^[a-z][a-z0-9_]*$/;function mapError(error,socket){let detail=error instanceof Error?error.message:String(error);if(error instanceof RpcCommandError){let code=error.errorCode??(BARE_CODE.test(detail)?detail:void 0);if(code===void 0)return hostError(detail,socket);let exitCode=USAGE_CODES.has(code)?HOST_EXIT_USAGE:FAILURE_CODES.has(code)?HOST_EXIT_ERROR:HOST_EXIT_REFUSED;return{exitCode,payload:{action:exitCode===HOST_EXIT_REFUSED?"refuse":"error",reason:REASON_FOR_CODE[code]??code,detail,socket,...error.errorData!==void 0&&{data:error.errorData}}}}return isTransportGoneError(error)?{exitCode:HOST_EXIT_ERROR,payload:{action:"error",reason:"transport_gone",detail,socket}}:hostError(detail,socket)}function hostError(detail,socket){return{exitCode:HOST_EXIT_ERROR,payload:{action:"error",reason:"host_error",detail,socket}}}async function openHostSession(client,request,socket,ensured){let opened=await client.openSession({cwd:request.cwd,retain_on_disconnect:!0,...request.model&&{provider:request.model.provider,modelId:request.model.id}});ensured?.release();let{state}=opened,identity={sessionId:opened.sessionId,sessionPath:state.sessionFile,durableSessionId:state.sessionId};try{request.name!==void 0&&await client.setSessionName(request.name);let disposition=request.prompt===void 0?void 0:await client.prompt(request.prompt);return{exitCode:HOST_EXIT_OK,payload:{action:"open",socket,pid:ensured?.pid,reused:ensured?.reused,...identity,cwd:state.cwd,model:state.model?{provider:state.model.provider,id:state.model.id}:null,attached:opened.attached??!1,...disposition!==void 0&&{prompt:{disposition}}}}}catch(error){let outcome=mapError(error,socket),closed=await closeOpened(client,opened.sessionId);return{...outcome,payload:{...outcome.payload,...identity,closed}}}}async function closeOpened(client,sessionId){try{return await client.closeSession(sessionId),!(await client.listSessions()).some(row=>row.sessionId===sessionId)}catch{return!1}}import{existsSync}from"node:fs";import{readdir}from"node:fs/promises";import{dirname,join}from"node:path";async function resolveSessionRef(client,ref,agentDir){let rows=await client.listSessions(),handle=rows.find(row=>row.sessionId===ref);if(handle)return{kind:"live",row:handle};if(isSessionId(ref)){let byId=await resolveDurableId(ref,rows,agentDir);if(byId)return byId}let named=rows.filter(row=>row.name===ref);if(named.length>1)return{kind:"ambiguous",candidates:named.map(row=>row.sessionId)};let live=named[0]??rows.find(row=>row.sessionPath!==void 0&&samePath(row.sessionPath,ref));return live?{kind:"live",row:live}:looksLikePath(ref)?parkedByPath(ref):{kind:"unknown"}}async function resolveDurableId(id,rows,agentDir){let liveRows=rows.filter(row=>row.durableSessionId===id),transcripts=(await transcriptsUnder(agentDir)).filter(session=>session.id===id),files=new Set([...liveRows.map(row=>row.sessionPath===void 0?row.sessionId:canonicalSessionPath(row.sessionPath)),...transcripts.map(session=>canonicalSessionPath(session.path))]);return files.size>1?{kind:"ambiguous",candidates:[...files]}:liveRows[0]?{kind:"live",row:liveRows[0]}:transcripts[0]?parked(transcripts[0]):void 0}function isSessionId(ref){try{return assertValidSessionId(ref),!0}catch{return!1}}function looksLikePath(ref){return ref.includes("/")||ref.includes("\\")||ref.endsWith(".jsonl")}async function parkedByPath(ref){let path=canonicalSessionPath(ref);if(!existsSync(path))return{kind:"unknown"};let info=(await SessionManager.listAll(dirname(path))).find(session=>samePath(session.path,path));return info?parked(info):{kind:"unknown"}}async function transcriptsUnder(agentDir){let root=join(agentDir,"sessions");if(!existsSync(root))return[];let dirs=(await readdir(root,{withFileTypes:!0})).filter(entry=>entry.isDirectory());return(await Promise.all(dirs.map(entry=>SessionManager.listAll(join(root,entry.name))))).flat()}function parked(info){return{kind:"parked",sessionPath:info.path,cwd:info.cwd,durableSessionId:info.id}}function samePath(left,right){return canonicalSessionPath(left)===canonicalSessionPath(right)}function waitForHostSession(client,sessionId,request,onTransportLoss){let started=Date.now();return new Promise((resolveWait,reject)=>{let finished=!1,observed=!1,state,timer,cleanup=()=>{finished=!0,clearTimeout(timer),unsubscribe(),onTransportLoss(void 0)},fail=error=>{finished||(cleanup(),reject(error))},finish=outcome=>{finished||(cleanup(),resolveWait({exitCode:HOST_EXIT_OK,payload:{action:"wait",sessionId,until:request.until,outcome,waited_ms:Date.now()-started,state:{isStreaming:state?.isStreaming??!1,pendingMessageCount:state?.pendingMessageCount??0,lastAbortSource:state?.lastAbortSource??null}}}))},unsubscribe=client.onEvent(record=>{let event=record;if(event.type==="session_closed"||event.type==="session_parked"){finish(event.type);return}if(event.type==="agent_settled"&&"reason"in event&&event.reason==="session_closed"){finish("session_closed");return}event.type!=="agent_idle"&&!(request.until==="done"&&event.type==="agent_settled")||(observed=!0,client.getState().then(snapshot=>{state=snapshot,request.until==="done"?finish("done"):isDrained(snapshot)&&finish("idle")},fail))});onTransportLoss(fail),timer=setTimeout(()=>{finished||(cleanup(),resolveWait({exitCode:HOST_EXIT_ERROR,payload:{action:"error",reason:"wait_timeout",sessionId,until:request.until,timeoutMs:request.timeoutMs}}))},request.timeoutMs),client.getState().then(snapshot=>{state=snapshot,!observed&&(request.until==="done"?!snapshot.isStreaming:isDrained(snapshot))&&finish("already_idle")},fail)})}function isDrained(state){return!state.isStreaming&&state.steering.length===0&&state.followUp.length===0&&state.ordered.length===0&&state.pendingMessageCount===0}async function runHostSessionRequest(request){let deadline=Date.now()+STOP_WAIT_BUDGET_MS;for(;;)try{return await runHostSessionRequestOnce(request,Math.max(0,deadline-Date.now()))}catch(error){if(request.action==="open"&&error instanceof RpcCommandError&&error.errorCode==="host_stopping"&&Date.now()<deadline)continue;return mapError(error,request.target.socket)}}async function runHostSessionRequestOnce(request,stoppingTimeoutMs){let{socket,agentDir}=request.target,client,ensured,disconnected,connectionUnusable=!1;try{if(await endpointKindOfSocket(socket,agentDir)==="tui")return refusal("refuse",void 0,{reason:"unsupported_endpoint_kind",socket,endpoint_kind:"tui"});request.action==="open"&&(ensured=await ensureHost({socket,agentDir,hostArgs:request.spec.hostArgs,env:daemonEnvOverrides(process.env,request.spec.env),policy:request.spec.policy,upgrade:"never",stoppingTimeoutMs}),ensured.reused||await writeDaemonEnvKeys(createHostDaemonPaths({socket,agentDir}),daemonEnvKeys(process.env,request.spec.env))),client=new RpcClient({socketPath:socket,onDisconnect:error=>{connectionUnusable=!0,disconnected?.(error)}});try{await client.start()}catch(error){if(error instanceof Error&&"code"in error&&(error.code==="ENOENT"||error.code==="ECONNREFUSED"))return refusal("refuse",void 0,{reason:"host_unavailable",socket,detail:error.message});throw error}let sessionId,durableSessionId;if("ref"in request){let found=await resolveSessionRef(client,request.ref,agentDir);if(found.kind==="unknown")return refusal("refuse",void 0,{reason:"unknown_session",ref:request.ref,socket});if(found.kind==="ambiguous"){let detail={reason:"ambiguous_session",ref:request.ref,candidates:found.candidates,socket};return refusal("refuse",void 0,detail)}let reopen=found.kind==="parked"?{sessionPath:found.sessionPath,cwd:found.cwd,retain_on_disconnect:!0,attended:!1}:{sessionPath:found.row.sessionPath,cwd:found.row.cwd};durableSessionId=found.kind==="parked"?found.durableSessionId:found.row.durableSessionId,sessionId=(await client.openSession(reopen)).sessionId}switch(request.action){case"open":return await openHostSession(client,request,socket,ensured);case"prompt":return{exitCode:HOST_EXIT_OK,payload:{action:"prompt",sessionId,disposition:await client.prompt(request.text)}};case"steer":{let streaming=(await client.getState()).isStreaming,disposition=await client.steer(request.text);return{exitCode:HOST_EXIT_OK,payload:{action:"steer",sessionId,disposition,streaming}}}case"abort":{let aborted=(await client.getState()).isStreaming;return await client.abortStrict(),{exitCode:HOST_EXIT_OK,payload:{action:"abort",sessionId,acknowledged:!0,aborted}}}case"model":{await client.setModel(request.model.provider,request.model.id);let state=await client.getState();return{exitCode:HOST_EXIT_OK,payload:{action:"model",sessionId,requested:request.model,model:state.model?{provider:state.model.provider,id:state.model.id}:null,pendingModelSwitch:state.pendingModelSwitch??null}}}case"list":return{exitCode:HOST_EXIT_OK,payload:{action:"list",socket,sessions:await client.listSessions({observe:!0})}};case"state":return{exitCode:HOST_EXIT_OK,payload:{action:"state",sessionId,durableSessionId,state:await client.getState()}};case"read":{if(request.messages){let all=await client.getMessages(),messages=request.tail===void 0?all:all.slice(-request.tail);return{exitCode:HOST_EXIT_OK,payload:{action:"read",sessionId,messages,count:messages.length}}}let{entries,leafId}=await client.getEntries(request.since),slice=request.tail===void 0?entries:entries.slice(-request.tail);return{exitCode:HOST_EXIT_OK,payload:{action:"read",sessionId,entries:slice,count:slice.length,total:entries.length,leafId,nextSince:slice.at(-1)?.id??request.since??null,...request.since!==void 0&&{since:request.since}}}}case"wait":return await waitForHostSession(client,sessionId,request,handler=>{disconnected=handler});case"unload":{let answer=await client.unloadSession({sessionId,interrupt:request.interrupt,force:request.force,clearQueue:request.clearQueue,children:request.children});return{exitCode:answer.outcome==="unloaded"?HOST_EXIT_OK:HOST_EXIT_REFUSED,payload:{action:"unload",sessionId,...answer}}}case"close":{let reason,unsubscribe=client.onEvent(record=>{let event=record;event.type==="session_closed"&&(reason=event.reason)});try{await client.closeSession(sessionId);let remaining=(await client.listSessions()).find(row=>row.sessionId===sessionId);return{exitCode:HOST_EXIT_OK,payload:remaining?{action:"close",sessionId,closed:!1,attachments:remaining.attachments}:{action:"close",sessionId,closed:!0,reason:reason??"client_close"}}}finally{unsubscribe()}}default:return assertNever(request)}}catch(error){if((error instanceof RpcRequestTimeoutError||isTransportGoneError(error))&&(connectionUnusable=!0),request.action==="open"&&error instanceof RpcCommandError&&error.errorCode==="host_stopping")throw error;return error instanceof HostEnsureRefusedError?refusal("refuse",void 0,{reason:error.reason,socket,detail:error.detail}):mapError(error,socket)}finally{ensured?.release(),client&&!connectionUnusable&&await detachBeforeClose(client,line=>process.stderr.write(`senpi host session: ${line}
|
|
2
|
+
import{RpcClient,RpcCommandError,RpcRequestTimeoutError,RpcTransportGoneError,isTransportGoneError}from"./chunk-UJPG4ROT.js";import"./chunk-GY5MR5KR.js";import{SessionManager,assertValidSessionId}from"./chunk-CYOHFREV.js";import"./chunk-CNPDUC4D.js";import{DEFAULT_HOST_LAUNCH_SPEC,HOST_EXIT_ERROR,HOST_EXIT_OK,HOST_EXIT_REFUSED,HOST_EXIT_USAGE,HostLaunchSpecError,STOP_WAIT_BUDGET_MS,daemonEnvKeys,daemonEnvOverrides,emit,ensureHost,loadHostLaunchSpec,refusal,resolveHostSocket,writeDaemonEnvKeys}from"./chunk-7IZH2KQX.js";import{HostEnsureRefusedError}from"./chunk-CNDPCYNT.js";import"./chunk-QMRJYMNH.js";import{endpointKindOfSocket}from"./chunk-XMNPK472.js";import"./chunk-FQDARFHT.js";import"./chunk-KLAX467B.js";import"./chunk-KUPQO7MC.js";import"./chunk-SOMFLLPD.js";import"./chunk-IHKHCWWG.js";import"./chunk-26UBFF6N.js";import"./chunk-L2O6K3SJ.js";import{withRpcKeyRoot}from"./chunk-H4WJ4LY3.js";import"./chunk-Z6SAQ5O3.js";import"./chunk-ZAUVY6ZC.js";import"./chunk-J2YAYTB2.js";import{canonicalSessionPath,createHostDaemonPaths}from"./chunk-4WZRVZNX.js";import"./chunk-U3VOXCGP.js";import"./chunk-GWGNVYPB.js";import"./chunk-YI7SPFDN.js";import"./chunk-FDL4CF6F.js";import"./chunk-6GAMRAVM.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-EQNUL2WB.js";import"./chunk-GVSBCJFI.js";import"./chunk-IY4G44MN.js";import"./chunk-QGJLZ6BI.js";import"./chunk-WHPDEDCC.js";import"./chunk-AA2L2RHH.js";import"./chunk-HK46JMSC.js";import"./chunk-PY4ZQHTN.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-5W3DTM2J.js";import"./chunk-45SZOLCU.js";import"./chunk-KBSFTXAT.js";import"./chunk-PJ34QVL5.js";import"./chunk-VRDU425E.js";import"./chunk-ZGAB7WQA.js";import{APP_NAME,getAgentDir}from"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-O5RYI3IW.js";import"./chunk-IKOFCODM.js";import{readFileSync}from"node:fs";import{resolve}from"node:path";var DETACH_ACK_TIMEOUT_MS=5e3;async function detachBeforeClose(client,report,timeoutMs=DETACH_ACK_TIMEOUT_MS){let timer,late=new Promise(resolve2=>{timer=setTimeout(()=>resolve2("late"),timeoutMs)});try{await Promise.race([client.detachConnection(),late])==="late"&&report(`the host did not confirm the detach within ${timeoutMs} ms; closing the connection anyway`)}catch(error){if(error instanceof RpcTransportGoneError)return;report(`the host refused the detach (${error instanceof Error?error.message:String(error)}); closing the connection anyway`)}finally{clearTimeout(timer)}}var USAGE_CODES=new Set(["missing_session_id","invalid_path","invalid_session_context","invalid_session_kind","invalid_launch_profile","invalid_session_id","invalid_release_reason","empty","unknown_command"]),FAILURE_CODES=new Set(["open_failed","warm_failed","release_failed"]),REASON_FOR_CODE={streaming:"busy",not_found:"unknown_cursor"},BARE_CODE=/^[a-z][a-z0-9_]*$/;function mapError(error,socket){let detail=error instanceof Error?error.message:String(error);if(error instanceof RpcCommandError){let code=error.errorCode??(BARE_CODE.test(detail)?detail:void 0);if(code===void 0)return hostError(detail,socket);let exitCode=USAGE_CODES.has(code)?HOST_EXIT_USAGE:FAILURE_CODES.has(code)?HOST_EXIT_ERROR:HOST_EXIT_REFUSED;return{exitCode,payload:{action:exitCode===HOST_EXIT_REFUSED?"refuse":"error",reason:REASON_FOR_CODE[code]??code,detail,socket,...error.errorData!==void 0&&{data:error.errorData}}}}return isTransportGoneError(error)?{exitCode:HOST_EXIT_ERROR,payload:{action:"error",reason:"transport_gone",detail,socket}}:hostError(detail,socket)}function hostError(detail,socket){return{exitCode:HOST_EXIT_ERROR,payload:{action:"error",reason:"host_error",detail,socket}}}async function openHostSession(client,request,socket,ensured){let opened=await client.openSession({cwd:request.cwd,retain_on_disconnect:!0,...request.model&&{provider:request.model.provider,modelId:request.model.id}});ensured?.release();let{state}=opened,identity={sessionId:opened.sessionId,sessionPath:state.sessionFile,durableSessionId:state.sessionId};try{request.name!==void 0&&await client.setSessionName(request.name);let disposition=request.prompt===void 0?void 0:await client.prompt(request.prompt);return{exitCode:HOST_EXIT_OK,payload:{action:"open",socket,pid:ensured?.pid,reused:ensured?.reused,...identity,cwd:state.cwd,model:state.model?{provider:state.model.provider,id:state.model.id}:null,attached:opened.attached??!1,...disposition!==void 0&&{prompt:{disposition}}}}}catch(error){let outcome=mapError(error,socket),closed=await closeOpened(client,opened.sessionId);return{...outcome,payload:{...outcome.payload,...identity,closed}}}}async function closeOpened(client,sessionId){try{return await client.closeSession(sessionId),!(await client.listSessions()).some(row=>row.sessionId===sessionId)}catch{return!1}}import{existsSync}from"node:fs";import{readdir}from"node:fs/promises";import{dirname,join}from"node:path";async function resolveSessionRef(client,ref,agentDir){let rows=await client.listSessions(),handle=rows.find(row=>row.sessionId===ref);if(handle)return{kind:"live",row:handle};if(isSessionId(ref)){let byId=await resolveDurableId(ref,rows,agentDir);if(byId)return byId}let named=rows.filter(row=>row.name===ref);if(named.length>1)return{kind:"ambiguous",candidates:named.map(row=>row.sessionId)};let live=named[0]??rows.find(row=>row.sessionPath!==void 0&&samePath(row.sessionPath,ref));return live?{kind:"live",row:live}:looksLikePath(ref)?parkedByPath(ref):{kind:"unknown"}}async function resolveDurableId(id,rows,agentDir){let liveRows=rows.filter(row=>row.durableSessionId===id),transcripts=(await transcriptsUnder(agentDir)).filter(session=>session.id===id),files=new Set([...liveRows.map(row=>row.sessionPath===void 0?row.sessionId:canonicalSessionPath(row.sessionPath)),...transcripts.map(session=>canonicalSessionPath(session.path))]);return files.size>1?{kind:"ambiguous",candidates:[...files]}:liveRows[0]?{kind:"live",row:liveRows[0]}:transcripts[0]?parked(transcripts[0]):void 0}function isSessionId(ref){try{return assertValidSessionId(ref),!0}catch{return!1}}function looksLikePath(ref){return ref.includes("/")||ref.includes("\\")||ref.endsWith(".jsonl")}async function parkedByPath(ref){let path=canonicalSessionPath(ref);if(!existsSync(path))return{kind:"unknown"};let info=(await SessionManager.listAll(dirname(path))).find(session=>samePath(session.path,path));return info?parked(info):{kind:"unknown"}}async function transcriptsUnder(agentDir){let root=join(agentDir,"sessions");if(!existsSync(root))return[];let dirs=(await readdir(root,{withFileTypes:!0})).filter(entry=>entry.isDirectory());return(await Promise.all(dirs.map(entry=>SessionManager.listAll(join(root,entry.name))))).flat()}function parked(info){return{kind:"parked",sessionPath:info.path,cwd:info.cwd,durableSessionId:info.id}}function samePath(left,right){return canonicalSessionPath(left)===canonicalSessionPath(right)}function waitForHostSession(client,sessionId,request,onTransportLoss){let started=Date.now();return new Promise((resolveWait,reject)=>{let finished=!1,observed=!1,state,timer,cleanup=()=>{finished=!0,clearTimeout(timer),unsubscribe(),onTransportLoss(void 0)},fail=error=>{finished||(cleanup(),reject(error))},finish=outcome=>{finished||(cleanup(),resolveWait({exitCode:HOST_EXIT_OK,payload:{action:"wait",sessionId,until:request.until,outcome,waited_ms:Date.now()-started,state:{isStreaming:state?.isStreaming??!1,pendingMessageCount:state?.pendingMessageCount??0,lastAbortSource:state?.lastAbortSource??null}}}))},unsubscribe=client.onEvent(record=>{let event=record;if(event.type==="session_closed"||event.type==="session_parked"){finish(event.type);return}if(event.type==="agent_settled"&&"reason"in event&&event.reason==="session_closed"){finish("session_closed");return}event.type!=="agent_idle"&&!(request.until==="done"&&event.type==="agent_settled")||(observed=!0,client.getState().then(snapshot=>{state=snapshot,request.until==="done"?finish("done"):isDrained(snapshot)&&finish("idle")},fail))});onTransportLoss(fail),timer=setTimeout(()=>{finished||(cleanup(),resolveWait({exitCode:HOST_EXIT_ERROR,payload:{action:"error",reason:"wait_timeout",sessionId,until:request.until,timeoutMs:request.timeoutMs}}))},request.timeoutMs),client.getState().then(snapshot=>{state=snapshot,!observed&&(request.until==="done"?!snapshot.isStreaming:isDrained(snapshot))&&finish("already_idle")},fail)})}function isDrained(state){return!state.isStreaming&&state.steering.length===0&&state.followUp.length===0&&state.ordered.length===0&&state.pendingMessageCount===0}async function runHostSessionRequest(request){let deadline=Date.now()+STOP_WAIT_BUDGET_MS;for(;;)try{return await runHostSessionRequestOnce(request,Math.max(0,deadline-Date.now()))}catch(error){if(request.action==="open"&&error instanceof RpcCommandError&&error.errorCode==="host_stopping"&&Date.now()<deadline)continue;return mapError(error,request.target.socket)}}async function runHostSessionRequestOnce(request,stoppingTimeoutMs){let{socket,agentDir}=request.target,client,ensured,disconnected,connectionUnusable=!1;try{if(await endpointKindOfSocket(socket,agentDir)==="tui")return refusal("refuse",void 0,{reason:"unsupported_endpoint_kind",socket,endpoint_kind:"tui"});request.action==="open"&&(ensured=await ensureHost({socket,agentDir,hostArgs:request.spec.hostArgs,env:daemonEnvOverrides(process.env,request.spec.env),policy:request.spec.policy,upgrade:"never",stoppingTimeoutMs}),ensured.reused||await writeDaemonEnvKeys(createHostDaemonPaths({socket,agentDir}),daemonEnvKeys(process.env,request.spec.env))),client=new RpcClient({socketPath:socket,onDisconnect:error=>{connectionUnusable=!0,disconnected?.(error)}});try{await client.start()}catch(error){if(error instanceof Error&&"code"in error&&(error.code==="ENOENT"||error.code==="ECONNREFUSED"))return refusal("refuse",void 0,{reason:"host_unavailable",socket,detail:error.message});throw error}let sessionId,durableSessionId;if("ref"in request){let found=await resolveSessionRef(client,request.ref,agentDir);if(found.kind==="unknown")return refusal("refuse",void 0,{reason:"unknown_session",ref:request.ref,socket});if(found.kind==="ambiguous"){let detail={reason:"ambiguous_session",ref:request.ref,candidates:found.candidates,socket};return refusal("refuse",void 0,detail)}let reopen=found.kind==="parked"?{sessionPath:found.sessionPath,cwd:found.cwd,retain_on_disconnect:!0,attended:!1}:{sessionPath:found.row.sessionPath,cwd:found.row.cwd};durableSessionId=found.kind==="parked"?found.durableSessionId:found.row.durableSessionId,sessionId=(await client.openSession(reopen)).sessionId}switch(request.action){case"open":return await openHostSession(client,request,socket,ensured);case"prompt":return{exitCode:HOST_EXIT_OK,payload:{action:"prompt",sessionId,disposition:await client.prompt(request.text)}};case"steer":{let streaming=(await client.getState()).isStreaming,disposition=await client.steer(request.text);return{exitCode:HOST_EXIT_OK,payload:{action:"steer",sessionId,disposition,streaming}}}case"abort":{let aborted=(await client.getState()).isStreaming;return await client.abortStrict(),{exitCode:HOST_EXIT_OK,payload:{action:"abort",sessionId,acknowledged:!0,aborted}}}case"model":{await client.setModel(request.model.provider,request.model.id);let state=await client.getState();return{exitCode:HOST_EXIT_OK,payload:{action:"model",sessionId,requested:request.model,model:state.model?{provider:state.model.provider,id:state.model.id}:null,pendingModelSwitch:state.pendingModelSwitch??null}}}case"list":return{exitCode:HOST_EXIT_OK,payload:{action:"list",socket,sessions:await client.listSessions({observe:!0})}};case"state":return{exitCode:HOST_EXIT_OK,payload:{action:"state",sessionId,durableSessionId,state:await client.getState()}};case"read":{if(request.messages){let all=await client.getMessages(),messages=request.tail===void 0?all:all.slice(-request.tail);return{exitCode:HOST_EXIT_OK,payload:{action:"read",sessionId,messages,count:messages.length}}}let{entries,leafId}=await client.getEntries(request.since),slice=request.tail===void 0?entries:entries.slice(-request.tail);return{exitCode:HOST_EXIT_OK,payload:{action:"read",sessionId,entries:slice,count:slice.length,total:entries.length,leafId,nextSince:slice.at(-1)?.id??request.since??null,...request.since!==void 0&&{since:request.since}}}}case"wait":return await waitForHostSession(client,sessionId,request,handler=>{disconnected=handler});case"unload":{let answer=await client.unloadSession({sessionId,interrupt:request.interrupt,force:request.force,clearQueue:request.clearQueue,children:request.children});return{exitCode:answer.outcome==="unloaded"?HOST_EXIT_OK:HOST_EXIT_REFUSED,payload:{action:"unload",sessionId,...answer}}}case"close":{let reason,unsubscribe=client.onEvent(record=>{let event=record;event.type==="session_closed"&&(reason=event.reason)});try{await client.closeSession(sessionId);let remaining=(await client.listSessions()).find(row=>row.sessionId===sessionId);return{exitCode:HOST_EXIT_OK,payload:remaining?{action:"close",sessionId,closed:!1,attachments:remaining.attachments}:{action:"close",sessionId,closed:!0,reason:reason??"client_close"}}}finally{unsubscribe()}}default:return assertNever(request)}}catch(error){if((error instanceof RpcRequestTimeoutError||isTransportGoneError(error))&&(connectionUnusable=!0),request.action==="open"&&error instanceof RpcCommandError&&error.errorCode==="host_stopping")throw error;return error instanceof HostEnsureRefusedError?refusal("refuse",void 0,{reason:error.reason,socket,detail:error.detail}):mapError(error,socket)}finally{ensured?.release(),client&&!connectionUnusable&&await detachBeforeClose(client,line=>process.stderr.write(`senpi host session: ${line}
|
|
3
3
|
`)),await client?.stop()}}function assertNever(value){throw new Error(`unreachable host session request: ${JSON.stringify(value)}`)}var USAGE=`usage: ${APP_NAME} host session <command> [--socket <path>] [--rpc-key-root <dir>] [--json]
|
|
4
4
|
|
|
5
5
|
open --cwd <dir> [--model <provider/id>] [--name <text>] [--prompt <text|@file>] [--launch-spec <file>]
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{InteractiveMode,OptimisticUserEchoController,createInteractiveTui,createInteractiveTuiReference,formatCrashExtensionHint,formatResumeCommand,isApiKeyLoginProvider,shouldShowRetryIndicator,showsStartupDetails,showsStartupHeader}from"./chunk-
|
|
2
|
+
import{InteractiveMode,OptimisticUserEchoController,createInteractiveTui,createInteractiveTuiReference,formatCrashExtensionHint,formatResumeCommand,isApiKeyLoginProvider,shouldShowRetryIndicator,showsStartupDetails,showsStartupHeader}from"./chunk-RPW3XQW3.js";import"./chunk-UJPG4ROT.js";import"./chunk-XM36IFP3.js";import"./chunk-ZP6JJDYV.js";import"./chunk-PDG4XWO2.js";import"./chunk-DXJJP6RP.js";import"./chunk-GXY5JEI5.js";import"./chunk-2XF6W6F6.js";import"./chunk-GY5MR5KR.js";import"./chunk-DNDZPKIQ.js";import"./chunk-CYOHFREV.js";import"./chunk-CNPDUC4D.js";import"./chunk-MLVIYDHK.js";import"./chunk-Y3TMJV3J.js";import"./chunk-TQ67PB7U.js";import"./chunk-JPGT64RV.js";import"./chunk-HWTD4QF3.js";import"./chunk-7IZH2KQX.js";import"./chunk-CNDPCYNT.js";import"./chunk-QMRJYMNH.js";import"./chunk-XMNPK472.js";import"./chunk-TIVW4P37.js";import"./chunk-H4QOEVS5.js";import"./chunk-RQ5JTXUC.js";import"./chunk-XMJKZK5H.js";import"./chunk-6VWIMHMH.js";import"./chunk-FQDARFHT.js";import"./chunk-KLAX467B.js";import"./chunk-JFFS72FL.js";import"./chunk-ORXZXUMC.js";import"./chunk-GZVCRV7I.js";import"./chunk-KUPQO7MC.js";import"./chunk-SOMFLLPD.js";import"./chunk-IHKHCWWG.js";import"./chunk-26UBFF6N.js";import"./chunk-MTQQ2VQH.js";import"./chunk-L2O6K3SJ.js";import"./chunk-H4WJ4LY3.js";import"./chunk-Z6SAQ5O3.js";import"./chunk-ZAUVY6ZC.js";import"./chunk-J2YAYTB2.js";import"./chunk-4WZRVZNX.js";import"./chunk-U3VOXCGP.js";import"./chunk-GWGNVYPB.js";import"./chunk-YI7SPFDN.js";import"./chunk-HB35RBP4.js";import"./chunk-Z6WGAK7W.js";import"./chunk-DLAY7CIU.js";import"./chunk-NDNIMC5W.js";import"./chunk-QXREUA5F.js";import"./chunk-RUGYFYH7.js";import"./chunk-OEFCY46F.js";import"./chunk-KRNXUTZJ.js";import"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import"./chunk-KTDIIF2F.js";import"./chunk-FDL4CF6F.js";import"./chunk-GPPOPK76.js";import"./chunk-YU4AYH4C.js";import"./chunk-6GAMRAVM.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-EQNUL2WB.js";import"./chunk-GVSBCJFI.js";import"./chunk-WASCMT6Y.js";import"./chunk-IY4G44MN.js";import"./chunk-QGJLZ6BI.js";import"./chunk-WHPDEDCC.js";import"./chunk-AA2L2RHH.js";import"./chunk-HK46JMSC.js";import"./chunk-PY4ZQHTN.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-5W3DTM2J.js";import"./chunk-45SZOLCU.js";import"./chunk-KBSFTXAT.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import"./chunk-YU2P3CAR.js";import"./chunk-ESNSRUW4.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import"./chunk-V3CK2AVC.js";import"./chunk-VRDU425E.js";import"./chunk-ZGAB7WQA.js";import"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-OXNWERO4.js";import"./chunk-QN2BHP3M.js";import"./chunk-NTK2MHJ5.js";import"./chunk-O5RYI3IW.js";import"./chunk-IKOFCODM.js";export{InteractiveMode,OptimisticUserEchoController,createInteractiveTui,createInteractiveTuiReference,formatCrashExtensionHint,formatResumeCommand,isApiKeyLoginProvider,shouldShowRetryIndicator,showsStartupDetails,showsStartupHeader};
|
package/dist/bundle/chunks/{mistral-conversations-RAE4K2XY.js → mistral-conversations-I2PI7DDF.js}
RENAMED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
|
|
2
|
-
import{getPiUserAgent}from"./chunk-QTG7MY2X.js";import{MISTRAL_RESERVED_BODY_KEYS,applyExtraBody,buildBaseOptions}from"./chunk-XQ45JMGN.js";import{getJsonSchemaToolParameters,resolveJsonSchemaStrictSampling,shortHash,transformMessages}from"./chunk-5LWUUXMH.js";import{sanitizeSurrogates}from"./chunk-WDTJ6JKE.js";import{parseStreamingJson}from"./chunk-3W47LTXQ.js";import{calculateCost,clampThinkingLevel,getCurrentTools,getSystemMessageText,renderSystemMessageUpdate,resolveTranscript}from"./chunk-ZXHLH4MW.js";import{AssistantMessageEventStream}from"./chunk-GQJYNFMO.js";import{headersToRecord}from"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";var MISTRAL_TOOL_CALL_ID_LENGTH=9,MAX_MISTRAL_ERROR_BODY_CHARS=4e3,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream({captureBlocks:!0}),normalizedContext=resolveTranscript(context,model.compat?.supportsMidConvoSystemMessages);return(async()=>{let output=createOutput(model);try{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let normalizeMistralToolCallId=createMistralToolCallIdNormalizer(),preserveThinking=options?.promptMode==="reasoning"||options?.reasoningEffort!==void 0&&options.reasoningEffort!=="none",transformedMessages=transformMessages(normalizedContext.messages,model,id=>normalizeMistralToolCallId(id),{preserveThinking}),payload=buildChatPayload(model,normalizedContext,transformedMessages,options),nextPayload=await options?.onPayload?.(payload,model);nextPayload!==void 0&&(payload=nextPayload);let mistralStream=await requestMistralStream(model,payload,apiKey,options);if(stream2.push({type:"start",partial:output}),await consumeChatStream(model,output,stream2,mistralStream,options?.onProviderStreamEvent),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Mistral stream ended without a finish reason");if(output.stopReason==="aborted"||output.stopReason==="error")throw new Error(output.errorMessage||"An unknown error occurred");stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)delete block.partialArgs;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatMistralError(error),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let base={...buildBaseOptions(model,context,options,apiKey),toolChoice:options?.toolChoice},clampedReasoning=options?.reasoning?clampThinkingLevel(model,options.reasoning):void 0,reasoning=clampedReasoning==="off"?void 0:clampedReasoning,effortMap=model.reasoning?model.thinkingLevelMap:void 0,reasoningEffort=effortMap?reasoning?effortMap[reasoning]??"high":effortMap.off??void 0:void 0;return stream(model,context,{...base,promptMode:model.reasoning&&!effortMap&&reasoning?"reasoning":void 0,reasoningEffort})};function createOutput(model){return{role:"assistant",content:[],api:model.api,provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()}}function createMistralToolCallIdNormalizer(){let idMap=new Map,reverseMap=new Map;return id=>{let existing=idMap.get(id);if(existing)return existing;let attempt=0;for(;;){let candidate=deriveMistralToolCallId(id,attempt),owner=reverseMap.get(candidate);if(!owner||owner===id)return idMap.set(id,candidate),reverseMap.set(candidate,id),candidate;attempt++}}}function deriveMistralToolCallId(id,attempt){let normalized=id.replace(/[^a-zA-Z0-9]/g,"");if(attempt===0&&normalized.length===MISTRAL_TOOL_CALL_ID_LENGTH)return normalized;let seedBase=normalized||id,seed=attempt===0?seedBase:`${seedBase}:${attempt}`;return shortHash(seed).replace(/[^a-zA-Z0-9]/g,"").slice(0,MISTRAL_TOOL_CALL_ID_LENGTH)}function formatMistralError(error){if(error instanceof Error){let httpError=error,statusCode=typeof httpError.statusCode=="number"?httpError.statusCode:void 0,bodyText=typeof httpError.body=="string"?httpError.body.trim():void 0;return statusCode!==void 0&&bodyText?`Mistral API error (${statusCode}): ${truncateErrorText(bodyText,MAX_MISTRAL_ERROR_BODY_CHARS)}`:statusCode!==void 0?`Mistral API error (${statusCode}): ${error.message}`:error.message}return safeJsonStringify(error)}function truncateErrorText(text,maxChars){return text.length<=maxChars?text:`${text.slice(0,maxChars)}... [truncated ${text.length-maxChars} chars]`}function safeJsonStringify(value){try{let serialized=JSON.stringify(value);return serialized===void 0?String(value):serialized}catch{return String(value)}}async function requestMistralStream(model,payload,apiKey,options){let baseUrl=new URL(model.baseUrl);baseUrl.pathname=`${baseUrl.pathname.replace(/\/+$/u,"")}/`;let url=new URL("v1/chat/completions",baseUrl),headers=buildMistralHeaders(model,apiKey,options),timeoutSignal=AbortSignal.timeout(options?.timeoutMs??6e4),signal=options?.signal?AbortSignal.any([options.signal,timeoutSignal]):timeoutSignal,response=await(options?.fetch??globalThis.fetch)(url,{method:"POST",headers,body:JSON.stringify(toMistralWirePayload(payload)),signal});if(await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),!response.ok){let body=await response.text();throw new MistralHttpError(response.status,body,response.statusText)}if(!response.body)throw new Error("Mistral response has no body");return readMistralEvents(response.body,signal)}var MistralHttpError=class extends Error{constructor(statusCode,body,statusText){super(statusText||`Request failed with status ${statusCode}`),this.name="MistralHttpError",this.statusCode=statusCode,this.body=body}};function buildMistralHeaders(model,apiKey,options){let headers=new Headers({"User-Agent":getPiUserAgent(),accept:"text/event-stream",authorization:`Bearer ${apiKey}`,"content-type":"application/json"});applyMistralHeaderOverrides(headers,model.headers),applyMistralHeaderOverrides(headers,options?.headers);let hasExplicitAffinity=hasMistralHeaderOverride(model.headers,"x-affinity")||hasMistralHeaderOverride(options?.headers,"x-affinity");return shouldUsePromptCaching(options)&&!hasExplicitAffinity&&headers.set("x-affinity",options.sessionId),headers}function applyMistralHeaderOverrides(headers,overrides){if(overrides)for(let[name,value]of Object.entries(overrides))value===null?headers.delete(name):headers.set(name,value)}function hasMistralHeaderOverride(overrides,target){return!!overrides&&Object.keys(overrides).some(name=>name.toLowerCase()===target)}function toMistralWirePayload(payload){let wirePayload={...payload};for(let[source,target]of[["topP","top_p"],["maxTokens","max_tokens"],["randomSeed","random_seed"],["responseFormat","response_format"],["toolChoice","tool_choice"],["presencePenalty","presence_penalty"],["frequencyPenalty","frequency_penalty"],["parallelToolCalls","parallel_tool_calls"],["reasoningEffort","reasoning_effort"],["promptMode","prompt_mode"],["promptCacheKey","prompt_cache_key"],["safePrompt","safe_prompt"]])remapMistralProperty(wirePayload,source,target);wirePayload.messages=payload.messages.map(message=>toMistralWireMessage(message));let responseFormat=wirePayload.response_format;if(isMistralRecord(responseFormat)){let wireResponseFormat={...responseFormat};remapMistralProperty(wireResponseFormat,"jsonSchema","json_schema");let jsonSchema=wireResponseFormat.json_schema;if(isMistralRecord(jsonSchema)){let wireJsonSchema={...jsonSchema};remapMistralProperty(wireJsonSchema,"schemaDefinition","schema"),wireResponseFormat.json_schema=wireJsonSchema}wirePayload.response_format=wireResponseFormat}return wirePayload}function toMistralWireMessage(message){let wireMessage={...message};return remapMistralProperty(wireMessage,"toolCalls","tool_calls"),remapMistralProperty(wireMessage,"toolCallId","tool_call_id"),Array.isArray(message.content)&&(wireMessage.content=message.content.map(chunk=>toMistralWireContentChunk(chunk))),wireMessage}function toMistralWireContentChunk(chunk){let wireChunk={...chunk};for(let[source,target]of[["imageUrl","image_url"],["documentUrl","document_url"],["documentName","document_name"],["fileId","file_id"],["referenceIds","reference_ids"],["inputAudio","input_audio"]])remapMistralProperty(wireChunk,source,target);return wireChunk}function remapMistralProperty(record,source,target){source in record&&(record[target]=record[source],delete record[source])}function isMistralRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var MISTRAL_STREAM_DONE=Symbol("mistral-stream-done");async function*readMistralEvents(body,signal){let reader=body.getReader(),decoder=new TextDecoder,buffer="",onAbort=()=>{reader.cancel().catch(()=>{})};signal.addEventListener("abort",onAbort,{once:!0});try{for(;;){if(signal.aborted)throw signal.reason;let{done,value}=await reader.read();if(signal.aborted)throw signal.reason;buffer+=done?decoder.decode():decoder.decode(value,{stream:!0});let boundary=findMistralEventBoundary(buffer);for(;boundary;){let event=parseMistralEvent(buffer.slice(0,boundary.index));if(buffer=buffer.slice(boundary.index+boundary.length),event===MISTRAL_STREAM_DONE)return;event&&(yield event),boundary=findMistralEventBoundary(buffer)}if(done)break}if(buffer.trim()){let event=parseMistralEvent(buffer);event!==MISTRAL_STREAM_DONE&&event&&(yield event)}}finally{signal.removeEventListener("abort",onAbort);try{await reader.cancel()}catch{}try{reader.releaseLock()}catch{}}}function findMistralEventBoundary(buffer){let match=/\r\n\r\n|\r\n\r|\r\n\n|\r\r\n|\n\r\n|\r\r|\n\r|\n\n/u.exec(buffer);return match?.index===void 0?void 0:{index:match.index,length:match[0].length}}function parseMistralEvent(raw){let data=raw.split(/\r\n|\r|\n/u).filter(line=>line.startsWith("data:")).map(line=>line.slice(5).trimStart()).join(`
|
|
2
|
+
import{getPiUserAgent}from"./chunk-QTG7MY2X.js";import{MISTRAL_RESERVED_BODY_KEYS,applyExtraBody,buildBaseOptions}from"./chunk-Z6BREXV3.js";import{getJsonSchemaToolParameters,resolveJsonSchemaStrictSampling,shortHash,transformMessages}from"./chunk-PY4ZQHTN.js";import{sanitizeSurrogates}from"./chunk-WDTJ6JKE.js";import{parseStreamingJson}from"./chunk-3W47LTXQ.js";import{calculateCost,clampThinkingLevel,getCurrentTools,getSystemMessageText,renderSystemMessageUpdate,resolveTranscript}from"./chunk-5W3DTM2J.js";import{AssistantMessageEventStream}from"./chunk-KBSFTXAT.js";import{headersToRecord}from"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";var MISTRAL_TOOL_CALL_ID_LENGTH=9,MAX_MISTRAL_ERROR_BODY_CHARS=4e3,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream({captureBlocks:!0}),normalizedContext=resolveTranscript(context,model.compat?.supportsMidConvoSystemMessages);return(async()=>{let output=createOutput(model);try{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let normalizeMistralToolCallId=createMistralToolCallIdNormalizer(),preserveThinking=options?.promptMode==="reasoning"||options?.reasoningEffort!==void 0&&options.reasoningEffort!=="none",transformedMessages=transformMessages(normalizedContext.messages,model,id=>normalizeMistralToolCallId(id),{preserveThinking}),payload=buildChatPayload(model,normalizedContext,transformedMessages,options),nextPayload=await options?.onPayload?.(payload,model);nextPayload!==void 0&&(payload=nextPayload);let mistralStream=await requestMistralStream(model,payload,apiKey,options);if(stream2.push({type:"start",partial:output}),await consumeChatStream(model,output,stream2,mistralStream,options?.onProviderStreamEvent),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Mistral stream ended without a finish reason");if(output.stopReason==="aborted"||output.stopReason==="error")throw new Error(output.errorMessage||"An unknown error occurred");stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)delete block.partialArgs;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatMistralError(error),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let base={...buildBaseOptions(model,context,options,apiKey),toolChoice:options?.toolChoice},clampedReasoning=options?.reasoning?clampThinkingLevel(model,options.reasoning):void 0,reasoning=clampedReasoning==="off"?void 0:clampedReasoning,effortMap=model.reasoning?model.thinkingLevelMap:void 0,reasoningEffort=effortMap?reasoning?effortMap[reasoning]??"high":effortMap.off??void 0:void 0;return stream(model,context,{...base,promptMode:model.reasoning&&!effortMap&&reasoning?"reasoning":void 0,reasoningEffort})};function createOutput(model){return{role:"assistant",content:[],api:model.api,provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()}}function createMistralToolCallIdNormalizer(){let idMap=new Map,reverseMap=new Map;return id=>{let existing=idMap.get(id);if(existing)return existing;let attempt=0;for(;;){let candidate=deriveMistralToolCallId(id,attempt),owner=reverseMap.get(candidate);if(!owner||owner===id)return idMap.set(id,candidate),reverseMap.set(candidate,id),candidate;attempt++}}}function deriveMistralToolCallId(id,attempt){let normalized=id.replace(/[^a-zA-Z0-9]/g,"");if(attempt===0&&normalized.length===MISTRAL_TOOL_CALL_ID_LENGTH)return normalized;let seedBase=normalized||id,seed=attempt===0?seedBase:`${seedBase}:${attempt}`;return shortHash(seed).replace(/[^a-zA-Z0-9]/g,"").slice(0,MISTRAL_TOOL_CALL_ID_LENGTH)}function formatMistralError(error){if(error instanceof Error){let httpError=error,statusCode=typeof httpError.statusCode=="number"?httpError.statusCode:void 0,bodyText=typeof httpError.body=="string"?httpError.body.trim():void 0;return statusCode!==void 0&&bodyText?`Mistral API error (${statusCode}): ${truncateErrorText(bodyText,MAX_MISTRAL_ERROR_BODY_CHARS)}`:statusCode!==void 0?`Mistral API error (${statusCode}): ${error.message}`:error.message}return safeJsonStringify(error)}function truncateErrorText(text,maxChars){return text.length<=maxChars?text:`${text.slice(0,maxChars)}... [truncated ${text.length-maxChars} chars]`}function safeJsonStringify(value){try{let serialized=JSON.stringify(value);return serialized===void 0?String(value):serialized}catch{return String(value)}}async function requestMistralStream(model,payload,apiKey,options){let baseUrl=new URL(model.baseUrl);baseUrl.pathname=`${baseUrl.pathname.replace(/\/+$/u,"")}/`;let url=new URL("v1/chat/completions",baseUrl),headers=buildMistralHeaders(model,apiKey,options),timeoutSignal=AbortSignal.timeout(options?.timeoutMs??6e4),signal=options?.signal?AbortSignal.any([options.signal,timeoutSignal]):timeoutSignal,response=await(options?.fetch??globalThis.fetch)(url,{method:"POST",headers,body:JSON.stringify(toMistralWirePayload(payload)),signal});if(await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),!response.ok){let body=await response.text();throw new MistralHttpError(response.status,body,response.statusText)}if(!response.body)throw new Error("Mistral response has no body");return readMistralEvents(response.body,signal)}var MistralHttpError=class extends Error{constructor(statusCode,body,statusText){super(statusText||`Request failed with status ${statusCode}`),this.name="MistralHttpError",this.statusCode=statusCode,this.body=body}};function buildMistralHeaders(model,apiKey,options){let headers=new Headers({"User-Agent":getPiUserAgent(),accept:"text/event-stream",authorization:`Bearer ${apiKey}`,"content-type":"application/json"});applyMistralHeaderOverrides(headers,model.headers),applyMistralHeaderOverrides(headers,options?.headers);let hasExplicitAffinity=hasMistralHeaderOverride(model.headers,"x-affinity")||hasMistralHeaderOverride(options?.headers,"x-affinity");return shouldUsePromptCaching(options)&&!hasExplicitAffinity&&headers.set("x-affinity",options.sessionId),headers}function applyMistralHeaderOverrides(headers,overrides){if(overrides)for(let[name,value]of Object.entries(overrides))value===null?headers.delete(name):headers.set(name,value)}function hasMistralHeaderOverride(overrides,target){return!!overrides&&Object.keys(overrides).some(name=>name.toLowerCase()===target)}function toMistralWirePayload(payload){let wirePayload={...payload};for(let[source,target]of[["topP","top_p"],["maxTokens","max_tokens"],["randomSeed","random_seed"],["responseFormat","response_format"],["toolChoice","tool_choice"],["presencePenalty","presence_penalty"],["frequencyPenalty","frequency_penalty"],["parallelToolCalls","parallel_tool_calls"],["reasoningEffort","reasoning_effort"],["promptMode","prompt_mode"],["promptCacheKey","prompt_cache_key"],["safePrompt","safe_prompt"]])remapMistralProperty(wirePayload,source,target);wirePayload.messages=payload.messages.map(message=>toMistralWireMessage(message));let responseFormat=wirePayload.response_format;if(isMistralRecord(responseFormat)){let wireResponseFormat={...responseFormat};remapMistralProperty(wireResponseFormat,"jsonSchema","json_schema");let jsonSchema=wireResponseFormat.json_schema;if(isMistralRecord(jsonSchema)){let wireJsonSchema={...jsonSchema};remapMistralProperty(wireJsonSchema,"schemaDefinition","schema"),wireResponseFormat.json_schema=wireJsonSchema}wirePayload.response_format=wireResponseFormat}return wirePayload}function toMistralWireMessage(message){let wireMessage={...message};return remapMistralProperty(wireMessage,"toolCalls","tool_calls"),remapMistralProperty(wireMessage,"toolCallId","tool_call_id"),Array.isArray(message.content)&&(wireMessage.content=message.content.map(chunk=>toMistralWireContentChunk(chunk))),wireMessage}function toMistralWireContentChunk(chunk){let wireChunk={...chunk};for(let[source,target]of[["imageUrl","image_url"],["documentUrl","document_url"],["documentName","document_name"],["fileId","file_id"],["referenceIds","reference_ids"],["inputAudio","input_audio"]])remapMistralProperty(wireChunk,source,target);return wireChunk}function remapMistralProperty(record,source,target){source in record&&(record[target]=record[source],delete record[source])}function isMistralRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var MISTRAL_STREAM_DONE=Symbol("mistral-stream-done");async function*readMistralEvents(body,signal){let reader=body.getReader(),decoder=new TextDecoder,buffer="",onAbort=()=>{reader.cancel().catch(()=>{})};signal.addEventListener("abort",onAbort,{once:!0});try{for(;;){if(signal.aborted)throw signal.reason;let{done,value}=await reader.read();if(signal.aborted)throw signal.reason;buffer+=done?decoder.decode():decoder.decode(value,{stream:!0});let boundary=findMistralEventBoundary(buffer);for(;boundary;){let event=parseMistralEvent(buffer.slice(0,boundary.index));if(buffer=buffer.slice(boundary.index+boundary.length),event===MISTRAL_STREAM_DONE)return;event&&(yield event),boundary=findMistralEventBoundary(buffer)}if(done)break}if(buffer.trim()){let event=parseMistralEvent(buffer);event!==MISTRAL_STREAM_DONE&&event&&(yield event)}}finally{signal.removeEventListener("abort",onAbort);try{await reader.cancel()}catch{}try{reader.releaseLock()}catch{}}}function findMistralEventBoundary(buffer){let match=/\r\n\r\n|\r\n\r|\r\n\n|\r\r\n|\n\r\n|\r\r|\n\r|\n\n/u.exec(buffer);return match?.index===void 0?void 0:{index:match.index,length:match[0].length}}function parseMistralEvent(raw){let data=raw.split(/\r\n|\r|\n/u).filter(line=>line.startsWith("data:")).map(line=>line.slice(5).trimStart()).join(`
|
|
3
3
|
`).trim();if(!data)return;if(data==="[DONE]")return MISTRAL_STREAM_DONE;let parsed=JSON.parse(data);if(!isMistralRecord(parsed)||!Array.isArray(parsed.choices))throw new Error("Invalid Mistral streaming event");return{data:parsed}}function buildChatPayload(model,context,messages,options){let payload={model:model.id,stream:!0,messages:toChatMessages(messages,model.input.includes("image"))},currentTools=getCurrentTools(context.messages);return currentTools.length>0&&(payload.tools=toFunctionTools(currentTools)),options?.temperature!==void 0&&(payload.temperature=options.temperature),options?.maxTokens!==void 0&&(payload.maxTokens=options.maxTokens),options?.toolChoice&&(payload.toolChoice=mapToolChoice(options.toolChoice)),options?.promptMode&&(payload.promptMode=options.promptMode),options?.reasoningEffort&&(payload.reasoningEffort=options.reasoningEffort),shouldUsePromptCaching(options)&&(payload.promptCacheKey=options.sessionId),applyExtraBody(payload,options?.extraBody,MISTRAL_RESERVED_BODY_KEYS),payload}function shouldUsePromptCaching(options){return options?.cacheRetention!=="none"&&!!options?.sessionId}function getMistralCachedPromptTokens(usage,promptTokens){let rawUsage=usage,rawCachedTokens=rawUsage.promptTokensDetails?.cachedTokens??rawUsage.prompt_tokens_details?.cached_tokens??rawUsage.promptTokenDetails?.cachedTokens??rawUsage.prompt_token_details?.cached_tokens??rawUsage.numCachedTokens??rawUsage.num_cached_tokens??0,cachedTokens=typeof rawCachedTokens=="number"&&Number.isFinite(rawCachedTokens)?rawCachedTokens:0;return Math.min(promptTokens,Math.max(0,cachedTokens))}async function consumeChatStream(model,output,stream2,mistralStream,onProviderStreamEvent){let currentBlock=null,blocks=output.content,blockIndex=()=>blocks.length-1,toolBlocksByKey=new Map,finishCurrentBlock=block=>{if(block){if(block.type==="text"){stream2.push({type:"text_end",contentIndex:blockIndex(),content:block.text,partial:output});return}block.type==="thinking"&&stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:block.thinking,partial:output})}};for await(let event of mistralStream){let chunk=event.data;if(await onProviderStreamEvent?.(chunk,model),output.responseId||=chunk.id,chunk.usage){let promptTokens=chunk.usage.prompt_tokens||0,cachedPromptTokens=getMistralCachedPromptTokens(chunk.usage,promptTokens);output.usage.input=Math.max(0,promptTokens-cachedPromptTokens),output.usage.output=chunk.usage.completion_tokens||0,output.usage.cacheRead=cachedPromptTokens,output.usage.cacheWrite=0,output.usage.totalTokens=chunk.usage.total_tokens||output.usage.input+output.usage.output+output.usage.cacheRead+output.usage.cacheWrite,calculateCost(model,output.usage)}let choice=chunk.choices[0];if(!choice)continue;if(choice.finish_reason){output.rawStopReason=choice.finish_reason;let stopReasonResult=mapChatStopReason(choice.finish_reason);output.stopReason=stopReasonResult.stopReason,stopReasonResult.errorMessage&&(output.errorMessage=stopReasonResult.errorMessage)}let delta=choice.delta;if(delta.content!==null&&delta.content!==void 0){let contentItems=typeof delta.content=="string"?[delta.content]:delta.content;for(let item of contentItems){if(typeof item=="string"){let textDelta=sanitizeSurrogates(item);if(!textDelta)continue;currentBlock?.type!=="text"&&(finishCurrentBlock(currentBlock),currentBlock={type:"text",text:""},output.content.push(currentBlock),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output})),currentBlock.text+=textDelta,stream2.push({type:"text_delta",contentIndex:blockIndex(),delta:textDelta,partial:output});continue}if(item.type==="thinking"){let deltaText=(item.thinking??[]).map(part=>part.text??"").filter(text=>text.length>0).join(""),thinkingDelta=sanitizeSurrogates(deltaText);if(!thinkingDelta)continue;currentBlock?.type!=="thinking"&&(finishCurrentBlock(currentBlock),currentBlock={type:"thinking",thinking:""},output.content.push(currentBlock),stream2.push({type:"thinking_start",contentIndex:blockIndex(),partial:output})),currentBlock.thinking+=thinkingDelta,stream2.push({type:"thinking_delta",contentIndex:blockIndex(),delta:thinkingDelta,partial:output});continue}if(item.type==="text"){let textDelta=sanitizeSurrogates(item.text??"");if(!textDelta)continue;currentBlock?.type!=="text"&&(finishCurrentBlock(currentBlock),currentBlock={type:"text",text:""},output.content.push(currentBlock),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output})),currentBlock.text+=textDelta,stream2.push({type:"text_delta",contentIndex:blockIndex(),delta:textDelta,partial:output})}}}let toolCalls=delta.tool_calls||[];for(let toolCall of toolCalls){currentBlock&&(finishCurrentBlock(currentBlock),currentBlock=null);let callId=toolCall.id&&toolCall.id!=="null"?toolCall.id:deriveMistralToolCallId(`toolcall:${toolCall.index??0}`,0),key=toolCall.index??callId,existingIndex=toolBlocksByKey.get(key),block;if(existingIndex!==void 0){let existing=output.content[existingIndex];existing?.type==="toolCall"&&(block=existing)}block||(block={type:"toolCall",id:callId,name:toolCall.function.name,arguments:{},partialArgs:""},output.content.push(block),toolBlocksByKey.set(key,output.content.length-1),stream2.push({type:"toolcall_start",contentIndex:output.content.length-1,partial:output}));let argsDelta=typeof toolCall.function.arguments=="string"?toolCall.function.arguments:JSON.stringify(toolCall.function.arguments||{});block.partialArgs=(block.partialArgs||"")+argsDelta,block.arguments=parseStreamingJson(block.partialArgs),stream2.push({type:"toolcall_delta",contentIndex:toolBlocksByKey.get(key),delta:argsDelta,partial:output})}}finishCurrentBlock(currentBlock);for(let index of toolBlocksByKey.values()){let block=output.content[index];if(block.type!=="toolCall")continue;let toolBlock=block;toolBlock.arguments=parseStreamingJson(toolBlock.partialArgs),delete toolBlock.partialArgs,stream2.push({type:"toolcall_end",contentIndex:index,toolCall:toolBlock,partial:output})}}function toFunctionTools(tools){return tools.map(tool=>{let strict=resolveJsonSchemaStrictSampling(tool,!0);return{type:"function",function:{name:tool.name,description:tool.description,parameters:stripSymbolKeys(getJsonSchemaToolParameters(tool,strict)),strict:strict??!1}}})}function stripSymbolKeys(value){if(Array.isArray(value))return value.map(item=>stripSymbolKeys(item));if(value&&typeof value=="object"){let result={};for(let[key,entry]of Object.entries(value))result[key]=stripSymbolKeys(entry);return result}return value}function appendUserMessage(result,content){let previous=result[result.length-1];if(previous?.role!=="user"){result.push({role:"user",content});return}let chunks=value=>typeof value=="string"?[{type:"text",text:value}]:value??[];previous.content=[...chunks(previous.content),...chunks(content)]}function toChatMessages(messages,supportsImages){let result=[];for(let[index,msg]of messages.entries()){if(msg.role==="configurationUpdate")continue;if(msg.role==="system"){let text=index===0?getSystemMessageText(msg):renderSystemMessageUpdate(msg);text.length>0&&result.push({role:"system",content:sanitizeSurrogates(text)});continue}if(msg.role==="user"){if(typeof msg.content=="string"){appendUserMessage(result,sanitizeSurrogates(msg.content));continue}let hadImages=msg.content.some(item=>item.type==="image"),content=msg.content.filter(item=>item.type==="text"||supportsImages).map(item=>item.type==="text"?{type:"text",text:sanitizeSurrogates(item.text)}:{type:"image_url",imageUrl:`data:${item.mimeType};base64,${item.data}`});if(content.length>0){appendUserMessage(result,content);continue}hadImages&&!supportsImages&&appendUserMessage(result,"(image omitted: model does not support images)");continue}if(msg.role==="assistant"){let contentParts=[],toolCalls=[];for(let block of msg.content){if(block.type==="text"){block.text.trim().length>0&&contentParts.push({type:"text",text:sanitizeSurrogates(block.text)});continue}if(block.type==="thinking"){block.thinking.trim().length>0&&contentParts.push({type:"thinking",thinking:[{type:"text",text:sanitizeSurrogates(block.thinking)}]});continue}block.type==="toolCall"&&toolCalls.push({id:block.id,type:"function",function:{name:block.name,arguments:JSON.stringify(block.arguments||{})},index:0})}let assistantMessage={role:"assistant",prefix:!1};contentParts.length>0&&(assistantMessage.content=contentParts),toolCalls.length>0&&(assistantMessage.toolCalls=toolCalls),(contentParts.length>0||toolCalls.length>0)&&result.push(assistantMessage);continue}let toolContent=[],textResult=msg.content.filter(part=>part.type==="text").map(part=>part.type==="text"?sanitizeSurrogates(part.text):"").join(`
|
|
4
4
|
`),hasImages=msg.content.some(part=>part.type==="image"),toolText=buildToolResultText(textResult,hasImages,supportsImages,msg.isError);toolContent.push({type:"text",text:toolText});for(let part of msg.content)supportsImages&&part.type==="image"&&toolContent.push({type:"image_url",imageUrl:`data:${part.mimeType};base64,${part.data}`});result.push({role:"tool",toolCallId:msg.toolCallId,name:msg.toolName,content:toolContent})}return result}function buildToolResultText(text,hasImages,supportsImages,isError){let trimmed=text.trim(),errorPrefix=isError?"[tool error] ":"";return trimmed.length>0?`${errorPrefix}${trimmed}${hasImages&&!supportsImages?`
|
|
5
5
|
[tool image omitted: model does not support images]`:""}`:hasImages?supportsImages?isError?"[tool error] (see attached image)":"(see attached image)":isError?"[tool error] (image omitted: model does not support images)":"(image omitted: model does not support images)":isError?"[tool error] (no tool output)":"(no tool output)"}function mapToolChoice(choice){if(choice)return choice==="auto"||choice==="none"||choice==="any"||choice==="required"?choice:{type:"function",function:{name:choice.function.name}}}function mapChatStopReason(reason){if(reason===null)return{stopReason:"stop"};switch(reason){case"stop":return{stopReason:"stop"};case"length":case"model_length":return{stopReason:"length"};case"tool_calls":return{stopReason:"toolUse"};case"error":return{stopReason:"error",errorMessage:"Provider stopped with: error"};default:return{stopReason:"error",errorMessage:`Provider stopped with: ${reason}`}}}export{stream,streamSimple};
|