raga-cli 0.9.0 → 0.10.0
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 +14 -0
- package/README.md +6 -1
- package/bundled-skills/bundle.json +9 -9
- package/bundled-skills/docs/guide/01-setup.md +1 -1
- package/bundled-skills/skills/peak/SKILL.md +1 -1
- package/bundled-skills/skills/peak/references/peak-setup/SKILL.md +1 -1
- package/bundled-skills/skills/peak/references/raga-runtime/SKILL.md +3 -3
- package/bundled-skills/skills/peak/references/raga-runtime/raga_runtime.py +12 -5
- package/bundled-skills/skills/raga-artifacts/artifact.mjs +5 -0
- package/dist/bundle/chunks/agent-attach-ZCS2QGIU.js +9 -0
- package/dist/bundle/chunks/chunk-4OPO7UJ6.js +4 -0
- package/dist/bundle/chunks/{chunk-ENUUAC3O.js → chunk-A4342OQJ.js} +9 -9
- package/dist/bundle/chunks/{chunk-OPPYO2IE.js → chunk-ABE5B2U7.js} +1 -1
- package/dist/bundle/chunks/{chunk-P2QCWBFM.js → chunk-D2SEW6VC.js} +1 -1
- package/dist/bundle/chunks/chunk-FTQDEUXY.js +242 -0
- package/dist/bundle/chunks/chunk-HRI5E2Y3.js +2 -0
- package/dist/bundle/chunks/{chunk-S5J3UB5O.js → chunk-JNHUOSVT.js} +1 -1
- package/dist/bundle/chunks/chunk-K22YTJFL.js +3 -0
- package/dist/bundle/chunks/chunk-MXJNFS34.js +47 -0
- package/dist/bundle/chunks/{chunk-NP6TH6UT.js → chunk-NXGZMUQX.js} +3 -48
- package/dist/bundle/chunks/{chunk-JQDZ4Z7L.js → chunk-NYFFOHME.js} +1 -1
- package/dist/bundle/chunks/chunk-P2EB6CEF.js +6 -0
- package/dist/bundle/chunks/{chunk-KNY3PXQI.js → chunk-SK25JXS4.js} +1 -1
- package/dist/bundle/chunks/chunk-VEV3PRRP.js +1358 -0
- package/dist/bundle/chunks/chunk-XBBS7V4D.js +2 -0
- package/dist/bundle/chunks/{cli-QLDCDYOR.js → cli-XZ774I3U.js} +1 -1
- package/dist/bundle/chunks/{easter-egg-3d-NPDBBPPF.js → easter-egg-3d-XWC5XWQO.js} +1 -1
- package/dist/bundle/chunks/{execute-WPTMS4XG.js → execute-7BWE4ZV3.js} +1 -1
- package/dist/bundle/chunks/runtime-K76CFDG5.js +2 -0
- package/dist/bundle/chunks/virtual-modules-YAFG26WW.js +2 -0
- package/dist/bundle/cli-runtime.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/raga-runtime.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/docs/cli.md +2 -0
- package/package.json +1 -1
- package/python/raga_rlm/__init__.py +10 -2
- package/schemas/keybindings.schema.json +36 -0
- package/schemas/settings.schema.json +60 -1
- package/schemas/theme.schema.json +2 -2
- package/dist/bundle/chunks/chunk-3MNXTBQ3.js +0 -2
- package/dist/bundle/chunks/chunk-F7LFZTHT.js +0 -1591
- package/dist/bundle/chunks/chunk-RFPFZTK2.js +0 -7
- package/dist/bundle/chunks/chunk-RP2WKNT7.js +0 -4
- package/dist/bundle/chunks/runtime-N5MUH2WA.js +0 -2
- package/dist/bundle/chunks/virtual-modules-4I6Y6DPQ.js +0 -2
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
+
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()}export{openBrowser};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
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,isObject,mcpNamespace,
|
|
2
|
+
import{FileAuthStorageBackend,JSON_RPC_ERROR_CODES,LATEST_PROTOCOL_VERSION,McpAuthRequiredError,McpClient,McpError,McpHttpError,McpSessionExpiredError,StdioTransport,StreamableHttpTransport,isObject,mcpNamespace,resolveConfigValueOrThrow,resolveHeadersOrThrow}from"./chunk-P2EB6CEF.js";import{require_proper_lockfile}from"./chunk-K22YTJFL.js";import{APP_NAME,VERSION,getAgentDir}from"./chunk-SK25JXS4.js";import{__toESM}from"./chunk-JXWJOIH4.js";import{homedir}from"node:os";import{basename,join as join2,resolve}from"node:path";import{setTimeout as sleep}from"node:timers/promises";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
3
|
|
|
4
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){let format=issuer=>issuer===void 0?"none":JSON.stringify(issuer);super(`OAuth issuer mismatch: expected ${format(expected)}, received ${format(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,signal){return fetch(url,{headers:{Accept:"application/json","MCP-Protocol-Version":protocolVersion},signal})}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,options.signal);if(!options.resourceMetadataUrl&&server.pathname!=="/"&&isDiscoveryMiss(response.status)&&(discard(response),response=await fetchMetadata(new URL("/.well-known/oauth-protected-resource",server.origin),fetch,version,options.signal)),!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,options.signal);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,signal:options.signal})}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,options.signal);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,signal:options.signal}),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 applicationType(redirectUris){return redirectUris.some(uri=>{if(!URL.canParse(uri))return!1;let url=new URL(uri);return url.protocol!=="http:"&&url.protocol!=="https:"||loopback(url.hostname)})?"native":"web"}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,signal:options.signal}),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,application_type:options.clientMetadata.application_type??applicationType(options.clientMetadata.redirect_uris),...options.scope?{scope:options.scope}:{}}),signal:options.signal});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,signal:options.signal}),resourceMetadata:cached.resourceMetadata}:await discoverOAuthServerInfo(options.serverUrl,{resourceMetadataUrl:options.resourceMetadataUrl,authorizationServerMetadataUrl:metadataUrl,fetch:options.fetch,skipIssuerValidation:options.skipIssuerValidation,signal:options.signal});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,signal:options.signal}),await provider.saveClientInformation(client)}let redirectUrl=clientDocument?.redirectUrl??provider.redirectUrl,tokenOptions={metadata,clientInformation:client,resource,addClientAuthentication:provider.addClientAuthentication,fetch:options.fetch,signal:options.signal};if(options.authorizationCode){let iss=options.iss;if((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(options.signal?.aborted||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";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
5
|
<html lang="en">
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
+
import{__commonJS,__require}from"./chunk-JXWJOIH4.js";var require_polyfills=__commonJS({"node_modules/graceful-fs/polyfills.js"(exports,module){var constants=__require("constants"),origCwd=process.cwd,cwd=null,platform=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return cwd||(cwd=origCwd.call(process)),cwd};try{process.cwd()}catch{}typeof process.chdir=="function"&&(chdir=process.chdir,process.chdir=function(d){cwd=null,chdir.call(process,d)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,chdir));var chdir;module.exports=patch;function patch(fs){constants.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&patchLchmod(fs),fs.lutimes||patchLutimes(fs),fs.chown=chownFix(fs.chown),fs.fchown=chownFix(fs.fchown),fs.lchown=chownFix(fs.lchown),fs.chmod=chmodFix(fs.chmod),fs.fchmod=chmodFix(fs.fchmod),fs.lchmod=chmodFix(fs.lchmod),fs.chownSync=chownFixSync(fs.chownSync),fs.fchownSync=chownFixSync(fs.fchownSync),fs.lchownSync=chownFixSync(fs.lchownSync),fs.chmodSync=chmodFixSync(fs.chmodSync),fs.fchmodSync=chmodFixSync(fs.fchmodSync),fs.lchmodSync=chmodFixSync(fs.lchmodSync),fs.stat=statFix(fs.stat),fs.fstat=statFix(fs.fstat),fs.lstat=statFix(fs.lstat),fs.statSync=statFixSync(fs.statSync),fs.fstatSync=statFixSync(fs.fstatSync),fs.lstatSync=statFixSync(fs.lstatSync),fs.chmod&&!fs.lchmod&&(fs.lchmod=function(path,mode,cb){cb&&process.nextTick(cb)},fs.lchmodSync=function(){}),fs.chown&&!fs.lchown&&(fs.lchown=function(path,uid,gid,cb){cb&&process.nextTick(cb)},fs.lchownSync=function(){}),platform==="win32"&&(fs.rename=typeof fs.rename!="function"?fs.rename:(function(fs$rename){function rename(from,to,cb){var start=Date.now(),backoff=0;fs$rename(from,to,function CB(er){if(er&&(er.code==="EACCES"||er.code==="EPERM"||er.code==="EBUSY")&&Date.now()-start<6e4){setTimeout(function(){fs.stat(to,function(stater,st){stater&&stater.code==="ENOENT"?fs$rename(from,to,CB):cb(er)})},backoff),backoff<100&&(backoff+=10);return}cb&&cb(er)})}return Object.setPrototypeOf&&Object.setPrototypeOf(rename,fs$rename),rename})(fs.rename)),fs.read=typeof fs.read!="function"?fs.read:(function(fs$read){function read(fd,buffer,offset,length,position,callback_){var callback;if(callback_&&typeof callback_=="function"){var eagCounter=0;callback=function(er,_,__){if(er&&er.code==="EAGAIN"&&eagCounter<10)return eagCounter++,fs$read.call(fs,fd,buffer,offset,length,position,callback);callback_.apply(this,arguments)}}return fs$read.call(fs,fd,buffer,offset,length,position,callback)}return Object.setPrototypeOf&&Object.setPrototypeOf(read,fs$read),read})(fs.read),fs.readSync=typeof fs.readSync!="function"?fs.readSync:(function(fs$readSync){return function(fd,buffer,offset,length,position){for(var eagCounter=0;;)try{return fs$readSync.call(fs,fd,buffer,offset,length,position)}catch(er){if(er.code==="EAGAIN"&&eagCounter<10){eagCounter++;continue}throw er}}})(fs.readSync);function patchLchmod(fs2){fs2.lchmod=function(path,mode,callback){fs2.open(path,constants.O_WRONLY|constants.O_SYMLINK,mode,function(err,fd){if(err){callback&&callback(err);return}fs2.fchmod(fd,mode,function(err2){fs2.close(fd,function(err22){callback&&callback(err2||err22)})})})},fs2.lchmodSync=function(path,mode){var fd=fs2.openSync(path,constants.O_WRONLY|constants.O_SYMLINK,mode),threw=!0,ret;try{ret=fs2.fchmodSync(fd,mode),threw=!1}finally{if(threw)try{fs2.closeSync(fd)}catch{}else fs2.closeSync(fd)}return ret}}function patchLutimes(fs2){constants.hasOwnProperty("O_SYMLINK")&&fs2.futimes?(fs2.lutimes=function(path,at,mt,cb){fs2.open(path,constants.O_SYMLINK,function(er,fd){if(er){cb&&cb(er);return}fs2.futimes(fd,at,mt,function(er2){fs2.close(fd,function(er22){cb&&cb(er2||er22)})})})},fs2.lutimesSync=function(path,at,mt){var fd=fs2.openSync(path,constants.O_SYMLINK),ret,threw=!0;try{ret=fs2.futimesSync(fd,at,mt),threw=!1}finally{if(threw)try{fs2.closeSync(fd)}catch{}else fs2.closeSync(fd)}return ret}):fs2.futimes&&(fs2.lutimes=function(_a,_b,_c,cb){cb&&process.nextTick(cb)},fs2.lutimesSync=function(){})}function chmodFix(orig){return orig&&function(target,mode,cb){return orig.call(fs,target,mode,function(er){chownErOk(er)&&(er=null),cb&&cb.apply(this,arguments)})}}function chmodFixSync(orig){return orig&&function(target,mode){try{return orig.call(fs,target,mode)}catch(er){if(!chownErOk(er))throw er}}}function chownFix(orig){return orig&&function(target,uid,gid,cb){return orig.call(fs,target,uid,gid,function(er){chownErOk(er)&&(er=null),cb&&cb.apply(this,arguments)})}}function chownFixSync(orig){return orig&&function(target,uid,gid){try{return orig.call(fs,target,uid,gid)}catch(er){if(!chownErOk(er))throw er}}}function statFix(orig){return orig&&function(target,options,cb){typeof options=="function"&&(cb=options,options=null);function callback(er,stats){stats&&(stats.uid<0&&(stats.uid+=4294967296),stats.gid<0&&(stats.gid+=4294967296)),cb&&cb.apply(this,arguments)}return options?orig.call(fs,target,options,callback):orig.call(fs,target,callback)}}function statFixSync(orig){return orig&&function(target,options){var stats=options?orig.call(fs,target,options):orig.call(fs,target);return stats&&(stats.uid<0&&(stats.uid+=4294967296),stats.gid<0&&(stats.gid+=4294967296)),stats}}function chownErOk(er){if(!er||er.code==="ENOSYS")return!0;var nonroot=!process.getuid||process.getuid()!==0;return!!(nonroot&&(er.code==="EINVAL"||er.code==="EPERM"))}}}});var require_legacy_streams=__commonJS({"node_modules/graceful-fs/legacy-streams.js"(exports,module){var Stream=__require("stream").Stream;module.exports=legacy;function legacy(fs){return{ReadStream,WriteStream};function ReadStream(path,options){if(!(this instanceof ReadStream))return new ReadStream(path,options);Stream.call(this);var self=this;this.path=path,this.fd=null,this.readable=!0,this.paused=!1,this.flags="r",this.mode=438,this.bufferSize=64*1024,options=options||{};for(var keys=Object.keys(options),index=0,length=keys.length;index<length;index++){var key=keys[index];this[key]=options[key]}if(this.encoding&&this.setEncoding(this.encoding),this.start!==void 0){if(typeof this.start!="number")throw TypeError("start must be a Number");if(this.end===void 0)this.end=1/0;else if(typeof this.end!="number")throw TypeError("end must be a Number");if(this.start>this.end)throw new Error("start must be <= end");this.pos=this.start}if(this.fd!==null){process.nextTick(function(){self._read()});return}fs.open(this.path,this.flags,this.mode,function(err,fd){if(err){self.emit("error",err),self.readable=!1;return}self.fd=fd,self.emit("open",fd),self._read()})}function WriteStream(path,options){if(!(this instanceof WriteStream))return new WriteStream(path,options);Stream.call(this),this.path=path,this.fd=null,this.writable=!0,this.flags="w",this.encoding="binary",this.mode=438,this.bytesWritten=0,options=options||{};for(var keys=Object.keys(options),index=0,length=keys.length;index<length;index++){var key=keys[index];this[key]=options[key]}if(this.start!==void 0){if(typeof this.start!="number")throw TypeError("start must be a Number");if(this.start<0)throw new Error("start must be >= zero");this.pos=this.start}this.busy=!1,this._queue=[],this.fd===null&&(this._open=fs.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush())}}}});var require_clone=__commonJS({"node_modules/graceful-fs/clone.js"(exports,module){"use strict";module.exports=clone;var getPrototypeOf=Object.getPrototypeOf||function(obj){return obj.__proto__};function clone(obj){if(obj===null||typeof obj!="object")return obj;if(obj instanceof Object)var copy={__proto__:getPrototypeOf(obj)};else var copy=Object.create(null);return Object.getOwnPropertyNames(obj).forEach(function(key){Object.defineProperty(copy,key,Object.getOwnPropertyDescriptor(obj,key))}),copy}}});var require_graceful_fs=__commonJS({"node_modules/graceful-fs/graceful-fs.js"(exports,module){var fs=__require("fs"),polyfills=require_polyfills(),legacy=require_legacy_streams(),clone=require_clone(),util=__require("util"),gracefulQueue,previousSymbol;typeof Symbol=="function"&&typeof Symbol.for=="function"?(gracefulQueue=Symbol.for("graceful-fs.queue"),previousSymbol=Symbol.for("graceful-fs.previous")):(gracefulQueue="___graceful-fs.queue",previousSymbol="___graceful-fs.previous");function noop(){}function publishQueue(context,queue2){Object.defineProperty(context,gracefulQueue,{get:function(){return queue2}})}var debug=noop;util.debuglog?debug=util.debuglog("gfs4"):/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&(debug=function(){var m=util.format.apply(util,arguments);m="GFS4: "+m.split(/\n/).join(`
|
|
3
|
+
GFS4: `),console.error(m)});fs[gracefulQueue]||(queue=global[gracefulQueue]||[],publishQueue(fs,queue),fs.close=(function(fs$close){function close(fd,cb){return fs$close.call(fs,fd,function(err){err||resetQueue(),typeof cb=="function"&&cb.apply(this,arguments)})}return Object.defineProperty(close,previousSymbol,{value:fs$close}),close})(fs.close),fs.closeSync=(function(fs$closeSync){function closeSync(fd){fs$closeSync.apply(fs,arguments),resetQueue()}return Object.defineProperty(closeSync,previousSymbol,{value:fs$closeSync}),closeSync})(fs.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&process.on("exit",function(){debug(fs[gracefulQueue]),__require("assert").equal(fs[gracefulQueue].length,0)}));var queue;global[gracefulQueue]||publishQueue(global,fs[gracefulQueue]);module.exports=patch(clone(fs));process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!fs.__patched&&(module.exports=patch(fs),fs.__patched=!0);function patch(fs2){polyfills(fs2),fs2.gracefulify=patch,fs2.createReadStream=createReadStream,fs2.createWriteStream=createWriteStream;var fs$readFile=fs2.readFile;fs2.readFile=readFile;function readFile(path,options,cb){return typeof options=="function"&&(cb=options,options=null),go$readFile(path,options,cb);function go$readFile(path2,options2,cb2,startTime){return fs$readFile(path2,options2,function(err){err&&(err.code==="EMFILE"||err.code==="ENFILE")?enqueue([go$readFile,[path2,options2,cb2],err,startTime||Date.now(),Date.now()]):typeof cb2=="function"&&cb2.apply(this,arguments)})}}var fs$writeFile=fs2.writeFile;fs2.writeFile=writeFile;function writeFile(path,data,options,cb){return typeof options=="function"&&(cb=options,options=null),go$writeFile(path,data,options,cb);function go$writeFile(path2,data2,options2,cb2,startTime){return fs$writeFile(path2,data2,options2,function(err){err&&(err.code==="EMFILE"||err.code==="ENFILE")?enqueue([go$writeFile,[path2,data2,options2,cb2],err,startTime||Date.now(),Date.now()]):typeof cb2=="function"&&cb2.apply(this,arguments)})}}var fs$appendFile=fs2.appendFile;fs$appendFile&&(fs2.appendFile=appendFile);function appendFile(path,data,options,cb){return typeof options=="function"&&(cb=options,options=null),go$appendFile(path,data,options,cb);function go$appendFile(path2,data2,options2,cb2,startTime){return fs$appendFile(path2,data2,options2,function(err){err&&(err.code==="EMFILE"||err.code==="ENFILE")?enqueue([go$appendFile,[path2,data2,options2,cb2],err,startTime||Date.now(),Date.now()]):typeof cb2=="function"&&cb2.apply(this,arguments)})}}var fs$copyFile=fs2.copyFile;fs$copyFile&&(fs2.copyFile=copyFile);function copyFile(src,dest,flags,cb){return typeof flags=="function"&&(cb=flags,flags=0),go$copyFile(src,dest,flags,cb);function go$copyFile(src2,dest2,flags2,cb2,startTime){return fs$copyFile(src2,dest2,flags2,function(err){err&&(err.code==="EMFILE"||err.code==="ENFILE")?enqueue([go$copyFile,[src2,dest2,flags2,cb2],err,startTime||Date.now(),Date.now()]):typeof cb2=="function"&&cb2.apply(this,arguments)})}}var fs$readdir=fs2.readdir;fs2.readdir=readdir;var noReaddirOptionVersions=/^v[0-5]\./;function readdir(path,options,cb){typeof options=="function"&&(cb=options,options=null);var go$readdir=noReaddirOptionVersions.test(process.version)?function(path2,options2,cb2,startTime){return fs$readdir(path2,fs$readdirCallback(path2,options2,cb2,startTime))}:function(path2,options2,cb2,startTime){return fs$readdir(path2,options2,fs$readdirCallback(path2,options2,cb2,startTime))};return go$readdir(path,options,cb);function fs$readdirCallback(path2,options2,cb2,startTime){return function(err,files){err&&(err.code==="EMFILE"||err.code==="ENFILE")?enqueue([go$readdir,[path2,options2,cb2],err,startTime||Date.now(),Date.now()]):(files&&files.sort&&files.sort(),typeof cb2=="function"&&cb2.call(this,err,files))}}}if(process.version.substr(0,4)==="v0.8"){var legStreams=legacy(fs2);ReadStream=legStreams.ReadStream,WriteStream=legStreams.WriteStream}var fs$ReadStream=fs2.ReadStream;fs$ReadStream&&(ReadStream.prototype=Object.create(fs$ReadStream.prototype),ReadStream.prototype.open=ReadStream$open);var fs$WriteStream=fs2.WriteStream;fs$WriteStream&&(WriteStream.prototype=Object.create(fs$WriteStream.prototype),WriteStream.prototype.open=WriteStream$open),Object.defineProperty(fs2,"ReadStream",{get:function(){return ReadStream},set:function(val){ReadStream=val},enumerable:!0,configurable:!0}),Object.defineProperty(fs2,"WriteStream",{get:function(){return WriteStream},set:function(val){WriteStream=val},enumerable:!0,configurable:!0});var FileReadStream=ReadStream;Object.defineProperty(fs2,"FileReadStream",{get:function(){return FileReadStream},set:function(val){FileReadStream=val},enumerable:!0,configurable:!0});var FileWriteStream=WriteStream;Object.defineProperty(fs2,"FileWriteStream",{get:function(){return FileWriteStream},set:function(val){FileWriteStream=val},enumerable:!0,configurable:!0});function ReadStream(path,options){return this instanceof ReadStream?(fs$ReadStream.apply(this,arguments),this):ReadStream.apply(Object.create(ReadStream.prototype),arguments)}function ReadStream$open(){var that=this;open(that.path,that.flags,that.mode,function(err,fd){err?(that.autoClose&&that.destroy(),that.emit("error",err)):(that.fd=fd,that.emit("open",fd),that.read())})}function WriteStream(path,options){return this instanceof WriteStream?(fs$WriteStream.apply(this,arguments),this):WriteStream.apply(Object.create(WriteStream.prototype),arguments)}function WriteStream$open(){var that=this;open(that.path,that.flags,that.mode,function(err,fd){err?(that.destroy(),that.emit("error",err)):(that.fd=fd,that.emit("open",fd))})}function createReadStream(path,options){return new fs2.ReadStream(path,options)}function createWriteStream(path,options){return new fs2.WriteStream(path,options)}var fs$open=fs2.open;fs2.open=open;function open(path,flags,mode,cb){return typeof mode=="function"&&(cb=mode,mode=null),go$open(path,flags,mode,cb);function go$open(path2,flags2,mode2,cb2,startTime){return fs$open(path2,flags2,mode2,function(err,fd){err&&(err.code==="EMFILE"||err.code==="ENFILE")?enqueue([go$open,[path2,flags2,mode2,cb2],err,startTime||Date.now(),Date.now()]):typeof cb2=="function"&&cb2.apply(this,arguments)})}}return fs2}function enqueue(elem){debug("ENQUEUE",elem[0].name,elem[1]),fs[gracefulQueue].push(elem),retry()}var retryTimer;function resetQueue(){for(var now=Date.now(),i=0;i<fs[gracefulQueue].length;++i)fs[gracefulQueue][i].length>2&&(fs[gracefulQueue][i][3]=now,fs[gracefulQueue][i][4]=now);retry()}function retry(){if(clearTimeout(retryTimer),retryTimer=void 0,fs[gracefulQueue].length!==0){var elem=fs[gracefulQueue].shift(),fn=elem[0],args=elem[1],err=elem[2],startTime=elem[3],lastTime=elem[4];if(startTime===void 0)debug("RETRY",fn.name,args),fn.apply(null,args);else if(Date.now()-startTime>=6e4){debug("TIMEOUT",fn.name,args);var cb=args.pop();typeof cb=="function"&&cb.call(null,err)}else{var sinceAttempt=Date.now()-lastTime,sinceStart=Math.max(lastTime-startTime,1),desiredDelay=Math.min(sinceStart*1.2,100);sinceAttempt>=desiredDelay?(debug("RETRY",fn.name,args),fn.apply(null,args.concat([startTime]))):fs[gracefulQueue].push(elem)}retryTimer===void 0&&(retryTimer=setTimeout(retry,0))}}}});var require_retry_operation=__commonJS({"node_modules/proper-lockfile/node_modules/retry/lib/retry_operation.js"(exports,module){function RetryOperation(timeouts,options){typeof options=="boolean"&&(options={forever:options}),this._originalTimeouts=JSON.parse(JSON.stringify(timeouts)),this._timeouts=timeouts,this._options=options||{},this._maxRetryTime=options&&options.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}module.exports=RetryOperation;RetryOperation.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts};RetryOperation.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timeouts=[],this._cachedTimeouts=null};RetryOperation.prototype.retry=function(err){if(this._timeout&&clearTimeout(this._timeout),!err)return!1;var currentTime=new Date().getTime();if(err&¤tTime-this._operationStart>=this._maxRetryTime)return this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(err);var timeout=this._timeouts.shift();if(timeout===void 0)if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),timeout=this._timeouts.shift();else return!1;var self=this,timer=setTimeout(function(){self._attempts++,self._operationTimeoutCb&&(self._timeout=setTimeout(function(){self._operationTimeoutCb(self._attempts)},self._operationTimeout),self._options.unref&&self._timeout.unref()),self._fn(self._attempts)},timeout);return this._options.unref&&timer.unref(),!0};RetryOperation.prototype.attempt=function(fn,timeoutOps){this._fn=fn,timeoutOps&&(timeoutOps.timeout&&(this._operationTimeout=timeoutOps.timeout),timeoutOps.cb&&(this._operationTimeoutCb=timeoutOps.cb));var self=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){self._operationTimeoutCb()},self._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};RetryOperation.prototype.try=function(fn){console.log("Using RetryOperation.try() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=function(fn){console.log("Using RetryOperation.start() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=RetryOperation.prototype.try;RetryOperation.prototype.errors=function(){return this._errors};RetryOperation.prototype.attempts=function(){return this._attempts};RetryOperation.prototype.mainError=function(){if(this._errors.length===0)return null;for(var counts={},mainError=null,mainErrorCount=0,i=0;i<this._errors.length;i++){var error=this._errors[i],message=error.message,count=(counts[message]||0)+1;counts[message]=count,count>=mainErrorCount&&(mainError=error,mainErrorCount=count)}return mainError}}});var require_retry=__commonJS({"node_modules/proper-lockfile/node_modules/retry/lib/retry.js"(exports){var RetryOperation=require_retry_operation();exports.operation=function(options){var timeouts=exports.timeouts(options);return new RetryOperation(timeouts,{forever:options&&options.forever,unref:options&&options.unref,maxRetryTime:options&&options.maxRetryTime})};exports.timeouts=function(options){if(options instanceof Array)return[].concat(options);var opts={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var key in options)opts[key]=options[key];if(opts.minTimeout>opts.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var timeouts=[],i=0;i<opts.retries;i++)timeouts.push(this.createTimeout(i,opts));return options&&options.forever&&!timeouts.length&&timeouts.push(this.createTimeout(i,opts)),timeouts.sort(function(a,b){return a-b}),timeouts};exports.createTimeout=function(attempt,opts){var random=opts.randomize?Math.random()+1:1,timeout=Math.round(random*opts.minTimeout*Math.pow(opts.factor,attempt));return timeout=Math.min(timeout,opts.maxTimeout),timeout};exports.wrap=function(obj,options,methods){if(options instanceof Array&&(methods=options,options=null),!methods){methods=[];for(var key in obj)typeof obj[key]=="function"&&methods.push(key)}for(var i=0;i<methods.length;i++){var method=methods[i],original=obj[method];obj[method]=function(original2){var op=exports.operation(options),args=Array.prototype.slice.call(arguments,1),callback=args.pop();args.push(function(err){op.retry(err)||(err&&(arguments[0]=op.mainError()),callback.apply(this,arguments))}),op.attempt(function(){original2.apply(obj,args)})}.bind(obj,original),obj[method].options=options}}}});var require_retry2=__commonJS({"node_modules/proper-lockfile/node_modules/retry/index.js"(exports,module){module.exports=require_retry()}});var require_signals=__commonJS({"node_modules/signal-exit/signals.js"(exports,module){module.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];process.platform!=="win32"&&module.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&module.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")}});var require_signal_exit=__commonJS({"node_modules/signal-exit/index.js"(exports,module){var process2=global.process,processOk=function(process3){return process3&&typeof process3=="object"&&typeof process3.removeListener=="function"&&typeof process3.emit=="function"&&typeof process3.reallyExit=="function"&&typeof process3.listeners=="function"&&typeof process3.kill=="function"&&typeof process3.pid=="number"&&typeof process3.on=="function"};processOk(process2)?(assert=__require("assert"),signals=require_signals(),isWin=/^win/i.test(process2.platform),EE=__require("events"),typeof EE!="function"&&(EE=EE.EventEmitter),process2.__signal_exit_emitter__?emitter=process2.__signal_exit_emitter__:(emitter=process2.__signal_exit_emitter__=new EE,emitter.count=0,emitter.emitted={}),emitter.infinite||(emitter.setMaxListeners(1/0),emitter.infinite=!0),module.exports=function(cb,opts){if(!processOk(global.process))return function(){};assert.equal(typeof cb,"function","a callback must be provided for exit handler"),loaded===!1&&load();var ev="exit";opts&&opts.alwaysLast&&(ev="afterexit");var remove=function(){emitter.removeListener(ev,cb),emitter.listeners("exit").length===0&&emitter.listeners("afterexit").length===0&&unload()};return emitter.on(ev,cb),remove},unload=function(){!loaded||!processOk(global.process)||(loaded=!1,signals.forEach(function(sig){try{process2.removeListener(sig,sigListeners[sig])}catch{}}),process2.emit=originalProcessEmit,process2.reallyExit=originalProcessReallyExit,emitter.count-=1)},module.exports.unload=unload,emit=function(event,code,signal){emitter.emitted[event]||(emitter.emitted[event]=!0,emitter.emit(event,code,signal))},sigListeners={},signals.forEach(function(sig){sigListeners[sig]=function(){if(processOk(global.process)){var listeners=process2.listeners(sig);listeners.length===emitter.count&&(unload(),emit("exit",null,sig),emit("afterexit",null,sig),isWin&&sig==="SIGHUP"&&(sig="SIGINT"),process2.kill(process2.pid,sig))}}}),module.exports.signals=function(){return signals},loaded=!1,load=function(){loaded||!processOk(global.process)||(loaded=!0,emitter.count+=1,signals=signals.filter(function(sig){try{return process2.on(sig,sigListeners[sig]),!0}catch{return!1}}),process2.emit=processEmit,process2.reallyExit=processReallyExit)},module.exports.load=load,originalProcessReallyExit=process2.reallyExit,processReallyExit=function(code){processOk(global.process)&&(process2.exitCode=code||0,emit("exit",process2.exitCode,null),emit("afterexit",process2.exitCode,null),originalProcessReallyExit.call(process2,process2.exitCode))},originalProcessEmit=process2.emit,processEmit=function(ev,arg){if(ev==="exit"&&processOk(global.process)){arg!==void 0&&(process2.exitCode=arg);var ret=originalProcessEmit.apply(this,arguments);return emit("exit",process2.exitCode,null),emit("afterexit",process2.exitCode,null),ret}else return originalProcessEmit.apply(this,arguments)}):module.exports=function(){return function(){}};var assert,signals,isWin,EE,emitter,unload,emit,sigListeners,loaded,load,originalProcessReallyExit,processReallyExit,originalProcessEmit,processEmit}});var require_mtime_precision=__commonJS({"node_modules/proper-lockfile/lib/mtime-precision.js"(exports,module){"use strict";var cacheSymbol=Symbol();function probe(file,fs,callback){let cachedPrecision=fs[cacheSymbol];if(cachedPrecision)return fs.stat(file,(err,stat)=>{if(err)return callback(err);callback(null,stat.mtime,cachedPrecision)});let mtime=new Date(Math.ceil(Date.now()/1e3)*1e3+5);fs.utimes(file,mtime,mtime,err=>{if(err)return callback(err);fs.stat(file,(err2,stat)=>{if(err2)return callback(err2);let precision=stat.mtime.getTime()%1e3===0?"s":"ms";Object.defineProperty(fs,cacheSymbol,{value:precision}),callback(null,stat.mtime,precision)})})}function getMtime(precision){let now=Date.now();return precision==="s"&&(now=Math.ceil(now/1e3)*1e3),new Date(now)}module.exports.probe=probe;module.exports.getMtime=getMtime}});var require_lockfile=__commonJS({"node_modules/proper-lockfile/lib/lockfile.js"(exports,module){"use strict";var path=__require("path"),fs=require_graceful_fs(),retry=require_retry2(),onExit=require_signal_exit(),mtimePrecision=require_mtime_precision(),locks={};function getLockFile(file,options){return options.lockfilePath||`${file}.lock`}function resolveCanonicalPath(file,options,callback){if(!options.realpath)return callback(null,path.resolve(file));options.fs.realpath(file,callback)}function acquireLock(file,options,callback){let lockfilePath=getLockFile(file,options);options.fs.mkdir(lockfilePath,err=>{if(!err)return mtimePrecision.probe(lockfilePath,options.fs,(err2,mtime,mtimePrecision2)=>{if(err2)return options.fs.rmdir(lockfilePath,()=>{}),callback(err2);callback(null,mtime,mtimePrecision2)});if(err.code!=="EEXIST")return callback(err);if(options.stale<=0)return callback(Object.assign(new Error("Lock file is already being held"),{code:"ELOCKED",file}));options.fs.stat(lockfilePath,(err2,stat)=>{if(err2)return err2.code==="ENOENT"?acquireLock(file,{...options,stale:0},callback):callback(err2);if(!isLockStale(stat,options))return callback(Object.assign(new Error("Lock file is already being held"),{code:"ELOCKED",file}));removeLock(file,options,err3=>{if(err3)return callback(err3);acquireLock(file,{...options,stale:0},callback)})})})}function isLockStale(stat,options){return stat.mtime.getTime()<Date.now()-options.stale}function removeLock(file,options,callback){options.fs.rmdir(getLockFile(file,options),err=>{if(err&&err.code!=="ENOENT")return callback(err);callback()})}function updateLock(file,options){let lock2=locks[file];lock2.updateTimeout||(lock2.updateDelay=lock2.updateDelay||options.update,lock2.updateTimeout=setTimeout(()=>{lock2.updateTimeout=null,options.fs.stat(lock2.lockfilePath,(err,stat)=>{let isOverThreshold=lock2.lastUpdate+options.stale<Date.now();if(err)return err.code==="ENOENT"||isOverThreshold?setLockAsCompromised(file,lock2,Object.assign(err,{code:"ECOMPROMISED"})):(lock2.updateDelay=1e3,updateLock(file,options));if(!(lock2.mtime.getTime()===stat.mtime.getTime()))return setLockAsCompromised(file,lock2,Object.assign(new Error("Unable to update lock within the stale threshold"),{code:"ECOMPROMISED"}));let mtime=mtimePrecision.getMtime(lock2.mtimePrecision);options.fs.utimes(lock2.lockfilePath,mtime,mtime,err2=>{let isOverThreshold2=lock2.lastUpdate+options.stale<Date.now();if(!lock2.released){if(err2)return err2.code==="ENOENT"||isOverThreshold2?setLockAsCompromised(file,lock2,Object.assign(err2,{code:"ECOMPROMISED"})):(lock2.updateDelay=1e3,updateLock(file,options));lock2.mtime=mtime,lock2.lastUpdate=Date.now(),lock2.updateDelay=null,updateLock(file,options)}})})},lock2.updateDelay),lock2.updateTimeout.unref&&lock2.updateTimeout.unref())}function setLockAsCompromised(file,lock2,err){lock2.released=!0,lock2.updateTimeout&&clearTimeout(lock2.updateTimeout),locks[file]===lock2&&delete locks[file],lock2.options.onCompromised(err)}function lock(file,options,callback){options={stale:1e4,update:null,realpath:!0,retries:0,fs,onCompromised:err=>{throw err},...options},options.retries=options.retries||0,options.retries=typeof options.retries=="number"?{retries:options.retries}:options.retries,options.stale=Math.max(options.stale||0,2e3),options.update=options.update==null?options.stale/2:options.update||0,options.update=Math.max(Math.min(options.update,options.stale/2),1e3),resolveCanonicalPath(file,options,(err,file2)=>{if(err)return callback(err);let operation=retry.operation(options.retries);operation.attempt(()=>{acquireLock(file2,options,(err2,mtime,mtimePrecision2)=>{if(operation.retry(err2))return;if(err2)return callback(operation.mainError());let lock2=locks[file2]={lockfilePath:getLockFile(file2,options),mtime,mtimePrecision:mtimePrecision2,options,lastUpdate:Date.now()};updateLock(file2,options),callback(null,releasedCallback=>{if(lock2.released)return releasedCallback&&releasedCallback(Object.assign(new Error("Lock is already released"),{code:"ERELEASED"}));unlock(file2,{...options,realpath:!1},releasedCallback)})})})})}function unlock(file,options,callback){options={fs,realpath:!0,...options},resolveCanonicalPath(file,options,(err,file2)=>{if(err)return callback(err);let lock2=locks[file2];if(!lock2)return callback(Object.assign(new Error("Lock is not acquired/owned by you"),{code:"ENOTACQUIRED"}));lock2.updateTimeout&&clearTimeout(lock2.updateTimeout),lock2.released=!0,delete locks[file2],removeLock(file2,options,callback)})}function check(file,options,callback){options={stale:1e4,realpath:!0,fs,...options},options.stale=Math.max(options.stale||0,2e3),resolveCanonicalPath(file,options,(err,file2)=>{if(err)return callback(err);options.fs.stat(getLockFile(file2,options),(err2,stat)=>err2?err2.code==="ENOENT"?callback(null,!1):callback(err2):callback(null,!isLockStale(stat,options)))})}function getLocks(){return locks}onExit(()=>{for(let file in locks){let options=locks[file].options;try{options.fs.rmdirSync(getLockFile(file,options))}catch{}}});module.exports.lock=lock;module.exports.unlock=unlock;module.exports.check=check;module.exports.getLocks=getLocks}});var require_adapter=__commonJS({"node_modules/proper-lockfile/lib/adapter.js"(exports,module){"use strict";var fs=require_graceful_fs();function createSyncFs(fs2){let methods=["mkdir","realpath","stat","rmdir","utimes"],newFs={...fs2};return methods.forEach(method=>{newFs[method]=(...args)=>{let callback=args.pop(),ret;try{ret=fs2[`${method}Sync`](...args)}catch(err){return callback(err)}callback(null,ret)}}),newFs}function toPromise(method){return(...args)=>new Promise((resolve,reject)=>{args.push((err,result)=>{err?reject(err):resolve(result)}),method(...args)})}function toSync(method){return(...args)=>{let err,result;if(args.push((_err,_result)=>{err=_err,result=_result}),method(...args),err)throw err;return result}}function toSyncOptions(options){if(options={...options},options.fs=createSyncFs(options.fs||fs),typeof options.retries=="number"&&options.retries>0||options.retries&&typeof options.retries.retries=="number"&&options.retries.retries>0)throw Object.assign(new Error("Cannot use retries with the sync api"),{code:"ESYNC"});return options}module.exports={toPromise,toSync,toSyncOptions}}});var require_proper_lockfile=__commonJS({"node_modules/proper-lockfile/index.js"(exports,module){"use strict";var lockfile=require_lockfile(),{toPromise,toSync,toSyncOptions}=require_adapter();async function lock(file,options){let release=await toPromise(lockfile.lock)(file,options);return toPromise(release)}function lockSync(file,options){let release=toSync(lockfile.lock)(file,toSyncOptions(options));return toSync(release)}function unlock(file,options){return toPromise(lockfile.unlock)(file,options)}function unlockSync(file,options){return toSync(lockfile.unlock)(file,toSyncOptions(options))}function check(file,options){return toPromise(lockfile.check)(file,options)}function checkSync(file,options){return toSync(lockfile.check)(file,toSyncOptions(options))}module.exports=lock;module.exports.lock=lock;module.exports.unlock=unlock;module.exports.lockSync=lockSync;module.exports.unlockSync=unlockSync;module.exports.check=check;module.exports.checkSync=checkSync}});export{require_proper_lockfile};
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
+
import{SETTINGS_DEFAULTS,VisualLinePreview,getTextOutput,replaceTabs,startToolTimer,str,toolTimerText,typebox_exports}from"./chunk-NXGZMUQX.js";import{Container,Spacer,Text,highlightCode,keyHint}from"./chunk-A4342OQJ.js";import{getDocsPath}from"./chunk-SK25JXS4.js";import{randomBytes}from"node:crypto";import{createWriteStream}from"node:fs";import{writeFile}from"node:fs/promises";import{tmpdir}from"node:os";import{join}from"node:path";var OUTPUT_FILE_MODE=384;function createOutputFilePath(prefix,extension){return join(tmpdir(),`${prefix}-${randomBytes(8).toString("hex")}${extension}`)}async function writeOutputFile(prefix,extension,data){let path=createOutputFilePath(prefix,extension);return await writeFile(path,data,{mode:OUTPUT_FILE_MODE,flag:"wx"}),path}function createOutputFileStream(prefix,extension){let path=createOutputFilePath(prefix,extension);return{path,stream:createWriteStream(path,{mode:OUTPUT_FILE_MODE,flags:"wx"})}}function toCodemodeIdentifier(name){let identifier="";for(let char of name){let valid=identifier===""?/^[A-Za-z_$]$/.test(char):/^[A-Za-z0-9_$]$/.test(char);identifier+=valid?char:"_"}return identifier===""?"_":identifier}var IDENTIFIER=/^[A-Za-z_$][A-Za-z0-9_$]*$/,INDENT=" ",DEFAULT_INPUT_SCHEMA_MAX_CHARS=16e3,MAX_REF_EXPANSIONS=32,TAG_KEYWORDS=["minimum","exclusiveMinimum","maximum","exclusiveMaximum","multipleOf","minLength","maxLength","pattern","format","minItems","maxItems"],LOWER_BOUNDS=new Set(["minimum","exclusiveMinimum","minLength","minItems"]),UPPER_BOUNDS=new Set(["maximum","exclusiveMaximum","maxLength","maxItems"]),MAX_TAG_CHARS=80,LINE_TERMINATORS=/[\r\n\u2028\u2029]/g;function renderToolSignature(tool,options={}){let input=tool.inputSchema===void 0?"unknown":schemaToType(tool.inputSchema,{maxChars:options.inputMaxChars??DEFAULT_INPUT_SCHEMA_MAX_CHARS});return`${toCodemodeIdentifier(tool.name)}(args: ${input}): Promise<${renderToolOutputType(tool.outputSchema)}>;`}function renderToolSample(tool,options={}){let declaration=`declare const tools: { ${renderToolSignature(tool,options)} };`;return`${tool.description?.trim()??""}
|
|
3
|
+
|
|
4
|
+
codemode tool declaration:
|
|
5
|
+
\`\`\`ts
|
|
6
|
+
${declaration}
|
|
7
|
+
\`\`\``}function renderToolOutputType(schema){return schema===void 0?"unknown":schemaToType(schema)}function propertyKey(name){return IDENTIFIER.test(name)?name:JSON.stringify(name)}function union(types){let unique=[...new Set(types)];return unique.includes("unknown")?"unknown":unique.length===0?"never":unique.join(" | ")}function schemaToType(schema,options={}){let render=tags=>toType(schema,{root:schema,resolving:new Set,expansions:0,tags}),type=render(!0);if(options.maxChars===void 0||type.length<=options.maxChars)return type;let untagged=render(!1);return untagged.length<=options.maxChars?untagged:"unknown"}function resolveRef(ref,root){if(ref!=="#"&&!ref.startsWith("#/"))return;let current=root;for(let segment of ref.slice(2).split("/").filter(Boolean)){let key=decodeURIComponent(segment).replaceAll("~1","/").replaceAll("~0","~");if(typeof current!="object"||current===null||Array.isArray(current)||!(key in current))return;current=current[key]}return typeof current=="boolean"||typeof current=="object"&¤t!==null&&!Array.isArray(current)?current:void 0}function toType(schema,context){if(schema===!0)return"unknown";if(schema===!1)return"never";if(typeof schema!="object"||schema===null||Array.isArray(schema))return"unknown";if(typeof schema.$ref=="string"){let ref=schema.$ref;if(context.resolving.has(ref)||context.expansions>=MAX_REF_EXPANSIONS)return"unknown";let target=resolveRef(ref,context.root);if(target===void 0)return"unknown";context.expansions++,context.resolving.add(ref);try{return toType(target,context)}finally{context.resolving.delete(ref)}}if("const"in schema)return JSON.stringify(schema.const)??"unknown";if(Array.isArray(schema.enum))return union(schema.enum.map(value=>JSON.stringify(value)??"unknown"));let variants=Array.isArray(schema.anyOf)?schema.anyOf:Array.isArray(schema.oneOf)?schema.oneOf:void 0;if(variants)return union(variants.map(variant=>toType(variant,context)));if(Array.isArray(schema.allOf)){let parts=schema.allOf.map(part=>toType(part,context)).filter(part=>part!=="unknown");return parts.length===0?"unknown":parts.map(part=>part.includes(" | ")?`(${part})`:part).join(" & ")}let type=schema.type;if(Array.isArray(type))return union(type.map(entry=>toType({...schema,type:entry},context)));switch(type){case"string":return"string";case"number":case"integer":return"number";case"boolean":return"boolean";case"null":return"null";case"array":return arrayType(schema,context);case"object":return objectType(schema,context);case void 0:return"properties"in schema||"additionalProperties"in schema||"required"in schema?objectType(schema,context):"items"in schema||"prefixItems"in schema?arrayType(schema,context):"unknown";default:return"unknown"}}function arrayType(schema,context){if(schema.items!==void 0&&!Array.isArray(schema.items))return`Array<${toType(schema.items,context)}>`;let tuple=Array.isArray(schema.prefixItems)?schema.prefixItems:Array.isArray(schema.items)?schema.items:[];return tuple.length>0?`[${tuple.map(item=>toType(item,context)).join(", ")}]`:"unknown[]"}function descriptionOf(property){let description=property?.description;return typeof description=="string"?description.trim():""}function constraintTags(schema){if(typeof schema!="object"||schema===null||Array.isArray(schema))return"";let property=schema,variants=Array.isArray(property.anyOf)?property.anyOf:property.oneOf,nonNull=Array.isArray(variants)?variants.filter(variant=>variant?.type!=="null"):[],branch=nonNull.length===1?nonNull[0]:void 0,schemas=(typeof branch=="object"&&branch!==null&&!Array.isArray(branch)?[property,branch]:[property]).map(schema2=>({...schema2,...schema2.exclusiveMinimum===!0?{minimum:void 0,exclusiveMinimum:schema2.minimum}:{},...schema2.exclusiveMaximum===!0?{maximum:void 0,exclusiveMaximum:schema2.maximum}:{}})),tags=[],isInteger=type=>type==="integer"||Array.isArray(type)&&type.includes("integer");schemas.some(schema2=>isInteger(schema2.type))&&tags.push("@integer");for(let keyword of TAG_KEYWORDS){let values=schemas.map(schema2=>schema2[keyword]);if(LOWER_BOUNDS.has(keyword)||UPPER_BOUNDS.has(keyword)){let numbers=values.filter(value=>typeof value=="number");if(numbers.length===0)continue;tags.push(`@${keyword} ${LOWER_BOUNDS.has(keyword)?Math.max(...numbers):Math.min(...numbers)}`);continue}for(let value of new Set(values))(typeof value=="number"||typeof value=="string")&&tags.push(`@${keyword} ${value}`)}return schemas.some(schema2=>schema2.uniqueItems===!0)&&tags.push("@uniqueItems"),property.default!==void 0&&property.default!==null&&tags.push(`@default ${JSON.stringify(property.default)}`),property.deprecated===!0&&tags.push("@deprecated"),tags.filter(tag=>tag.length<=MAX_TAG_CHARS).map(tag=>tag.replace(LINE_TERMINATORS,char=>`\\u${char.charCodeAt(0).toString(16).padStart(4,"0")}`)).join(" ")}function objectType(schema,context){let properties=typeof schema.properties=="object"&&schema.properties!==null&&!Array.isArray(schema.properties)?schema.properties:{},required=new Set(Array.isArray(schema.required)?schema.required:[]),names=Object.keys(properties).sort(),members=names.map(name=>{let optional=required.has(name)?"":"?";return`${propertyKey(name)}${optional}: ${toType(properties[name],context)};`}),additional=schema.additionalProperties;if(additional!==void 0&&additional!==!1){let type=additional===!0?"unknown":toType(additional,context);members.push(`[key: string]: ${type};`)}else additional===void 0&&names.length===0&&members.push("[key: string]: unknown;");if(members.length===0)return"{}";let comments=names.map(name=>{let lines2=descriptionOf(properties[name]).split(LINE_TERMINATORS).map(line=>line.trim()).filter(Boolean),tags=context.tags?constraintTags(properties[name]):"";return tags?[...lines2,tags]:lines2});if(!comments.some(comment=>comment.length>0))return`{ ${members.join(" ")} }`;let lines=["{"];comments.forEach((comment,index)=>{for(let line of comment)lines.push(`${INDENT}// ${line}`);lines.push(`${INDENT}${members[index].replaceAll(`
|
|
8
|
+
`,`
|
|
9
|
+
${INDENT}`)}`)});for(let member of members.slice(names.length))lines.push(`${INDENT}${member}`);return lines.push("}"),lines.join(`
|
|
10
|
+
`)}var CODEMODE_OPTIONS_PREFIX="// @options:",SUPPORTED_FIELDS=["max_output_tokens","timeout_ms"],SUPPORTED_FIELDS_TEXT="`max_output_tokens` and `timeout_ms`";var CODEMODE_SOURCE_GRAMMAR=String.raw`
|
|
11
|
+
start: options_source | plain_source
|
|
12
|
+
options_source: OPTIONS_LINE NEWLINE SOURCE
|
|
13
|
+
plain_source: SOURCE
|
|
14
|
+
|
|
15
|
+
OPTIONS_LINE: /[ \t]*\/\/ @options:[^\r\n]*/
|
|
16
|
+
NEWLINE: /\r?\n/
|
|
17
|
+
SOURCE: /[\s\S]+/
|
|
18
|
+
`,CodemodeSourceError=class extends Error{constructor(message){super(message),this.name="CodemodeSourceError"}};function isSafeInteger(value){return typeof value=="number"&&Number.isSafeInteger(value)&&value>=0}function parseOptions(directive){if(directive==="")throw new CodemodeSourceError(`@options must be a JSON object with supported fields ${SUPPORTED_FIELDS_TEXT}`);let value;try{value=JSON.parse(directive)}catch(error){throw new CodemodeSourceError(`@options must be valid JSON with supported fields ${SUPPORTED_FIELDS_TEXT}: ${error instanceof Error?error.message:String(error)}`)}if(typeof value!="object"||value===null||Array.isArray(value))throw new CodemodeSourceError(`@options must be a JSON object with supported fields ${SUPPORTED_FIELDS_TEXT}`);let fields=value;for(let key of Object.keys(fields))if(!SUPPORTED_FIELDS.includes(key))throw new CodemodeSourceError(`@options only supports ${SUPPORTED_FIELDS_TEXT}; got \`${key}\``);let options={},{max_output_tokens,timeout_ms}=fields;if(max_output_tokens!==void 0){if(!isSafeInteger(max_output_tokens))throw new CodemodeSourceError("@options field `max_output_tokens` must be a non-negative safe integer");options.maxOutputTokens=max_output_tokens}if(timeout_ms!==void 0){if(!isSafeInteger(timeout_ms)||timeout_ms===0||timeout_ms>2147483647)throw new CodemodeSourceError("@options field `timeout_ms` must be a positive integer up to 2147483647");options.timeoutMs=timeout_ms}return options}function parseCodemodeSource(input){if(input.trim()==="")throw new CodemodeSourceError('Expected JavaScript source text (non-empty). Provide JS only, optionally with a first line `// @options: {"max_output_tokens": 1000}`.');let lines=input.split(`
|
|
19
|
+
`),misplaced=lines.findIndex((line,index)=>index>0&&line.trimStart().startsWith(CODEMODE_OPTIONS_PREFIX));if(misplaced!==-1)throw new CodemodeSourceError(`The ${CODEMODE_OPTIONS_PREFIX} line must be the first line of the input; found one on line ${misplaced+1}`);let newline=input.indexOf(`
|
|
20
|
+
`),trimmed=lines[0].replace(/\r$/,"").trimStart();if(!trimmed.startsWith(CODEMODE_OPTIONS_PREFIX))return{code:input,options:{}};let code=newline===-1?"":input.slice(newline);if(code.trim()==="")throw new CodemodeSourceError("The @options line must be followed by JavaScript source on subsequent lines");return{code,options:parseOptions(trimmed.slice(CODEMODE_OPTIONS_PREFIX.length).trim())}}var TOOL_SEARCH_TOOL_NAME="tool_search",DEFAULT_TOOL_SEARCH_LIMIT=8,STOP_WORDS=new Set(["a","an","and","are","as","at","be","by","for","from","in","is","it","of","on","or","that","the","this","to","with"]);function stem(term){return term.length>4&&term.endsWith("ies")?`${term.slice(0,-3)}y`:term.length>4&&/(ches|shes|sses|xes|zes)$/.test(term)?term.slice(0,-2):term.length>3&&term.endsWith("s")&&!term.endsWith("ss")?term.slice(0,-1):term}function tokenize(text){return text.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(term=>term.length>0&&!STOP_WORDS.has(term)).map(stem)}function isObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function schemaText(schema,parts){if(isObject(schema)){if(typeof schema.description=="string"&&parts.push(schema.description),isObject(schema.properties))for(let[name,property]of Object.entries(schema.properties))parts.push(name),schemaText(property,parts);schemaText(schema.items,parts);for(let key of["anyOf","oneOf","allOf"]){let variants=schema[key];if(Array.isArray(variants))for(let variant of variants)schemaText(variant,parts)}}}function createToolSearchDocument(tool,namespace){let parts=[tool.name,tool.name.replaceAll("_"," "),tool.description];return schemaText(tool.parameters,parts),namespace&&parts.push(namespace.name,namespace.description??"",namespace.instructions??""),{name:tool.name,text:parts.filter(part=>part.trim()).join(" ")}}var Bm25Ranker=class{k1;b;constructor(options={}){this.k1=options.k1??1.2,this.b=options.b??.75}rank(query,documents,limit){let queryTerms=[...new Set(tokenize(query))];if(queryTerms.length===0||documents.length===0||limit<=0)return[];let termCounts=documents.map(document=>{let counts=new Map;for(let term of tokenize(document.text))counts.set(term,(counts.get(term)??0)+1);return counts}),lengths=termCounts.map(counts=>[...counts.values()].reduce((sum,count)=>sum+count,0)),averageLength=lengths.reduce((sum,length)=>sum+length,0)/documents.length||1,idf=new Map(queryTerms.map(term=>{let frequency=termCounts.filter(counts=>counts.has(term)).length;return[term,Math.log(1+(documents.length-frequency+.5)/(frequency+.5))]})),matches=[];return documents.forEach((document,index)=>{let score=0;for(let term of queryTerms){let count=termCounts[index].get(term);if(!count)continue;let norm=this.k1*(1-this.b+this.b*lengths[index]/averageLength);score+=(idf.get(term)??0)*(count*(this.k1+1)/(count+norm))}score>0&&matches.push({name:document.name,score})}),matches.sort((a,b)=>b.score-a.score).slice(0,limit)}},toolSearchSchema=typebox_exports.Object({query:typebox_exports.String({description:"Search query for deferred tools."}),limit:typebox_exports.Optional(typebox_exports.Number({description:`Maximum number of tools to return. Defaults to ${DEFAULT_TOOL_SEARCH_LIMIT}.`}))});function isSearchable(exposure){return exposure==="codemode"||exposure==="deferred"}function searchAndLoad(tools,query,limit){let active=tools.getActiveTools(),candidates=tools.getAllTools().filter(tool=>isSearchable(tool.exposure)&&!active.includes(tool.name)),documents=candidates.map(tool=>createToolSearchDocument(tool,tool.namespace)),matches=new Bm25Ranker().rank(query,documents,limit);return matches.length>0&&tools.setActiveTools([...active,...matches.map(match=>match.name)]),matches.map(match=>({name:match.name,description:candidates.find(tool=>tool.name===match.name)?.description??""}))}var TOOL_SEARCH_DESCRIPTION=`# Tool discovery
|
|
21
|
+
|
|
22
|
+
Searches over deferred tool metadata with BM25 and exposes matching tools for the next model call.
|
|
23
|
+
|
|
24
|
+
Some of the tools, such as tools of MCP servers, may not have been provided to you upfront, and you should use this tool (\`${TOOL_SEARCH_TOOL_NAME}\`) to search for the required tools. For MCP tool discovery, always use \`${TOOL_SEARCH_TOOL_NAME}\`.`;function createToolSearchToolDefinition(options={}){return{name:TOOL_SEARCH_TOOL_NAME,label:TOOL_SEARCH_TOOL_NAME,description:TOOL_SEARCH_DESCRIPTION,promptSnippet:"Search for tools that are not loaded yet and load the matches",parameters:toolSearchSchema,exposure:"model-only",reachesTools:()=>"all",async execute(_toolCallId,{query,limit}){if(query.trim()==="")throw new Error("query must not be empty");let max=limit??DEFAULT_TOOL_SEARCH_LIMIT;if(!Number.isInteger(max)||max<=0)throw new Error("limit must be a positive integer");let tools=options.tools?searchAndLoad(options.tools,query,max):[];return{content:[{type:"text",text:tools.length===0?"No matching tools found.":`Loaded ${tools.length} tool${tools.length===1?"":"s"}. They are available from your next call:
|
|
25
|
+
${tools.map(tool=>`- ${tool.name}: ${tool.description.trim().split(/\r?\n/)[0]}`).join(`
|
|
26
|
+
`)}`}],details:{loaded:tools.map(tool=>tool.name)}}}}}import{join as join2}from"node:path";function wrapToolDefinition(definition,ctxFactory){return{name:definition.name,label:definition.label,description:definition.description,parameters:definition.parameters,outputSchema:definition.outputSchema,constrainedSampling:definition.constrainedSampling,prepareArguments:definition.prepareArguments,executionMode:definition.executionMode,execute:(toolCallId,params,signal,onUpdate,ctx)=>definition.execute(toolCallId,params,signal,onUpdate,ctx??ctxFactory?.(toolCallId,signal))}}function createToolDefinitionFromAgentTool(tool){return{name:tool.name,label:tool.label,description:tool.description,parameters:tool.parameters,outputSchema:tool.outputSchema,constrainedSampling:tool.constrainedSampling,prepareArguments:tool.prepareArguments,executionMode:tool.executionMode,execute:async(toolCallId,params,signal,onUpdate)=>tool.execute(toolCallId,params,signal,onUpdate)}}var loadCodemodeExecutor=()=>import("./execute-7BWE4ZV3.js");var CODE_PREVIEW_LINES=10,CALL_PREVIEW_COUNT=8,OUTPUT_PREVIEW_LINES=5,COLLAPSED_ARGS_CHARS=80,SCRIPT_HEADER=/^Script (completed|failed)\nWall time [\d.]+ seconds\nOutput:\n$/;function expandHint(theme,hidden,noun){return`${theme.fg("muted",`... (${hidden} more ${noun},`)} ${keyHint("app.tools.expand","to expand")}${theme.fg("muted",")")}`}function formatDuration(ms){return ms===void 0?"":ms<1e3?`${Math.round(ms)}ms`:`${(ms/1e3).toFixed(1)}s`}function formatCost(cost){return`$${cost>=.01?cost.toFixed(2):cost.toPrecision(2)}`}function statusIcon(call,theme){switch(call.status){case"running":return theme.fg("warning","\u2026");case"ok":return theme.fg("success","\u2713");case"error":return theme.fg("error","\u2717");case"cancelled":return theme.fg("muted","\u2298")}}function formatCall(call,theme,expanded){let args=!expanded&&call.args.length>COLLAPSED_ARGS_CHARS?`${call.args.slice(0,COLLAPSED_ARGS_CHARS-3)}...`:call.args,duration=formatDuration(call.durationMs),line=`${statusIcon(call,theme)} ${theme.fg("toolTitle",call.name)}`;return args&&(line+=` ${theme.fg("muted",args)}`),duration&&(line+=` ${theme.fg("dim",duration)}`),call.cost&&(line+=` ${theme.fg("dim",formatCost(call.cost))}`),expanded&&call.error&&(line+=`
|
|
27
|
+
${theme.fg("error",call.error.split(`
|
|
28
|
+
`).join(`
|
|
29
|
+
`))}`),line}var codemodeRenderers={renderCall(args,theme,context){startToolTimer(context);let code=str(args?.code),title=theme.fg("toolTitle",theme.bold("codemode")),component=context.lastComponent??new Container;if(component.clear(),code===null)return component.addChild(new Text(`${title} ${theme.fg("error","[invalid arg]")}`,0,0)),component;if(component.addChild(new Text(title,0,0)),code){let highlighted=highlightCode(replaceTabs(code.replace(/\r/g,"").trimEnd()),"javascript").join(`
|
|
30
|
+
`);component.addChild(context.expanded?new Text(highlighted,0,0):new VisualLinePreview({text:highlighted,maxVisualLines:CODE_PREVIEW_LINES,keep:"start",formatHint:hidden=>expandHint(theme,hidden,"lines")}))}return component},renderResult(result,options,theme,context){let timerText=toolTimerText(context,options.isPartial),component=context.lastComponent??new Container;component.clear();let calls=result.details?.calls??[];if(calls.length>0){let shown=options.expanded?calls:calls.slice(-CALL_PREVIEW_COUNT),lines=shown.map(call=>formatCall(call,theme,options.expanded));shown.length<calls.length&&lines.unshift(`${theme.fg("muted",`... (${calls.length-shown.length} earlier calls,`)} ${keyHint("app.tools.expand","to expand")}${theme.fg("muted",")")}`);let priced=calls.filter(call=>call.cost);if(priced.length>1){let total=priced.reduce((sum,call)=>sum+(call.cost??0),0);lines.push(theme.fg("muted",`Model calls: ${formatCost(total)}`))}component.addChild(new Spacer(1)),component.addChild(new Text(lines.join(`
|
|
31
|
+
`),0,0))}let[first,...rest]=result.content,hasHeader=first?.type==="text"&&SCRIPT_HEADER.test(first.text),output=options.isPartial?"":getTextOutput({...result,content:hasHeader?rest:result.content},context.showImages).trim();if(output){let color=context.isError?"error":"toolOutput",styled=replaceTabs(output).split(`
|
|
32
|
+
`).map(line=>theme.fg(color,line)).join(`
|
|
33
|
+
`);if(component.addChild(new Spacer(1)),options.expanded)component.addChild(new Text(styled,0,0));else{component.addChild(new VisualLinePreview({text:styled,maxVisualLines:OUTPUT_PREVIEW_LINES,keep:"start",formatHint:hidden=>expandHint(theme,hidden,"lines")}));let fullOutputPath=result.details?.fullOutputPath;fullOutputPath&&component.addChild(new Text(theme.fg("muted",`Full output: ${fullOutputPath}`),0,0))}}return timerText&&(component.addChild(new Spacer(1)),component.addChild(new Text(theme.fg("muted",timerText),0,0))),component}};var CODEMODE_TOOL_NAME="codemode",CODEMODE_STORE_ENTRY_TYPE="codemode-store",TEXT_OUTPUT_SCHEMA={type:"string"},codemodeSchema=typebox_exports.Object({code:typebox_exports.String({description:"Raw JavaScript source."})}),codemodeToolSystemPromptContribution={snippet:"Run JavaScript that calls other tools",guidelines:["Use codemode to batch independent tool calls (Promise.allSettled), chain them, or filter large output, instead of many separate calls."]},CODEMODE_DOCS_PATH=join2(getDocsPath(),"codemode.md"),DESCRIPTION_INTRO='Run JavaScript that calls other tools. The input is raw JavaScript (not JSON, no code fence), run as an async function body in a QuickJS sandbox: top-level `await` and `return` work. No Node, file system, network, or timers.\n- `await tools.<name>({ ...args })` resolves to a string, or an object if the tool\'s declaration says so, and rejects with an Error on failure. A tool whose declaration returns an object resolves on failure too when it returned that object; check its fields. Calls still running when the script ends are cancelled.\n- Optional first line: `// @options: {"max_output_tokens": 10000, "timeout_ms": 60000}`';function describeGlobals(models){let lines=["Globals:","- `text(value)`, `image(dataUrlOrImageBlock)`, `console.log(...)`, and top-level `return` add output; `exit()` ends the script. With several text items, each starts with a `==> text N/M <==` line, and `console` lines follow the other output in one `<console_output>` block. `image()` also saves the image to a temp file and the result names its path.","- `store(key, value)` and `load(key)` keep JSON values across codemode calls.","- `ALL_TOOLS`, `await searchTools(query, { limit?, namespace? })`, `await describeTool(name)`, `await describeNamespace(name)`: find unlisted tools, such as MCP tools."];return models&&lines.push(`- \`models\`: classifiers and image generation. Read ${CODEMODE_DOCS_PATH} first.`),lines.join(`
|
|
34
|
+
`)}var DEFAULT_CODEMODE_INLINE_BUDGET=SETTINGS_DEFAULTS.codemode.inlineBudget,CHARS_PER_TOKEN=4;function toCodemodeDeclaration(tool,guidelines=[]){let bullets=guidelines.flatMap(guideline=>guideline.trim()?[`- ${guideline.trim()}`]:[]);return{name:tool.name,description:bullets.length>0?`${tool.description.trim()}
|
|
35
|
+
|
|
36
|
+
${bullets.join(`
|
|
37
|
+
`)}`:tool.description,inputSchema:tool.parameters,outputSchema:tool.outputSchema??TEXT_OUTPUT_SCHEMA}}function getCodemodeCallableTools(tools){return tools.filter(tool=>tool.name!==CODEMODE_TOOL_NAME)}function renderToolSection(declaration){let id=toCodemodeIdentifier(declaration.name);return`${id===declaration.name?`### \`${id}\``:`### \`${id}\` (\`${declaration.name}\`)`}
|
|
38
|
+
${renderToolSample(declaration).trim()}`}function selectCatalog(groups,budget){if(budget===void 0)return new Set(groups.flatMap(group=>group.entries.map(entry=>entry.name)));let queues=groups.map(group=>[...group.entries].sort((a,b)=>a.cost-b.cost)),shown=new Set,remaining=budget,active=queues.filter(queue=>queue.length>0);for(;active.length>0;)active=active.filter(queue=>{let next=queue[0];return next.cost>remaining?!1:(remaining-=next.cost,shown.add(next.name),queue.shift(),queue.length>0)});return shown}function createCodemodeDescription(tools,options={}){let declarations=getCodemodeCallableTools(tools).filter(tool=>!options.deferred?.has(tool.name)).map(tool=>toCodemodeDeclaration(tool,options.guidelines?.get(tool.name))),groups=new Map([["",{namespace:void 0,entries:[]}]]);for(let declaration of declarations){let namespace=options.namespaces?.get(declaration.name),key=namespace?`ns:${namespace.name}`:"",group=groups.get(key)??{namespace,entries:[]};groups.set(key,group);let section=renderToolSection(declaration);group.entries.push({name:declaration.name,section,cost:Math.ceil(section.length/CHARS_PER_TOKEN)})}let ordered=[...groups.values()].sort((a,b)=>a.namespace===void 0?-1:b.namespace===void 0?1:a.namespace.name.localeCompare(b.namespace.name)),shown=selectCatalog(ordered,options.inlineBudget),sections=[DESCRIPTION_INTRO,describeGlobals(options.models===!0)];if(declarations.length===0)return sections.join(`
|
|
39
|
+
|
|
40
|
+
`);let toolSections=["Nested tools:"];for(let{namespace,entries}of ordered){let visible=entries.filter(entry=>shown.has(entry.name));if(namespace){let listing=visible.length===entries.length?"":visible.length===0?" (tools not listed)":" (some tools not listed)",description=namespace.description?.trim();toolSections.push(`## ${namespace.name}${listing}${description?`
|
|
41
|
+
${description}`:""}`)}for(let entry of visible)toolSections.push(entry.section)}return sections.push(toolSections.join(`
|
|
42
|
+
|
|
43
|
+
`)),sections.join(`
|
|
44
|
+
|
|
45
|
+
`)}function describeFields(schema,depth){if(typeof schema!="object"||schema===null)return;let{type,properties,required}=schema;if(type!=="object"||typeof properties!="object"||properties===null)return;let requiredNames=new Set(Array.isArray(required)?required:[]);return`{ ${Object.entries(properties).map(([name,field])=>{let nested=depth>0?describeFields(field,depth-1):void 0;return`${name}${requiredNames.has(name)?"":"?"}${nested?`: ${nested}`:""}`}).join(", ")} }`}function describeOutput(schema){let type=renderToolOutputType(schema);return type==="string"?"a string":`\`${describeFields(schema,1)??type.replace(/\s+/g," ")}\``}function describeScriptCall(tool){return`${tool.description.trim()}
|
|
46
|
+
|
|
47
|
+
Codemode: \`tools.${toCodemodeIdentifier(tool.name)}(args)\` resolves to ${describeOutput(toCodemodeDeclaration(tool).outputSchema)}.`}function prepareCodemodeLoadout(loadout,options){let mode=options.getMode?.()??SETTINGS_DEFAULTS.codemode.mode,isDirect=tool=>loadout.getExposure(tool.name)==="direct",callable=getCodemodeCallableTools(loadout.callable),callableNames=new Set(callable.map(tool=>tool.name)),descriptions={};if(mode==="on")for(let tool of loadout.declared)callableNames.has(tool.name)&&(descriptions[tool.name]=describeScriptCall(tool));let listed=mode==="only"?callable:callable.filter(tool=>!isDirect(tool)),namespaces=new Map(listed.flatMap(tool=>{let namespace=loadout.getNamespace(tool.name);return namespace?[[tool.name,namespace]]:[]})),guidelines=new Map(listed.map(tool=>[tool.name,loadout.getPromptGuidelines(tool.name)]));descriptions[CODEMODE_TOOL_NAME]=createCodemodeDescription(listed,{models:options.models===!0,namespaces,guidelines,deferred:new Set(listed.filter(tool=>loadout.getExposure(tool.name)==="deferred").map(tool=>tool.name)),inlineBudget:options.getInlineBudget?.()??DEFAULT_CODEMODE_INLINE_BUDGET});let declaredNames=new Set(loadout.declared.map(tool=>tool.name));return{descriptions,hiddenDeclarations:mode==="only"?callable.filter(tool=>isDirect(tool)&&declaredNames.has(tool.name)).map(tool=>tool.name):[]}}var DISCOVERY_GLOBALS=/\b(searchTools|describeNamespace|describeTool|ALL_TOOLS)\b/;function getScriptReach(code){return typeof code!="string"?[]:DISCOVERY_GLOBALS.test(code)?"all":code.match(/\w+/g)??[]}function createCodemodeToolDefinition(options={}){return{name:CODEMODE_TOOL_NAME,label:CODEMODE_TOOL_NAME,description:createCodemodeDescription([],{models:options.models===!0}),promptSnippet:codemodeToolSystemPromptContribution.snippet,promptGuidelines:[...codemodeToolSystemPromptContribution.guidelines],parameters:codemodeSchema,exposure:"model-only",prepareLoadout:loadout=>prepareCodemodeLoadout(loadout,options),reachesTools:input=>getScriptReach(input.code),constrainedSampling:{type:"grammar",variants:{openai_lark:CODEMODE_SOURCE_GRAMMAR}},execute:async(toolCallId,params,signal,onUpdate,ctx)=>(await loadCodemodeExecutor()).executeCodemode(toolCallId,params,signal,onUpdate,ctx,options),...codemodeRenderers}}export{writeOutputFile,createOutputFileStream,wrapToolDefinition,createToolDefinitionFromAgentTool,toCodemodeIdentifier,renderToolSample,parseCodemodeSource,TOOL_SEARCH_TOOL_NAME,DEFAULT_TOOL_SEARCH_LIMIT,createToolSearchDocument,Bm25Ranker,createToolSearchToolDefinition,CODEMODE_TOOL_NAME,CODEMODE_STORE_ENTRY_TYPE,CODEMODE_DOCS_PATH,toCodemodeDeclaration,getCodemodeCallableTools,createCodemodeToolDefinition};
|