pi-namespace-patch 1.0.0-namespace.2 → 1.0.2-namespace.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +54 -0
- package/README.md +3 -3
- package/dist/bundle/chunks/{anthropic-messages-UID2PALB.js → anthropic-messages-MVG2FL56.js} +3 -3
- package/dist/bundle/chunks/azure-openai-responses-7AMFUIWJ.js +2 -0
- package/dist/bundle/chunks/bedrock-converse-stream.js +2 -2
- package/dist/bundle/chunks/chunk-2KAZSACP.js +2 -0
- package/dist/bundle/chunks/{chunk-2KTBZM5G.js → chunk-6FX7UEPL.js} +5 -5
- package/dist/bundle/chunks/{chunk-2VNGUWBO.js → chunk-BYB6ZAAQ.js} +1 -1
- package/dist/bundle/chunks/chunk-DN3QEIXS.js +2 -0
- package/dist/bundle/chunks/chunk-F5ZABL6Z.js +20 -0
- package/dist/bundle/chunks/{chunk-3LH3ZQKY.js → chunk-G7EDXK4D.js} +1 -1
- package/dist/bundle/chunks/chunk-IKZJX7ZT.js +2 -0
- package/dist/bundle/chunks/{chunk-4N5K4RKC.js → chunk-OLBCNJCL.js} +31 -32
- package/dist/bundle/chunks/{chunk-PRD6WYBT.js → chunk-OYBSLV7Y.js} +1 -1
- package/dist/bundle/chunks/{chunk-IBCPYVFK.js → chunk-PDFMCAOZ.js} +4 -4
- package/dist/bundle/chunks/{chunk-LTXEMVMA.js → chunk-SYF2TF6W.js} +2 -2
- package/dist/bundle/chunks/chunk-WCQZGZ6I.js +82 -0
- package/dist/bundle/chunks/{chunk-KDN6RCEQ.js → chunk-ZSI3BL5Q.js} +2 -2
- package/dist/bundle/chunks/{cli-QOMC26IJ.js → cli-KILDDGW3.js} +2 -2
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-NPQN263E.js → cloudflare-workers-ai-system-one-X5PVWWYJ.js} +1 -1
- package/dist/bundle/chunks/codemode-worker.js +24 -3
- package/dist/bundle/chunks/easter-egg-3d-T5FFWIBR.js +2 -0
- package/dist/bundle/chunks/{execute-GVRSEGHL.js → execute-RYVK27GT.js} +25 -4
- package/dist/bundle/chunks/{google-generative-ai-APTPZOQL.js → google-generative-ai-ZOK6CV7D.js} +1 -1
- package/dist/bundle/chunks/{google-vertex-MXCOSOY3.js → google-vertex-VKWZQ3AY.js} +1 -1
- package/dist/bundle/chunks/{mistral-conversations-DKVFNQL6.js → mistral-conversations-7DAUEE4N.js} +1 -1
- package/dist/bundle/chunks/node-N5BSDOA5.js +16 -0
- package/dist/bundle/chunks/openai-chatgpt.js +1 -1
- package/dist/bundle/chunks/{openai-codex-responses-GK67DQQJ.js → openai-codex-responses-TC3OK7B4.js} +1 -1
- package/dist/bundle/chunks/openai-completions-GWHGMQ3T.js +7 -0
- package/dist/bundle/chunks/openai-responses-EZ7FJ2KL.js +3 -0
- package/dist/bundle/chunks/{runtime-2SO2JDWM.js → runtime-D5I2NTIF.js} +1 -1
- package/dist/bundle/chunks/virtual-modules-J2M3WAR2.js +2 -0
- package/dist/bundle/cli-runtime.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +4 -1
- package/dist/cli/args.js.map +1 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +3 -0
- package/dist/config.js.map +1 -1
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +1 -1
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/export-html/tool-renderer.d.ts +3 -3
- package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
- package/dist/core/export-html/tool-renderer.js +3 -3
- package/dist/core/export-html/tool-renderer.js.map +1 -1
- package/dist/core/extensions/index.d.ts +1 -1
- package/dist/core/extensions/index.d.ts.map +1 -1
- package/dist/core/extensions/index.js.map +1 -1
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +5 -0
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/runner.d.ts +3 -1
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +6 -0
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/types.d.ts +9 -0
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/mcp-servers.d.ts +6 -0
- package/dist/core/mcp-servers.d.ts.map +1 -1
- package/dist/core/mcp-servers.js +11 -0
- package/dist/core/mcp-servers.js.map +1 -1
- package/dist/core/model-config.d.ts +36 -0
- package/dist/core/model-config.d.ts.map +1 -1
- package/dist/core/model-config.js +14 -2
- package/dist/core/model-config.js.map +1 -1
- package/dist/core/model-resolver.js +1 -1
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/provider-composer.d.ts +2 -1
- package/dist/core/provider-composer.d.ts.map +1 -1
- package/dist/core/provider-composer.js +13 -0
- package/dist/core/provider-composer.js.map +1 -1
- package/dist/core/tools/renderers/index.d.ts +2 -2
- package/dist/core/tools/renderers/index.d.ts.map +1 -1
- package/dist/core/tools/renderers/index.js.map +1 -1
- package/dist/extensions/mcp/cli.d.ts.map +1 -1
- package/dist/extensions/mcp/cli.js +3 -0
- package/dist/extensions/mcp/cli.js.map +1 -1
- package/dist/extensions/mcp/config.d.ts +15 -3
- package/dist/extensions/mcp/config.d.ts.map +1 -1
- package/dist/extensions/mcp/config.js +46 -10
- package/dist/extensions/mcp/config.js.map +1 -1
- package/dist/extensions/mcp/index.d.ts +4 -1
- package/dist/extensions/mcp/index.d.ts.map +1 -1
- package/dist/extensions/mcp/index.js +80 -45
- package/dist/extensions/mcp/index.js.map +1 -1
- package/dist/extensions/mcp/oauth.d.ts +4 -1
- package/dist/extensions/mcp/oauth.d.ts.map +1 -1
- package/dist/extensions/mcp/oauth.js +54 -10
- package/dist/extensions/mcp/oauth.js.map +1 -1
- package/dist/extensions/mcp/runtime.d.ts.map +1 -1
- package/dist/extensions/mcp/runtime.js +1 -0
- package/dist/extensions/mcp/runtime.js.map +1 -1
- package/dist/extensions/mcp/tools.d.ts +3 -1
- package/dist/extensions/mcp/tools.d.ts.map +1 -1
- package/dist/extensions/mcp/tools.js +19 -13
- package/dist/extensions/mcp/tools.js.map +1 -1
- package/dist/extensions/mcp/ui.d.ts.map +1 -1
- package/dist/extensions/mcp/ui.js +8 -4
- package/dist/extensions/mcp/ui.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/modes/interactive/components/armin.d.ts +3 -0
- package/dist/modes/interactive/components/armin.d.ts.map +1 -1
- package/dist/modes/interactive/components/armin.js +7 -5
- package/dist/modes/interactive/components/armin.js.map +1 -1
- package/dist/modes/interactive/components/auth-url.d.ts +14 -0
- package/dist/modes/interactive/components/auth-url.d.ts.map +1 -0
- package/dist/modes/interactive/components/auth-url.js +37 -0
- package/dist/modes/interactive/components/auth-url.js.map +1 -0
- package/dist/modes/interactive/components/easter-egg-3d.d.ts +104 -0
- package/dist/modes/interactive/components/easter-egg-3d.d.ts.map +1 -0
- package/dist/modes/interactive/components/{pi-logo-animation.js → easter-egg-3d.js} +127 -74
- package/dist/modes/interactive/components/easter-egg-3d.js.map +1 -0
- package/dist/modes/interactive/components/easter-egg-3d.lazy.d.ts +6 -0
- package/dist/modes/interactive/components/easter-egg-3d.lazy.d.ts.map +1 -0
- package/dist/modes/interactive/components/easter-egg-3d.lazy.js +23 -0
- package/dist/modes/interactive/components/easter-egg-3d.lazy.js.map +1 -0
- package/dist/modes/interactive/components/index.d.ts +0 -1
- package/dist/modes/interactive/components/index.d.ts.map +1 -1
- package/dist/modes/interactive/components/index.js +0 -1
- package/dist/modes/interactive/components/index.js.map +1 -1
- package/dist/modes/interactive/components/login-dialog.d.ts +2 -0
- package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
- package/dist/modes/interactive/components/login-dialog.js +11 -5
- package/dist/modes/interactive/components/login-dialog.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts +6 -18
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +22 -45
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +2 -2
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +15 -17
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/package-manager-cli.d.ts.map +1 -1
- package/dist/package-manager-cli.js +12 -0
- package/dist/package-manager-cli.js.map +1 -1
- package/dist/utils/image-convert.d.ts +12 -0
- package/dist/utils/image-convert.d.ts.map +1 -1
- package/dist/utils/image-convert.js +45 -6
- package/dist/utils/image-convert.js.map +1 -1
- package/docs/cli.md +2 -0
- package/docs/codemode.md +1 -1
- package/docs/extensions.md +4 -0
- package/docs/keybindings.md +1 -1
- package/docs/mcp.md +23 -1
- package/docs/models.md +28 -2
- package/docs/quickstart.md +16 -2
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/package.json +13 -14
- package/dist/bundle/chunks/azure-openai-responses-AFMVM6NP.js +0 -2
- package/dist/bundle/chunks/chunk-6D7LHLKG.js +0 -2
- package/dist/bundle/chunks/chunk-7FH3BDRG.js +0 -82
- package/dist/bundle/chunks/chunk-DTD7JQ7Y.js +0 -42
- package/dist/bundle/chunks/chunk-MJOHEBV7.js +0 -2
- package/dist/bundle/chunks/node-O3RIBJRH.js +0 -16
- package/dist/bundle/chunks/openai-completions-JXDDPZ23.js +0 -7
- package/dist/bundle/chunks/openai-responses-CQDDLDQF.js +0 -3
- package/dist/bundle/chunks/pi-logo-animation-MPKZE4EK.js +0 -2
- package/dist/bundle/chunks/virtual-modules-3THEGRQQ.js +0 -2
- package/dist/modes/interactive/components/daxnuts.d.ts +0 -23
- package/dist/modes/interactive/components/daxnuts.d.ts.map +0 -1
- package/dist/modes/interactive/components/daxnuts.js +0 -140
- package/dist/modes/interactive/components/daxnuts.js.map +0 -1
- package/dist/modes/interactive/components/pi-logo-animation.d.ts +0 -68
- package/dist/modes/interactive/components/pi-logo-animation.d.ts.map +0 -1
- package/dist/modes/interactive/components/pi-logo-animation.js.map +0 -1
- package/dist/modes/interactive/components/pi-logo-animation.lazy.d.ts +0 -7
- package/dist/modes/interactive/components/pi-logo-animation.lazy.d.ts.map +0 -1
- package/dist/modes/interactive/components/pi-logo-animation.lazy.js +0 -12
- package/dist/modes/interactive/components/pi-logo-animation.lazy.js.map +0 -1
- package/npm-shrinkwrap.json +0 -1952
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
+
import{FileAuthStorageBackend,JSON_RPC_ERROR_CODES,LATEST_PROTOCOL_VERSION,McpAuthRequiredError,McpClient,McpError,McpHttpError,McpSessionExpiredError,StdioTransport,StreamableHttpTransport,isMcpAppResource,isObject,mcpNamespace,require_proper_lockfile,resolveConfigValueOrThrow,resolveHeadersOrThrow}from"./chunk-PDFMCAOZ.js";import{APP_NAME,VERSION,getAgentDir}from"./chunk-6FX7UEPL.js";import{__toESM}from"./chunk-4L3WN2XY.js";import{homedir}from"node:os";import{basename,join as join2,resolve}from"node:path";import{pathToFileURL}from"node:url";import{createServer}from"node:http";function plainText(page){return page.ok?"Authorization complete. You may close this window.":page.details?`${page.message}
|
|
3
|
+
|
|
4
|
+
${page.details}`:page.message}var OAuthCallbackServer=class _OAuthCallbackServer{redirectUrl;server;paths;timeoutMs;renderPage;pending=new Map;constructor(server,redirectUrl,paths,timeoutMs,renderPage2){this.server=server,this.redirectUrl=redirectUrl,this.paths=paths,this.timeoutMs=timeoutMs,this.renderPage=renderPage2}static async listen(options={}){let host=options.host??"127.0.0.1",redirectHost=options.redirectHost??host,path=options.path??"/callback",instance,server=createServer((request,response)=>instance?.handle(request.url??"/",response));await new Promise((resolve2,reject)=>{server.once("error",reject),server.listen(options.port??0,host,()=>{server.off("error",reject),resolve2()})});let address=server.address();if(!address||typeof address=="string")throw new Error("OAuth callback server did not bind to TCP");return instance=new _OAuthCallbackServer(server,`http://${redirectHost.includes(":")?`[${redirectHost}]`:redirectHost}:${address.port}${path}`,[path,...options.extraPaths??[]],options.timeoutMs??5*6e4,options.renderPage),instance}waitForCallback(state,path){if(this.pending.has(state))throw new Error("OAuth state is already pending");return new Promise((resolve2,reject)=>{let timer=setTimeout(()=>{this.pending.delete(state),reject(new Error("OAuth callback timed out"))},this.timeoutMs);this.pending.set(state,{resolve:resolve2,reject,timer,path})})}async close(){for(let pending of this.pending.values())clearTimeout(pending.timer),pending.reject(new Error("OAuth callback server closed"));this.pending.clear(),await new Promise((resolve2,reject)=>{this.server.close(error=>error?reject(error):resolve2())})}reply(response,status,page){this.renderPage?(response.writeHead(status,{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}),response.end(this.renderPage(page))):response.writeHead(status,{"content-type":"text/plain; charset=utf-8"}).end(plainText(page))}handle(rawUrl,response){let url=new URL(rawUrl,this.redirectUrl);if(!this.paths.includes(url.pathname)){this.reply(response,404,{ok:!1,message:"Not found"});return}let state=url.searchParams.get("state"),pending=state?this.pending.get(state):void 0;if(!state||!pending){this.reply(response,400,{ok:!1,message:"Invalid or expired OAuth state"});return}if(clearTimeout(pending.timer),this.pending.delete(state),pending.path!==void 0&&url.pathname!==pending.path){pending.reject(new Error("The authorization response arrived on another redirect URI")),this.reply(response,400,{ok:!1,message:"Unexpected redirect URI"});return}let error=url.searchParams.get("error");if(error){let description=url.searchParams.get("error_description")??error;pending.reject(new Error(description)),this.reply(response,200,{ok:!1,message:"Authorization failed. You may close this window.",details:description});return}let code=url.searchParams.get("code");if(!code){pending.reject(new Error("OAuth callback did not include an authorization code")),this.reply(response,400,{ok:!1,message:"Missing authorization code"});return}let iss=url.searchParams.get("iss");pending.resolve({code,state,...iss?{iss}:{}}),this.reply(response,200,{ok:!0})}};var OAuthError=class extends Error{code;errorUri;constructor(code,message,errorUri){super(message||code),this.name="OAuthError",this.code=code,this.errorUri=errorUri}},OAuthIssuerMismatchError=class extends Error{expected;received;constructor(expected,received){super(`OAuth issuer mismatch: expected ${JSON.stringify(expected)}, received ${received===void 0?"none":JSON.stringify(received)}`),this.name="OAuthIssuerMismatchError",this.expected=expected,this.received=received}},OAuthInsecureEndpointError=class extends Error{endpoint;constructor(endpoint){super(`Refusing to send OAuth credentials to non-HTTPS endpoint ${endpoint}`),this.name="OAuthInsecureEndpointError",this.endpoint=endpoint}},OAuthRegistrationError=class extends Error{status;body;constructor(status,body){super(`OAuth dynamic client registration failed with status ${status}: ${body}`),this.name="OAuthRegistrationError",this.status=status,this.body=body}},McpOAuthAuthorizationRequiredError=class extends Error{constructor(){super("MCP OAuth authorization requires user interaction"),this.name="McpOAuthAuthorizationRequiredError"}};function object(value,name){if(!isObject(value))throw new Error(`Invalid ${name}`);return value}function compact(value){return Object.fromEntries(Object.entries(value).filter(([,item])=>item!==void 0))}function requiredString(value,name){if(typeof value!="string"||value.length===0)throw new Error(`Invalid ${name}`);return value}function absent(value){return value==null||value===""}function optionalString(value,name){if(!absent(value))return requiredString(value,name)}function optionalStrings(value,name){if(value!=null){if(!Array.isArray(value)||value.some(item=>typeof item!="string"))throw new Error(`Invalid ${name}`);return[...value]}}function safeUrl(value,name){let text=requiredString(value,name);if(!URL.canParse(text))throw new Error(`Invalid ${name}`);let url=new URL(text);if(["javascript:","data:","vbscript:"].includes(url.protocol))throw new Error(`Invalid ${name}`);return text}function optionalUrl(value,name){return absent(value)?void 0:safeUrl(value,name)}function parseProtectedResourceMetadata(value){let input=object(value,"OAuth protected resource metadata");return compact({...input,resource:safeUrl(input.resource,"OAuth protected resource metadata resource"),authorization_servers:optionalStrings(input.authorization_servers,"authorization_servers")?.map(url=>safeUrl(url,"authorization server URL")),scopes_supported:optionalStrings(input.scopes_supported,"scopes_supported")})}function parseAuthorizationServerMetadata(value){let input=object(value,"authorization server metadata"),responseTypes=optionalStrings(input.response_types_supported,"response_types_supported");if(!responseTypes)throw new Error("Invalid response_types_supported");return compact({...input,issuer:safeUrl(input.issuer,"authorization server issuer"),authorization_endpoint:safeUrl(input.authorization_endpoint,"authorization endpoint"),token_endpoint:safeUrl(input.token_endpoint,"token endpoint"),registration_endpoint:optionalUrl(input.registration_endpoint,"registration endpoint"),scopes_supported:optionalStrings(input.scopes_supported,"scopes_supported"),response_types_supported:responseTypes,grant_types_supported:optionalStrings(input.grant_types_supported,"grant_types_supported"),token_endpoint_auth_methods_supported:optionalStrings(input.token_endpoint_auth_methods_supported,"token_endpoint_auth_methods_supported"),code_challenge_methods_supported:optionalStrings(input.code_challenge_methods_supported,"code_challenge_methods_supported"),client_id_metadata_document_supported:typeof input.client_id_metadata_document_supported=="boolean"?input.client_id_metadata_document_supported:void 0,authorization_response_iss_parameter_supported:typeof input.authorization_response_iss_parameter_supported=="boolean"?input.authorization_response_iss_parameter_supported:void 0})}function parseOAuthTokens(value){let input=object(value,"OAuth token response"),expires=absent(input.expires_in)?void 0:Number(input.expires_in);if(expires!==void 0&&!Number.isFinite(expires))throw new Error("Invalid expires_in");return compact({access_token:requiredString(input.access_token,"access_token"),token_type:requiredString(input.token_type,"token_type"),expires_in:expires,scope:optionalString(input.scope,"scope"),refresh_token:optionalString(input.refresh_token,"refresh_token"),id_token:optionalString(input.id_token,"id_token")})}function parseClientInformation(value){let input=object(value,"OAuth client registration response");return compact({...input,client_id:requiredString(input.client_id,"client_id"),client_secret:optionalString(input.client_secret,"client_secret"),client_id_issued_at:typeof input.client_id_issued_at=="number"?input.client_id_issued_at:void 0,client_secret_expires_at:typeof input.client_secret_expires_at=="number"?input.client_secret_expires_at:void 0,redirect_uris:optionalStrings(input.redirect_uris,"redirect_uris")??[]})}function discard(response){response?.body?.cancel().catch(()=>{})}function isDiscoveryMiss(status){return status>=400&&status<500||status===502}function pathSuffix(pathname){return pathname.endsWith("/")?pathname.slice(0,-1):pathname}function field(header,name){let match=header.match(new RegExp(String.raw`(?:^|[,\s])${name}=(?:"([^"]*)"|([^\s,]+))`,"i"));return match?.[1]||match?.[2]||void 0}function parseWwwAuthenticate(header){if(!header)return{};let scheme=header.trimStart().split(/\s+/,1)[0]?.toLowerCase();if(scheme!=="bearer"&&scheme!=="dpop")return{};let resourceMetadata=field(header,"resource_metadata"),resourceMetadataUrl;if(resourceMetadata)try{resourceMetadataUrl=new URL(resourceMetadata)}catch{}return{resourceMetadataUrl,scope:field(header,"scope"),error:field(header,"error"),errorDescription:field(header,"error_description")}}async function fetchMetadata(url,fetch,protocolVersion){return fetch(url,{headers:{Accept:"application/json","MCP-Protocol-Version":protocolVersion}})}async function discoverProtectedResourceMetadata(serverUrl,options={}){let server=new URL(serverUrl),fetch=options.fetch??globalThis.fetch,version=options.protocolVersion??LATEST_PROTOCOL_VERSION,response=await fetchMetadata(options.resourceMetadataUrl?new URL(options.resourceMetadataUrl):new URL(`/.well-known/oauth-protected-resource${pathSuffix(server.pathname)}`,server.origin),fetch,version);if(!options.resourceMetadataUrl&&server.pathname!=="/"&&isDiscoveryMiss(response.status)&&(discard(response),response=await fetchMetadata(new URL("/.well-known/oauth-protected-resource",server.origin),fetch,version)),!response.ok)throw discard(response),new Error(`HTTP ${response.status} loading OAuth protected resource metadata`);return parseProtectedResourceMetadata(await response.json())}function buildAuthorizationServerDiscoveryUrls(authorizationServerUrl){let issuer=new URL(authorizationServerUrl),path=pathSuffix(issuer.pathname),urls=[{url:new URL(`/.well-known/oauth-authorization-server${path}`,issuer.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${path}`,issuer.origin),type:"oidc"}];return path&&urls.push({url:new URL(`${path}/.well-known/openid-configuration`,issuer.origin),type:"oidc"}),urls}async function discoverAuthorizationServerMetadata(authorizationServerUrl,options={}){let fetch=options.fetch??globalThis.fetch;for(let{url}of buildAuthorizationServerDiscoveryUrls(authorizationServerUrl)){let response=await fetchMetadata(url,fetch,options.protocolVersion??LATEST_PROTOCOL_VERSION);if(!response.ok){if(discard(response),isDiscoveryMiss(response.status))continue;throw new Error(`HTTP ${response.status} loading authorization server metadata from ${url}`)}let metadata=parseAuthorizationServerMetadata(await response.json());if(!options.skipIssuerValidation){let expected=String(authorizationServerUrl),trim=value=>value.endsWith("/")?value.slice(0,-1):value;if(trim(metadata.issuer)!==trim(expected))throw new OAuthIssuerMismatchError(expected,metadata.issuer)}return metadata}}async function discoverOAuthServerInfo(serverUrl,options={}){let resourceMetadata;try{resourceMetadata=await discoverProtectedResourceMetadata(serverUrl,{resourceMetadataUrl:options.resourceMetadataUrl,fetch:options.fetch})}catch(error){if(error instanceof TypeError)throw error}if(options.authorizationServerMetadataUrl){let url=options.authorizationServerMetadataUrl,response=await fetchMetadata(url,options.fetch??globalThis.fetch,LATEST_PROTOCOL_VERSION);if(!response.ok)throw discard(response),new Error(`HTTP ${response.status} loading authorization server metadata from ${url}`);let metadata=parseAuthorizationServerMetadata(await response.json());return{authorizationServerUrl:metadata.issuer,authorizationServerMetadata:metadata,resourceMetadata}}let authorizationServerUrl=resourceMetadata?.authorization_servers?.[0]??String(new URL("/",serverUrl));return{authorizationServerUrl,authorizationServerMetadata:await discoverAuthorizationServerMetadata(authorizationServerUrl,{fetch:options.fetch,skipIssuerValidation:options.skipIssuerValidation}),resourceMetadata}}function resourceUrlFromServerUrl(value){let url=new URL(value);return url.hash="",url}function selectResource(serverUrl,metadata){if(!metadata)return;let requested=resourceUrlFromServerUrl(serverUrl),configured=new URL(metadata.resource);if(requested.origin!==configured.origin)throw new Error(`Protected resource ${metadata.resource} does not match MCP server ${requested}`);let requestedPath=requested.pathname.endsWith("/")?requested.pathname:`${requested.pathname}/`,configuredPath=configured.pathname.endsWith("/")?configured.pathname:`${configured.pathname}/`;if(!requestedPath.startsWith(configuredPath))throw new Error(`Protected resource ${metadata.resource} does not match MCP server ${requested}`);return metadata.resource}function loopback(hostname){return hostname==="localhost"||hostname==="127.0.0.1"||hostname==="[::1]"||hostname==="::1"}function secureEndpoint(value){let url=new URL(value);if(url.protocol!=="https:"&&!loopback(url.hostname))throw new OAuthInsecureEndpointError(url.href);return url}function selectClientAuthMethod(information,supported){let hinted="token_endpoint_auth_method"in information?information.token_endpoint_auth_method:void 0;return hinted&&["client_secret_basic","client_secret_post","none"].includes(hinted)&&(supported.length===0||supported.includes(hinted))?hinted:supported.length===0?information.client_secret?"client_secret_basic":"none":information.client_secret&&supported.includes("client_secret_basic")?"client_secret_basic":information.client_secret&&supported.includes("client_secret_post")?"client_secret_post":supported.includes("none")?"none":information.client_secret?"client_secret_post":"none"}function applyClientAuthentication(method,information,headers,params){if(method==="client_secret_basic"){if(!information.client_secret)throw new Error("client_secret_basic requires a client secret");headers.set("Authorization",`Basic ${Buffer.from(`${information.client_id}:${information.client_secret}`).toString("base64")}`)}else params.set("client_id",information.client_id),method==="client_secret_post"&&information.client_secret&¶ms.set("client_secret",information.client_secret)}async function pkce(){let bytes=crypto.getRandomValues(new Uint8Array(32)),verifier=Buffer.from(bytes).toString("base64url"),digest=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(verifier));return{verifier,challenge:Buffer.from(digest).toString("base64url")}}async function startAuthorization(authorizationServerUrl,options){let metadata=options.metadata;if(metadata&&!metadata.response_types_supported.includes("code"))throw new Error("Authorization server does not support authorization codes");if(metadata?.code_challenge_methods_supported&&!metadata.code_challenge_methods_supported.includes("S256"))throw new Error("Authorization server does not support PKCE S256");let url=new URL(metadata?.authorization_endpoint??new URL("/authorize",authorizationServerUrl)),{verifier,challenge}=await pkce();return url.searchParams.set("response_type","code"),url.searchParams.set("client_id",options.clientInformation.client_id),url.searchParams.set("code_challenge",challenge),url.searchParams.set("code_challenge_method","S256"),url.searchParams.set("redirect_uri",String(options.redirectUrl)),options.state&&url.searchParams.set("state",options.state),options.scope&&url.searchParams.set("scope",options.scope),options.scope?.split(/\s+/).includes("offline_access")&&url.searchParams.set("prompt","consent"),options.resource&&url.searchParams.set("resource",options.resource),{authorizationUrl:url,codeVerifier:verifier}}async function tokenRequest(authorizationServerUrl,options,params){let url=secureEndpoint(options.metadata?.token_endpoint??new URL("/token",authorizationServerUrl)),headers=new Headers({Accept:"application/json","content-type":"application/x-www-form-urlencoded"});options.resource&¶ms.set("resource",options.resource),options.addClientAuthentication?await options.addClientAuthentication(headers,params,url,options.metadata):applyClientAuthentication(selectClientAuthMethod(options.clientInformation,options.metadata?.token_endpoint_auth_methods_supported??[]),options.clientInformation,headers,params);let response=await(options.fetch??globalThis.fetch)(url,{method:"POST",headers,body:params}),text=await response.text(),value;try{value=JSON.parse(text)}catch{}if(isObject(value)&&typeof value.error=="string")throw new OAuthError(value.error,typeof value.error_description=="string"?value.error_description:value.error,typeof value.error_uri=="string"?value.error_uri:void 0);if(!response.ok)throw new OAuthError("server_error",`HTTP ${response.status}: ${text}`);return parseOAuthTokens(value)}async function registerClient(authorizationServerUrl,options){let endpoint=options.metadata?.registration_endpoint;if(options.metadata&&!endpoint)throw new Error("Authorization server does not support dynamic client registration");let response=await(options.fetch??globalThis.fetch)(new URL(endpoint??new URL("/register",authorizationServerUrl)),{method:"POST",headers:{Accept:"application/json","content-type":"application/json"},body:JSON.stringify({...options.clientMetadata,...options.scope?{scope:options.scope}:{}})});if(!response.ok)throw new OAuthRegistrationError(response.status,await response.text());return parseClientInformation(await response.json())}async function exchangeAuthorizationCode(authorizationServerUrl,options){return tokenRequest(authorizationServerUrl,options,new URLSearchParams({grant_type:"authorization_code",code:options.code,code_verifier:options.codeVerifier,redirect_uri:String(options.redirectUrl)}))}async function refreshAuthorization(authorizationServerUrl,options){let tokens=await tokenRequest(authorizationServerUrl,options,new URLSearchParams({grant_type:"refresh_token",refresh_token:options.refreshToken}));return{refresh_token:options.refreshToken,...tokens}}function withScope(tokens,scope){return tokens.scope===void 0&&scope?{...tokens,scope}:tokens}function stepUpScope(granted,challenged){if(!challenged)return;let scopes=[granted,challenged].flatMap(scope=>scope?.split(/\s+/).filter(Boolean)??[]);return[...new Set(scopes)].join(" ")}async function runFlow(provider,options){let metadataUrl=options.authorizationServerMetadataUrl&&secureEndpoint(options.authorizationServerMetadataUrl),cached=metadataUrl?void 0:await provider.discoveryState?.(),discovered=cached?.authorizationServerUrl?{authorizationServerUrl:cached.authorizationServerUrl,authorizationServerMetadata:cached.authorizationServerMetadata??await discoverAuthorizationServerMetadata(cached.authorizationServerUrl,{fetch:options.fetch,skipIssuerValidation:options.skipIssuerValidation}),resourceMetadata:cached.resourceMetadata}:await discoverOAuthServerInfo(options.serverUrl,{resourceMetadataUrl:options.resourceMetadataUrl,authorizationServerMetadataUrl:metadataUrl,fetch:options.fetch,skipIssuerValidation:options.skipIssuerValidation});metadataUrl||await provider.saveDiscoveryState?.({...discovered,...options.resourceMetadataUrl?{resourceMetadataUrl:options.resourceMetadataUrl.href}:{}});let metadata=discovered.authorizationServerMetadata,resource=selectResource(options.serverUrl,discovered.resourceMetadata),scope=options.scope||discovered.resourceMetadata?.scopes_supported?.join(" ")||provider.clientMetadata.scope,stored=await provider.clientInformation(),clientDocument=stored?void 0:provider.clientMetadataDocument?.(metadata);if(clientDocument){let url=new URL(clientDocument.url);if(url.protocol!=="https:"||url.pathname==="/")throw new Error("Invalid OAuth client metadata URL")}let client=stored??(clientDocument&&{client_id:clientDocument.url});if(!client){if(options.authorizationCode)throw new Error("OAuth client information is missing during code exchange");if(!provider.saveClientInformation)throw new Error("OAuth client information cannot be persisted");client=await registerClient(discovered.authorizationServerUrl,{metadata,clientMetadata:provider.clientMetadata,scope,fetch:options.fetch}),await provider.saveClientInformation(client)}let redirectUrl=clientDocument?.redirectUrl??provider.redirectUrl,tokenOptions={metadata,clientInformation:client,resource,addClientAuthentication:provider.addClientAuthentication,fetch:options.fetch};if(options.authorizationCode){let iss=options.iss;if(metadata&&(iss!==void 0||metadata.authorization_response_iss_parameter_supported)&&iss!==metadata.issuer)throw new OAuthIssuerMismatchError(metadata.issuer,iss);let tokens=await exchangeAuthorizationCode(discovered.authorizationServerUrl,{...tokenOptions,code:options.authorizationCode,codeVerifier:await provider.codeVerifier(),redirectUrl});return await provider.saveTokens(withScope(tokens,scope)),"AUTHORIZED"}let existing=options.skipRefresh?void 0:await provider.tokens();if(existing?.refresh_token)try{let tokens=await refreshAuthorization(discovered.authorizationServerUrl,{...tokenOptions,refreshToken:existing.refresh_token});return await provider.saveTokens(withScope(tokens,existing.scope)),"AUTHORIZED"}catch(error){if(error instanceof OAuthInsecureEndpointError||error instanceof OAuthError&&error.code!=="server_error")throw error}let state=await provider.state?.(),authorization=await startAuthorization(discovered.authorizationServerUrl,{metadata,clientInformation:client,redirectUrl,scope,state,resource});return await provider.saveCodeVerifier(authorization.codeVerifier),await provider.redirectToAuthorization(authorization.authorizationUrl),"REDIRECT"}async function authorizeMcp(provider,options){try{return await runFlow(provider,options)}catch(error){if(error instanceof OAuthError&&["invalid_client","unauthorized_client"].includes(error.code))return await provider.invalidateCredentials?.("all"),runFlow(provider,options);if(error instanceof OAuthError&&error.code==="invalid_grant")return await provider.invalidateCredentials?.("tokens"),runFlow(provider,options);throw error}}var MemoryOAuthStateStore=class{value;load(){return this.value===void 0?void 0:structuredClone(this.value)}save(state){this.value=structuredClone(state)}},McpOAuthProvider=class{redirectUrl;clientMetadata;clientMetadataDocument;serverUrl;configuredClient;store;onRedirect;writes=Promise.resolve();constructor(options){this.serverUrl=String(new URL(options.serverUrl)),this.redirectUrl=String(options.redirectUrl),this.clientMetadata={...options.clientMetadata,redirect_uris:options.clientMetadata.redirect_uris??[this.redirectUrl],grant_types:options.clientMetadata.grant_types??["authorization_code","refresh_token"],response_types:options.clientMetadata.response_types??["code"],token_endpoint_auth_method:options.clientMetadata.token_endpoint_auth_method??(options.clientSecret?"client_secret_post":"none")},this.clientMetadataDocument=options.clientMetadataDocument,this.configuredClient=options.clientId?{client_id:options.clientId,...options.clientSecret?{client_secret:options.clientSecret}:{}}:void 0,this.store=options.store??new MemoryOAuthStateStore,this.onRedirect=options.onRedirect}async state(){let existing=(await this.load()).oauthState;if(existing)return existing;let state=Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("hex");return await this.update(value=>({...value,oauthState:state})),state}async clientInformation(){return this.configuredClient??(await this.load()).clientInformation}async saveClientInformation(information){this.configuredClient||await this.update(value=>({...value,clientInformation:information}))}async tokens(){return(await this.load()).tokens}async saveTokens(tokens){let expiresAt=tokens.expires_in===void 0?void 0:Date.now()+tokens.expires_in*1e3;await this.update(value=>{let next={...value,tokens};return expiresAt===void 0?delete next.tokensExpireAt:next.tokensExpireAt=expiresAt,next})}async redirectToAuthorization(url){await this.onRedirect(url)}async saveCodeVerifier(verifier){await this.update(value=>({...value,codeVerifier:verifier}))}async codeVerifier(){let verifier=(await this.load()).codeVerifier;if(!verifier)throw new Error("No OAuth PKCE code verifier is stored");return verifier}async invalidateCredentials(kind){await this.update(value=>{let next={...value};return(kind==="all"||kind==="client")&&delete next.clientInformation,(kind==="all"||kind==="tokens")&&(delete next.tokens,delete next.tokensExpireAt),(kind==="all"||kind==="verifier")&&delete next.codeVerifier,(kind==="all"||kind==="discovery")&&delete next.discovery,kind==="all"&&delete next.oauthState,next})}async saveDiscoveryState(discovery){await this.update(value=>({...value,discovery}))}async discoveryState(){return(await this.load()).discovery}async load(){return await this.writes,this.own(await this.store.load())}async update(update){this.writes=this.writes.then(async()=>{await this.store.save(update(this.own(await this.store.load())))}),await this.writes}own(state){return state?.serverUrl===this.serverUrl?state:{serverUrl:this.serverUrl}}};import{createHash}from"node:crypto";import{mkdirSync}from"node:fs";import{join}from"node:path";var LOGO_SVG='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 800" aria-hidden="true"><path fill="#F09082" d="M165.29 165.29H517.36V400H400V282.65H165.29Z"/><path fill="#4D9ABF" d="M165.29 282.65H282.65V400H400V517.36H282.65V634.72H165.29Z"/><path fill="#F1BE58" d="M517.36 400H634.72V634.72H517.36Z"/></svg>';function escapeHtml(value){return value.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function renderPage(options){let title=escapeHtml(options.title),heading=escapeHtml(options.heading),message=escapeHtml(options.message),details=options.details?escapeHtml(options.details):void 0;return`<!doctype html>
|
|
5
|
+
<html lang="en">
|
|
6
|
+
<head>
|
|
7
|
+
<meta charset="utf-8" />
|
|
8
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
9
|
+
<title>${title}</title>
|
|
10
|
+
<style>
|
|
11
|
+
:root {
|
|
12
|
+
--text: #fafafa;
|
|
13
|
+
--text-dim: #a1a1aa;
|
|
14
|
+
--page-bg: #09090b;
|
|
15
|
+
--font-sans: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
|
|
16
|
+
--font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
|
|
17
|
+
}
|
|
18
|
+
* { box-sizing: border-box; }
|
|
19
|
+
html { color-scheme: dark; }
|
|
20
|
+
body {
|
|
21
|
+
margin: 0;
|
|
22
|
+
min-height: 100vh;
|
|
23
|
+
display: flex;
|
|
24
|
+
align-items: center;
|
|
25
|
+
justify-content: center;
|
|
26
|
+
padding: 24px;
|
|
27
|
+
background: var(--page-bg);
|
|
28
|
+
color: var(--text);
|
|
29
|
+
font-family: var(--font-sans);
|
|
30
|
+
text-align: center;
|
|
31
|
+
}
|
|
32
|
+
main {
|
|
33
|
+
width: 100%;
|
|
34
|
+
max-width: 560px;
|
|
35
|
+
display: flex;
|
|
36
|
+
flex-direction: column;
|
|
37
|
+
align-items: center;
|
|
38
|
+
justify-content: center;
|
|
39
|
+
}
|
|
40
|
+
.logo {
|
|
41
|
+
width: 72px;
|
|
42
|
+
height: 72px;
|
|
43
|
+
display: block;
|
|
44
|
+
margin-bottom: 24px;
|
|
45
|
+
}
|
|
46
|
+
h1 {
|
|
47
|
+
margin: 0 0 10px;
|
|
48
|
+
font-size: 28px;
|
|
49
|
+
line-height: 1.15;
|
|
50
|
+
font-weight: 650;
|
|
51
|
+
color: var(--text);
|
|
52
|
+
}
|
|
53
|
+
p {
|
|
54
|
+
margin: 0;
|
|
55
|
+
line-height: 1.7;
|
|
56
|
+
color: var(--text-dim);
|
|
57
|
+
font-size: 15px;
|
|
58
|
+
}
|
|
59
|
+
.details {
|
|
60
|
+
margin-top: 16px;
|
|
61
|
+
font-family: var(--font-mono);
|
|
62
|
+
font-size: 13px;
|
|
63
|
+
color: var(--text-dim);
|
|
64
|
+
white-space: pre-wrap;
|
|
65
|
+
word-break: break-word;
|
|
66
|
+
}
|
|
67
|
+
</style>
|
|
68
|
+
</head>
|
|
69
|
+
<body>
|
|
70
|
+
<main>
|
|
71
|
+
<div class="logo">${LOGO_SVG}</div>
|
|
72
|
+
<h1>${heading}</h1>
|
|
73
|
+
<p>${message}</p>
|
|
74
|
+
${details?`<div class="details">${details}</div>`:""}
|
|
75
|
+
</main>
|
|
76
|
+
</body>
|
|
77
|
+
</html>`}function oauthSuccessHtml(message){return renderPage({title:"Authentication successful",heading:"Authentication successful",message})}function oauthErrorHtml(message,details){return renderPage({title:"Authentication failed",heading:"Authentication failed",message,details})}var import_proper_lockfile=__toESM(require_proper_lockfile(),1);var CALLBACK_HOST="127.0.0.1",CALLBACK_PATH="/callback",CLIENT_METADATA_BASE_URL="https://pi.dev/oauth",FALLBACK_REDIRECT_URL=`http://${CALLBACK_HOST}${CALLBACK_PATH}`,REFRESH_SKEW_MS=3e4,REFRESH_REQUEST_TIMEOUT_MS=15e3,REFRESH_LOCK_STALE_MS=2e4,REFRESH_LOCK_WAIT_MS=25e3,REFRESH_LOCK_RETRY_MS=100;function callbackSettings(settings){let url=new URL(settings.callbackUrl??`http://${CALLBACK_HOST}${CALLBACK_PATH}`),address=url.hostname.replace(/^\[|\]$/g,""),port=url.port?Number(url.port):settings.callbackPort,fixedRedirectUrl;return url.port?fixedRedirectUrl=settings.callbackUrl:port!==void 0&&(url.port=String(port),fixedRedirectUrl=url.href),{host:address==="localhost"?CALLBACK_HOST:address,redirectHost:address,port,path:url.pathname,fixedRedirectUrl}}function mergeScopes(...scopes){let merged=[...new Set(scopes.flatMap(scope=>scope?.split(/\s+/).filter(Boolean)??[]))];return merged.length>0?merged.join(" "):void 0}function parseStates(content){if(!content?.trim())return{};let parsed=JSON.parse(content);return typeof parsed=="object"&&parsed!==null&&!Array.isArray(parsed)?parsed:{}}function serializeStates(states){return`${JSON.stringify(states,null,2)}
|
|
78
|
+
`}function storeKeys(name,serverUrl){let legacyKey=String(new URL(serverUrl));return{key:`${mcpNamespace(name)}|${legacyKey}`,legacyKey}}var McpOAuthCredentialStore=class{backend;lockDir;constructor(backend,lockDir){this.backend=backend??new FileAuthStorageBackend(join(getAgentDir(),"mcp-auth.json")),this.lockDir=backend?lockDir:getAgentDir()}forServer(name,serverUrl){let{key,legacyKey}=storeKeys(name,serverUrl);return{load:()=>this.backend.withLock(current=>{let states=parseStates(current);return states[key]||!states[legacyKey]?{result:states[key]}:(states[key]=states[legacyKey],delete states[legacyKey],{result:states[key],next:serializeStates(states)})}),save:state=>this.write(states=>{states[key]=state}),withRefreshLock:fn=>this.withRefreshLock(key,fn)}}async withRefreshLock(key,fn){if(!this.lockDir)return fn();mkdirSync(this.lockDir,{recursive:!0,mode:448});let hash=createHash("sha256").update(key).digest("hex").slice(0,16),release=await import_proper_lockfile.default.lock(join(this.lockDir,`mcp-auth-refresh-${hash}`),{realpath:!1,stale:REFRESH_LOCK_STALE_MS,retries:{retries:REFRESH_LOCK_WAIT_MS/REFRESH_LOCK_RETRY_MS,factor:1,minTimeout:REFRESH_LOCK_RETRY_MS,maxTimeout:REFRESH_LOCK_RETRY_MS},onCompromised:()=>{}});try{return await fn()}finally{await release().catch(()=>{})}}tokens(name,serverUrl){let{key,legacyKey}=storeKeys(name,serverUrl),states=this.backend.withLock(current=>({result:parseStates(current)}));return(states[key]??states[legacyKey])?.tokens}remove(name,serverUrl){let{key,legacyKey}=storeKeys(name,serverUrl);return this.backend.withLock(current=>{let states=parseStates(current),stored=key in states?key:legacyKey in states?legacyKey:void 0;return stored?(delete states[stored],{result:!0,next:serializeStates(states)}):{result:!1}})}write(update){this.backend.withLock(current=>{let states=parseStates(current);return update(states),{result:void 0,next:serializeStates(states)}})}};function registeredRedirectUrls(client){return client&&"redirect_uris"in client?client.redirect_uris:[]}function callbackId(serverUrl){let url=new URL(serverUrl);return url.hash="",createHash("sha256").update(url.href).digest().subarray(0,9).toString("base64url")}function clientMetadataDocument(serverUrl,redirectUrl,metadata){if(!metadata?.client_id_metadata_document_supported||!metadata.token_endpoint_auth_methods_supported?.includes("none"))throw new Error('The authorization server does not support Client ID Metadata Documents for public clients; remove oauth.clientRegistration "cimd"');if(metadata.authorization_response_iss_parameter_supported)return{url:`${CLIENT_METADATA_BASE_URL}/client.json`,redirectUrl};let id=callbackId(serverUrl),redirect=new URL(redirectUrl);return redirect.pathname=`${CALLBACK_PATH}/${id}`,{url:`${CLIENT_METADATA_BASE_URL}/${id}/client.json`,redirectUrl:redirect.href}}function createProvider(serverUrl,store,settings,redirectUrl,onRedirect){return new McpOAuthProvider({serverUrl,redirectUrl,clientMetadata:{client_name:settings.clientName??APP_NAME},clientMetadataDocument:settings.clientRegistration==="cimd"?metadata=>clientMetadataDocument(serverUrl,redirectUrl,metadata):void 0,clientId:settings.clientId,clientSecret:settings.clientSecret,store,onRedirect})}function createMcpAuthProvider(options){let{serverUrl,store}=options,refreshing,refresh=(staleToken,fetch=globalThis.fetch,challenge)=>(refreshing??=store.withRefreshLock(async()=>{let state=await store.load();if(state?.tokens?.access_token!==staleToken)return;if(!state?.tokens?.refresh_token)throw new McpOAuthAuthorizationRequiredError;let settings=options.settings(),redirectUrl=callbackSettings(settings).fixedRedirectUrl??registeredRedirectUrls(state.clientInformation)[0]??FALLBACK_REDIRECT_URL,provider=createProvider(serverUrl,store,settings,redirectUrl,()=>{});if(await authorizeMcp(provider,{serverUrl,resourceMetadataUrl:challenge?.resourceMetadataUrl,authorizationServerMetadataUrl:settings.authServerMetadataUrl,scope:challenge?.scope,fetch:(input,init)=>fetch(input,{...init,signal:AbortSignal.timeout(REFRESH_REQUEST_TIMEOUT_MS)})})==="REDIRECT")throw new McpOAuthAuthorizationRequiredError}).finally(()=>{refreshing=void 0}),refreshing);return{token:async()=>{await refreshing?.catch(()=>{});let state=await store.load(),token=state?.tokens?.access_token;return!(state?.tokensExpireAt!==void 0&&state.tokensExpireAt-REFRESH_SKEW_MS<=Date.now())||!state?.tokens?.refresh_token?token:(await refresh(token).catch(()=>{}),(await store.load())?.tokens?.access_token)},onUnauthorized:async context=>{let challenge=parseWwwAuthenticate(context.response.headers.get("www-authenticate"));if(options.onChallenge(challenge),challenge.error==="insufficient_scope")throw new McpOAuthAuthorizationRequiredError;await refresh(context.token,context.fetch,challenge)},settled:async()=>{await refreshing?.catch(()=>{})}}}var McpSignInCancelledError=class extends Error{constructor(){super("Sign-in cancelled"),this.name="McpSignInCancelledError"}};function responseFromRedirectUrl(input,state,redirectUrl){let url;try{url=new URL(input.trim())}catch{throw new Error("Expected the full redirect URL from the browser address bar")}if(url.origin!==redirectUrl.origin||url.pathname!==redirectUrl.pathname)throw new Error("The redirect URL does not match this sign-in's redirect URI");let error=url.searchParams.get("error");if(error)throw new Error(url.searchParams.get("error_description")??error);if(url.searchParams.get("state")!==state)throw new Error("The redirect URL belongs to a different sign-in");let code=url.searchParams.get("code");if(!code)throw new Error("The redirect URL does not contain an authorization code");return{code,iss:url.searchParams.get("iss")??void 0}}async function waitForAuthorizationResponse(callback,state,redirectUrl,prompt){let controller=new AbortController,fromBrowser=callback.waitForCallback(state,redirectUrl.pathname),fromUser=prompt.promptForRedirectUrl(controller.signal).then(input=>{if(!input?.trim())throw new McpSignInCancelledError;return responseFromRedirectUrl(input,state,redirectUrl)});try{return await Promise.race([fromBrowser,fromUser])}finally{controller.abort(),fromBrowser.catch(()=>{}),fromUser.catch(()=>{})}}async function listenForCallback(settings,extraPaths,port,required){let options={host:settings.host,redirectHost:settings.redirectHost,path:settings.path,extraPaths,renderPage:page=>page.ok?oauthSuccessHtml("Signed in to the MCP server. You may now close this page."):oauthErrorHtml(page.message,page.details)};try{return await OAuthCallbackServer.listen({...options,port:port??0})}catch(error){if(required||port===void 0)throw error;return OAuthCallbackServer.listen(options)}}async function signInMcpServer(options){let{serverUrl,store,settings}=options,stored=await store.load(),stepUp=options.challenge?.error==="insufficient_scope",callbackOptions=callbackSettings(settings),registered=registeredRedirectUrls(stored?.clientInformation)[0],preferredPort=callbackOptions.port??(registered&&Number(new URL(registered).port)||void 0),cimd=settings.clientRegistration==="cimd",callback=await listenForCallback(callbackOptions,cimd?[`${CALLBACK_PATH}/${callbackId(serverUrl)}`]:[],preferredPort,callbackOptions.port!==void 0),redirectUrl=callbackOptions.fixedRedirectUrl??callback.redirectUrl;try{if(stored){let next={...stored};delete next.oauthState,settings.clientId||(cimd?!stored.clientInformation:registeredRedirectUrls(stored.clientInformation).includes(redirectUrl))||(delete next.clientInformation,delete next.tokens,delete next.tokensExpireAt),await store.save(next)}let authorizationUrl,provider=createProvider(serverUrl,store,settings,redirectUrl,url=>{authorizationUrl=url}),flow={serverUrl,resourceMetadataUrl:options.challenge?.resourceMetadataUrl,authorizationServerMetadataUrl:settings.authServerMetadataUrl,scope:mergeScopes(settings.scope,stepUp?stepUpScope(stored?.tokens?.scope,options.challenge?.scope):options.challenge?.scope)};if(await authorizeMcp(provider,{...flow,skipRefresh:stepUp})==="AUTHORIZED")return;if(!authorizationUrl)throw new Error("OAuth flow did not produce an authorization URL");let state=await provider.state(),authorizationRedirectUrl=new URL(authorizationUrl.searchParams.get("redirect_uri")??redirectUrl);options.prompt.showAuthorizationUrl(authorizationUrl);let{code,iss}=await waitForAuthorizationResponse(callback,state,authorizationRedirectUrl,options.prompt);await authorizeMcp(provider,{...flow,authorizationCode:code,iss})}finally{await callback.close()}}import{appendFileSync,mkdirSync as mkdirSync2,renameSync,statSync}from"node:fs";import{dirname}from"node:path";var MAX_LOG_BYTES=5*1024*1024;function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function formatData(data){if(typeof data=="string")return data;try{return JSON.stringify(data)??String(data)}catch{return String(data)}}function formatMcpLogMessage(server,params,now=new Date){let message=isRecord(params)?params:{data:params},level=typeof message.level=="string"?message.level:"info",logger=typeof message.logger=="string"&&message.logger?` ${message.logger}:`:"",text=formatData(message.data).replace(/\r?\n/g,`
|
|
79
|
+
`);return`${now.toISOString()} [${server}] ${level}${logger} ${text}
|
|
80
|
+
`}var McpServerLog=class{path;size;constructor(path){this.path=path}write(server,params){let line=formatMcpLogMessage(server,params);try{this.size===void 0&&(mkdirSync2(dirname(this.path),{recursive:!0}),this.size=this.currentSize()),this.size>MAX_LOG_BYTES&&(this.currentSize()>MAX_LOG_BYTES&&renameSync(this.path,`${this.path}.1`),this.size=this.currentSize()),appendFileSync(this.path,line),this.size+=Buffer.byteLength(line)}catch{}}currentSize(){try{return statSync(this.path).size}catch{return 0}}};var DEFAULT_TIMEOUT_SECONDS=60,STDERR_TAIL_CHARS=2e3,CONNECT_RETRY_DELAYS_MS=[250,1e3];function errorMessage(error){return error instanceof Error?error.message:String(error)}function isTransientError(error){return error instanceof McpHttpError?error.status===408||error.status===429||error.status>=500&&error.status!==501:error instanceof TypeError}function signInRequiredMessage(entry){let provider="url"in entry.config?entry.config.auth?.provider:void 0;return`MCP server "${entry.name}" requires sign-in. Run ${provider?`/login ${provider}`:"/mcp"} to sign in.`}function usesOAuth(entry){let{config}=entry;return!("url"in config)||config.auth?!1:!Object.keys(config.headers??{}).some(header=>header.toLowerCase()==="authorization")}function expandHome(value){return value==="~"?homedir():value.startsWith("~/")||process.platform==="win32"&&value.startsWith("~\\")?join2(homedir(),value.slice(2)):value}function createDefaultTransport(entry,cwd,authProvider){let{config,name}=entry;if("url"in config)return new StreamableHttpTransport({url:config.url,headers:resolveHeadersOrThrow(config.headers,`MCP server "${name}"`),authProvider});let env={};for(let[key,value]of Object.entries(config.env??{}))env[key]=resolveConfigValueOrThrow(value,`MCP server "${name}" env "${key}"`);return new StdioTransport({command:expandHome(config.command),args:config.args?.map(expandHome),cwd:resolve(cwd,expandHome(config.cwd??".")),env,stderr:"pipe"})}async function withoutTemplates(list,empty){try{return await list()}catch(error){if(error instanceof McpError&&error.code===JSON_RPC_ERROR_CODES.methodNotFound)return empty;throw error}}function listTemplates(client,options={}){return withoutTemplates(()=>client.listResourceTemplates(options),[])}async function fetchResources(client){let[resources,resourceTemplates]=await Promise.all([client.listResources().catch(()=>[]),listTemplates(client).catch(()=>[])]);return{resources:resources.filter(resource=>!isMcpAppResource(resource)),resourceTemplates:resourceTemplates.filter(template=>!isMcpAppResource(template))}}var McpServerConnection=class{entry;state="connecting";error;tools=[];hasResources=!1;resources=[];resourceTemplates=[];instructions;challenge;client;opening;closed=!1;stderrTail;cwd;createTransport;authProvider;onTools;onChange;log;constructor(options){this.entry=options.entry,this.cwd=options.cwd,this.createTransport=options.createTransport,this.onTools=options.onTools,this.onChange=options.onChange,this.log=options.log;let url=this.oauthUrl,provider="url"in this.entry.config?this.entry.config.auth?.provider:void 0;this.authProvider=url?createMcpAuthProvider({serverUrl:url,store:options.credentials.forServer(this.entry.name,url),settings:()=>this.oauthSettings(),onChallenge:challenge=>{this.challenge=challenge}}):provider?{token:async()=>options.providerToken?.(provider),settled:async()=>{}}:void 0}get name(){return this.entry.name}get timeoutMs(){return(this.entry.config.timeout??DEFAULT_TIMEOUT_SECONDS)*1e3}get oauthUrl(){return usesOAuth(this.entry)&&"url"in this.entry.config?this.entry.config.url:void 0}oauthSettings(){let oauth="url"in this.entry.config?this.entry.config.oauth:void 0;return oauth?{clientId:oauth.clientId,clientSecret:oauth.clientSecret===void 0?void 0:resolveConfigValueOrThrow(oauth.clientSecret,`MCP server "${this.entry.name}" oauth.clientSecret`),callbackPort:oauth.callbackPort,callbackUrl:oauth.callbackUrl,scope:oauth.scope,clientName:oauth.clientName,clientRegistration:oauth.clientRegistration,authServerMetadataUrl:oauth.authServerMetadataUrl?new URL(oauth.authServerMetadataUrl):void 0}:{}}getClient(){return this.closed?Promise.reject(new Error(`MCP server "${this.entry.name}" is shut down`)):this.client?.connectionState==="connected"?Promise.resolve(this.client):(this.opening??=this.open().finally(()=>{this.opening=void 0}),this.opening)}callTool(name,args,options){return this.withClient(client=>client.callTool(name,args,options))}readResource(uri,options){return this.withClient(client=>client.readResource(uri,options),!0)}resourcesPage(cursor,options){return this.withClient(client=>client.listResourcesPage(cursor,options),!0)}resourceTemplatesPage(cursor,options){return this.withClient(client=>withoutTemplates(()=>client.listResourceTemplatesPage(cursor,options),{resourceTemplates:[]}),!0)}allResources(options){return this.withClient(client=>client.listResources(options),!0)}allResourceTemplates(options){return this.withClient(client=>listTemplates(client,options),!0)}async withClient(run,readOnly=!1){for(let attempt=1;;attempt++){let client=await this.getClient();try{return await run(client)}catch(error){if(readOnly&&attempt===1&&error instanceof McpHttpError&&isTransientError(error)){await new Promise(resolve2=>setTimeout(resolve2,CONNECT_RETRY_DELAYS_MS[0]));continue}if(error instanceof McpSessionExpiredError&&attempt===1){this.client===client&&(this.client=void 0);continue}throw this.needsSignIn(error)?(await this.dropClient(client),this.markNeedsAuth(),new Error(signInRequiredMessage(this.entry))):error}}}async reconnect(){await this.opening?.catch(()=>{}),this.client&&await this.dropClient(this.client),await this.getClient()}async signOut(){await this.opening?.catch(()=>{}),this.client&&await this.dropClient(this.client),this.closed||this.markNeedsAuth()}needsSignIn(error){return error instanceof McpOAuthAuthorizationRequiredError||this.authProvider!==void 0&&error instanceof McpAuthRequiredError}markNeedsAuth(){this.state="needs-auth",this.error=void 0,this.changed()}changed(){this.onChange?.(this)}async dropClient(client){this.client===client&&(this.client=void 0),await client.close().catch(()=>{})}async open(){this.state="connecting",this.changed();let retries="url"in this.entry.config?CONNECT_RETRY_DELAYS_MS:[];for(let attempt=0;;attempt++){this.stderrTail=void 0;try{return await this.connectOnce()}catch(error){let delay=retries[attempt];if(this.closed||delay===void 0||!isTransientError(error))throw this.connectFailed(error);if(await new Promise(resolve2=>setTimeout(resolve2,delay)),this.closed)throw this.connectFailed(error)}}}async connectOnce(){let client=new McpClient({name:"pi",version:VERSION,requestTimeoutMs:this.timeoutMs,roots:[{uri:pathToFileURL(this.cwd).href,name:basename(this.cwd)}]}),log=this.log;log&&client.onNotification("notifications/message",params=>log.write(this.entry.name,params));let transport;try{transport=this.createTransport(this.entry,this.cwd,this.authProvider),await client.connect(transport),client.onNotification("notifications/tools/list_changed",()=>{this.refreshTools(client)}),client.onNotification("notifications/resources/list_changed",()=>{this.refreshResources(client)});let stdio=transport instanceof StdioTransport?transport:void 0;client.onClose(()=>this.handleClientClose(client,stdio));let hasResources=client.serverCapabilities?.resources!==void 0,[tools,resources]=await Promise.all([client.serverCapabilities?.tools?client.listTools():[],hasResources?fetchResources(client):{resources:[],resourceTemplates:[]}]);if(this.closed)throw new Error("shut down while connecting");if(client.connectionState!=="connected")throw new Error("connection closed during setup");return this.client=client,this.tools=tools,this.hasResources=hasResources,this.resources=resources.resources,this.resourceTemplates=resources.resourceTemplates,this.instructions=client.instructions?.trim()||void 0,this.state="connected",this.error=void 0,this.onTools(this),this.changed(),client}catch(error){throw await client.close().catch(()=>{}),transport instanceof StdioTransport&&(this.stderrTail=transport.stderr.trim().slice(-STDERR_TAIL_CHARS)||void 0),error}}connectFailed(error){return this.needsSignIn(error)&&!this.closed?(this.markNeedsAuth(),new Error(signInRequiredMessage(this.entry))):(this.state=this.closed?"closed":"failed",this.error=this.stderrTail?`${errorMessage(error)}
|
|
81
|
+
${this.stderrTail}`:errorMessage(error),this.changed(),new Error(`MCP server "${this.entry.name}" failed to connect: ${this.error}`))}handleClientClose(client,stdio){if(this.client!==client||this.closed)return;this.client=void 0,this.state="disconnected";let stderr=stdio?.stderr.trim().slice(-STDERR_TAIL_CHARS);this.error=stderr?`Connection closed
|
|
82
|
+
${stderr}`:"Connection closed",this.changed()}async refreshTools(client){try{let tools=await client.listTools();if(this.client!==client||this.closed)return;this.tools=tools,this.onTools(this)}catch(error){this.error=`Failed to refresh tools: ${errorMessage(error)}`}this.changed()}async refreshResources(client){let{resources,resourceTemplates}=await fetchResources(client);this.client!==client||this.closed||(this.resources=resources,this.resourceTemplates=resourceTemplates,this.onTools(this),this.changed())}async close(){this.closed=!0,this.state="closed",this.changed();let client=this.client;this.client=void 0,await client?.close().catch(()=>{}),await this.authProvider?.settled()}};export{McpOAuthCredentialStore,McpSignInCancelledError,signInMcpServer,McpServerLog,createDefaultTransport,McpServerConnection};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{mcpNamespace,require_proper_lockfile,validateMcpServerConfig}from"./chunk-
|
|
3
|
-
`,"utf-8")}function acquireTrustLockSync(path){let trustDir=dirname(path);mkdirSync(trustDir,{recursive:!0});let maxAttempts=10,delayMs=20,lastError;for(let attempt=1;attempt<=maxAttempts;attempt++)try{return import_proper_lockfile.default.lockSync(trustDir,{realpath:!1,lockfilePath:`${path}.lock`})}catch(error){if((typeof error=="object"&&error!==null&&"code"in error?String(error.code):void 0)!=="ELOCKED"||attempt===maxAttempts)throw error;lastError=error;let start=Date.now();for(;Date.now()-start<delayMs;);}throw lastError instanceof Error?lastError:new Error("Failed to acquire trust store lock")}function withTrustFileLock(path,fn){let release=acquireTrustLockSync(path);try{return fn()}finally{release()}}function hasTrustRequiringProjectResources(cwd){let homeDir=canonicalizePath(resolvePath(process.env.HOME||homedir())),userAgentsSkillsDir=join(homeDir,".agents","skills"),currentDir=canonicalizePath(resolvePath(cwd)),configDir=join(currentDir,CONFIG_DIR_NAME);if(TRUST_REQUIRING_PROJECT_CONFIG_RESOURCES.some(entry=>existsSync(join(configDir,entry))))return!0;for(;;){let agentsSkillsDir=join(currentDir,".agents","skills");if(agentsSkillsDir!==userAgentsSkillsDir&&existsSync(agentsSkillsDir))return!0;let parentDir=dirname(currentDir);if(parentDir===currentDir)return!1;currentDir=parentDir}}var ProjectTrustStore=class{trustPath;constructor(agentDir){this.trustPath=join(resolvePath(agentDir),"trust.json")}get(cwd){return this.getEntry(cwd)?.decision??null}getEntry(cwd){return withTrustFileLock(this.trustPath,()=>{let data=readTrustFile(this.trustPath);return findNearestTrustEntry(data,cwd)})}set(cwd,decision){this.setMany([{path:cwd,decision}])}setMany(decisions){withTrustFileLock(this.trustPath,()=>{let data=readTrustFile(this.trustPath);for(let{path,decision}of decisions){let key=normalizeCwd(path);decision===null?delete data[key]:data[key]=decision}writeTrustFile(this.trustPath,data)})}};import{spawn}from"node:child_process";function openBrowser(target){let[cmd,args]=process.platform==="darwin"?["open",[target]]:process.platform==="win32"?["rundll32",["url.dll,FileProtocolHandler",target]]:["xdg-open",[target]];spawn(cmd,args,{stdio:"ignore",detached:!0}).on("error",()=>{}).unref()}import{existsSync as existsSync2,mkdirSync as mkdirSync2,readFileSync as readFileSync2,writeFileSync as writeFileSync2}from"node:fs";import{dirname as dirname2,join as join2}from"node:path";function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function readConfigFile(path,scope,state){let{servers,errors}=state;if(!existsSync2(path))return;let parsed;try{parsed=JSON.parse(readFileSync2(path,"utf8"))}catch(error){errors.push(`${path}: ${error instanceof Error?error.message:String(error)}`);return}if(!isRecord(parsed)||parsed.mcpServers!==void 0&&!isRecord(parsed.mcpServers)){errors.push(`${path}: expected an object with an "mcpServers" object`);return}typeof parsed.autoEnableCodemode=="boolean"?state.autoEnableCodemode=parsed.autoEnableCodemode:parsed.autoEnableCodemode!==void 0&&errors.push(`${path}: autoEnableCodemode must be a boolean`);for(let[name,value]of Object.entries(parsed.mcpServers??{})){let config=validateMcpServerConfig(name,value);if(typeof config=="string"){errors.push(`${path}: ${config}`);continue}let clash=[...servers.keys()].find(other=>other!==name&&mcpNamespace(other)===mcpNamespace(name));if(clash){errors.push(`${path}: server "${name}" conflicts with "${clash}"`);continue}if(scope==="project"&&"url"in config&&config.auth){errors.push(`${path}: server "${name}": auth is only allowed in the global mcp.json`);continue}servers.set(name,{name,config,source:path,scope})}}function loadMcpConfig(options){let state={servers:new Map,errors:[]};
|
|
2
|
+
import{mcpNamespace,require_proper_lockfile,validateMcpServerConfig}from"./chunk-PDFMCAOZ.js";import{CONFIG_DIR_NAME,canonicalizePath,resolvePath,stripBom}from"./chunk-6FX7UEPL.js";import{__toESM}from"./chunk-4L3WN2XY.js";var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import{existsSync,mkdirSync,readFileSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{dirname,join}from"node:path";var TRUST_REQUIRING_PROJECT_CONFIG_RESOURCES=["settings.json","mcp.json","extensions","skills","prompts","themes","SYSTEM.md","APPEND_SYSTEM.md"];function normalizeCwd(cwd){return canonicalizePath(resolvePath(cwd))}function findNearestTrustEntry(data,cwd){let currentDir=normalizeCwd(cwd);for(;;){let value=data[currentDir];if(value===!0||value===!1)return{path:currentDir,decision:value};let parentDir=dirname(currentDir);if(parentDir===currentDir)return null;currentDir=parentDir}}function getProjectTrustParentPath(cwd){let trustPath=normalizeCwd(cwd),parentDir=dirname(trustPath);return parentDir===trustPath?void 0:parentDir}function getProjectTrustOptions(cwd,options){let trustPath=normalizeCwd(cwd),trustOptions=[{label:"Trust",trusted:!0,updates:[{path:trustPath,decision:!0}],savedPath:trustPath}],parentPath=getProjectTrustParentPath(cwd);return parentPath!==void 0&&trustOptions.push({label:`Trust parent folder (${parentPath})`,trusted:!0,updates:[{path:parentPath,decision:!0},{path:trustPath,decision:null}],savedPath:parentPath}),options?.includeSessionOnly&&trustOptions.push({label:"Trust (this session only)",trusted:!0,updates:[]}),trustOptions.push({label:"Do not trust",trusted:!1,updates:[{path:trustPath,decision:!1}],savedPath:trustPath}),options?.includeSessionOnly&&trustOptions.push({label:"Do not trust (this session only)",trusted:!1,updates:[]}),trustOptions}function readTrustFile(path){if(!existsSync(path))return{};let parsed;try{parsed=JSON.parse(stripBom(readFileSync(path,"utf-8")))}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`Failed to read trust store ${path}: ${message}`)}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))throw new Error(`Invalid trust store ${path}: expected an object`);let data={};for(let[key,value]of Object.entries(parsed)){if(value!==!0&&value!==!1&&value!==null)throw new Error(`Invalid trust store ${path}: value for ${JSON.stringify(key)} must be true, false, or null`);data[key]=value}return data}function writeTrustFile(path,data){let sorted={};for(let key of Object.keys(data).sort()){let value=data[key];(value===!0||value===!1||value===null)&&(sorted[key]=value)}mkdirSync(dirname(path),{recursive:!0}),writeFileSync(path,`${JSON.stringify(sorted,null,2)}
|
|
3
|
+
`,"utf-8")}function acquireTrustLockSync(path){let trustDir=dirname(path);mkdirSync(trustDir,{recursive:!0});let maxAttempts=10,delayMs=20,lastError;for(let attempt=1;attempt<=maxAttempts;attempt++)try{return import_proper_lockfile.default.lockSync(trustDir,{realpath:!1,lockfilePath:`${path}.lock`})}catch(error){if((typeof error=="object"&&error!==null&&"code"in error?String(error.code):void 0)!=="ELOCKED"||attempt===maxAttempts)throw error;lastError=error;let start=Date.now();for(;Date.now()-start<delayMs;);}throw lastError instanceof Error?lastError:new Error("Failed to acquire trust store lock")}function withTrustFileLock(path,fn){let release=acquireTrustLockSync(path);try{return fn()}finally{release()}}function hasTrustRequiringProjectResources(cwd){let homeDir=canonicalizePath(resolvePath(process.env.HOME||homedir())),userAgentsSkillsDir=join(homeDir,".agents","skills"),currentDir=canonicalizePath(resolvePath(cwd)),configDir=join(currentDir,CONFIG_DIR_NAME);if(TRUST_REQUIRING_PROJECT_CONFIG_RESOURCES.some(entry=>existsSync(join(configDir,entry))))return!0;for(;;){let agentsSkillsDir=join(currentDir,".agents","skills");if(agentsSkillsDir!==userAgentsSkillsDir&&existsSync(agentsSkillsDir))return!0;let parentDir=dirname(currentDir);if(parentDir===currentDir)return!1;currentDir=parentDir}}var ProjectTrustStore=class{trustPath;constructor(agentDir){this.trustPath=join(resolvePath(agentDir),"trust.json")}get(cwd){return this.getEntry(cwd)?.decision??null}getEntry(cwd){return withTrustFileLock(this.trustPath,()=>{let data=readTrustFile(this.trustPath);return findNearestTrustEntry(data,cwd)})}set(cwd,decision){this.setMany([{path:cwd,decision}])}setMany(decisions){withTrustFileLock(this.trustPath,()=>{let data=readTrustFile(this.trustPath);for(let{path,decision}of decisions){let key=normalizeCwd(path);decision===null?delete data[key]:data[key]=decision}writeTrustFile(this.trustPath,data)})}};import{spawn}from"node:child_process";function openBrowser(target){let[cmd,args]=process.platform==="darwin"?["open",[target]]:process.platform==="win32"?["rundll32",["url.dll,FileProtocolHandler",target]]:["xdg-open",[target]];spawn(cmd,args,{stdio:"ignore",detached:!0}).on("error",()=>{}).unref()}import{existsSync as existsSync2,mkdirSync as mkdirSync2,readFileSync as readFileSync2,writeFileSync as writeFileSync2}from"node:fs";import{dirname as dirname2,join as join2}from"node:path";var OVERRIDE_KEYS=["enabled","exposure","toolExposure"];function isOverride(value){return value.command===void 0&&value.url===void 0&&value.type===void 0}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function readConfigFile(path,scope,state){let{servers,errors}=state;if(!existsSync2(path))return;let parsed;try{parsed=JSON.parse(readFileSync2(path,"utf8"))}catch(error){errors.push(`${path}: ${error instanceof Error?error.message:String(error)}`);return}if(!isRecord(parsed)||parsed.mcpServers!==void 0&&!isRecord(parsed.mcpServers)){errors.push(`${path}: expected an object with an "mcpServers" object`);return}typeof parsed.autoEnableCodemode=="boolean"?state.autoEnableCodemode=parsed.autoEnableCodemode:parsed.autoEnableCodemode!==void 0&&errors.push(`${path}: autoEnableCodemode must be a boolean`);for(let[name,value]of Object.entries(parsed.mcpServers??{})){if(scope==="project"&&isRecord(value)&&isOverride(value)){let base=servers.get(name),extra=Object.keys(value).filter(key=>!OVERRIDE_KEYS.includes(key));if(!base)errors.push(`${path}: server "${name}" needs "command" or "url", or a global server to override`);else if(extra.length>0)errors.push(`${path}: server "${name}": an override can only set ${OVERRIDE_KEYS.join(", ")}`);else{let config2=validateMcpServerConfig(name,{...base.config,...value});typeof config2=="string"?errors.push(`${path}: ${config2}`):servers.set(name,{...base,config:config2,override:path})}continue}let config=validateMcpServerConfig(name,value);if(typeof config=="string"){errors.push(`${path}: ${config}`);continue}let clash=[...servers.keys()].find(other=>other!==name&&mcpNamespace(other)===mcpNamespace(name));if(clash){errors.push(`${path}: server "${name}" conflicts with "${clash}"`);continue}if(scope==="project"&&"url"in config&&config.auth){errors.push(`${path}: server "${name}": auth is only allowed in the global mcp.json`);continue}servers.set(name,{name,config,source:path,scope})}}function loadMcpConfig(options){let state={servers:new Map,errors:[]};readConfigFile(join2(options.agentDir,"mcp.json"),"global",state);let projectConfig=options.projectTrusted?join2(options.cwd,CONFIG_DIR_NAME,"mcp.json"):void 0;return projectConfig&&readConfigFile(projectConfig,"project",state),{servers:[...state.servers.values()],...state.autoEnableCodemode===void 0?{}:{autoEnableCodemode:state.autoEnableCodemode},errors:state.errors,...projectConfig?{projectConfig}:{}}}function updateMcpServerConfig(path,name,patch,options={}){editMcpServers(path,(servers,parsed)=>{let server=servers?.[name];if(server===void 0&&options.override&&(server={},parsed.mcpServers={...servers,[name]:server}),!isRecord(server))throw new Error(`${path} does not define MCP server "${name}"`);let keepDefaults=isOverride(server);return patch.enabled!==void 0&&(patch.enabled&&!keepDefaults?delete server.enabled:server.enabled=patch.enabled),patch.exposure!==void 0&&(patch.exposure==="codemode"&&!keepDefaults?delete server.exposure:server.exposure=patch.exposure),!0})}function addMcpServerConfig(path,name,config){let replaced=!1;return editMcpServers(path,(servers,parsed)=>{let target=servers??{};return replaced=target[name]!==void 0,target[name]=config,parsed.mcpServers=target,!0}),replaced}function removeMcpServerConfig(path,name){if(!existsSync2(path))return!1;let removed=!1;return editMcpServers(path,servers=>!servers||servers[name]===void 0?!1:(delete servers[name],removed=!0,!0)),removed}function editMcpServers(path,edit){let text=existsSync2(path)?readFileSync2(path,"utf8"):void 0,parsed=text===void 0?{}:JSON.parse(text);if(!isRecord(parsed)||parsed.mcpServers!==void 0&&!isRecord(parsed.mcpServers))throw new Error(`${path}: expected an object with an "mcpServers" object`);let servers=isRecord(parsed.mcpServers)?parsed.mcpServers:void 0;if(!edit(servers,parsed))return;let indent=text&&/^([ \t]+)\S/m.exec(text)?.[1]||" ";mkdirSync2(dirname2(path),{recursive:!0}),writeFileSync2(path,`${JSON.stringify(parsed,null,indent)}
|
|
4
4
|
`)}export{getProjectTrustOptions,hasTrustRequiringProjectResources,ProjectTrustStore,openBrowser,loadMcpConfig,updateMcpServerConfig,addMcpServerConfig,removeMcpServerConfig};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{McpOAuthCredentialStore,McpServerConnection,McpServerLog,McpSignInCancelledError,createDefaultTransport,signInMcpServer}from"./chunk-
|
|
2
|
+
import{McpOAuthCredentialStore,McpServerConnection,McpServerLog,McpSignInCancelledError,createDefaultTransport,signInMcpServer}from"./chunk-WCQZGZ6I.js";import{ProjectTrustStore,addMcpServerConfig,loadMcpConfig,openBrowser,removeMcpServerConfig}from"./chunk-ZSI3BL5Q.js";import{getMcpToolExposure,validateMcpServerConfig}from"./chunk-PDFMCAOZ.js";import"./chunk-OYBSLV7Y.js";import{APP_NAME,CONFIG_DIR_NAME,source_default}from"./chunk-6FX7UEPL.js";import"./chunk-S3GGRYIO.js";import"./chunk-4L3WN2XY.js";import{existsSync}from"node:fs";import{join}from"node:path";import{createInterface}from"node:readline/promises";var HELP=`${source_default.bold("Usage:")}
|
|
3
3
|
${APP_NAME} mcp add <server> [options] -- <command> [args...]
|
|
4
4
|
${APP_NAME} mcp add <server> [options] --url <url>
|
|
5
5
|
${APP_NAME} mcp remove <server> [-l]
|
|
@@ -45,7 +45,7 @@ ${HELP_HINT}`),1):list(loaded,parsed.values.has("json"),untrustedNote,options,cr
|
|
|
45
45
|
${HELP_HINT}`),1;let entry=loaded.servers.find(server=>server.name===name);if(!entry)return error(`No MCP server named "${name}".${untrustedNote?` ${untrustedNote}`:""} Configured: ${loaded.servers.map(server=>server.name).join(", ")||"none"}.`),1;let connection=createConnection(entry,options,credentials),url=connection.oauthUrl;if(!url)return error(`MCP server "${name}" does not use OAuth. Only HTTP servers without an Authorization header do.`),1;if(command==="logout"){let removed=credentials.remove(name,url);return log(removed?`Signed out of MCP server "${name}".`:`No stored credentials for MCP server "${name}".`),0}let timeout=Number(parsed.values.get("timeout")??DEFAULT_LOGIN_TIMEOUT_SECONDS);if(!Number.isFinite(timeout)||timeout<=0)return error("--timeout must be a positive number of seconds."),1;try{return await login(entry,connection,url,timeout*1e3,options,credentials,log,error)}finally{await connection.close()}}default:return error(`Unknown mcp command "${command}".
|
|
46
46
|
${HELP_HINT}`),1}}function parsePairs(option,pairs,error){if(!pairs)return{};let record={};for(let pair of pairs){let separator=pair.indexOf("=");if(separator<=0){error(`--${option} expects KEY=VALUE, got "${pair}".`);return}record[pair.slice(0,separator)]=pair.slice(separator+1)}return record}function add(args,projectConfig,options,log,error){let usage=`Usage: ${APP_NAME} mcp add <server> [options] (--url <url> | -- <command> [args...])
|
|
47
47
|
${HELP_HINT}`,parsed=parseOptions(args,{local:"flag",url:"value",env:"list",cwd:"value",header:"list","bearer-token-env-var":"value","oauth-client-id":"value","oauth-client-secret":"value","oauth-callback-port":"value","oauth-client-name":"value",exposure:"value",description:"value"},error,2);if(!parsed)return 1;let{positional,values,lists}=parsed,[name,...command]=positional,url=values.get("url");if(!name||url===void 0==(command.length===0))return error(usage),1;let value=option=>{let found=values.get(option);return typeof found=="string"?found:void 0},exposure=value("exposure"),misplaced=(url===void 0?["header","bearer-token-env-var","oauth-client-id","oauth-client-secret","oauth-callback-port","oauth-client-name"]:["env","cwd"]).find(option=>values.has(option)||lists.has(option));if(misplaced)return error(`--${misplaced} only applies to ${url===void 0?"HTTP servers (--url)":"stdio servers"}.`),1;let config;if(typeof url=="string"){let headers=parsePairs("header",lists.get("header"),error);if(!headers)return 1;let bearer=value("bearer-token-env-var");bearer!==void 0&&(headers.Authorization=`Bearer \${${bearer}}`);let port=value("oauth-callback-port"),oauth={...value("oauth-client-id")===void 0?{}:{clientId:value("oauth-client-id")},...value("oauth-client-secret")===void 0?{}:{clientSecret:value("oauth-client-secret")},...port===void 0?{}:{callbackPort:Number(port)},...value("oauth-client-name")===void 0?{}:{clientName:value("oauth-client-name")}};config={url,...Object.keys(headers).length>0?{headers}:{},...Object.keys(oauth).length>0?{oauth}:{}}}else{let env=parsePairs("env",lists.get("env"),error);if(!env)return 1;let[executable,...commandArgs]=command;config={command:executable,...commandArgs.length>0?{args:commandArgs}:{},...Object.keys(env).length>0?{env}:{},...value("cwd")===void 0?{}:{cwd:value("cwd")}}}exposure!==void 0&&(config.exposure=exposure);let description=value("description");description!==void 0&&(config.description=description);let validated=validateMcpServerConfig(name,config);if(typeof validated=="string")return error(validated),1;let project=values.has("local"),path=project?projectConfig:join(options.agentDir,"mcp.json"),scope=project?"project":"global",replaced;try{replaced=addMcpServerConfig(path,name,validated)}catch(addError){return error(`Could not update ${path}: ${errorMessage(addError)}`),1}log(`${replaced?"Replaced":"Added"} ${scope} MCP server "${name}" in ${path}.`),project&&new ProjectTrustStore(options.agentDir).get(options.cwd)!==!0&&log(`The project is not trusted, so ${path} is ignored until you start ${APP_NAME} in the project and trust it.`);let mayNeedSignIn="url"in validated&&!Object.keys(validated.headers??{}).some(header=>header.toLowerCase()==="authorization");return log(`Check it with: ${APP_NAME} mcp list${mayNeedSignIn?`. If it requires sign-in: ${APP_NAME} mcp login ${name}`:""}`),0}function remove(args,projectConfig,options,log,error){let parsed=parseOptions(args,{local:"flag"},error);if(!parsed)return 1;let[name,...extra]=parsed.positional;if(!name||extra.length>0)return error(`Usage: ${APP_NAME} mcp remove <server> [-l]
|
|
48
|
-
${HELP_HINT}`),1;let project=parsed.values.has("local"),globalConfig=join(options.agentDir,"mcp.json"),path=project?projectConfig:globalConfig,scope=project?"project":"global",removed;try{removed=removeMcpServerConfig(path,name)}catch(removeError){return error(`Could not update ${path}: ${errorMessage(removeError)}`),1}if(removed)return log(`Removed ${scope} MCP server "${name}" from ${path}.`),0;let other=loadMcpConfig({agentDir:options.agentDir,cwd:options.cwd,projectTrusted:!0}).servers.find(server=>server.name===name&&server.scope!==scope);return error(`No ${scope} MCP server named "${name}" in ${path}.${other?` It is defined in ${other.source}${other.scope==="project"?"; use --local":"; omit --local"}.`:""}`),1}async function list(loaded,json,untrustedNote,options,credentials,log){let reports=await Promise.all(loaded.servers.map(async entry=>{let report={name:entry.name,scope:entry.scope??"global",source:entry.source,enabled:entry.config.enabled!==!1,exposure:entry.config.exposure??"codemode",transport:describeTransport(entry),state:"disabled",tools:[]};if(!report.enabled)return report;let connection=createConnection(entry,options,credentials);try{await connection.getClient()}catch{}report.state=connection.state,report.tools=connection.tools.map(tool=>tool.name);let overrides=connection.tools.flatMap(tool=>{let exposure=getMcpToolExposure(entry.config,tool.name);return exposure===report.exposure?[]:[[tool.name,exposure]]});return overrides.length>0&&(report.toolExposure=Object.fromEntries(overrides)),connection.hasResources&&(report.resources=connection.resources.length,report.resourceTemplates=connection.resourceTemplates.length),connection.state!=="connected"&&connection.error&&(report.error=connection.error),await connection.close(),report})),failed=loaded.errors.length>0||reports.some(report=>report.enabled&&report.state!=="connected");if(json)return log(JSON.stringify({servers:reports,errors:loaded.errors,...untrustedNote?{note:untrustedNote}:{}},null,2)),failed?1:0;reports.length===0&&loaded.errors.length===0&&log(`No MCP servers configured. Add them to ${join(options.agentDir,"mcp.json")} or .pi/mcp.json.`);for(let report of reports){let state=report.state==="connected"?`connected, ${report.tools.length} tool${report.tools.length===1?"":"s"}`:report.state==="needs-auth"?"needs sign-in":report.state;if(log(`${report.name}: ${state} (${report.exposure}, ${report.scope})`),log(` ${report.transport}`),report.state==="needs-auth"&&log(` sign in with: ${APP_NAME} mcp login ${report.name}`),report.tools.length>0){let tools=report.tools.map(tool=>{let exposure=report.toolExposure?.[tool];return exposure?`${tool} [${exposure}]`:tool});log(` tools: ${tools.join(", ")}`)}report.resources!==void 0&&log(` resources: ${report.resources}, URI templates: ${report.resourceTemplates??0}`),report.error&&log(` ${report.error.split(`
|
|
48
|
+
${HELP_HINT}`),1;let project=parsed.values.has("local"),globalConfig=join(options.agentDir,"mcp.json"),path=project?projectConfig:globalConfig,scope=project?"project":"global",removed;try{removed=removeMcpServerConfig(path,name)}catch(removeError){return error(`Could not update ${path}: ${errorMessage(removeError)}`),1}if(removed)return log(`Removed ${scope} MCP server "${name}" from ${path}.`),0;let other=loadMcpConfig({agentDir:options.agentDir,cwd:options.cwd,projectTrusted:!0}).servers.find(server=>server.name===name&&server.scope!==scope);return error(`No ${scope} MCP server named "${name}" in ${path}.${other?` It is defined in ${other.source}${other.scope==="project"?"; use --local":"; omit --local"}.`:""}`),1}async function list(loaded,json,untrustedNote,options,credentials,log){let reports=await Promise.all(loaded.servers.map(async entry=>{let report={name:entry.name,scope:entry.scope??"global",source:entry.source,...entry.override?{override:entry.override}:{},enabled:entry.config.enabled!==!1,exposure:entry.config.exposure??"codemode",transport:describeTransport(entry),state:"disabled",tools:[]};if(!report.enabled)return report;let connection=createConnection(entry,options,credentials);try{await connection.getClient()}catch{}report.state=connection.state,report.tools=connection.tools.map(tool=>tool.name);let overrides=connection.tools.flatMap(tool=>{let exposure=getMcpToolExposure(entry.config,tool.name);return exposure===report.exposure?[]:[[tool.name,exposure]]});return overrides.length>0&&(report.toolExposure=Object.fromEntries(overrides)),connection.hasResources&&(report.resources=connection.resources.length,report.resourceTemplates=connection.resourceTemplates.length),connection.state!=="connected"&&connection.error&&(report.error=connection.error),await connection.close(),report})),failed=loaded.errors.length>0||reports.some(report=>report.enabled&&report.state!=="connected");if(json)return log(JSON.stringify({servers:reports,errors:loaded.errors,...untrustedNote?{note:untrustedNote}:{}},null,2)),failed?1:0;reports.length===0&&loaded.errors.length===0&&log(`No MCP servers configured. Add them to ${join(options.agentDir,"mcp.json")} or .pi/mcp.json.`);for(let report of reports){let state=report.state==="connected"?`connected, ${report.tools.length} tool${report.tools.length===1?"":"s"}`:report.state==="needs-auth"?"needs sign-in":report.state;if(log(`${report.name}: ${state} (${report.exposure}, ${report.scope})`),log(` ${report.transport}`),report.override&&log(` project override: ${report.override}`),report.state==="needs-auth"&&log(` sign in with: ${APP_NAME} mcp login ${report.name}`),report.tools.length>0){let tools=report.tools.map(tool=>{let exposure=report.toolExposure?.[tool];return exposure?`${tool} [${exposure}]`:tool});log(` tools: ${tools.join(", ")}`)}report.resources!==void 0&&log(` resources: ${report.resources}, URI templates: ${report.resourceTemplates??0}`),report.error&&log(` ${report.error.split(`
|
|
49
49
|
`).join(`
|
|
50
50
|
`)}`)}for(let configError of loaded.errors)log(`config error: ${configError}`);return untrustedNote&&log(untrustedNote),failed?1:0}async function login(entry,connection,url,timeoutMs,options,credentials,log,error){let{name}=entry;try{return await connection.getClient(),log(`Already signed in to MCP server "${name}" (${connection.tools.length} tools).`),0}catch{if(connection.state!=="needs-auth")return error(`MCP server "${name}" failed to connect: ${connection.error??"unknown error"}`),1}let openUrl=options.openUrl??openBrowser,interactive=process.stdin.isTTY===!0&&options.openUrl===void 0;try{await signInMcpServer({serverUrl:url,store:credentials.forServer(name,url),settings:connection.oauthSettings(),challenge:connection.challenge,prompt:{showAuthorizationUrl:authorizationUrl=>{log(`Sign in to MCP server "${name}" in your browser:
|
|
51
51
|
${authorizationUrl.href}`),openUrl(authorizationUrl.href)},promptForRedirectUrl:signal=>waitForRedirectUrl(signal,timeoutMs,interactive)}})}catch(signInError){return error(signInError instanceof McpSignInCancelledError?`Sign-in to MCP server "${name}" was cancelled or not completed within ${Math.round(timeoutMs/1e3)} seconds.`:`Sign-in to MCP server "${name}" failed: ${errorMessage(signInError)}`),1}connection.challenge=void 0;try{await connection.reconnect()}catch(connectError){return error(`Signed in, but ${errorMessage(connectError)}`),1}return log(`Signed in to MCP server "${name}" (${connection.tools.length} tools).`),0}async function waitForRedirectUrl(signal,timeoutMs,interactive){let controller=new AbortController,abort=()=>controller.abort();signal.addEventListener("abort",abort,{once:!0});let timer=setTimeout(abort,timeoutMs);try{if(!interactive){await new Promise(resolve=>controller.signal.addEventListener("abort",()=>resolve(),{once:!0}));return}let readline=createInterface({input:process.stdin,output:process.stderr});try{return await readline.question("If the browser cannot reach this machine, paste the URL it was redirected to: ",{signal:controller.signal})}catch{return}finally{readline.close()}}finally{clearTimeout(timer),signal.removeEventListener("abort",abort)}}export{runMcpCommand};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{classifySystemOne,isRecord}from"./chunk-OSKPX3Z5.js";import"./chunk-TEPMHNKQ.js";import"./chunk-LD2P6SFZ.js";import"./chunk-UTB4DTYQ.js";import"./chunk-7JGR3GZN.js";import"./chunk-A3JYRWB6.js";import"./chunk-4L3WN2XY.js";var LABEL="Cloudflare Workers AI";function cloudflareErrorMessage(errors){if(Array.isArray(errors)){let messages=errors.map(error=>isRecord(error)&&typeof error.message=="string"?error.message:void 0).filter(message=>message!==void 0);if(messages.length>0)return`${LABEL} error: ${messages.join("; ")}`}return`${LABEL} request failed`}var transport={api:"cloudflare-workers-ai-system-one",label:LABEL,url:model=>new URL("run",`${model.baseUrl.replace(/\/+$/u,"")}/`),payload:(model,request)=>({model:model.id,input:request}),output:body=>{if(!isRecord(body))throw new Error(`${LABEL} returned an unexpected response`);if(body.success===!1)throw new Error(cloudflareErrorMessage(body.errors));let
|
|
2
|
+
import{classifySystemOne,isRecord}from"./chunk-OSKPX3Z5.js";import"./chunk-TEPMHNKQ.js";import"./chunk-LD2P6SFZ.js";import"./chunk-UTB4DTYQ.js";import"./chunk-7JGR3GZN.js";import"./chunk-A3JYRWB6.js";import"./chunk-4L3WN2XY.js";var LABEL="Cloudflare Workers AI";function cloudflareErrorMessage(errors){if(Array.isArray(errors)){let messages=errors.map(error=>isRecord(error)&&typeof error.message=="string"?error.message:void 0).filter(message=>message!==void 0);if(messages.length>0)return`${LABEL} error: ${messages.join("; ")}`}return`${LABEL} request failed`}var transport={api:"cloudflare-workers-ai-system-one",label:LABEL,url:model=>new URL("run",`${model.baseUrl.replace(/\/+$/u,"")}/`),payload:(model,request)=>({model:model.id,input:request}),output:body=>{if(!isRecord(body))throw new Error(`${LABEL} returned an unexpected response`);if(body.success===!1)throw new Error(cloudflareErrorMessage(body.errors));let result=body.result;if(!isRecord(result))throw new Error(`${LABEL} returned an unexpected response`);if("answers"in result)return result;if(result.state!=="Completed")throw new Error(`${LABEL} run did not complete (state: ${String(result.state)})`);if(!isRecord(result.result))throw new Error(`${LABEL} returned an unexpected response`);return result.result}},classify=(model,context,options)=>classifySystemOne(transport,model,context,options);export{classify};
|
|
@@ -7,6 +7,7 @@ import{parentPort,workerData}from"node:worker_threads";function createWasiShim(m
|
|
|
7
7
|
const promiseThen = Promise.prototype.then;
|
|
8
8
|
const ErrorCtor = Error;
|
|
9
9
|
const TypeErrorCtor = TypeError;
|
|
10
|
+
const RangeErrorCtor = RangeError;
|
|
10
11
|
const pending = new Map();
|
|
11
12
|
let nextId = 1;
|
|
12
13
|
let finished = false;
|
|
@@ -192,6 +193,26 @@ import{parentPort,workerData}from"node:worker_threads";function createWasiShim(m
|
|
|
192
193
|
Object.defineProperty(globalThis, "store", { value: store, enumerable: true });
|
|
193
194
|
Object.defineProperty(globalThis, "load", { value: load, enumerable: true });
|
|
194
195
|
|
|
196
|
+
let outputChars = 0;
|
|
197
|
+
let outputItems = 0;
|
|
198
|
+
|
|
199
|
+
// Past the output limits the script fails: done() reports the error, so catching it does not
|
|
200
|
+
// resume output, and the host ends the script.
|
|
201
|
+
function output(kind, data, mimeType) {
|
|
202
|
+
if (finished) return;
|
|
203
|
+
outputChars += data.length;
|
|
204
|
+
outputItems++;
|
|
205
|
+
if (outputChars > 16777216 || outputItems > 100000) {
|
|
206
|
+
const error = new RangeErrorCtor(
|
|
207
|
+
"script output exceeded the limit of 16777216 characters or 100000 text(), image(), and console calls. " +
|
|
208
|
+
"Print a summary instead, or write large data to a file with a tool.",
|
|
209
|
+
);
|
|
210
|
+
done(false, describeError(error));
|
|
211
|
+
throw error;
|
|
212
|
+
}
|
|
213
|
+
bridge("output", kind, data, mimeType);
|
|
214
|
+
}
|
|
215
|
+
|
|
195
216
|
// Primitives become their string form, everything else JSON.
|
|
196
217
|
function outputText(value) {
|
|
197
218
|
if (value === undefined || value === null || typeof value !== "object" && typeof value !== "function") {
|
|
@@ -208,7 +229,7 @@ import{parentPort,workerData}from"node:worker_threads";function createWasiShim(m
|
|
|
208
229
|
} catch (error) {
|
|
209
230
|
throw new TypeErrorCtor(error instanceof ErrorCtor ? error.message : String(error));
|
|
210
231
|
}
|
|
211
|
-
|
|
232
|
+
output("text", rendered);
|
|
212
233
|
}
|
|
213
234
|
|
|
214
235
|
function imageUrl(value) {
|
|
@@ -263,7 +284,7 @@ import{parentPort,workerData}from"node:worker_threads";function createWasiShim(m
|
|
|
263
284
|
if (!signature) {
|
|
264
285
|
throw new TypeErrorCtor("invalid image output. The image data is not a PNG, JPEG, GIF, or WebP image");
|
|
265
286
|
}
|
|
266
|
-
|
|
287
|
+
output("image", data, signature[0]);
|
|
267
288
|
}
|
|
268
289
|
|
|
269
290
|
function exit() {
|
|
@@ -281,7 +302,7 @@ import{parentPort,workerData}from"node:worker_threads";function createWasiShim(m
|
|
|
281
302
|
const console = {};
|
|
282
303
|
for (const level of ["log", "info", "warn", "error", "debug"]) {
|
|
283
304
|
console[level] = (...args) => {
|
|
284
|
-
|
|
305
|
+
output("text", args.map(format).join(" "));
|
|
285
306
|
};
|
|
286
307
|
}
|
|
287
308
|
Object.freeze(console);
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
+
import{ARMIN_HEIGHT,ARMIN_WIDTH,isArminPixel}from"./chunk-2KAZSACP.js";import{backgroundAnsi,colorToRgb,foregroundAnsi,formatKeyText,getKeybindings,indexedColor,rgbColor,theme,visibleWidth}from"./chunk-6FX7UEPL.js";import"./chunk-S3GGRYIO.js";import"./chunk-4L3WN2XY.js";var DEPTH=.7,FLY_START=.1,FLY_DURATION=1.3,START_SCALE=.1;function createModel(columns,rows,pixel,options){let blocks=[];for(let row=0;row<rows;row++)for(let column=0;column<columns;column++){let color=pixel(column,row);color&&blocks.push({home:[column,row,0],color})}return{columns,rows,blocks,cameraDistance:options.cameraDistance,radius:Math.hypot(columns/2,rows/2,1+DEPTH/2),widthShare:options.widthShare,puzzleMoves:random=>options.puzzleMoves(random,blocks.length),origin:options.origin}}var CORAL=[228,138,122],BLUE=[79,142,179],YELLOW=[234,182,93],PI_LOGO_PIXELS=["ccc.","b.c.","bb.y","b..y"],PI_LOGO_COLORS={c:CORAL,b:BLUE,y:YELLOW};function piLogoModel(origin){return createModel(4,4,(column,row)=>PI_LOGO_COLORS[PI_LOGO_PIXELS[row][column]],{cameraDistance:10,widthShare:.35,puzzleMoves:random=>random<.4?2:1,origin})}function arminModel(color){return createModel(ARMIN_WIDTH,ARMIN_HEIGHT,(column,row)=>isArminPixel(column,row)?color:void 0,{cameraDistance:80,widthShare:.45,puzzleMoves:(random,blockCount)=>Math.round(blockCount*(.03+random*.04)),origin:void 0})}var PUZZLE_START=FLY_START+FLY_DURATION+3,PUZZLE_STEP=.3,PUZZLE_STEPS=12,PUZZLE_RETURN=1,PUZZLE_HOLD=.6,PUZZLE_CYCLE=PUZZLE_STEP*PUZZLE_STEPS+PUZZLE_RETURN+PUZZLE_HOLD,PUZZLE_MOVES=[[1,0,0],[-1,0,0],[0,1,0],[0,-1,0],[1,0,0],[-1,0,0],[0,1,0],[0,-1,0],[0,0,1],[0,0,-1]];function shuffleSteps(model,cycle){let{columns,rows}=model,positions=model.blocks.map(block=>block.home),steps=[positions],lastMoved=new Set,random=cycle*7919+1,next=()=>hash(random++),key=([x,y,z])=>((z+1)*rows+y)*columns+x;for(let step=0;step<PUZZLE_STEPS;step++){let occupied=new Set(positions.map(key)),nextPositions=[...positions],moved=new Set,moveCount=model.puzzleMoves(next());for(let move=0;move<moveCount;move++){let candidates=[];for(let block=0;block<positions.length;block++){if(moved.has(block))continue;let[x,y,z]=positions[block];for(let[dx,dy,dz]of PUZZLE_MOVES){let target=[x+dx,y+dy,z+dz];target[0]<0||target[0]>=columns||target[1]<0||target[1]>=rows||target[2]<-1||target[2]>1||occupied.has(key(target))||candidates.push({block,target})}}let fresh=candidates.filter(candidate=>!lastMoved.has(candidate.block)),pool=fresh.length>0?fresh:candidates,choice=pool[Math.floor(next()*pool.length)];if(!choice)break;occupied.add(key(choice.target)),nextPositions[choice.block]=choice.target,moved.add(choice.block)}lastMoved.clear();for(let block of moved)lastMoved.add(block);positions=nextPositions,steps.push(positions)}return steps}var FRAME_MS=1e3/30,DUST_DURATION=.35,WAVE_SPREAD=.55,WAVE_JITTER=.12,DISSOLVE_END=FLY_START+WAVE_SPREAD+WAVE_JITTER+DUST_DURATION,BACKGROUND_FADE=.5,EXIT_DURATION=1.1,STARS_START=2.5,STARS_FADE=2,STAR_DENSITY=.018,STAR_TINTS=[[255,255,255],[170,195,255],[255,225,170],[255,190,205]],LOGO_COLOR_STEP=5,LIGHT_HALO_STRENGTH=.3,HALO_RADIUS_X=6,HALO_RADIUS_Y=3,HALO_LEVELS=32,STAR_ALPHA_LEVELS=8,STAR_FLICKER_LEVELS=3,HINT_FADE=.5,DOT_BITS=[1,8,2,16,4,32,64,128],BRAILLE=Array.from({length:256},(_,bits)=>String.fromCharCode(10240+bits)),LIGHT=normalize([-.45,-.6,.75]),HALF_VECTOR=normalize([LIGHT[0],LIGHT[1],LIGHT[2]+1]);function normalize(v){let length=Math.hypot(v[0],v[1],v[2]);return[v[0]/length,v[1]/length,v[2]/length]}function clamp01(value){return value<0?0:value>1?1:value}function smooth(value){let t=clamp01(value);return t*t*t*(t*(t*6-15)+10)}function easeOut(value){let t=1-clamp01(value);return 1-t*t*t}function mix(a,b,amount){return[a[0]+(b[0]-a[0])*amount,a[1]+(b[1]-a[1])*amount,a[2]+(b[2]-a[2])*amount]}function hash(value){let x=Math.imul(value^2654435769,2246822507);return x^=x>>>13,x=Math.imul(x,3266489909),x^=x>>>16,(x>>>0)/4294967296}function isLight([r,g,b]){return .2126*r+.7152*g+.0722*b>128}function toRgb(color){let{r,g,b}=colorToRgb(color);return[r,g,b]}function glyphInk(text,seed){return text.trim()===""?0:/^[.,:;'`\-_·]$/.test(text)?2:/^[\u2500-\u257f]$/.test(text)?3:4+Math.floor(seed*3)}var segmenter=new Intl.Segmenter;function parseScreen(lines,width,foreground,background){let palette=index=>toRgb(indexedColor(index));return lines.map(line=>{let cells=[],fg,bg,dim=!1,inverse=!1,applySgr=params=>{let codes=params===""?["0"]:params.split(";");for(let i2=0;i2<codes.length;i2++){let parts=codes[i2].split(":").map(part=>Number.parseInt(part,10)),code=parts[0]??0;if(code===38||code===48){let args;if(parts.length>1)args=parts.slice(1).filter(part=>!Number.isNaN(part));else{let kind=Number.parseInt(codes[i2+1]??"",10),count=kind===5?2:kind===2?4:1;args=codes.slice(i2+1,i2+1+count).map(part=>Number.parseInt(part,10)),i2+=count}let color;args[0]===5&&args[1]!==void 0?color=palette(args[1]):args[0]===2&&args.length>=4&&(color=[args[1],args[2],args[3]]),color&&(code===38?fg=color:bg=color)}else code===0?(fg=void 0,bg=void 0,dim=!1,inverse=!1):code===2?dim=!0:code===22?dim=!1:code===7?inverse=!0:code===27?inverse=!1:code>=30&&code<=37?fg=palette(code-30):code>=90&&code<=97?fg=palette(code-90+8):code===39?fg=void 0:code>=40&&code<=47?bg=palette(code-40):code>=100&&code<=107?bg=palette(code-100+8):code===49&&(bg=void 0)}},pushText=text=>{for(let{segment}of segmenter.segment(text)){let glyphWidth=visibleWidth(segment);if(glyphWidth===0||cells.length+glyphWidth>width)continue;let cellFg=fg??foreground,cellBg=bg;inverse&&(cellFg=bg??background,cellBg=fg??foreground),dim&&(cellFg=mix(cellFg,cellBg??background,.4));let cell={text:segment,width:glyphWidth,fg:cellFg,bg:cellBg,delay:0,ink:0,seed:0};cells.push(cell),glyphWidth===2&&cells.push({...cell,text:"",width:0})}},i=0;for(;i<line.length;){let sequenceStart=line.indexOf("\x1B",i);if(sequenceStart===-1){pushText(line.slice(i));break}sequenceStart>i&&pushText(line.slice(i,sequenceStart));let kind=line[sequenceStart+1];if(kind==="["){let end=sequenceStart+2;for(;end<line.length&&(line.charCodeAt(end)<64||line.charCodeAt(end)>126);)end++;line[end]==="m"&&applySgr(line.slice(sequenceStart+2,end)),i=end+1}else if(kind==="]"||kind==="_"||kind==="P"||kind==="^"){let bell=line.indexOf("\x07",sequenceStart+2),st=line.indexOf("\x1B\\",sequenceStart+2);if(bell===-1&&st===-1)break;i=bell!==-1&&(st===-1||bell<st)?bell+1:st+2}else i=sequenceStart+2}return cells})}function rotation(yaw,pitch,roll){let[sy,cy,sx,cx,sz,cz]=[Math.sin(yaw),Math.cos(yaw),Math.sin(pitch),Math.cos(pitch),Math.sin(roll),Math.cos(roll)],ry=[cy,0,sy,0,1,0,-sy,0,cy],rx=[1,0,0,0,cx,-sx,0,sx,cx],rz=[cz,-sz,0,sz,cz,0,0,0,1];return multiply(rz,multiply(rx,ry))}function multiply(a,b){let result=new Array(9);for(let row=0;row<3;row++)for(let column=0;column<3;column++)result[row*3+column]=a[row*3]*b[column]+a[row*3+1]*b[3+column]+a[row*3+2]*b[6+column];return result}var SPIN_RAMP=1.4,SPIN_SPEED=Math.PI*2/PUZZLE_CYCLE,SPIN_LINGER=.6,FIRST_FRONT_VIEW=PUZZLE_START+PUZZLE_STEP*PUZZLE_STEPS+PUZZLE_RETURN+PUZZLE_HOLD/2;function baseSpinPhase(time){let elapsed=time-FLY_START;if(elapsed<=0)return 0;let u=elapsed/SPIN_RAMP;return u<1?SPIN_SPEED*SPIN_RAMP*(u**6-3*u**5+2.5*u**4):SPIN_SPEED*(SPIN_RAMP*.5+elapsed-SPIN_RAMP)}var SPIN_ALIGNMENT=Math.PI*2-baseSpinPhase(FIRST_FRONT_VIEW)%(Math.PI*2);function spinPhase(time){return baseSpinPhase(time)+SPIN_ALIGNMENT*smooth((time-FLY_START)/FLY_DURATION)}function spinAngle(time){let phase=spinPhase(time);return phase-SPIN_LINGER*Math.sin(phase)}var BlockRaster=class{bits=new Uint8Array(0);counts=new Uint8Array(0);rgb=new Float32Array(0);haloAmount=new Float32Array(0);haloRgb=new Float32Array(0);width=0;height=0;depth=new Float32Array(0);faceIds=new Uint16Array(0);dirty;haloDirty;cameraDistance;constructor(cameraDistance){this.cameraDistance=cameraDistance}render(width,height,pose,boxes,background,haloStrength){let dotWidth=width*2,dotHeight=height*4;if(width!==this.width||height!==this.height)this.width=width,this.height=height,this.bits=new Uint8Array(width*height),this.counts=new Uint8Array(width*height),this.rgb=new Float32Array(width*height*3),this.haloAmount=new Float32Array(width*height),this.haloRgb=new Float32Array(width*height*3),this.haloDirty=void 0,this.depth=new Float32Array(dotWidth*dotHeight).fill(1/0),this.faceIds=new Uint16Array(dotWidth*dotHeight),this.dirty=void 0;else if(this.dirty){let{minX:minX2,minY:minY2,maxX:maxX2,maxY:maxY2}=this.dirty;for(let row=minY2;row<=maxY2;row++)this.bits.fill(0,row*width+minX2,row*width+maxX2+1),this.counts.fill(0,row*width+minX2,row*width+maxX2+1),this.rgb.fill(0,(row*width+minX2)*3,(row*width+maxX2+1)*3);this.dirty=void 0}if(this.haloDirty){let{minX:minX2,minY:minY2,maxX:maxX2,maxY:maxY2}=this.haloDirty;for(let row=minY2;row<=maxY2;row++)this.haloAmount.fill(0,row*width+minX2,row*width+maxX2+1),this.haloRgb.fill(0,(row*width+minX2)*3,(row*width+maxX2+1)*3);this.haloDirty=void 0}let m=rotation(pose.yaw,pose.pitch,pose.roll),{centerX,centerY,scale}=pose,cameraDistance=this.cameraDistance,origin=[m[6]*cameraDistance,m[7]*cameraDistance,m[8]*cameraDistance],light=isLight(background),faces=this.visibleFaces(m,origin,pose,boxes,dotWidth,dotHeight,light);if(faces.length===0)return;let minX=dotWidth,minY=dotHeight,maxX=-1,maxY=-1;for(let face of faces)minX=Math.min(minX,face.minX),minY=Math.min(minY,face.minY),maxX=Math.max(maxX,face.maxX),maxY=Math.max(maxY,face.maxY);if(maxX<minX||maxY<minY)return;let depth=this.depth,faceIds=this.faceIds;for(let faceIndex=0;faceIndex<faces.length;faceIndex++){let face=faces[faceIndex],a=face.axis,u=(a+1)%3,v=(a+2)%3,originA=origin[a],originU=origin[u],originV=origin[v],stepA=m[a]/scale,stepU=m[u]/scale,stepV=m[v]/scale,sx=(face.minX+.5-centerX)/scale;for(let dotY=face.minY;dotY<=face.maxY;dotY++){let sy=(dotY+.5-centerY)/scale,directionA=m[a]*sx+m[3+a]*sy-m[6+a]*cameraDistance,directionU=m[u]*sx+m[3+u]*sy-m[6+u]*cameraDistance,directionV=m[v]*sx+m[3+v]*sy-m[6+v]*cameraDistance,index=dotY*dotWidth+face.minX;for(let dotX=face.minX;dotX<=face.maxX;dotX++,index++){let t=(face.plane-originA)/directionA;if(t>0&&t<depth[index]){let hitU=originU+t*directionU,hitV=originV+t*directionV;hitU>=face.uMin&&hitU<=face.uMax&&hitV>=face.vMin&&hitV<=face.vMax&&(depth[index]=t,faceIds[index]=faceIndex+1)}directionA+=stepA,directionU+=stepU,directionV+=stepV}}}let bits=this.bits,counts=this.counts,rgb=this.rgb,cellMinX=width,cellMinY=height,cellMaxX=-1,cellMaxY=-1;for(let dotY=minY;dotY<=maxY;dotY++){let index=dotY*dotWidth+minX;for(let dotX=minX;dotX<=maxX;dotX++,index++){let id=faceIds[index];if(id===0)continue;let face=faces[id-1],fog=clamp01(.15-cameraDistance*(1-depth[index])*.12)*(light?.5:1);faceIds[index]=0,depth[index]=1/0;let cellX=dotX>>1,cellY=dotY>>2,cell=cellY*width+cellX;bits[cell]|=DOT_BITS[(dotY&3)*2+(dotX&1)],counts[cell]++,rgb[cell*3]+=face.red+(background[0]-face.red)*fog,rgb[cell*3+1]+=face.green+(background[1]-face.green)*fog,rgb[cell*3+2]+=face.blue+(background[2]-face.blue)*fog,cellX<cellMinX&&(cellMinX=cellX),cellX>cellMaxX&&(cellMaxX=cellX),cellY<cellMinY&&(cellMinY=cellY),cellY>cellMaxY&&(cellMaxY=cellY)}}cellMaxX>=0&&(this.dirty={minX:cellMinX,minY:cellMinY,maxX:cellMaxX,maxY:cellMaxY}),haloStrength>0&&this.renderHalo(haloStrength)}renderHalo(strength){let cells=this.dirty;if(!cells)return;let{width,height,counts,rgb}=this,minX=Math.max(0,cells.minX-HALO_RADIUS_X),maxX=Math.min(width-1,cells.maxX+HALO_RADIUS_X),minY=Math.max(0,cells.minY-HALO_RADIUS_Y),maxY=Math.min(height-1,cells.maxY+HALO_RADIUS_Y),regionWidth=maxX-minX+1,tent=radius=>{let weights=Array.from({length:radius*2+1},(_,i)=>radius+1-Math.abs(i-radius)),total=weights.reduce((sum,weight)=>sum+weight,0);return weights.map(weight=>weight/total)},weightsX=tent(HALO_RADIUS_X),weightsY=tent(HALO_RADIUS_Y),rows=cells.maxY-cells.minY+1,horizontal=new Float32Array(rows*regionWidth*4);for(let y=cells.minY;y<=cells.maxY;y++)for(let x=minX;x<=maxX;x++){let coverage=0,red=0,green=0,blue=0;for(let dx=-HALO_RADIUS_X;dx<=HALO_RADIUS_X;dx++){let sourceX=x+dx;if(sourceX<cells.minX||sourceX>cells.maxX)continue;let source=y*width+sourceX,count=counts[source];if(count===0)continue;let weight=weightsX[dx+HALO_RADIUS_X]/8;coverage+=count*weight,red+=rgb[source*3]*weight,green+=rgb[source*3+1]*weight,blue+=rgb[source*3+2]*weight}let target=((y-cells.minY)*regionWidth+(x-minX))*4;horizontal[target]=coverage,horizontal[target+1]=red,horizontal[target+2]=green,horizontal[target+3]=blue}for(let y=minY;y<=maxY;y++)for(let x=minX;x<=maxX;x++){let coverage=0,red=0,green=0,blue=0;for(let dy=-HALO_RADIUS_Y;dy<=HALO_RADIUS_Y;dy++){let sourceY=y+dy;if(sourceY<cells.minY||sourceY>cells.maxY)continue;let weight=weightsY[dy+HALO_RADIUS_Y],source=((sourceY-cells.minY)*regionWidth+(x-minX))*4;coverage+=horizontal[source]*weight,red+=horizontal[source+1]*weight,green+=horizontal[source+2]*weight,blue+=horizontal[source+3]*weight}let target=y*width+x,count=counts[target];if(count>0&&count/8>coverage&&(coverage=count/8,red=rgb[target*3]/count*coverage,green=rgb[target*3+1]/count*coverage,blue=rgb[target*3+2]/count*coverage),coverage<=0)continue;let amount=Math.round(strength*Math.min(1,coverage)**.7*HALO_LEVELS)/HALO_LEVELS;amount<=0||(this.haloAmount[target]=amount,this.haloRgb[target*3]=Math.round(red/coverage/LOGO_COLOR_STEP)*LOGO_COLOR_STEP,this.haloRgb[target*3+1]=Math.round(green/coverage/LOGO_COLOR_STEP)*LOGO_COLOR_STEP,this.haloRgb[target*3+2]=Math.round(blue/coverage/LOGO_COLOR_STEP)*LOGO_COLOR_STEP)}this.haloDirty={minX,minY,maxX,maxY}}visibleFaces(m,origin,pose,boxes,dotWidth,dotHeight,lightBackground){let faces=[],cameraDistance=this.cameraDistance;for(let box of boxes)for(let a=0;a<3;a++){let u=(a+1)%3,v=(a+2)%3;for(let side of[-1,1]){let plane=side>0?box.max[a]:box.min[a];if((origin[a]-plane)*side<=0||boxes.some(other=>other!==box&&(side>0?other.min[a]:other.max[a])===plane&&other.min[u]<=box.min[u]&&other.max[u]>=box.max[u]&&other.min[v]<=box.min[v]&&other.max[v]>=box.max[v]))continue;let minX=1/0,minY=1/0,maxX=-1/0,maxY=-1/0,corner=[0,0,0];for(let cornerU of[box.min[u],box.max[u]])for(let cornerV of[box.min[v],box.max[v]]){corner[a]=plane,corner[u]=cornerU,corner[v]=cornerV;let x=m[0]*corner[0]+m[1]*corner[1]+m[2]*corner[2],y=m[3]*corner[0]+m[4]*corner[1]+m[5]*corner[2],z=m[6]*corner[0]+m[7]*corner[1]+m[8]*corner[2],perspective=pose.scale*cameraDistance/(cameraDistance-z),screenX=pose.centerX+x*perspective,screenY=pose.centerY+y*perspective;minX=Math.min(minX,screenX),minY=Math.min(minY,screenY),maxX=Math.max(maxX,screenX),maxY=Math.max(maxY,screenY)}let face={minX:Math.max(0,Math.floor(minX)),minY:Math.max(0,Math.floor(minY)),maxX:Math.min(dotWidth-1,Math.ceil(maxX)),maxY:Math.min(dotHeight-1,Math.ceil(maxY))};if(face.maxX<face.minX||face.maxY<face.minY)continue;let nx=m[a]*side,ny=m[3+a]*side,nz=m[6+a]*side,diffuse=Math.max(0,nx*LIGHT[0]+ny*LIGHT[1]+nz*LIGHT[2]),rim=Math.max(0,nx*.8-nz*.3),specular=lightBackground?0:Math.max(0,nx*HALF_VECTOR[0]+ny*HALF_VECTOR[1]+nz*HALF_VECTOR[2])**24*.6*255,light=lightBackground?Math.min(1,.55+diffuse*.45+rim*.1):.45+diffuse*.78+rim*.25;faces.push({axis:a,plane,uMin:box.min[u],uMax:box.max[u],vMin:box.min[v],vMax:box.max[v],...face,red:Math.min(255,box.color[0]*light+specular),green:Math.min(255,box.color[1]*light+specular),blue:Math.min(255,box.color[2]*light+specular)})}}return faces}},playing=!1;async function playEasterEgg3d(tui,screen,egg){if(playing)return;playing=!0;let reported=await tui.queryTerminalColors({timeoutMs:100}),dark=theme.appearance==="dark",toRgbTuple=(rgb,fallback)=>rgb?[rgb.r,rgb.g,rgb.b]:fallback,colors={foreground:toRgbTuple(reported.foreground,toRgb(theme.colors.text)),background:toRgbTuple(reported.background,dark?[0,0,0]:[255,255,255])};if(tui.hasOverlay()){playing=!1;return}let model=egg.kind==="armin"?arminModel(toRgb(theme.colors.accent)):piLogoModel({column:egg.column,row:egg.row}),animation=new EasterEgg3dAnimation(tui,screen,model,colors,()=>{playing=!1,overlay.hide()}),overlay=tui.showOverlay(animation,{anchor:"top-left",width:"100%",maxHeight:"100%"})}var EasterEgg3dAnimation=class{tui;screen;model;foreground;background;onDone;startTime=performance.now();lastRender=performance.now();timer;exit;shuffle;screenWidth=-1;screenHeight=-1;stars=[];cells=[];ansiCache=new Map;raster;constructor(tui,screen,model,colors,onDone){this.tui=tui,this.screen=screen,this.model=model,this.raster=new BlockRaster(model.cameraDistance),this.foreground=colors.foreground,this.background=colors.background,this.onDone=onDone,this.timer=setInterval(()=>{this.exit&&this.exitProgress()>=1||performance.now()-this.lastRender>1e3?this.finish():this.tui.requestRender()},FRAME_MS),this.timer.unref?.()}close(){if(this.exit){this.finish();return}let time=this.elapsed(),yaw=spinAngle(time),turn=Math.PI*2;this.exit={start:performance.now(),time,yaw,targetYaw:Math.ceil(yaw/turn)*turn,offsets:this.blockOffsets(time)}}handleInput(data){let keybindings=getKeybindings();(keybindings.matches(data,"tui.select.cancel")||keybindings.matches(data,"app.clear"))&&this.close()}handleMouse(event){return event.type==="click"&&this.close(),{handled:!0,render:!1}}invalidate(){this.screenWidth=-1,this.screenHeight=-1,this.ansiCache.clear()}render(width){let height=Math.max(1,this.tui.terminal.rows),foreground=this.foreground,background=this.background;this.lastRender=performance.now(),(width!==this.screenWidth||height!==this.screenHeight)&&(this.screenWidth=width,this.screenHeight=height,this.cells=this.prepareCells(width,foreground),this.stars=this.prepareStars(width,height));let dissolveTime,pose,hintAlpha,starAlpha,offsets;if(this.exit){let progress=this.exitProgress(),landing=clamp01(progress/.8),settle=1-smooth(landing);dissolveTime=Math.min(this.exit.time,DISSOLVE_END)*(1-progress),pose=this.pose(width,height,this.flyProgress(this.exit.time)*settle,this.exit.time),pose.yaw=this.exit.yaw+(this.exit.targetYaw-this.exit.yaw)*easeOut(landing),pose.pitch*=settle,pose.roll*=settle,hintAlpha=this.hintAlpha(this.exit.time)*(1-smooth(progress/.2)),starAlpha=this.starAlpha(this.exit.time)*(1-smooth(progress/.3));let gather=1-smooth(progress/.5);offsets=this.exit.offsets.map(([x,y,z])=>[x*gather,y*gather,z*gather])}else{let time=this.elapsed();dissolveTime=time,pose=this.pose(width,height,this.flyProgress(time),time),hintAlpha=this.hintAlpha(time),starAlpha=this.starAlpha(time),offsets=this.blockOffsets(time)}let{columns,rows}=this.model,boxes=this.model.blocks.map((block,index)=>{let[dx,dy,dz]=offsets[index],x=block.home[0]-columns/2+dx,y=block.home[1]-rows/2+dy;return{min:[x,y,dz-DEPTH/2],max:[x+1,y+1,dz+DEPTH/2],color:block.color}}),raster=this.raster;raster.render(width,height,pose,boxes,background,isLight(background)?LIGHT_HALO_STRENGTH:0);let halo=(index,base)=>{let amount=raster.haloAmount[index];if(amount<=0)return base;let color=raster.haloRgb;return mix(base??background,[color[index*3],color[index*3+1],color[index*3+2]],amount)},backgroundFade=smooth(dissolveTime/BACKGROUND_FADE),textFade=smooth(dissolveTime/.6)*.3,textActive=dissolveTime<DISSOLVE_END||backgroundFade<1,hint=this.hint(width,height,hintAlpha,background),frame=Math.floor(dissolveTime*14),now=this.elapsed(),starLevel=Math.round(starAlpha*STAR_ALPHA_LEVELS)/STAR_ALPHA_LEVELS,starfield=index=>{if(starLevel<=0)return;let star=this.stars[index];if(!star)return;let flicker=Math.round((.5+.5*Math.sin(now*star.speed+star.phase))*STAR_FLICKER_LEVELS)/STAR_FLICKER_LEVELS;return{text:star.glyph,fg:mix(background,mix(foreground,star.tint,.5),star.strength*(.7+.3*flicker)*starLevel)}},lines=[];for(let row=0;row<height;row++){let cells=this.cells[row]??[],line="",currentFg=-1,currentBg=-1,emit=(text,fg,bg)=>{let fgKey=fg?this.pack(fg):-1,bgKey=bg?this.pack(bg):-1;fgKey!==currentFg&&text!==" "&&(line+=fg?this.ansi(fgKey,!1):"\x1B[39m",currentFg=fgKey),bgKey!==currentBg&&(line+=bg?this.ansi(bgKey,!0):"\x1B[49m",currentBg=bgKey),line+=text};for(let column=0;column<width;column++){let index=row*width+column,cell=textActive?cells[column]:void 0,cellBg=halo(index,cell?.bg&&backgroundFade<1?mix(cell.bg,background,backgroundFade):void 0);if(hint&&row===hint.row&&column>=hint.start&&column<hint.start+hint.text.length){let offset=column-hint.start;emit(hint.text[offset],offset<hint.keyLength?hint.keyColor:hint.color,cellBg);continue}let dots=raster.bits[index];if(dots){let step=LOGO_COLOR_STEP*raster.counts[index],rgb=raster.rgb,color=[Math.round(rgb[index*3]/step)*LOGO_COLOR_STEP,Math.round(rgb[index*3+1]/step)*LOGO_COLOR_STEP,Math.round(rgb[index*3+2]/step)*LOGO_COLOR_STEP];emit(BRAILLE[dots],color,cellBg);continue}if(!cell){let star=starfield(index);emit(star?.text??" ",star?.fg,cellBg);continue}let dust=(dissolveTime-cell.delay)/DUST_DURATION;if(dust<0&&cell.width===2&&!raster.bits[index+1]){emit(cell.text,mix(cell.fg,background,textFade),cellBg),column++;continue}if(dust<0&&cell.width===1){emit(cell.text,mix(cell.fg,background,textFade),cellBg);continue}let dotCount=dust<0?cell.ink:Math.round(cell.ink*(1-clamp01(dust)));if(dotCount<=0){let star=starfield(index);emit(star?.text??" ",star?.fg,cellBg);continue}let bits=0,placed=0;for(let attempt=0;placed<dotCount&&attempt<32;attempt++){let bit=DOT_BITS[Math.floor(hash(cell.seed*7919+frame*131+attempt)*8)];bits&bit||(bits|=bit,placed++)}let fade=textFade+(1-textFade)*clamp01(dust)**.8;emit(BRAILLE[bits],mix(cell.fg,background,fade),cellBg)}lines.push(`${line}\x1B[0m`)}return lines}elapsed(){return(performance.now()-this.startTime)/1e3}exitProgress(){return this.exit?clamp01((performance.now()-this.exit.start)/1e3/EXIT_DURATION):0}finish(){this.timer&&(clearInterval(this.timer),this.timer=void 0,this.onDone())}blockOffsets(time){let blocks=this.model.blocks,home=()=>blocks.map(()=>[0,0,0]);if(time<PUZZLE_START)return home();let cycle=Math.floor((time-PUZZLE_START)/PUZZLE_CYCLE),local=time-PUZZLE_START-cycle*PUZZLE_CYCLE;this.shuffle?.cycle!==cycle&&(this.shuffle={cycle,steps:shuffleSteps(this.model,cycle)});let steps=this.shuffle.steps,offset=(position,index)=>{let block=blocks[index].home;return[position[0]-block[0],position[1]-block[1],position[2]-block[2]]},shuffleEnd=PUZZLE_STEP*PUZZLE_STEPS;if(local<shuffleEnd){let step=Math.floor(local/PUZZLE_STEP),progress=smooth((local-step*PUZZLE_STEP)/PUZZLE_STEP);return steps[step].map((from,index)=>{let a=offset(from,index),b=offset(steps[step+1][index],index);return[a[0]+(b[0]-a[0])*progress,a[1]+(b[1]-a[1])*progress,a[2]+(b[2]-a[2])*progress]})}if(local<shuffleEnd+PUZZLE_RETURN){let u=(local-shuffleEnd)/PUZZLE_RETURN,remaining=1-smooth(u),arc=Math.sin(Math.PI*clamp01(u))*.8;return steps[PUZZLE_STEPS].map((position,index)=>{let[x,y,z]=offset(position,index);return[x*remaining,y*remaining,z*remaining+(index%2===0?arc:-arc)]})}return home()}flyProgress(time){return smooth((time-FLY_START)/FLY_DURATION)}starAlpha(time){return smooth((time-STARS_START)/STARS_FADE)}hintAlpha(time){return smooth((time-FLY_START-FLY_DURATION)/HINT_FADE)}pose(width,height,progress,time){let{columns,rows,cameraDistance,radius,widthShare,origin}=this.model,reach=radius*(cameraDistance/(cameraDistance-radius)),startScale=origin?2*(cameraDistance-DEPTH/2)/cameraDistance:START_SCALE,endScale=Math.max(startScale,Math.min(width*2*widthShare,(height*4-8)*.48)/reach),endX=width,endY=height*2-2,startX=origin?origin.column*2+columns:endX,startY=origin?origin.row*4+rows:endY;return{centerX:startX+(endX-startX)*progress,centerY:startY+(endY-startY)*progress,scale:startScale*(endScale/startScale)**progress,yaw:spinAngle(time),pitch:.3*Math.sin(spinPhase(time))*progress,roll:.06*Math.sin(2*spinPhase(time))*progress}}hint(width,height,alpha,background){if(alpha<=0)return;let key=formatKeyText(getKeybindings().getKeys("tui.select.cancel")[0]??"escape"),text=`${key} to return`;if(!(text.length>width))return{row:height-2,start:Math.floor((width-text.length)/2),text,keyLength:key.length,keyColor:mix(background,toRgb(theme.colors.muted),alpha),color:mix(background,toRgb(theme.colors.dim),alpha)}}prepareStars(width,height){let stars=new Array(width*height);for(let index=0;index<width*height;index++){if(hash(index*3+20973)>=STAR_DENSITY)continue;let random=salt=>hash(index*7+salt*40503);stars[index]={glyph:BRAILLE[DOT_BITS[Math.floor(random(1)*8)]],tint:STAR_TINTS[Math.floor(random(2)*STAR_TINTS.length)],strength:.1+random(3)*.12,phase:random(4)*Math.PI*2,speed:.4+random(5)*.8}}return stars}prepareCells(width,foreground){let cells=parseScreen(this.screen,width,foreground,this.background),height=Math.max(1,this.tui.terminal.rows),{columns,rows,origin}=this.model,centerX=origin?origin.column+columns/2:width/2,centerY=origin?origin.row+rows/4:height/2,farthest=Math.hypot(Math.max(centerX,width-centerX),Math.max(centerY,height-centerY)*2);for(let row=0;row<cells.length;row++){let line=cells[row];for(let column=0;column<line.length;column++){let cell=line[column],owner=cell.width===0?line[column-1]:cell,seed=hash(row*65537+column);if(cell.width!==0){let distance=Math.hypot(column-centerX,(row-centerY)*2)/farthest;cell.delay=FLY_START+distance*WAVE_SPREAD+seed*WAVE_JITTER}else cell.delay=owner.delay;cell.seed=row*65537+column,cell.ink=glyphInk(owner.text,seed)}}if(origin)for(let row=origin.row;row<origin.row+Math.ceil(rows/2);row++){let line=cells[row];if(line)for(let column=origin.column;column<origin.column+columns;column++){let cell=line[column];cell&&(cell.text=" ",cell.width=1,cell.ink=0,cell.bg=void 0)}}return cells}pack(color){return Math.round(color[0])<<16|Math.round(color[1])<<8|Math.round(color[2])}ansi(key,isBackground){let cacheKey=key*2+(isBackground?1:0),value=this.ansiCache.get(cacheKey);if(value===void 0){let color=rgbColor(key>>16&255,key>>8&255,key&255),mode=theme.getColorMode();value=isBackground?backgroundAnsi(color,mode):foregroundAnsi(color,mode),this.ansiCache.set(cacheKey,value)}return value}};export{EasterEgg3dAnimation,playEasterEgg3d};
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{Bm25Ranker,CODEMODE_DOCS_PATH,CODEMODE_STORE_ENTRY_TYPE,DEFAULT_TOOL_SEARCH_LIMIT,combineUsage,createToolSearchDocument,getCodemodeCallableTools,parseCodemodeSource,renderToolSample,toCodemodeDeclaration,toCodemodeIdentifier}from"./chunk-
|
|
2
|
+
import{Bm25Ranker,CODEMODE_DOCS_PATH,CODEMODE_STORE_ENTRY_TYPE,DEFAULT_TOOL_SEARCH_LIMIT,combineUsage,createToolSearchDocument,getCodemodeCallableTools,parseCodemodeSource,renderToolSample,toCodemodeDeclaration,toCodemodeIdentifier}from"./chunk-SYF2TF6W.js";import"./chunk-OYBSLV7Y.js";import{getCodemodeWorkerSpecifier,getQuickJSWasmPath}from"./chunk-6FX7UEPL.js";import"./chunk-S3GGRYIO.js";import"./chunk-4L3WN2XY.js";import{randomBytes}from"node:crypto";import{writeFile}from"node:fs/promises";import{tmpdir}from"node:os";import{join}from"node:path";import{Worker}from"node:worker_threads";import{readFile}from"node:fs/promises";import{createRequire}from"node:module";var modules=new Map;function loadQuickJSWasm(path){let resolved=path??createRequire(import.meta.url).resolve("quickjs-wasi/quickjs.wasm"),module=modules.get(resolved);if(!module){let{WebAssembly}=globalThis;module=readFile(resolved).then(bytes=>WebAssembly.compile(bytes)).catch(error=>{throw modules.delete(resolved),error}),modules.set(resolved,module)}return module}function isWorkerToHostMessage(value){if(typeof value!="object"||value===null)return!1;let type=value.type;return type==="call"||type==="output"||type==="done"||type==="crash"}var DEFAULT_TIMEOUT_MS=3e5,IDENTIFIER=/^[A-Za-z_$][A-Za-z0-9_$]*$/,RESERVED_GLOBALS=new Set(["tools","ALL_TOOLS","console","text","image","exit","globalThis","store","load"]);function errorMessage(error){return error instanceof Error?error.message:String(error)}function serializeStore(store){let serialized={};for(let[key,value]of Object.entries(store??{})){let json=JSON.stringify(value);json!==void 0&&(serialized[key]=json)}return serialized}function parseStoreWrites(json){let writes={set:{},delete:[]};for(let[key,value]of JSON.parse(json))value===void 0?writes.delete.push(key):writes.set[key]=JSON.parse(value);return writes}function defaultWorkerUrl(){return new URL(import.meta.url.endsWith(".ts")?"./worker.ts":"./worker.js",import.meta.url)}var Execution=class{promise;resolveResult;worker;interrupt=new SharedArrayBuffer(4);tools;globals;signal;timer;output=[];calls=[];pending=new Map;finished=!1;constructor(options){this.promise=new Promise(resolve=>{this.resolveResult=resolve}),this.tools=options.tools,this.globals=options.globals,this.signal=options.signal,Number.isFinite(options.timeoutMs)&&(this.timer=setTimeout(()=>{this.finish({kind:"timeout",message:`Execution timed out after ${options.timeoutMs} ms`})},options.timeoutMs)),options.signal&&(options.signal.aborted?this.onAbort():options.signal.addEventListener("abort",this.onAbort,{once:!0})),options.wasm.then(wasm=>this.start(options,wasm),error=>{this.finish({kind:"sandbox",message:`Failed to load QuickJS: ${errorMessage(error)}`})})}abort(message){return this.finish({kind:"aborted",message}),this.promise}start(options,wasm){if(this.finished)return;let workerData={code:options.code,tools:[...options.tools.values()].map(tool=>({name:tool.name,jsName:toCodemodeIdentifier(tool.name),description:tool.description??""})),globals:[...options.globals.values()].map(global=>({name:global.name,spread:global.spread===!0})),wasm,memoryLimitBytes:options.memoryLimitBytes,store:options.store,interrupt:this.interrupt},worker;try{worker=new Worker(options.workerUrl,{workerData})}catch(error){this.finish({kind:"sandbox",message:`Failed to start worker: ${errorMessage(error)}`});return}this.worker=worker,worker.on("message",message=>this.handleMessage(message)),worker.on("error",error=>{this.finish({kind:"sandbox",name:error instanceof Error?error.name:void 0,message:errorMessage(error)})}),worker.on("exit",code=>{this.finish({kind:"sandbox",message:`Worker exited with code ${code} before the script settled`})})}onAbort=()=>{let reason=this.signal?.reason;this.finish({kind:"aborted",message:reason instanceof Error?reason.message:"Execution aborted"})};post(message){this.worker?.postMessage(message)}handleMessage(message){if(!(this.finished||!isWorkerToHostMessage(message)))switch(message.type){case"output":this.output.push(message.item);break;case"call":this.handleCall(message);break;case"done":this.handleDone(message);break;case"crash":this.finish({kind:"sandbox",message:message.message});break}}handleDone(message){if(!message.ok){let parsed=JSON.parse(message.error);this.finish({kind:"script",...parsed});return}this.finish(void 0,message.value===void 0?void 0:JSON.parse(message.value),message.writes)}async handleCall(message){let{id,name}=message,isTool=message.target==="tool",record=isTool?{name,status:"cancelled",durationMs:0}:void 0;record&&this.calls.push(record);let pending={record,startedAt:performance.now(),controller:new AbortController};this.pending.set(id,pending);let status,reply;try{let tool=(isTool?this.tools:this.globals).get(name);if(!tool)throw new Error(`Unknown ${isTool?"tool":"global"} "${name}"`);let args=message.args===void 0?void 0:JSON.parse(message.args),value=await tool.execute(args,{signal:pending.controller.signal});reply={type:"result",id,ok:!0,payload:value===void 0?void 0:JSON.stringify(value)},status="ok"}catch(error){reply={type:"result",id,ok:!1,payload:errorMessage(error)},status="error"}this.pending.delete(id)&&(record&&(record.status=status,record.durationMs=performance.now()-pending.startedAt),this.post(reply))}finish(error,value,writes){if(this.finished)return;this.finished=!0,clearTimeout(this.timer),this.signal?.removeEventListener("abort",this.onAbort);let now=performance.now();for(let pending of this.pending.values())pending.record&&(pending.record.durationMs=now-pending.startedAt),pending.controller.abort();this.pending.clear();let result=error?{ok:!1,error,output:this.output,calls:this.calls}:{ok:!0,value,output:this.output,calls:this.calls,storeWrites:writes===void 0?{set:{},delete:[]}:parseStoreWrites(writes)};if(!this.worker){this.resolveResult(result);return}Atomics.store(new Int32Array(this.interrupt),0,1),this.worker.terminate().catch(()=>{}).then(()=>this.resolveResult(result))}},CodemodeSandbox=class{toolsByName=new Map;globalsByName=new Map;timeoutMs;memoryLimitBytes;wasm;workerUrl;running=new Set;closed=!1;constructor(options={}){this.timeoutMs=options.timeoutMs??DEFAULT_TIMEOUT_MS,this.memoryLimitBytes=options.memoryLimitBytes,this.wasm=options.wasm,this.workerUrl=options.workerUrl??defaultWorkerUrl();for(let tool of options.tools??[])this.registerTool(tool);let namespaces=new Set;for(let global of options.globals??[]){let parts=global.name.split(".");if(parts.length>2||!parts.every(part=>IDENTIFIER.test(part))||RESERVED_GLOBALS.has(parts[0]))throw new Error(`Invalid global name "${global.name}"`);if(this.globalsByName.has(global.name))throw new Error(`Global "${global.name}" is already registered`);parts.length===2&&namespaces.add(parts[0]),this.globalsByName.set(global.name,global)}for(let name of namespaces)if(this.globalsByName.has(name))throw new Error(`Global "${name}" conflicts with the namespace "${name}"`)}registerTool(tool){if(this.toolsByName.has(tool.name))throw new Error(`Tool "${tool.name}" is already registered`);this.toolsByName.set(tool.name,tool)}unregisterTool(name){return this.toolsByName.delete(name)}get tools(){return[...this.toolsByName.values()]}get globals(){return[...this.globalsByName.values()]}execute(code,options={}){if(this.closed)return Promise.reject(new Error("Sandbox is closed"));let execution=new Execution({code,tools:new Map(this.toolsByName),globals:this.globalsByName,timeoutMs:options.timeoutMs??this.timeoutMs,signal:options.signal,memoryLimitBytes:this.memoryLimitBytes,store:serializeStore(options.store),wasm:this.wasm===void 0?loadQuickJSWasm():Promise.resolve(this.wasm),workerUrl:this.workerUrl});return this.running.add(execution),execution.promise.finally(()=>this.running.delete(execution))}async close(){this.closed=!0,await Promise.all([...this.running].map(execution=>execution.abort("Sandbox closed")))}};var IMAGE_HELPER_EXPECTS="image expects a non-empty image URL string, an object with image_url, or a raw MCP image block",PRELUDE_SOURCE=`(function (bridge, toolsJson, globalsJson, storeJson) {
|
|
3
3
|
"use strict";
|
|
4
4
|
const stringify = JSON.stringify;
|
|
5
5
|
const parse = JSON.parse;
|
|
6
6
|
const promiseThen = Promise.prototype.then;
|
|
7
7
|
const ErrorCtor = Error;
|
|
8
8
|
const TypeErrorCtor = TypeError;
|
|
9
|
+
const RangeErrorCtor = RangeError;
|
|
9
10
|
const pending = new Map();
|
|
10
11
|
let nextId = 1;
|
|
11
12
|
let finished = false;
|
|
@@ -191,6 +192,26 @@ import{Bm25Ranker,CODEMODE_DOCS_PATH,CODEMODE_STORE_ENTRY_TYPE,DEFAULT_TOOL_SEAR
|
|
|
191
192
|
Object.defineProperty(globalThis, "store", { value: store, enumerable: true });
|
|
192
193
|
Object.defineProperty(globalThis, "load", { value: load, enumerable: true });
|
|
193
194
|
|
|
195
|
+
let outputChars = 0;
|
|
196
|
+
let outputItems = 0;
|
|
197
|
+
|
|
198
|
+
// Past the output limits the script fails: done() reports the error, so catching it does not
|
|
199
|
+
// resume output, and the host ends the script.
|
|
200
|
+
function output(kind, data, mimeType) {
|
|
201
|
+
if (finished) return;
|
|
202
|
+
outputChars += data.length;
|
|
203
|
+
outputItems++;
|
|
204
|
+
if (outputChars > 16777216 || outputItems > 100000) {
|
|
205
|
+
const error = new RangeErrorCtor(
|
|
206
|
+
"script output exceeded the limit of 16777216 characters or 100000 text(), image(), and console calls. " +
|
|
207
|
+
"Print a summary instead, or write large data to a file with a tool.",
|
|
208
|
+
);
|
|
209
|
+
done(false, describeError(error));
|
|
210
|
+
throw error;
|
|
211
|
+
}
|
|
212
|
+
bridge("output", kind, data, mimeType);
|
|
213
|
+
}
|
|
214
|
+
|
|
194
215
|
// Primitives become their string form, everything else JSON.
|
|
195
216
|
function outputText(value) {
|
|
196
217
|
if (value === undefined || value === null || typeof value !== "object" && typeof value !== "function") {
|
|
@@ -207,7 +228,7 @@ import{Bm25Ranker,CODEMODE_DOCS_PATH,CODEMODE_STORE_ENTRY_TYPE,DEFAULT_TOOL_SEAR
|
|
|
207
228
|
} catch (error) {
|
|
208
229
|
throw new TypeErrorCtor(error instanceof ErrorCtor ? error.message : String(error));
|
|
209
230
|
}
|
|
210
|
-
|
|
231
|
+
output("text", rendered);
|
|
211
232
|
}
|
|
212
233
|
|
|
213
234
|
function imageUrl(value) {
|
|
@@ -262,7 +283,7 @@ import{Bm25Ranker,CODEMODE_DOCS_PATH,CODEMODE_STORE_ENTRY_TYPE,DEFAULT_TOOL_SEAR
|
|
|
262
283
|
if (!signature) {
|
|
263
284
|
throw new TypeErrorCtor("invalid image output. The image data is not a PNG, JPEG, GIF, or WebP image");
|
|
264
285
|
}
|
|
265
|
-
|
|
286
|
+
output("image", data, signature[0]);
|
|
266
287
|
}
|
|
267
288
|
|
|
268
289
|
function exit() {
|
|
@@ -280,7 +301,7 @@ import{Bm25Ranker,CODEMODE_DOCS_PATH,CODEMODE_STORE_ENTRY_TYPE,DEFAULT_TOOL_SEAR
|
|
|
280
301
|
const console = {};
|
|
281
302
|
for (const level of ["log", "info", "warn", "error", "debug"]) {
|
|
282
303
|
console[level] = (...args) => {
|
|
283
|
-
|
|
304
|
+
output("text", args.map(format).join(" "));
|
|
284
305
|
};
|
|
285
306
|
}
|
|
286
307
|
Object.freeze(console);
|
package/dist/bundle/chunks/{google-generative-ai-APTPZOQL.js → google-generative-ai-ZOK6CV7D.js}
RENAMED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{GoogleGenAI,convertMessages,convertTools,getDisabledGoogleThinkingConfig,isThinkingPart,mapStopReason,resolveGoogleFunctionCallingMode,resolveGoogleThinkingLevel,retainThoughtSignature,retryGoogleRequest,supportsGoogleStrictToolSampling,toGoogleSdkThinkingLevel,toGoogleThinkingLevel,usesGoogleThinkingLevel}from"./chunk-
|
|
2
|
+
import{GoogleGenAI,convertMessages,convertTools,getDisabledGoogleThinkingConfig,isThinkingPart,mapStopReason,resolveGoogleFunctionCallingMode,resolveGoogleThinkingLevel,retainThoughtSignature,retryGoogleRequest,supportsGoogleStrictToolSampling,toGoogleSdkThinkingLevel,toGoogleThinkingLevel,usesGoogleThinkingLevel}from"./chunk-G7EDXK4D.js";import{formatProviderError,normalizeProviderError}from"./chunk-TEPMHNKQ.js";import"./chunk-LD2P6SFZ.js";import{buildBaseOptions,getPiUserAgent}from"./chunk-IKZJX7ZT.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{providerHeadersToRecord}from"./chunk-UTB4DTYQ.js";import{calculateCost,clampThinkingLevel,collapseSystemMessages,getCurrentTools,getInitialSystemMessage,getSystemMessageText}from"./chunk-7JGR3GZN.js";import{AssistantMessageEventStream}from"./chunk-A3JYRWB6.js";import"./chunk-4L3WN2XY.js";var toolCallCounter=0,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=collapseSystemMessages(context);return(async()=>{let output={role:"assistant",content:[],api:"google-generative-ai",provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{if(options?.fetch&&options.fetch!==globalThis.fetch)throw new Error("Custom fetch is not supported by the Google Generative AI adapter");let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let client=createClient(model,apiKey,options?.headers),params=buildParams(model,normalizedContext,options),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let googleStream=await retryGoogleRequest(()=>client.models.generateContentStream(params),options);stream2.push({type:"start",partial:output});let currentBlock=null,blocks=output.content,blockIndex=()=>blocks.length-1;for await(let chunk of googleStream){await options?.onProviderStreamEvent?.(chunk,model),output.responseId||=chunk.responseId;let candidate=chunk.candidates?.[0];if(candidate?.content?.parts)for(let part of candidate.content.parts){if(part.text!==void 0){let isThinking=isThinkingPart(part);(!currentBlock||isThinking&¤tBlock.type!=="thinking"||!isThinking&¤tBlock.type!=="text")&&(currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blocks.length-1,content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),isThinking?(currentBlock={type:"thinking",thinking:"",thinkingSignature:void 0},output.content.push(currentBlock),stream2.push({type:"thinking_start",contentIndex:blockIndex(),partial:output})):(currentBlock={type:"text",text:""},output.content.push(currentBlock),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output}))),currentBlock.type==="thinking"?(currentBlock.thinking+=part.text,currentBlock.thinkingSignature=retainThoughtSignature(currentBlock.thinkingSignature,part.thoughtSignature),stream2.push({type:"thinking_delta",contentIndex:blockIndex(),delta:part.text,partial:output})):(currentBlock.text+=part.text,currentBlock.textSignature=retainThoughtSignature(currentBlock.textSignature,part.thoughtSignature),stream2.push({type:"text_delta",contentIndex:blockIndex(),delta:part.text,partial:output}))}if(part.functionCall){currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output}),currentBlock=null);let providedId=part.functionCall.id,toolCall={type:"toolCall",id:!providedId||output.content.some(b=>b.type==="toolCall"&&b.id===providedId)?`${part.functionCall.name}_${Date.now()}_${++toolCallCounter}`:providedId,name:part.functionCall.name||"",arguments:part.functionCall.args??{},...part.thoughtSignature&&{thoughtSignature:part.thoughtSignature}};output.content.push(toolCall),stream2.push({type:"toolcall_start",contentIndex:blockIndex(),partial:output}),stream2.push({type:"toolcall_delta",contentIndex:blockIndex(),delta:JSON.stringify(toolCall.arguments),partial:output}),stream2.push({type:"toolcall_end",contentIndex:blockIndex(),toolCall,partial:output})}}candidate?.finishReason&&(output.rawStopReason=candidate.finishReason,output.stopReason=mapStopReason(candidate.finishReason),output.content.some(b=>b.type==="toolCall")&&output.stopReason==="stop"&&(output.stopReason="toolUse")),chunk.usageMetadata&&(output.usage={input:(chunk.usageMetadata.promptTokenCount||0)-(chunk.usageMetadata.cachedContentTokenCount||0),output:(chunk.usageMetadata.candidatesTokenCount||0)+(chunk.usageMetadata.thoughtsTokenCount||0),cacheRead:chunk.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,reasoning:chunk.usageMetadata.thoughtsTokenCount||0,totalTokens:chunk.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},calculateCost(model,output.usage))}if(currentBlock&&(currentBlock.type==="text"?stream2.push({type:"text_end",contentIndex:blockIndex(),content:currentBlock.text,partial:output}):stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:currentBlock.thinking,partial:output})),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Google stream ended without a finish reason");if(output.stopReason==="aborted"||output.stopReason==="error"){let errorMessage=output.rawStopReason?`Provider stopped with: ${output.rawStopReason}`:"An unknown error occurred";throw new Error(errorMessage)}stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)"index"in block&&delete block.index;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error)),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let base={...buildBaseOptions(model,context,options,apiKey),toolChoice:options?.toolChoice};if(!options?.reasoning)return stream(model,context,{...base,thinking:{enabled:!1}});let clampedReasoning=clampThinkingLevel(model,options.reasoning);if(clampedReasoning==="off")return stream(model,context,{...base,thinking:{enabled:!1}});let resolvedLevel=resolveGoogleThinkingLevel(model,clampedReasoning);return usesGoogleThinkingLevel(model)?stream(model,context,{...base,thinking:{enabled:!0,level:toGoogleThinkingLevel(resolvedLevel)}}):stream(model,context,{...base,thinking:{enabled:!0,budgetTokens:getGoogleBudget(model,resolvedLevel,options.thinkingBudgets)}})};function createClient(model,apiKey,optionsHeaders){let httpOptions={};model.baseUrl&&(httpOptions.baseUrl=model.baseUrl,httpOptions.apiVersion="");let headers=providerHeadersToRecord({"User-Agent":getPiUserAgent(),...model.headers,...optionsHeaders});return headers&&(httpOptions.headers=headers),new GoogleGenAI({apiKey,httpOptions:Object.keys(httpOptions).length>0?httpOptions:void 0})}function buildParams(model,context,options={}){let contents=convertMessages(model,context),initialSystemMessage=getInitialSystemMessage(context.messages),currentTools=getCurrentTools(context.messages),generationConfig={};options.temperature!==void 0&&(generationConfig.temperature=options.temperature),options.maxTokens!==void 0&&(generationConfig.maxOutputTokens=options.maxTokens);let supportsStrictMode=supportsGoogleStrictToolSampling(model.id),functionCallingMode=currentTools.length>0?resolveGoogleFunctionCallingMode(currentTools,options.toolChoice,supportsStrictMode):void 0,systemInstruction=initialSystemMessage?getSystemMessageText(initialSystemMessage):"",config={...Object.keys(generationConfig).length>0&&generationConfig,...systemInstruction&&{systemInstruction:sanitizeSurrogates(systemInstruction)},...currentTools.length>0&&{tools:convertTools(currentTools,!1,supportsStrictMode)},...functionCallingMode!==void 0&&{toolConfig:{functionCallingConfig:{mode:functionCallingMode}}}};if(options.thinking?.enabled&&model.reasoning){let thinkingConfig={includeThoughts:!0};options.thinking.level!==void 0?thinkingConfig.thinkingLevel=toGoogleSdkThinkingLevel(options.thinking.level):options.thinking.budgetTokens!==void 0&&(thinkingConfig.thinkingBudget=options.thinking.budgetTokens),config.thinkingConfig=thinkingConfig}else model.reasoning&&options.thinking&&!options.thinking.enabled&&(config.thinkingConfig=getDisabledGoogleThinkingConfig(model));if(options.signal){if(options.signal.aborted)throw new Error("Request aborted");config.abortSignal=options.signal}return{model:model.id,contents,config}}function getGoogleBudget(model,level,customBudgets){return customBudgets?.[level]!==void 0?customBudgets[level]:model.id.includes("2.5-pro")?{minimal:128,low:2048,medium:8192,high:32768}[level]:model.id.includes("2.5-flash-lite")?{minimal:512,low:2048,medium:8192,high:24576}[level]:model.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[level]:-1}export{stream,streamSimple};
|