dal-code 1.0.29 → 1.0.31
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 +11 -0
- package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-guard/src/index.js +1 -1
- package/dist/node_modules/@dalcode/dal-guard/src/mode.js +2 -2
- package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
- package/dist/node_modules/@dalcode/dal-interactive/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-lsp/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-mcp/package.json +5 -5
- package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +2 -2
- package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
- package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +2 -2
- package/dist/node_modules/@dalcode/dal-plugins/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-review/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-router/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-skills/package.json +4 -3
- package/dist/node_modules/@dalcode/dal-skills/src/catalog.js +2 -0
- package/dist/node_modules/@dalcode/dal-skills/src/index.js +12 -11
- package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
- package/dist/node_modules/@dalcode/dal-telemetry/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-terminal/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-web/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-workflow/src/todo.js +2 -2
- package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
- package/dist/node_modules/@earendil-works/chord/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-agent-core/package.json +2 -2
- package/dist/node_modules/@earendil-works/pi-ai/dist/cli.js +0 -0
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-ai-gateway.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/github-copilot.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/google-vertex.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/google.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/meta.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode-go.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/radius.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/opencode-go.js +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/package.json +2 -2
- package/dist/node_modules/@earendil-works/pi-client/package.json +3 -3
- package/dist/node_modules/@earendil-works/pi-codemode/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-coding-agent/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-mcp/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-protocol/package.json +2 -2
- package/dist/node_modules/@earendil-works/pi-server/package.json +3 -3
- package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/dist/bundle/chunks/anthropic-messages-AZKHNVAG.js +0 -5
- package/dist/bundle/chunks/anthropic.js +0 -74
- package/dist/bundle/chunks/azure-openai-responses-LA3FYF3J.js +0 -1
- package/dist/bundle/chunks/bedrock-converse-stream.js +0 -82
- package/dist/bundle/chunks/chunk-4HEMJ3PG.js +0 -1140
- package/dist/bundle/chunks/chunk-4L3WN2XY.js +0 -1
- package/dist/bundle/chunks/chunk-4UTLMBZZ.js +0 -13
- package/dist/bundle/chunks/chunk-4XT6IQQ6.js +0 -1
- package/dist/bundle/chunks/chunk-5M7W2EDY.js +0 -3
- package/dist/bundle/chunks/chunk-5ULSWE2O.js +0 -43
- package/dist/bundle/chunks/chunk-6CYCI3EJ.js +0 -11
- package/dist/bundle/chunks/chunk-7ZC4UXSL.js +0 -1
- package/dist/bundle/chunks/chunk-ABVPQ2YN.js +0 -14
- package/dist/bundle/chunks/chunk-DRQDKNXA.js +0 -1
- package/dist/bundle/chunks/chunk-F5ZABL6Z.js +0 -19
- package/dist/bundle/chunks/chunk-GYI2XXNW.js +0 -10
- package/dist/bundle/chunks/chunk-H3QXYIF7.js +0 -30
- package/dist/bundle/chunks/chunk-HC56T2OZ.js +0 -134
- package/dist/bundle/chunks/chunk-HMFU7ZIF.js +0 -1
- package/dist/bundle/chunks/chunk-JEMNLK2O.js +0 -10
- package/dist/bundle/chunks/chunk-L2ZPNLYD.js +0 -1
- package/dist/bundle/chunks/chunk-LPXNMA2W.js +0 -1
- package/dist/bundle/chunks/chunk-PGXDEOVV.js +0 -1
- package/dist/bundle/chunks/chunk-PJACZCIR.js +0 -1
- package/dist/bundle/chunks/chunk-PMRZO46Y.js +0 -1
- package/dist/bundle/chunks/chunk-PRRNXB7S.js +0 -1
- package/dist/bundle/chunks/chunk-PRXLTI3Y.js +0 -81
- package/dist/bundle/chunks/chunk-Q6IMZXWD.js +0 -129
- package/dist/bundle/chunks/chunk-R4YWRKK4.js +0 -7
- package/dist/bundle/chunks/chunk-RDZVAGPR.js +0 -1
- package/dist/bundle/chunks/chunk-S3GGRYIO.js +0 -5
- package/dist/bundle/chunks/chunk-TEPMHNKQ.js +0 -1
- package/dist/bundle/chunks/chunk-TRDNDS6A.js +0 -3
- package/dist/bundle/chunks/chunk-USJZMAIR.js +0 -1
- package/dist/bundle/chunks/chunk-UTB4DTYQ.js +0 -1
- package/dist/bundle/chunks/chunk-WXULTH2D.js +0 -1
- package/dist/bundle/chunks/chunk-YKF7PQCJ.js +0 -1
- package/dist/bundle/chunks/chunk-YTERFI73.js +0 -1
- package/dist/bundle/chunks/chunk-ZBURYEWF.js +0 -1
- package/dist/bundle/chunks/chunk-ZKDITC7J.js +0 -35
- package/dist/bundle/chunks/cli-2LJMKSUZ.js +0 -50
- package/dist/bundle/chunks/cloudflare-workers-ai-system-one-6WEJUIW2.js +0 -1
- package/dist/bundle/chunks/codemode-worker.js +0 -470
- package/dist/bundle/chunks/dist-37IE4EWG.js +0 -10
- package/dist/bundle/chunks/easter-egg-3d-GHWWTBZN.js +0 -1
- package/dist/bundle/chunks/execute-JU22LJZT.js +0 -489
- package/dist/bundle/chunks/github-copilot.js +0 -1
- package/dist/bundle/chunks/google-generative-ai-RFPHNE43.js +0 -1
- package/dist/bundle/chunks/google-vertex-QDNCMHLE.js +0 -1
- package/dist/bundle/chunks/http-proxy-6TR4MP55.js +0 -1
- package/dist/bundle/chunks/https-proxy-agent-2VXB7436.js +0 -12
- package/dist/bundle/chunks/image-resize-worker.js +0 -1
- package/dist/bundle/chunks/jiti-loader-C3NU2SDH.js +0 -20
- package/dist/bundle/chunks/jiti-static-loader-E6ANQD5T.js +0 -1
- package/dist/bundle/chunks/kimi-coding.js +0 -1
- package/dist/bundle/chunks/lib-TEDK3E5I.js +0 -8
- package/dist/bundle/chunks/llama-cpp-classify-FYN623RH.js +0 -21
- package/dist/bundle/chunks/meta.js +0 -1
- package/dist/bundle/chunks/mistral-conversations-YHX5TRKG.js +0 -4
- package/dist/bundle/chunks/multipart-parser-SQ6GDJL7.js +0 -2
- package/dist/bundle/chunks/node-N5BSDOA5.js +0 -15
- package/dist/bundle/chunks/node-TWVVAGPO.js +0 -1
- package/dist/bundle/chunks/openai-chatgpt.js +0 -74
- package/dist/bundle/chunks/openai-codex-responses-UZEMMAYZ.js +0 -9
- package/dist/bundle/chunks/openai-codex.js +0 -74
- package/dist/bundle/chunks/openai-completions-H6WMELZZ.js +0 -6
- package/dist/bundle/chunks/openai-decisions-URHWCZPN.js +0 -4
- package/dist/bundle/chunks/openai-responses-7X65PCAB.js +0 -2
- package/dist/bundle/chunks/openrouter-images-DUPG5DZO.js +0 -1
- package/dist/bundle/chunks/openrouter.js +0 -74
- package/dist/bundle/chunks/pi-messages-YHKPQIHC.js +0 -7
- package/dist/bundle/chunks/radius.js +0 -74
- package/dist/bundle/chunks/runtime-LLITCT4N.js +0 -1
- package/dist/bundle/chunks/src-UK77SYZE.js +0 -3
- package/dist/bundle/chunks/typesafe-system-one-N7PKHI2N.js +0 -1
- package/dist/bundle/chunks/virtual-modules-H32OTUCD.js +0 -1
- package/dist/bundle/chunks/xai.js +0 -1
- package/dist/bundle/cli-runtime.js +0 -2
- package/dist/bundle/cli.js +0 -2
- package/dist/bundle/index.js +0 -1
- package/dist/bundle/rpc-entry.js +0 -2
- package/dist/core/key-id-schema.js +0 -1
- package/dist/core/keybindings-schema.js +0 -1
- package/dist/core/settings-defaults.js +0 -1
- package/dist/core/settings-schema.js +0 -1
- package/dist/modes/interactive/components/daxnuts.js +0 -1
- package/dist/modes/interactive/theme/theme-schema.js +0 -12
- package/dist/modes/interactive/theme/theme-tokens.js +0 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/compat-schema.js +0 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/model-schema.js +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var b=Object.defineProperty;var o=(e,r)=>b(e,"name",{value:r,configurable:!0});import{createRequire as g}from"node:module";const N=g(import.meta.url);import{retryProviderRequest as w}from"./chunk-PMRZO46Y.js";import{headersToRecord as q,providerHeadersToRecord as k}from"./chunk-UTB4DTYQ.js";import{calculateCost as x}from"./chunk-GYI2XXNW.js";function E(e,r,a){let i=new Error(`${e} returned ${r.status}`);return i.status=r.status,i.headers=r.headers,i.body=a,i}o(E,"httpError");function $(e){let r=new Error(`Request timed out after ${e}ms`);return r.name="TimeoutError",r.status=void 0,r.headers=void 0,r.body="",r}o($,"timeoutError");function m(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(m,"isRecord");function T(e,r,a){if(typeof r!="number"||!Number.isFinite(r))throw new Error(`${e} returned an invalid ${a}`);return r}o(T,"requiredNumber");function _(e,r,a){return k({authorization:`Bearer ${r}`,"content-type":"application/json"},e.headers,a)??{}}o(_,"requestHeaders");async function j(e,r,a,i,t,h){if(!t?.apiKey)throw new Error(`No API key for provider: ${a.provider}`);let y=t.apiKey,u=i,d=await t.onPayload?.(u,a);d!==void 0&&(u=d);let l=t.fetch??globalThis.fetch,{response:c,json:p}=await w(async()=>{let s=t.timeoutMs!==void 0?AbortSignal.timeout(t.timeoutMs):void 0,R=t.signal&&s?AbortSignal.any([t.signal,s]):t.signal??s;try{let n=await l(r,{method:"POST",headers:_(a,y,t.headers),body:JSON.stringify(u),signal:R});if(!n.ok)throw E(e,n,await n.text());return{response:n,json:await n.json()}}catch(n){throw s?.aborted&&!t.signal?.aborted?$(t.timeoutMs):n}},{maxRetries:t.maxRetries??2,maxRetryDelayMs:t.maxRetryDelayMs,signal:t.signal,noRetryStatuses:h});return await t.onResponse?.({status:c.status,headers:q(c.headers)},a),p}o(j,"postClassifierRequest");function f(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:0}o(f,"tokenCount");function A(e,r){if(!m(e)||e.input_tokens===void 0&&e.output_tokens===void 0)return;let a=f(e.input_tokens),i=f(e.output_tokens),t={input:a,output:i,cacheRead:0,cacheWrite:0,totalTokens:a+i,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return x(r,t),t}o(A,"parseClassifierUsage");export{m as isRecord,A as parseClassifierUsage,j as postClassifierRequest,T as requiredNumber};
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
var W=Object.defineProperty;var u=(s,o)=>W(s,"name",{value:o,configurable:!0});import{createRequire as B}from"node:module";const le=B(import.meta.url);import{shortHash as P}from"./chunk-PJACZCIR.js";import{appendGrammarToolInputJsonDelta as D,getGrammarToolInput as U,getJsonSchemaToolParameters as q,resolveGrammarConstrainedSampling as G,resolveJsonSchemaStrictSampling as F,transformMessages as H}from"./chunk-4XT6IQQ6.js";import{sanitizeSurrogates as S}from"./chunk-L2ZPNLYD.js";import{parseStreamingJson as A}from"./chunk-TRDNDS6A.js";import{calculateCost as L,getSystemMessageText as V,renderSystemMessageUpdate as Z,resolveTranscript as K,resolveTranscriptTools as Q}from"./chunk-GYI2XXNW.js";function X(s,o){let i={v:1,id:s};return o&&(i.phase=o),JSON.stringify(i)}u(X,"encodeTextSignatureV1");function Y(s){if(s){if(s.startsWith("{"))try{let o=JSON.parse(s);if(o.v===1&&typeof o.id=="string")return o.phase==="commentary"||o.phase==="final_answer"?{id:o.id,phase:o.phase}:{id:o.id}}catch{}return{id:s}}}u(Y,"parseTextSignature");function ee(s,o){let i=o.filter(p=>p.type==="text").map(p=>p.text).join(`
|
|
2
|
-
`),d=o.filter(p=>p.type==="image"),m=i.length>0;if(d.length===0||!s.input.includes("image"))return S(m?i:d.length>0?"(see attached image)":"(no tool output)");let c=[];m&&c.push({type:"input_text",text:S(i)});for(let p of d)c.push({type:"input_image",detail:"auto",image_url:`data:${p.mimeType};base64,${p.data}`});return c}u(ee,"convertToolResultOutput");function te(s,o,i,d){let m=K(o,d?.supportsMidConvoSystemMessages),c=[],p=u(n=>{let a=n.replace(/[^a-zA-Z0-9_-]/g,"_");return(a.length>64?a.slice(0,64):a).replace(/_+$/,"")},"normalizeIdPart"),x=u(n=>{let a=`fc_${P(n)}`;return a.length>64?a.slice(0,64):a},"buildForeignResponsesItemId"),k=u((n,a,r)=>{if(!i.has(s.provider)||!n.includes("|"))return p(n);let[l,_]=n.split("|"),y=p(l),b=r.provider!==s.provider||r.api!==s.api?x(_):p(_);return b.startsWith("fc_")||(b=p(`fc_${b}`)),`${y}|${b}`},"normalizeToolCallId"),f=H(m.messages,s,k),I=Q(m.messages,(d?.supportsAdditionalTools??!1)||(d?.supportsToolSearch??!1)),R=u((n,a)=>{let r=I.anchorsAdditions?n.toolsAdded??[]:[];if(r.length===0)return;if(d?.supportsAdditionalTools){c.push({type:"additional_tools",role:"developer",tools:z(r,d.toolOptions)});return}if(!d?.supportsToolSearch)return;let l=r.map(y=>y.name),_=`pi_tool_load_${P(`${a}:${l.join(",")}`)}`;c.push({type:"tool_search_call",call_id:_,execution:"client",status:"completed",arguments:{query:l.join(" "),limit:l.length}}),c.push({type:"tool_search_output",call_id:_,execution:"client",status:"completed",tools:z(r,{...d.toolOptions,toolSearchResult:!0})})},"appendSystemToolAdditions"),$=d?.includeSystemPrompt??!0,w=s.compat,M=s.reasoning&&w?.supportsDeveloperRole!==!1?"developer":"system",t=0,e=0;for(let n of f){let a=e++===0&&n.role==="system";if(n.role==="system"){if(a||R(n,`system:${t}`),!a||$){let r=a?V(n):Z(n);r.length>0&&c.push({role:M,content:S(r)})}}else if(n.role==="user")if(typeof n.content=="string")c.push({role:"user",content:[{type:"input_text",text:S(n.content)}]});else{let r=n.content.map(l=>l.type==="text"?{type:"input_text",text:S(l.text)}:{type:"input_image",detail:"auto",image_url:`data:${l.mimeType};base64,${l.data}`});if(r.length===0)continue;c.push({role:"user",content:r})}else if(n.role==="assistant"){let r=[],l=n,_=l.provider===s.provider&&l.api===s.api,y=_&&l.model===s.id,b=_&&l.model!==s.id,J=0;for(let v of n.content)if(v.type==="thinking"){if(v.thinkingSignature){let g=JSON.parse(v.thinkingSignature);r.push(g)}}else if(v.type==="text"){let g=v,T=Y(g.textSignature),O=J===0?`msg_pi_${t}`:`msg_pi_${t}_${J}`;J++;let h=T?.id;h?h.length>64&&(h=`msg_${P(h)}`):h=O,r.push({type:"message",role:"assistant",content:[{type:"output_text",text:S(g.text),annotations:[]}],status:"completed",id:h,phase:T?.phase})}else if(v.type==="toolCall"){let g=v,[T,O]=g.id.split("|"),h=d?.grammarToolInputProperties?.get(g.name),C=O,N=h===void 0?"fc_":"ctc_";(b||!C?.startsWith(N))&&(C=void 0),h!==void 0?r.push({type:"custom_tool_call",id:C,call_id:T,name:g.name,input:S(U(g.name,g.arguments,h)),...y&&g.namespace!==void 0?{namespace:g.namespace}:{}}):r.push({type:"function_call",id:C,call_id:T,name:g.name,arguments:JSON.stringify(g.arguments),...y&&g.namespace!==void 0?{namespace:g.namespace}:{}})}if(r.length===0)continue;c.push(...r)}else if(n.role==="toolResult"){let[r]=n.toolCallId.split("|"),l=ee(s,n.content);d?.grammarToolInputProperties?.has(n.toolName)?c.push({type:"custom_tool_call_output",call_id:r,output:l}):c.push({type:"function_call_output",call_id:r,output:l})}a||t++}return c}u(te,"convertResponsesMessages");function z(s,o){let i=o?.strict===void 0?!1:o.strict,d=o?.supportsStrictMode??!0,m=o?.supportsOpenAIGrammarTools??!1;return s.map(c=>{let p=G(c,m);if(p)return{type:"custom",name:c.name,description:c.description,format:{type:"grammar",syntax:p.format,definition:p.definition},...o?.toolSearchResult?{defer_loading:!0}:{}};let x=F(c,d)??i,k={type:"function",name:c.name,description:c.description,parameters:q(c,x===!0),...o?.toolSearchResult?{defer_loading:!0}:{}};return d&&(k.strict=x),k})}u(z,"convertResponsesTools");function E(s){let o=s.customInput?.property;if(o===void 0)return"";let i=s.arguments[o];return typeof i=="string"?i:""}u(E,"getCustomToolCallInput");function j(s,o,i){let d=s.customInput;if(!d)return;let m=D(d.jsonBuffer,d.property,o,i);return s.arguments={[d.property]:o},m}u(j,"appendCustomToolCallInput");async function ne(s,o,i,d,m){let c=!1,p=new Map,x=new Map,k=u(t=>{t.type==="message"&&t.phase==="final_answer"&&(o.stopReason="stop")},"applyMessagePhaseStopReason"),f=u((t,e)=>{let n=p.get(t);return n?.type===e?n:void 0},"getSlot"),I=u((t,e)=>{e!==void 0&&i.push({type:"toolcall_delta",contentIndex:t.contentIndex,delta:e,partial:o})},"pushToolCallDelta"),R=u((t,e)=>{if(e.type==="reasoning"){let n={type:"thinking",thinking:""};o.content.push(n);let a={type:"thinking",block:n,contentIndex:o.content.length-1};return p.set(t,a),i.push({type:"thinking_start",contentIndex:a.contentIndex,partial:o}),a}if(e.type==="message"){k(e);let n={type:"text",text:""};o.content.push(n);let a={type:"text",block:n,contentIndex:o.content.length-1};return p.set(t,a),i.push({type:"text_start",contentIndex:a.contentIndex,partial:o}),a}if(e.type==="function_call"){let n={type:"toolCall",id:`${e.call_id}|${e.id}`,name:e.name,arguments:{},...e.namespace!==void 0?{namespace:e.namespace}:{},partialJson:e.arguments||""};o.content.push(n);let a={type:"toolCall",block:n,contentIndex:o.content.length-1};return p.set(t,a),i.push({type:"toolcall_start",contentIndex:a.contentIndex,partial:o}),a}if(e.type==="custom_tool_call"){let n=m?.grammarToolInputProperties?.get(e.name)??"input",a=e.input||"",r={type:"toolCall",id:`${e.call_id}|${e.id}`,name:e.name,arguments:{[n]:a},...e.namespace!==void 0?{namespace:e.namespace}:{},customInput:{property:n,jsonBuffer:{input:"",started:!1,closed:!1}}};o.content.push(r);let l={type:"toolCall",block:r,contentIndex:o.content.length-1};return p.set(t,l),i.push({type:"toolcall_start",contentIndex:l.contentIndex,partial:o}),l}},"createSlot"),$=u((t,e)=>p.get(t)??R(t,e),"getOrCreateSlot"),w=u(t=>{for(let e of t){if(e.type!=="reasoning"||!e.encrypted_content)continue;let n=x.get(e.id);if(!n?.thinkingSignature)continue;let a=JSON.parse(n.thinkingSignature);a.encrypted_content||(n.thinkingSignature=JSON.stringify({...a,encrypted_content:e.encrypted_content}))}},"backfillReasoningSignatures"),M=u(t=>{if(c=!0,w(t.output??[]),t?.id&&(o.responseId=t.id),t?.usage){let l=t.usage.input_tokens_details,_=l?.cached_tokens||0,y=l?.cache_write_tokens||0;o.usage={input:Math.max(0,(t.usage.input_tokens||0)-_-y),output:t.usage.output_tokens||0,cacheRead:_,cacheWrite:y,reasoning:t.usage.output_tokens_details?.reasoning_tokens||0,totalTokens:t.usage.total_tokens||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}if(L(d,o.usage),m?.applyServiceTierPricing){let l=m.resolveServiceTier?m.resolveServiceTier(t?.service_tier,m.serviceTier):t?.service_tier??m.serviceTier;m.applyServiceTierPricing(o.usage,l)}let e=t?.status,n=t?.incomplete_details,a=typeof n?.reason=="string"?n.reason:void 0;o.rawStopReason=a?`${e}.${a}`:e;let r=oe(e,a);o.stopReason=r.stopReason,r.errorMessage===void 0?delete o.errorMessage:o.errorMessage=r.errorMessage,o.content.some(l=>l.type==="toolCall")&&o.stopReason==="stop"&&(o.stopReason="toolUse")},"finalizeResponse");for await(let t of s)if(await m?.onProviderStreamEvent?.(t,d),t.type==="response.created")o.responseId=t.response.id;else if(t.type==="response.output_item.added")R(t.output_index,t.item);else if(t.type==="response.reasoning_summary_text.delta"){let e=f(t.output_index,"thinking");if(!e)continue;e.block.thinking+=t.delta,i.push({type:"thinking_delta",contentIndex:e.contentIndex,delta:t.delta,partial:o})}else if(t.type==="response.reasoning_summary_part.done"){let e=f(t.output_index,"thinking");if(!e)continue;e.block.thinking+=`
|
|
3
|
-
|
|
4
|
-
`,i.push({type:"thinking_delta",contentIndex:e.contentIndex,delta:`
|
|
5
|
-
|
|
6
|
-
`,partial:o})}else if(t.type==="response.reasoning_text.delta"){let e=f(t.output_index,"thinking");if(!e)continue;e.block.thinking+=t.delta,i.push({type:"thinking_delta",contentIndex:e.contentIndex,delta:t.delta,partial:o})}else if(t.type==="response.output_text.delta"){let e=f(t.output_index,"text");if(!e)continue;e.block.text+=t.delta,i.push({type:"text_delta",contentIndex:e.contentIndex,delta:t.delta,partial:o})}else if(t.type==="response.refusal.delta"){let e=f(t.output_index,"text");if(!e)continue;e.block.text+=t.delta,i.push({type:"text_delta",contentIndex:e.contentIndex,delta:t.delta,partial:o})}else if(t.type==="response.function_call_arguments.delta"){let e=f(t.output_index,"toolCall");if(!e||e.block.partialJson===void 0)continue;e.block.partialJson+=t.delta,e.block.arguments=A(e.block.partialJson),I(e,t.delta)}else if(t.type==="response.function_call_arguments.done"){let e=f(t.output_index,"toolCall");if(!e||e.block.partialJson===void 0)continue;let n=e.block.partialJson;if(e.block.partialJson=t.arguments,e.block.arguments=A(e.block.partialJson),t.arguments.startsWith(n)){let a=t.arguments.slice(n.length);a.length>0&&I(e,a)}}else if(t.type==="response.custom_tool_call_input.delta"){let e=f(t.output_index,"toolCall");if(!e||!e.block.customInput)continue;I(e,j(e.block,E(e.block)+t.delta,!1))}else if(t.type==="response.custom_tool_call_input.done"){let e=f(t.output_index,"toolCall");if(!e||!e.block.customInput)continue;I(e,j(e.block,t.input,!0))}else if(t.type==="response.output_item.done"){let e=t.item;k(e);let n=$(t.output_index,e);if(e.type==="reasoning"&&n?.type==="thinking"){let a=e.summary?.map(l=>l.text).join(`
|
|
7
|
-
|
|
8
|
-
`)||"",r=e.content?.map(l=>l.text).join(`
|
|
9
|
-
|
|
10
|
-
`)||"";n.block.thinking=a||r||n.block.thinking,n.block.thinkingSignature=JSON.stringify(e),x.set(e.id,n.block),i.push({type:"thinking_end",contentIndex:n.contentIndex,content:n.block.thinking,partial:o}),p.delete(t.output_index)}else e.type==="message"&&n?.type==="text"?(n.block.text=e.content?.map(a=>a.type==="output_text"?a.text:a.refusal).join("")||"",n.block.textSignature=X(e.id,e.phase??void 0),i.push({type:"text_end",contentIndex:n.contentIndex,content:n.block.text,partial:o}),p.delete(t.output_index)):e.type==="function_call"&&n?.type==="toolCall"&&n.block.partialJson!==void 0?(n.block.arguments=A(e.arguments||n.block.partialJson||"{}"),e.namespace!==void 0&&(n.block.namespace=e.namespace),delete n.block.partialJson,i.push({type:"toolcall_end",contentIndex:n.contentIndex,toolCall:n.block,partial:o}),p.delete(t.output_index)):e.type==="custom_tool_call"&&n?.type==="toolCall"&&n.block.customInput&&(I(n,j(n.block,e.input??E(n.block),!0)),e.namespace!==void 0&&(n.block.namespace=e.namespace),delete n.block.customInput,i.push({type:"toolcall_end",contentIndex:n.contentIndex,toolCall:n.block,partial:o}),p.delete(t.output_index))}else if(t.type==="response.completed"||t.type==="response.incomplete")M(t.response);else{if(t.type==="error")throw new Error(`Error Code ${t.code}: ${t.message}`||"Unknown error");if(t.type==="response.failed"){c=!0,o.rawStopReason=t.response?.status;let e=t.response?.error,n=t.response?.incomplete_details,a=e?`${e.code||"unknown"}: ${e.message||"no message"}`:n?.reason?`incomplete: ${n.reason}`:"Unknown error (no error details in response)";throw new Error(a)}}if(!c)throw new Error("OpenAI Responses stream ended before a terminal response event");if(o.stopReason==="toolUse")for(let t of o.content){if(t.type!=="toolCall")continue;let e=t;if(e.partialJson!==void 0||e.customInput!==void 0)throw new Error(`OpenAI Responses stream completed with an unfinished tool call: ${e.name} (${e.id})`)}}u(ne,"processResponsesStream");function oe(s,o){if(!s)return{stopReason:"stop"};switch(s){case"completed":return{stopReason:"stop"};case"incomplete":return o==="max_output_tokens"?{stopReason:"length"}:{stopReason:"error",errorMessage:o?`Response incomplete: ${o}`:"Response incomplete without a provider reason"};case"failed":case"cancelled":return{stopReason:"error"};case"in_progress":case"queued":return{stopReason:"stop"};default:{let i=s;throw new Error(`Unhandled stop reason: ${i}`)}}}u(oe,"mapStopReason");export{te as convertResponsesMessages,z as convertResponsesTools,ne as processResponsesStream};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var t=Object.defineProperty;var r=(e,u)=>t(e,"name",{value:u,configurable:!0});import{createRequire as F}from"node:module";const o=F(import.meta.url);function i(e){return e.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,"")}r(i,"sanitizeSurrogates");export{i as sanitizeSurrogates};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var h=Object.defineProperty;var i=(e,t)=>h(e,"name",{value:t,configurable:!0});import{createRequire as c}from"node:module";const f=c(import.meta.url);var n=class{static{i(this,"FifoQueue")}incoming=[];outgoing=[];get length(){return this.incoming.length+this.outgoing.length}enqueue(e){this.incoming.push(e)}dequeue(){if(this.outgoing.length===0)for(;this.incoming.length>0;)this.outgoing.push(this.incoming.pop());return this.outgoing.pop()}},o=class{static{i(this,"EventStream")}queue=new n;waiting=new n;done=!1;finalResultPromise;resolveFinalResult;isComplete;extractResult;constructor(e,t){this.isComplete=e,this.extractResult=t,this.finalResultPromise=new Promise(s=>{this.resolveFinalResult=s})}push(e){if(this.done)return;this.isComplete(e)&&(this.done=!0,this.resolveFinalResult(this.extractResult(e)));let t=this.waiting.dequeue();t?t({value:e,done:!1}):this.queue.enqueue(e)}end(e){for(this.done=!0,e!==void 0&&this.resolveFinalResult(e);this.waiting.length>0;)this.waiting.dequeue()({value:void 0,done:!0})}async*[Symbol.asyncIterator](){for(;;)if(this.queue.length>0)yield this.queue.dequeue();else{if(this.done)return;{let e=await new Promise(t=>this.waiting.enqueue(t));if(e.done)return;yield e.value}}}result(){return this.finalResultPromise}},r=class extends o{static{i(this,"AssistantMessageEventStream")}#t=Date.now();#i=performance.now();constructor(){super(e=>e.type==="done"||e.type==="error",e=>{if(e.type==="done")return e.message;if(e.type==="error")return e.error;throw new Error("Unexpected event type for final result")})}push(e){e.type==="done"?this.#e(e.message):e.type==="error"&&this.#e(e.error),super.push(e)}end(e){e!==void 0&&this.#e(e),super.end(e)}#e(e){this.done||e.durationMs!==void 0||e.timestamp<this.#t||(e.durationMs=Math.max(0,Math.round(performance.now()-this.#i)))}};function g(){return new r}i(g,"createAssistantMessageEventStream");function a(e){return e instanceof Error?e.message||e.name:typeof e=="string"?e:String(e)}i(a,"formatThrownValue");function u(e){if(!(e instanceof Error))return{name:"ThrownValue",message:a(e)};let t=e.code;return{name:e.name||void 0,message:e.message||e.name,stack:e.stack,code:typeof t=="string"||typeof t=="number"?t:void 0}}i(u,"extractDiagnosticError");function l(e,t,s){return{type:e,timestamp:Date.now(),error:u(t),details:s}}i(l,"createAssistantMessageDiagnostic");function d(e,t){e.diagnostics=[...e.diagnostics??[],t]}i(d,"appendAssistantMessageDiagnostic");export{r as AssistantMessageEventStream,o as EventStream,d as appendAssistantMessageDiagnostic,l as createAssistantMessageDiagnostic,g as createAssistantMessageEventStream,u as extractDiagnosticError,a as formatThrownValue};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var n=Object.defineProperty;var r=(t,e)=>n(t,"name",{value:e,configurable:!0});import{createRequire as i}from"node:module";const p=i(import.meta.url);function a(t){let e=t[t.length-1];return e&&e.role!=="user"?"agent":"user"}r(a,"inferCopilotInitiator");function u(t){return t.some(e=>e.role==="user"&&Array.isArray(e.content)?e.content.some(o=>o.type==="image"):e.role==="toolResult"&&Array.isArray(e.content)?e.content.some(o=>o.type==="image"):!1)}r(u,"hasCopilotVisionInput");function s(t){let e={"X-Initiator":a(t.messages),"Openai-Intent":"conversation-edits"};return t.hasImages&&(e["Copilot-Vision-Request"]="true"),e}r(s,"buildCopilotDynamicHeaders");export{s as buildCopilotDynamicHeaders,u as hasCopilotVisionInput};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var u=Object.defineProperty;var a=(r,t)=>u(r,"name",{value:t,configurable:!0});import{createRequire as l}from"node:module";const M=l(import.meta.url);function o(r){let t=3735928559,e=1103547991;for(let i=0;i<r.length;i++){let h=r.charCodeAt(i);t=Math.imul(t^h,2654435761),e=Math.imul(e^h,1597334677)}return t=Math.imul(t^t>>>16,2246822507)^Math.imul(e^e>>>13,3266489909),e=Math.imul(e^e>>>16,2246822507)^Math.imul(t^t>>>13,3266489909),(e>>>0).toString(36)+(t>>>0).toString(36)}a(o,"shortHash");export{o as shortHash};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var m=Object.defineProperty;var n=(e,t)=>m(e,"name",{value:t,configurable:!0});import{createRequire as d}from"node:module";const w=d(import.meta.url);function f(e){return!(e instanceof Error)||!("status"in e)||!("headers"in e)?!1:(e.status===void 0||typeof e.status=="number")&&(e.headers===void 0||e.headers instanceof Headers)}n(f,"isProviderError");function c(e){let t=e.headers?.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===void 0?!0:e.status===408||e.status===409||e.status===429||typeof e.status=="number"&&e.status>=500}n(c,"isRetryableProviderError");function l(e,t,s){let r=t??6e4;if(r>0&&e>r)throw new Error(`Server requested ${Math.ceil(e/1e3)}s retry delay (max: ${Math.ceil(r/1e3)}s). ${s}`);return e}n(l,"validateServerRetryDelayMs");function y(e,t,s){let r=e.headers?.get("retry-after-ms");if(r){let i=Number.parseFloat(r);if(Number.isFinite(i))return l(i,s,e.message)}let a=e.headers?.get("retry-after");if(a){let i=Number.parseFloat(a),o=Number.isNaN(i)?Date.parse(a)-Date.now():i*1e3;if(Number.isFinite(o))return l(o,s,e.message)}return Math.min(.5*2**t,8)*1e3*(1-Math.random()*.25)}n(y,"getRetryDelayMs");function u(){let e=new Error("Request aborted");return e.name="AbortError",e}n(u,"createAbortError");function b(e,t){return new Promise((s,r)=>{if(t?.aborted){r(u());return}let a=n(()=>{clearTimeout(i),r(u())},"onAbort"),i=setTimeout(()=>{t?.removeEventListener("abort",a),s()},Math.max(0,e));t?.addEventListener("abort",a,{once:!0})})}n(b,"abortableSleep");async function h(e,t={}){let s=t.maxRetries??0,r=s;for(;;)try{return await e()}catch(a){if(t.signal?.aborted)throw u();if(r<=0||!f(a)||!c(a)||a.status!==void 0&&t.noRetryStatuses?.includes(a.status))throw a;let i=s-r;r--,await b(y(a,i,t.maxRetryDelayMs),t.signal)}}n(h,"retryProviderRequest");export{h as retryProviderRequest};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var i=Object.defineProperty;var t=(r,e)=>i(r,"name",{value:e,configurable:!0});import{createRequire as o}from"node:module";const m=o(import.meta.url);function a(r){if(r===void 0)return;let e=Array.from(r);return e.length<=64?r:e.slice(0,64).join("")}t(a,"clampOpenAIPromptCacheKey");export{a as clampOpenAIPromptCacheKey};
|
|
@@ -1,81 +0,0 @@
|
|
|
1
|
-
var be=Object.defineProperty;var s=(e,t)=>be(e,"name",{value:t,configurable:!0});import{createRequire as Ce}from"node:module";const Qt=Ce(import.meta.url);import{FileAuthStorageBackend as ze,JSON_RPC_ERROR_CODES as Pe,LATEST_PROTOCOL_VERSION as $,McpAuthRequiredError as xe,McpClient as Oe,McpError as $e,McpHttpError as W,McpSessionExpiredError as Le,StdioTransport as L,StreamableHttpTransport as Ie,isMcpAppResource as J,isObject as Y,mcpNamespace as He,require_proper_lockfile as De,resolveConfigValueOrThrow as Z,resolveHeadersOrThrow as Ne}from"./chunk-ABVPQ2YN.js";import{APP_NAME as je,VERSION as Ve,getAgentDir as G}from"./chunk-HC56T2OZ.js";import{__toESM as Fe}from"./chunk-4L3WN2XY.js";import{homedir as Q}from"node:os";import{basename as Be,join as qe,resolve as Ke}from"node:path";import{setTimeout as We}from"node:timers/promises";import{pathToFileURL as Je}from"node:url";import{createServer as Ye}from"node:http";function Ze(e){return e.ok?"Authorization complete. You may close this window.":e.details?`${e.message}
|
|
2
|
-
|
|
3
|
-
${e.details}`:e.message}s(Ze,"plainText");var X=class Me{static{s(this,"_OAuthCallbackServer")}redirectUrl;server;paths;timeoutMs;renderPage;pending=new Map;constructor(t,r,i,n,a){this.server=t,this.redirectUrl=r,this.paths=i,this.timeoutMs=n,this.renderPage=a}static async listen(t={}){let r=t.host??"127.0.0.1",i=t.redirectHost??r,n=t.path??"/callback",a,o=Ye((l,h)=>a?.handle(l.url??"/",h));await new Promise((l,h)=>{o.once("error",h),o.listen(t.port??0,r,()=>{o.off("error",h),l()})});let c=o.address();if(!c||typeof c=="string")throw new Error("OAuth callback server did not bind to TCP");return a=new Me(o,`http://${i.includes(":")?`[${i}]`:i}:${c.port}${n}`,[n,...t.extraPaths??[]],t.timeoutMs??5*6e4,t.renderPage),a}waitForCallback(t,r){if(this.pending.has(t))throw new Error("OAuth state is already pending");return new Promise((i,n)=>{let a=setTimeout(()=>{this.pending.delete(t),n(new Error("OAuth callback timed out"))},this.timeoutMs);this.pending.set(t,{resolve:i,reject:n,timer:a,path:r})})}async close(){for(let t of this.pending.values())clearTimeout(t.timer),t.reject(new Error("OAuth callback server closed"));this.pending.clear(),await new Promise((t,r)=>{this.server.close(i=>i?r(i):t())})}reply(t,r,i){this.renderPage?(t.writeHead(r,{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}),t.end(this.renderPage(i))):t.writeHead(r,{"content-type":"text/plain; charset=utf-8"}).end(Ze(i))}handle(t,r){let i=new URL(t,this.redirectUrl);if(!this.paths.includes(i.pathname)){this.reply(r,404,{ok:!1,message:"Not found"});return}let n=i.searchParams.get("state"),a=n?this.pending.get(n):void 0;if(!n||!a){this.reply(r,400,{ok:!1,message:"Invalid or expired OAuth state"});return}if(clearTimeout(a.timer),this.pending.delete(n),a.path!==void 0&&i.pathname!==a.path){a.reject(new Error("The authorization response arrived on another redirect URI")),this.reply(r,400,{ok:!1,message:"Unexpected redirect URI"});return}let o=i.searchParams.get("error");if(o){let h=i.searchParams.get("error_description")??o;a.reject(new Error(h)),this.reply(r,200,{ok:!1,message:"Authorization failed. You may close this window.",details:h});return}let c=i.searchParams.get("code");if(!c){a.reject(new Error("OAuth callback did not include an authorization code")),this.reply(r,400,{ok:!1,message:"Missing authorization code"});return}let l=i.searchParams.get("iss");a.resolve({code:c,state:n,...l?{iss:l}:{}}),this.reply(r,200,{ok:!0})}},S=class extends Error{static{s(this,"OAuthError")}code;errorUri;constructor(e,t,r){super(t||e),this.name="OAuthError",this.code=e,this.errorUri=r}},ee=class extends Error{static{s(this,"OAuthIssuerMismatchError")}expected;received;constructor(e,t){super(`OAuth issuer mismatch: expected ${JSON.stringify(e)}, received ${t===void 0?"none":JSON.stringify(t)}`),this.name="OAuthIssuerMismatchError",this.expected=e,this.received=t}},te=class extends Error{static{s(this,"OAuthInsecureEndpointError")}endpoint;constructor(e){super(`Refusing to send OAuth credentials to non-HTTPS endpoint ${e}`),this.name="OAuthInsecureEndpointError",this.endpoint=e}},Ge=class extends Error{static{s(this,"OAuthRegistrationError")}status;body;constructor(e,t){super(`OAuth dynamic client registration failed with status ${e}: ${t}`),this.name="OAuthRegistrationError",this.status=e,this.body=t}},U=class extends Error{static{s(this,"McpOAuthAuthorizationRequiredError")}constructor(){super("MCP OAuth authorization requires user interaction"),this.name="McpOAuthAuthorizationRequiredError"}};function R(e,t){if(!Y(e))throw new Error(`Invalid ${t}`);return e}s(R,"object");function A(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}s(A,"compact");function k(e,t){if(typeof e!="string"||e.length===0)throw new Error(`Invalid ${t}`);return e}s(k,"requiredString");function I(e){return e==null||e===""}s(I,"absent");function M(e,t){if(!I(e))return k(e,t)}s(M,"optionalString");function w(e,t){if(e!=null){if(!Array.isArray(e)||e.some(r=>typeof r!="string"))throw new Error(`Invalid ${t}`);return[...e]}}s(w,"optionalStrings");function _(e,t){let r=k(e,t);if(!URL.canParse(r))throw new Error(`Invalid ${t}`);let i=new URL(r);if(["javascript:","data:","vbscript:"].includes(i.protocol))throw new Error(`Invalid ${t}`);return r}s(_,"safeUrl");function Qe(e,t){return I(e)?void 0:_(e,t)}s(Qe,"optionalUrl");function Xe(e){let t=R(e,"OAuth protected resource metadata");return A({...t,resource:_(t.resource,"OAuth protected resource metadata resource"),authorization_servers:w(t.authorization_servers,"authorization_servers")?.map(r=>_(r,"authorization server URL")),scopes_supported:w(t.scopes_supported,"scopes_supported")})}s(Xe,"parseProtectedResourceMetadata");function re(e){let t=R(e,"authorization server metadata"),r=w(t.response_types_supported,"response_types_supported");if(!r)throw new Error("Invalid response_types_supported");return A({...t,issuer:_(t.issuer,"authorization server issuer"),authorization_endpoint:_(t.authorization_endpoint,"authorization endpoint"),token_endpoint:_(t.token_endpoint,"token endpoint"),registration_endpoint:Qe(t.registration_endpoint,"registration endpoint"),scopes_supported:w(t.scopes_supported,"scopes_supported"),response_types_supported:r,grant_types_supported:w(t.grant_types_supported,"grant_types_supported"),token_endpoint_auth_methods_supported:w(t.token_endpoint_auth_methods_supported,"token_endpoint_auth_methods_supported"),code_challenge_methods_supported:w(t.code_challenge_methods_supported,"code_challenge_methods_supported"),client_id_metadata_document_supported:typeof t.client_id_metadata_document_supported=="boolean"?t.client_id_metadata_document_supported:void 0,authorization_response_iss_parameter_supported:typeof t.authorization_response_iss_parameter_supported=="boolean"?t.authorization_response_iss_parameter_supported:void 0})}s(re,"parseAuthorizationServerMetadata");function et(e){let t=R(e,"OAuth token response"),r=I(t.expires_in)?void 0:Number(t.expires_in);if(r!==void 0&&!Number.isFinite(r))throw new Error("Invalid expires_in");return A({access_token:k(t.access_token,"access_token"),token_type:k(t.token_type,"token_type"),expires_in:r,scope:M(t.scope,"scope"),refresh_token:M(t.refresh_token,"refresh_token"),id_token:M(t.id_token,"id_token")})}s(et,"parseOAuthTokens");function tt(e){let t=R(e,"OAuth client registration response");return A({...t,client_id:k(t.client_id,"client_id"),client_secret:M(t.client_secret,"client_secret"),client_id_issued_at:typeof t.client_id_issued_at=="number"?t.client_id_issued_at:void 0,client_secret_expires_at:typeof t.client_secret_expires_at=="number"?t.client_secret_expires_at:void 0,redirect_uris:w(t.redirect_uris,"redirect_uris")??[]})}s(tt,"parseClientInformation");function E(e){e?.body?.cancel().catch(()=>{})}s(E,"discard");function ie(e){return e>=400&&e<500||e===502}s(ie,"isDiscoveryMiss");function ae(e){return e.endsWith("/")?e.slice(0,-1):e}s(ae,"pathSuffix");function T(e,t){let r=e.match(new RegExp(String.raw`(?:^|[,\s])${t}=(?:"([^"]*)"|([^\s,]+))`,"i"));return r?.[1]||r?.[2]||void 0}s(T,"field");function rt(e){if(!e)return{};let t=e.trimStart().split(/\s+/,1)[0]?.toLowerCase();if(t!=="bearer"&&t!=="dpop")return{};let r=T(e,"resource_metadata"),i;if(r)try{i=new URL(r)}catch{}return{resourceMetadataUrl:i,scope:T(e,"scope"),error:T(e,"error"),errorDescription:T(e,"error_description")}}s(rt,"parseWwwAuthenticate");async function b(e,t,r,i){return t(e,{headers:{Accept:"application/json","MCP-Protocol-Version":r},signal:i})}s(b,"fetchMetadata");async function it(e,t={}){let r=new URL(e),i=t.fetch??globalThis.fetch,n=t.protocolVersion??$,a=await b(t.resourceMetadataUrl?new URL(t.resourceMetadataUrl):new URL(`/.well-known/oauth-protected-resource${ae(r.pathname)}`,r.origin),i,n,t.signal);if(!t.resourceMetadataUrl&&r.pathname!=="/"&&ie(a.status)&&(E(a),a=await b(new URL("/.well-known/oauth-protected-resource",r.origin),i,n,t.signal)),!a.ok)throw E(a),new Error(`HTTP ${a.status} loading OAuth protected resource metadata`);return Xe(await a.json())}s(it,"discoverProtectedResourceMetadata");function at(e){let t=new URL(e),r=ae(t.pathname),i=[{url:new URL(`/.well-known/oauth-authorization-server${r}`,t.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${r}`,t.origin),type:"oidc"}];return r&&i.push({url:new URL(`${r}/.well-known/openid-configuration`,t.origin),type:"oidc"}),i}s(at,"buildAuthorizationServerDiscoveryUrls");async function ne(e,t={}){let r=t.fetch??globalThis.fetch;for(let{url:i}of at(e)){let n=await b(i,r,t.protocolVersion??$,t.signal);if(!n.ok){if(E(n),ie(n.status))continue;throw new Error(`HTTP ${n.status} loading authorization server metadata from ${i}`)}let a=re(await n.json());if(!t.skipIssuerValidation){let o=String(e),c=s(l=>l.endsWith("/")?l.slice(0,-1):l,"trim");if(c(a.issuer)!==c(o))throw new ee(o,a.issuer)}return a}}s(ne,"discoverAuthorizationServerMetadata");async function nt(e,t={}){let r;try{r=await it(e,{resourceMetadataUrl:t.resourceMetadataUrl,fetch:t.fetch,signal:t.signal})}catch(n){if(n instanceof TypeError)throw n}if(t.authorizationServerMetadataUrl){let n=t.authorizationServerMetadataUrl,a=await b(n,t.fetch??globalThis.fetch,$,t.signal);if(!a.ok)throw E(a),new Error(`HTTP ${a.status} loading authorization server metadata from ${n}`);let o=re(await a.json());return{authorizationServerUrl:o.issuer,authorizationServerMetadata:o,resourceMetadata:r}}let i=r?.authorization_servers?.[0]??String(new URL("/",e));return{authorizationServerUrl:i,authorizationServerMetadata:await ne(i,{fetch:t.fetch,skipIssuerValidation:t.skipIssuerValidation,signal:t.signal}),resourceMetadata:r}}s(nt,"discoverOAuthServerInfo");function st(e){let t=new URL(e);return t.hash="",t}s(st,"resourceUrlFromServerUrl");function ot(e,t){if(!t)return;let r=st(e),i=new URL(t.resource);if(r.origin!==i.origin)throw new Error(`Protected resource ${t.resource} does not match MCP server ${r}`);let n=r.pathname.endsWith("/")?r.pathname:`${r.pathname}/`,a=i.pathname.endsWith("/")?i.pathname:`${i.pathname}/`;if(!n.startsWith(a))throw new Error(`Protected resource ${t.resource} does not match MCP server ${r}`);return t.resource}s(ot,"selectResource");function se(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e==="::1"}s(se,"loopback");function ct(e){return e.some(t=>{if(!URL.canParse(t))return!1;let r=new URL(t);return r.protocol!=="http:"&&r.protocol!=="https:"||se(r.hostname)})?"native":"web"}s(ct,"applicationType");function oe(e){let t=new URL(e);if(t.protocol!=="https:"&&!se(t.hostname))throw new te(t.href);return t}s(oe,"secureEndpoint");function lt(e,t){let r="token_endpoint_auth_method"in e?e.token_endpoint_auth_method:void 0;return r&&["client_secret_basic","client_secret_post","none"].includes(r)&&(t.length===0||t.includes(r))?r:t.length===0?e.client_secret?"client_secret_basic":"none":e.client_secret&&t.includes("client_secret_basic")?"client_secret_basic":e.client_secret&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":e.client_secret?"client_secret_post":"none"}s(lt,"selectClientAuthMethod");function ht(e,t,r,i){if(e==="client_secret_basic"){if(!t.client_secret)throw new Error("client_secret_basic requires a client secret");r.set("Authorization",`Basic ${Buffer.from(`${t.client_id}:${t.client_secret}`).toString("base64")}`)}else i.set("client_id",t.client_id),e==="client_secret_post"&&t.client_secret&&i.set("client_secret",t.client_secret)}s(ht,"applyClientAuthentication");async function ut(){let e=crypto.getRandomValues(new Uint8Array(32)),t=Buffer.from(e).toString("base64url"),r=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return{verifier:t,challenge:Buffer.from(r).toString("base64url")}}s(ut,"pkce");async function dt(e,t){let r=t.metadata;if(r&&!r.response_types_supported.includes("code"))throw new Error("Authorization server does not support authorization codes");if(r?.code_challenge_methods_supported&&!r.code_challenge_methods_supported.includes("S256"))throw new Error("Authorization server does not support PKCE S256");let i=new URL(r?.authorization_endpoint??new URL("/authorize",e)),{verifier:n,challenge:a}=await ut();return i.searchParams.set("response_type","code"),i.searchParams.set("client_id",t.clientInformation.client_id),i.searchParams.set("code_challenge",a),i.searchParams.set("code_challenge_method","S256"),i.searchParams.set("redirect_uri",String(t.redirectUrl)),t.state&&i.searchParams.set("state",t.state),t.scope&&i.searchParams.set("scope",t.scope),t.scope?.split(/\s+/).includes("offline_access")&&i.searchParams.set("prompt","consent"),t.resource&&i.searchParams.set("resource",t.resource),{authorizationUrl:i,codeVerifier:n}}s(dt,"startAuthorization");async function ce(e,t,r){let i=oe(t.metadata?.token_endpoint??new URL("/token",e)),n=new Headers({Accept:"application/json","content-type":"application/x-www-form-urlencoded"});t.resource&&r.set("resource",t.resource),t.addClientAuthentication?await t.addClientAuthentication(n,r,i,t.metadata):ht(lt(t.clientInformation,t.metadata?.token_endpoint_auth_methods_supported??[]),t.clientInformation,n,r);let a=await(t.fetch??globalThis.fetch)(i,{method:"POST",headers:n,body:r,signal:t.signal}),o=await a.text(),c;try{c=JSON.parse(o)}catch{}if(Y(c)&&typeof c.error=="string")throw new S(c.error,typeof c.error_description=="string"?c.error_description:c.error,typeof c.error_uri=="string"?c.error_uri:void 0);if(!a.ok)throw new S("server_error",`HTTP ${a.status}: ${o}`);return et(c)}s(ce,"tokenRequest");async function ft(e,t){let r=t.metadata?.registration_endpoint;if(t.metadata&&!r)throw new Error("Authorization server does not support dynamic client registration");let i=await(t.fetch??globalThis.fetch)(new URL(r??new URL("/register",e)),{method:"POST",headers:{Accept:"application/json","content-type":"application/json"},body:JSON.stringify({...t.clientMetadata,application_type:t.clientMetadata.application_type??ct(t.clientMetadata.redirect_uris),...t.scope?{scope:t.scope}:{}}),signal:t.signal});if(!i.ok)throw new Ge(i.status,await i.text());return tt(await i.json())}s(ft,"registerClient");async function pt(e,t){return ce(e,t,new URLSearchParams({grant_type:"authorization_code",code:t.code,code_verifier:t.codeVerifier,redirect_uri:String(t.redirectUrl)}))}s(pt,"exchangeAuthorizationCode");async function wt(e,t){let r=await ce(e,t,new URLSearchParams({grant_type:"refresh_token",refresh_token:t.refreshToken}));return{refresh_token:t.refreshToken,...r}}s(wt,"refreshAuthorization");function le(e,t){return e.scope===void 0&&t?{...e,scope:t}:e}s(le,"withScope");function mt(e,t){if(!t)return;let r=[e,t].flatMap(i=>i?.split(/\s+/).filter(Boolean)??[]);return[...new Set(r)].join(" ")}s(mt,"stepUpScope");async function H(e,t){let r=t.authorizationServerMetadataUrl&&oe(t.authorizationServerMetadataUrl),i=r?void 0:await e.discoveryState?.(),n=i?.authorizationServerUrl?{authorizationServerUrl:i.authorizationServerUrl,authorizationServerMetadata:i.authorizationServerMetadata??await ne(i.authorizationServerUrl,{fetch:t.fetch,skipIssuerValidation:t.skipIssuerValidation,signal:t.signal}),resourceMetadata:i.resourceMetadata}:await nt(t.serverUrl,{resourceMetadataUrl:t.resourceMetadataUrl,authorizationServerMetadataUrl:r,fetch:t.fetch,skipIssuerValidation:t.skipIssuerValidation,signal:t.signal});r||await e.saveDiscoveryState?.({...n,...t.resourceMetadataUrl?{resourceMetadataUrl:t.resourceMetadataUrl.href}:{}});let a=n.authorizationServerMetadata,o=ot(t.serverUrl,n.resourceMetadata),c=t.scope||n.resourceMetadata?.scopes_supported?.join(" ")||e.clientMetadata.scope,l=await e.clientInformation(),h=l?void 0:e.clientMetadataDocument?.(a);if(h){let u=new URL(h.url);if(u.protocol!=="https:"||u.pathname==="/")throw new Error("Invalid OAuth client metadata URL")}let d=l??(h&&{client_id:h.url});if(!d){if(t.authorizationCode)throw new Error("OAuth client information is missing during code exchange");if(!e.saveClientInformation)throw new Error("OAuth client information cannot be persisted");d=await ft(n.authorizationServerUrl,{metadata:a,clientMetadata:e.clientMetadata,scope:c,fetch:t.fetch,signal:t.signal}),await e.saveClientInformation(d)}let p=h?.redirectUrl??e.redirectUrl,g={metadata:a,clientInformation:d,resource:o,addClientAuthentication:e.addClientAuthentication,fetch:t.fetch,signal:t.signal};if(t.authorizationCode){let u=t.iss;if(a&&(u!==void 0||a.authorization_response_iss_parameter_supported)&&u!==a.issuer)throw new ee(a.issuer,u);let O=await pt(n.authorizationServerUrl,{...g,code:t.authorizationCode,codeVerifier:await e.codeVerifier(),redirectUrl:p});return await e.saveTokens(le(O,c)),"AUTHORIZED"}let f=t.skipRefresh?void 0:await e.tokens();if(f?.refresh_token)try{let u=await wt(n.authorizationServerUrl,{...g,refreshToken:f.refresh_token});return await e.saveTokens(le(u,f.scope)),"AUTHORIZED"}catch(u){if(t.signal?.aborted||u instanceof te||u instanceof S&&u.code!=="server_error")throw u}let v=await e.state?.(),y=await dt(n.authorizationServerUrl,{metadata:a,clientInformation:d,redirectUrl:p,scope:c,state:v,resource:o});return await e.saveCodeVerifier(y.codeVerifier),await e.redirectToAuthorization(y.authorizationUrl),"REDIRECT"}s(H,"runFlow");async function D(e,t){try{return await H(e,t)}catch(r){if(r instanceof S&&["invalid_client","unauthorized_client"].includes(r.code))return await e.invalidateCredentials?.("all"),H(e,t);if(r instanceof S&&r.code==="invalid_grant")return await e.invalidateCredentials?.("tokens"),H(e,t);throw r}}s(D,"authorizeMcp");var gt=class{static{s(this,"MemoryOAuthStateStore")}value;load(){return this.value===void 0?void 0:structuredClone(this.value)}save(e){this.value=structuredClone(e)}},_t=class{static{s(this,"McpOAuthProvider")}redirectUrl;clientMetadata;clientMetadataDocument;serverUrl;configuredClient;store;onRedirect;writes=Promise.resolve();constructor(e){this.serverUrl=String(new URL(e.serverUrl)),this.redirectUrl=String(e.redirectUrl),this.clientMetadata={...e.clientMetadata,redirect_uris:e.clientMetadata.redirect_uris??[this.redirectUrl],grant_types:e.clientMetadata.grant_types??["authorization_code","refresh_token"],response_types:e.clientMetadata.response_types??["code"],token_endpoint_auth_method:e.clientMetadata.token_endpoint_auth_method??(e.clientSecret?"client_secret_post":"none")},this.clientMetadataDocument=e.clientMetadataDocument,this.configuredClient=e.clientId?{client_id:e.clientId,...e.clientSecret?{client_secret:e.clientSecret}:{}}:void 0,this.store=e.store??new gt,this.onRedirect=e.onRedirect}async state(){let e=(await this.load()).oauthState;if(e)return e;let t=Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("hex");return await this.update(r=>({...r,oauthState:t})),t}async clientInformation(){return this.configuredClient??(await this.load()).clientInformation}async saveClientInformation(e){this.configuredClient||await this.update(t=>({...t,clientInformation:e}))}async tokens(){return(await this.load()).tokens}async saveTokens(e){let t=e.expires_in===void 0?void 0:Date.now()+e.expires_in*1e3;await this.update(r=>{let i={...r,tokens:e};return t===void 0?delete i.tokensExpireAt:i.tokensExpireAt=t,i})}async redirectToAuthorization(e){await this.onRedirect(e)}async saveCodeVerifier(e){await this.update(t=>({...t,codeVerifier:e}))}async codeVerifier(){let e=(await this.load()).codeVerifier;if(!e)throw new Error("No OAuth PKCE code verifier is stored");return e}async invalidateCredentials(e){await this.update(t=>{let r={...t};return(e==="all"||e==="client")&&delete r.clientInformation,(e==="all"||e==="tokens")&&(delete r.tokens,delete r.tokensExpireAt),(e==="all"||e==="verifier")&&delete r.codeVerifier,(e==="all"||e==="discovery")&&delete r.discovery,e==="all"&&delete r.oauthState,r})}async saveDiscoveryState(e){await this.update(t=>({...t,discovery:e}))}async discoveryState(){return(await this.load()).discovery}async load(){return await this.writes,this.own(await this.store.load())}async update(e){this.writes=this.writes.then(async()=>{await this.store.save(e(this.own(await this.store.load())))}),await this.writes}own(e){return e?.serverUrl===this.serverUrl?e:{serverUrl:this.serverUrl}}};import{createHash as he}from"node:crypto";import{mkdirSync as vt}from"node:fs";import{join as ue}from"node:path";var yt='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 800" aria-hidden="true"><path fill="#F09082" d="M165.29 165.29H517.36V400H400V282.65H165.29Z"/><path fill="#4D9ABF" d="M165.29 282.65H282.65V400H400V517.36H282.65V634.72H165.29Z"/><path fill="#F1BE58" d="M517.36 400H634.72V634.72H517.36Z"/></svg>';function C(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}s(C,"escapeHtml");function de(e){let t=C(e.title),r=C(e.heading),i=C(e.message),n=e.details?C(e.details):void 0;return`<!doctype html>
|
|
4
|
-
<html lang="en">
|
|
5
|
-
<head>
|
|
6
|
-
<meta charset="utf-8" />
|
|
7
|
-
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
8
|
-
<title>${t}</title>
|
|
9
|
-
<style>
|
|
10
|
-
:root {
|
|
11
|
-
--text: #fafafa;
|
|
12
|
-
--text-dim: #a1a1aa;
|
|
13
|
-
--page-bg: #09090b;
|
|
14
|
-
--font-sans: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
|
|
15
|
-
--font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
|
|
16
|
-
}
|
|
17
|
-
* { box-sizing: border-box; }
|
|
18
|
-
html { color-scheme: dark; }
|
|
19
|
-
body {
|
|
20
|
-
margin: 0;
|
|
21
|
-
min-height: 100vh;
|
|
22
|
-
display: flex;
|
|
23
|
-
align-items: center;
|
|
24
|
-
justify-content: center;
|
|
25
|
-
padding: 24px;
|
|
26
|
-
background: var(--page-bg);
|
|
27
|
-
color: var(--text);
|
|
28
|
-
font-family: var(--font-sans);
|
|
29
|
-
text-align: center;
|
|
30
|
-
}
|
|
31
|
-
main {
|
|
32
|
-
width: 100%;
|
|
33
|
-
max-width: 560px;
|
|
34
|
-
display: flex;
|
|
35
|
-
flex-direction: column;
|
|
36
|
-
align-items: center;
|
|
37
|
-
justify-content: center;
|
|
38
|
-
}
|
|
39
|
-
.logo {
|
|
40
|
-
width: 72px;
|
|
41
|
-
height: 72px;
|
|
42
|
-
display: block;
|
|
43
|
-
margin-bottom: 24px;
|
|
44
|
-
}
|
|
45
|
-
h1 {
|
|
46
|
-
margin: 0 0 10px;
|
|
47
|
-
font-size: 28px;
|
|
48
|
-
line-height: 1.15;
|
|
49
|
-
font-weight: 650;
|
|
50
|
-
color: var(--text);
|
|
51
|
-
}
|
|
52
|
-
p {
|
|
53
|
-
margin: 0;
|
|
54
|
-
line-height: 1.7;
|
|
55
|
-
color: var(--text-dim);
|
|
56
|
-
font-size: 15px;
|
|
57
|
-
}
|
|
58
|
-
.details {
|
|
59
|
-
margin-top: 16px;
|
|
60
|
-
font-family: var(--font-mono);
|
|
61
|
-
font-size: 13px;
|
|
62
|
-
color: var(--text-dim);
|
|
63
|
-
white-space: pre-wrap;
|
|
64
|
-
word-break: break-word;
|
|
65
|
-
}
|
|
66
|
-
</style>
|
|
67
|
-
</head>
|
|
68
|
-
<body>
|
|
69
|
-
<main>
|
|
70
|
-
<div class="logo">${yt}</div>
|
|
71
|
-
<h1>${r}</h1>
|
|
72
|
-
<p>${i}</p>
|
|
73
|
-
${n?`<div class="details">${n}</div>`:""}
|
|
74
|
-
</main>
|
|
75
|
-
</body>
|
|
76
|
-
</html>`}s(de,"renderPage");function St(e){return de({title:"Authentication successful",heading:"Authentication successful",message:e})}s(St,"oauthSuccessHtml");function kt(e,t){return de({title:"Authentication failed",heading:"Authentication failed",message:e,details:t})}s(kt,"oauthErrorHtml");var Ut=Fe(De(),1),N="127.0.0.1",z="/callback",fe="https://pi.dev/oauth",Rt=`http://${N}${z}`,At=3e4,Mt=15e3,Et=2e4,Tt=25e3,j=100;function pe(e){let t=new URL(e.callbackUrl??`http://${N}${z}`),r=t.hostname.replace(/^\[|\]$/g,""),i=t.port?Number(t.port):e.callbackPort,n;return t.port?n=e.callbackUrl:i!==void 0&&(t.port=String(i),n=t.href),{host:r==="localhost"?N:r,redirectHost:r,port:i,path:t.pathname,fixedRedirectUrl:n}}s(pe,"callbackSettings");function bt(...e){let t=[...new Set(e.flatMap(r=>r?.split(/\s+/).filter(Boolean)??[]))];return t.length>0?t.join(" "):void 0}s(bt,"mergeScopes");function P(e){if(!e?.trim())return{};let t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{}}s(P,"parseStates");function V(e){return`${JSON.stringify(e,null,2)}
|
|
77
|
-
`}s(V,"serializeStates");function F(e,t){let r=String(new URL(t));return{key:`${He(e)}|${r}`,legacyKey:r}}s(F,"storeKeys");var Ct=class{static{s(this,"McpOAuthCredentialStore")}backend;lockDir;constructor(e,t){this.backend=e??new ze(ue(G(),"mcp-auth.json")),this.lockDir=e?t:G()}forServer(e,t){let{key:r,legacyKey:i}=F(e,t);return{load:s(()=>this.backend.withLock(n=>{let a=P(n);return a[r]||!a[i]?{result:a[r]}:(a[r]=a[i],delete a[i],{result:a[r],next:V(a)})}),"load"),save:s(n=>this.write(a=>{a[r]=n}),"save"),withRefreshLock:s(n=>this.withRefreshLock(r,n),"withRefreshLock")}}async withRefreshLock(e,t){if(!this.lockDir)return t();vt(this.lockDir,{recursive:!0,mode:448});let r=he("sha256").update(e).digest("hex").slice(0,16),i=await Ut.default.lock(ue(this.lockDir,`mcp-auth-refresh-${r}`),{realpath:!1,stale:Et,retries:{retries:Tt/j,factor:1,minTimeout:j,maxTimeout:j},onCompromised:s(()=>{},"onCompromised")});try{return await t()}finally{await i().catch(()=>{})}}tokens(e,t){let{key:r,legacyKey:i}=F(e,t),n=this.backend.withLock(a=>({result:P(a)}));return(n[r]??n[i])?.tokens}remove(e,t){let{key:r,legacyKey:i}=F(e,t);return this.backend.withLock(n=>{let a=P(n),o=r in a?r:i in a?i:void 0;return o?(delete a[o],{result:!0,next:V(a)}):{result:!1}})}write(e){this.backend.withLock(t=>{let r=P(t);return e(r),{result:void 0,next:V(r)}})}};function we(e=globalThis.fetch){return(t,r)=>{let i=AbortSignal.timeout(Mt);return e(t,{...r,signal:r?.signal?AbortSignal.any([r.signal,i]):i})}}s(we,"timedFetch");function B(e){return e&&"redirect_uris"in e?e.redirect_uris:[]}s(B,"registeredRedirectUrls");function me(e){let t=new URL(e);return t.hash="",he("sha256").update(t.href).digest().subarray(0,9).toString("base64url")}s(me,"callbackId");function zt(e,t,r){if(!r?.client_id_metadata_document_supported||!r.token_endpoint_auth_methods_supported?.includes("none"))throw new Error('The authorization server does not support Client ID Metadata Documents for public clients; remove oauth.clientRegistration "cimd"');if(r.authorization_response_iss_parameter_supported)return{url:`${fe}/client.json`,redirectUrl:t};let i=me(e),n=new URL(t);return n.pathname=`${z}/${i}`,{url:`${fe}/${i}/client.json`,redirectUrl:n.href}}s(zt,"clientMetadataDocument");function ge(e,t,r,i,n){return new _t({serverUrl:e,redirectUrl:i,clientMetadata:{client_name:r.clientName??je},clientMetadataDocument:r.clientRegistration==="cimd"?a=>zt(e,i,a):void 0,clientId:r.clientId,clientSecret:r.clientSecret,store:t,onRedirect:n})}s(ge,"createProvider");function Pt(e){let{serverUrl:t,store:r}=e,i,n=s((a,o=globalThis.fetch,c)=>(i??=r.withRefreshLock(async()=>{let l=await r.load();if(l?.tokens?.access_token!==a)return;if(!l?.tokens?.refresh_token)throw new U;let h=e.settings(),d=pe(h).fixedRedirectUrl??B(l.clientInformation)[0]??Rt,p=ge(t,r,h,d,()=>{});if(await D(p,{serverUrl:t,resourceMetadataUrl:c?.resourceMetadataUrl,authorizationServerMetadataUrl:h.authServerMetadataUrl,scope:c?.scope,fetch:we(o)})==="REDIRECT")throw new U}).finally(()=>{i=void 0}),i),"refresh");return{token:s(async()=>{await i?.catch(()=>{});let a=await r.load(),o=a?.tokens?.access_token;return!(a?.tokensExpireAt!==void 0&&a.tokensExpireAt-At<=Date.now())||!a?.tokens?.refresh_token?o:(await n(o).catch(()=>{}),(await r.load())?.tokens?.access_token)},"token"),onUnauthorized:s(async a=>{let o=rt(a.response.headers.get("www-authenticate"));if(e.onChallenge(o),o.error==="insufficient_scope")throw new U;await n(a.token,a.fetch,o)},"onUnauthorized"),settled:s(async()=>{await i?.catch(()=>{})},"settled")}}s(Pt,"createMcpAuthProvider");var x=class extends Error{static{s(this,"McpSignInCancelledError")}constructor(){super("Sign-in cancelled"),this.name="McpSignInCancelledError"}};function xt(e,t,r){let i;try{i=new URL(e.trim())}catch{throw new Error("Expected the full redirect URL from the browser address bar")}if(i.origin!==r.origin||i.pathname!==r.pathname)throw new Error("The redirect URL does not match this sign-in's redirect URI");let n=i.searchParams.get("error");if(n)throw new Error(i.searchParams.get("error_description")??n);if(i.searchParams.get("state")!==t)throw new Error("The redirect URL belongs to a different sign-in");let a=i.searchParams.get("code");if(!a)throw new Error("The redirect URL does not contain an authorization code");return{code:a,iss:i.searchParams.get("iss")??void 0}}s(xt,"responseFromRedirectUrl");async function Ot(e,t,r,i,n){let a=new AbortController,o=n?AbortSignal.any([a.signal,n]):a.signal,c=e.waitForCallback(t,r.pathname),l=i.promptForRedirectUrl(o).then(h=>{if(!h?.trim())throw new x;return xt(h,t,r)});try{return await Promise.race([c,l])}finally{a.abort(),c.catch(()=>{}),l.catch(()=>{})}}s(Ot,"waitForAuthorizationResponse");async function $t(e,t,r,i){let n={host:e.host,redirectHost:e.redirectHost,path:e.path,extraPaths:t,renderPage:s(a=>a.ok?St("Signed in to the MCP server. You may now close this page."):kt(a.message,a.details),"renderPage")};try{return await X.listen({...n,port:r??0})}catch(a){if(i||r===void 0)throw a;return X.listen(n)}}s($t,"listenForCallback");async function Lt(e){let{serverUrl:t,store:r,settings:i,signal:n}=e;if(n?.aborted)throw new x;let a=await r.load(),o=e.challenge?.error==="insufficient_scope",c=pe(i),l=B(a?.clientInformation)[0],h=c.port??(l&&Number(new URL(l).port)||void 0),d=i.clientRegistration==="cimd",p=await $t(c,d?[`${z}/${me(t)}`]:[],h,c.port!==void 0),g=c.fixedRedirectUrl??p.redirectUrl;try{if(a){let m={...a};delete m.oauthState,i.clientId||(d?!a.clientInformation:B(a.clientInformation).includes(g))||(delete m.clientInformation,delete m.tokens,delete m.tokensExpireAt),await r.save(m)}let f,v=ge(t,r,i,g,m=>{f=m}),y={serverUrl:t,fetch:we(),signal:n,resourceMetadataUrl:e.challenge?.resourceMetadataUrl,authorizationServerMetadataUrl:i.authServerMetadataUrl,scope:bt(i.scope,o?mt(a?.tokens?.scope,e.challenge?.scope):e.challenge?.scope)};if(await D(v,{...y,skipRefresh:o})==="AUTHORIZED")return;if(!f)throw new Error("OAuth flow did not produce an authorization URL");let u=await v.state(),O=new URL(f.searchParams.get("redirect_uri")??g);e.prompt.showAuthorizationUrl(f);let{code:Ee,iss:Te}=await Ot(p,u,O,e.prompt,n);await D(v,{...y,authorizationCode:Ee,iss:Te})}catch(f){throw n?.aborted?new x:f}finally{await p.close()}}s(Lt,"signInMcpServer");import{appendFileSync as It,mkdirSync as Ht,renameSync as Dt,statSync as Nt}from"node:fs";import{dirname as jt}from"node:path";var _e=5*1024*1024;function Vt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}s(Vt,"isRecord");function Ft(e){if(typeof e=="string")return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}s(Ft,"formatData");function Bt(e,t,r=new Date){let i=Vt(t)?t:{data:t},n=typeof i.level=="string"?i.level:"info",a=typeof i.logger=="string"&&i.logger?` ${i.logger}:`:"",o=Ft(i.data).replace(/\r?\n/g,`
|
|
78
|
-
`);return`${r.toISOString()} [${e}] ${n}${a} ${o}
|
|
79
|
-
`}s(Bt,"formatMcpLogMessage");var qt=class{static{s(this,"McpServerLog")}path;size;constructor(e){this.path=e}write(e,t){let r=Bt(e,t);try{this.size===void 0&&(Ht(jt(this.path),{recursive:!0}),this.size=this.currentSize()),this.size>_e&&(this.currentSize()>_e&&Dt(this.path,`${this.path}.1`),this.size=this.currentSize()),It(this.path,r),this.size+=Buffer.byteLength(r)}catch{}}currentSize(){try{return Nt(this.path).size}catch{return 0}}},Kt=60,ve=2e3,ye=[250,1e3];function q(e){return e instanceof Error?e.message:String(e)}s(q,"errorMessage");function Se(e){return e instanceof W?e.status===408||e.status===429||e.status>=500&&e.status!==501:e instanceof TypeError}s(Se,"isTransientError");function ke(e){let t="url"in e.config?e.config.auth?.provider:void 0;return`MCP server "${e.name}" requires sign-in. Run ${t?`/login ${t}`:"/mcp"} to sign in.`}s(ke,"signInRequiredMessage");function Wt(e){let{config:t}=e;return!("url"in t)||t.auth?!1:!Object.keys(t.headers??{}).some(r=>r.toLowerCase()==="authorization")}s(Wt,"usesOAuth");function K(e){return e==="~"?Q():e.startsWith("~/")||process.platform==="win32"&&e.startsWith("~\\")?qe(Q(),e.slice(2)):e}s(K,"expandHome");function Jt(e,t,r){let{config:i,name:n}=e;if("url"in i)return new Ie({url:i.url,headers:Ne(i.headers,`MCP server "${n}"`),authProvider:r});let a={};for(let[o,c]of Object.entries(i.env??{}))a[o]=Z(c,`MCP server "${n}" env "${o}"`);return new L({command:K(i.command),args:i.args?.map(K),cwd:Ke(t,K(i.cwd??".")),env:a,stderr:"pipe"})}s(Jt,"createDefaultTransport");async function Ue(e,t){try{return await e()}catch(r){if(r instanceof $e&&r.code===Pe.methodNotFound)return t;throw r}}s(Ue,"withoutTemplates");function Re(e,t={}){return Ue(()=>e.listResourceTemplates(t),[])}s(Re,"listTemplates");async function Ae(e){let[t,r]=await Promise.all([e.listResources().catch(()=>[]),Re(e).catch(()=>[])]);return{resources:t.filter(i=>!J(i)),resourceTemplates:r.filter(i=>!J(i))}}s(Ae,"fetchResources");var Yt=class{static{s(this,"McpServerConnection")}entry;state="connecting";error;tools=[];hasResources=!1;resources=[];resourceTemplates=[];instructions;challenge;client;opening;shutdown=new AbortController;stderrTail;cwd;createTransport;authProvider;onTools;onChange;log;constructor(e){this.entry=e.entry,this.cwd=e.cwd,this.createTransport=e.createTransport,this.onTools=e.onTools,this.onChange=e.onChange,this.log=e.log;let t=this.oauthUrl,r="url"in this.entry.config?this.entry.config.auth?.provider:void 0;this.authProvider=t?Pt({serverUrl:t,store:e.credentials.forServer(this.entry.name,t),settings:s(()=>this.oauthSettings(),"settings"),onChallenge:s(i=>{this.challenge=i},"onChallenge")}):r?{token:s(async()=>e.providerToken?.(r),"token"),settled:s(async()=>{},"settled")}:void 0}get name(){return this.entry.name}get closed(){return this.shutdown.signal.aborted}get timeoutMs(){return(this.entry.config.timeout??Kt)*1e3}get oauthUrl(){return Wt(this.entry)&&"url"in this.entry.config?this.entry.config.url:void 0}oauthSettings(){let e="url"in this.entry.config?this.entry.config.oauth:void 0;return e?{clientId:e.clientId,clientSecret:e.clientSecret===void 0?void 0:Z(e.clientSecret,`MCP server "${this.entry.name}" oauth.clientSecret`),callbackPort:e.callbackPort,callbackUrl:e.callbackUrl,scope:e.scope,clientName:e.clientName,clientRegistration:e.clientRegistration,authServerMetadataUrl:e.authServerMetadataUrl?new URL(e.authServerMetadataUrl):void 0}:{}}getClient(){return this.closed?Promise.reject(new Error(`MCP server "${this.entry.name}" is shut down`)):this.client?.connectionState==="connected"?Promise.resolve(this.client):(this.opening??=this.open().finally(()=>{this.opening=void 0}),this.opening)}callTool(e,t,r){return this.withClient(i=>i.callTool(e,t,r))}readResource(e,t){return this.withClient(r=>r.readResource(e,t),!0)}resourcesPage(e,t){return this.withClient(r=>r.listResourcesPage(e,t),!0)}resourceTemplatesPage(e,t){return this.withClient(r=>Ue(()=>r.listResourceTemplatesPage(e,t),{resourceTemplates:[]}),!0)}allResources(e){return this.withClient(t=>t.listResources(e),!0)}allResourceTemplates(e){return this.withClient(t=>Re(t,e),!0)}async withClient(e,t=!1){for(let r=1;;r++){let i=await this.getClient();try{return await e(i)}catch(n){if(t&&r===1&&n instanceof W&&Se(n)){await new Promise(a=>setTimeout(a,ye[0]));continue}if(n instanceof Le&&r===1){this.client===i&&(this.client=void 0);continue}throw this.needsSignIn(n)?(await this.dropClient(i),this.markNeedsAuth(),new Error(ke(this.entry))):n}}}async reconnect(){await this.opening?.catch(()=>{}),this.client&&await this.dropClient(this.client),await this.getClient()}async signOut(){await this.opening?.catch(()=>{}),this.client&&await this.dropClient(this.client),this.closed||this.markNeedsAuth()}needsSignIn(e){return e instanceof U||this.authProvider!==void 0&&e instanceof xe}markNeedsAuth(){this.state="needs-auth",this.error=void 0,this.changed()}changed(){this.onChange?.(this)}async dropClient(e){this.client===e&&(this.client=void 0),await e.close().catch(()=>{})}async open(){this.state="connecting",this.changed();let e="url"in this.entry.config?ye:[];for(let t=0;;t++){this.stderrTail=void 0;try{return await this.connectOnce()}catch(r){let i=e[t];if(this.closed||i===void 0||!Se(r))throw this.connectFailed(r);if(await We(i,void 0,{signal:this.shutdown.signal}).catch(()=>{}),this.closed)throw this.connectFailed(r)}}}async connectOnce(){let e=new Oe({name:"pi",version:Ve,requestTimeoutMs:this.timeoutMs,roots:[{uri:Je(this.cwd).href,name:Be(this.cwd)}]}),t=this.log;t&&e.onNotification("notifications/message",a=>t.write(this.entry.name,a));let r,i=s(()=>(r??=e.close().catch(()=>{}),r),"closeClient");this.shutdown.signal.addEventListener("abort",i,{once:!0});let n;try{n=this.createTransport(this.entry,this.cwd,this.authProvider),await e.connect(n),e.onNotification("notifications/tools/list_changed",()=>{this.refreshTools(e)}),e.onNotification("notifications/resources/list_changed",()=>{this.refreshResources(e)});let a=n instanceof L?n:void 0;e.onClose(()=>this.handleClientClose(e,a));let o=e.serverCapabilities?.resources!==void 0,[c,l]=await Promise.all([e.serverCapabilities?.tools?e.listTools():[],o?Ae(e):{resources:[],resourceTemplates:[]}]);if(this.closed)throw new Error("shut down while connecting");if(e.connectionState!=="connected")throw new Error("connection closed during setup");return this.client=e,this.tools=c,this.hasResources=o,this.resources=l.resources,this.resourceTemplates=l.resourceTemplates,this.instructions=e.instructions?.trim()||void 0,this.state="connected",this.error=void 0,this.onTools(this),this.changed(),e}catch(a){throw await i(),n instanceof L&&(this.stderrTail=n.stderr.trim().slice(-ve)||void 0),a}finally{this.shutdown.signal.removeEventListener("abort",i)}}connectFailed(e){return this.needsSignIn(e)&&!this.closed?(this.markNeedsAuth(),new Error(ke(this.entry))):(this.state=this.closed?"closed":"failed",this.error=this.stderrTail?`${q(e)}
|
|
80
|
-
${this.stderrTail}`:q(e),this.changed(),new Error(`MCP server "${this.entry.name}" failed to connect: ${this.error}`))}handleClientClose(e,t){if(this.client!==e||this.closed)return;this.client=void 0,this.state="disconnected";let r=t?.stderr.trim().slice(-ve);this.error=r?`Connection closed
|
|
81
|
-
${r}`:"Connection closed",this.changed()}async refreshTools(e){try{let t=await e.listTools();if(this.client!==e||this.closed)return;this.tools=t,this.onTools(this)}catch(t){this.error=`Failed to refresh tools: ${q(t)}`}this.changed()}async refreshResources(e){let{resources:t,resourceTemplates:r}=await Ae(e);this.client!==e||this.closed||(this.resources=t,this.resourceTemplates=r,this.onTools(this),this.changed())}async close(){this.shutdown.abort(),this.state="closed",this.changed();let e=this.client;this.client=void 0,await Promise.all([e?.close().catch(()=>{}),this.opening?.catch(()=>{})]),await this.authProvider?.settled()}};export{Ct as McpOAuthCredentialStore,Yt as McpServerConnection,qt as McpServerLog,x as McpSignInCancelledError,Jt as createDefaultTransport,Lt as signInMcpServer};
|