copilot-api-node20 0.23.0 → 0.24.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/README.md +2 -1
- package/dist/main.mjs +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -149,7 +149,7 @@ See **[docs/claude-cowork.md](./docs/claude-cowork.md)** for the full setup guid
|
|
|
149
149
|
|
|
150
150
|
## API Endpoints
|
|
151
151
|
|
|
152
|
-
All endpoints are served at `http://localhost:4141` by default (`https://` when `--https` or `--claude-cowork` is used).
|
|
152
|
+
All endpoints are served at `http://localhost:4141` by default (`https://` when `--https` or `--claude-cowork` is used). The server binds to `127.0.0.1` (localhost only) by default. To expose to LAN/network/Docker, pass `--hostname 0.0.0.0`.
|
|
153
153
|
|
|
154
154
|
| Method | Path | Compatibility |
|
|
155
155
|
|:--|:--|:--|
|
|
@@ -187,6 +187,7 @@ All OpenAI-compatible routes are also available without the `/v1/` prefix.
|
|
|
187
187
|
| Flag | Alias | Default | Description |
|
|
188
188
|
|:--|:--|:--|:--|
|
|
189
189
|
| `--port` | `-p` | `4141` | Port to listen on |
|
|
190
|
+
| `--hostname` | `-H` | `127.0.0.1` | Hostname/IP to bind to. Use `0.0.0.0` for LAN/Docker exposure |
|
|
190
191
|
| `--claude-code` | `-c` | | Enable Claude Code compatibility mode |
|
|
191
192
|
| `--codex` | | | Enable Codex CLI compatibility mode |
|
|
192
193
|
| `--model` | `-m` | | Primary model to use |
|
package/dist/main.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{defineCommand as e,runMain as t}from"citty";import o from"consola";import n from"node:fs/promises";import r from"node:os";import i from"node:path";import{SpanKind as a,SpanStatusCode as s,context as l,metrics as c,trace as u}from"@opentelemetry/api";import p from"clipboardy";import{execFile as d,execSync as m}from"node:child_process";import f from"node:process";import{SeverityNumber as h,logs as g}from"@opentelemetry/api-logs";import{OTLPLogExporter as _}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as y}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as k}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as b}from"@opentelemetry/resources";import{BatchLogRecordProcessor as w}from"@opentelemetry/sdk-logs";import{PeriodicExportingMetricReader as v}from"@opentelemetry/sdk-metrics";import{NodeSDK as $}from"@opentelemetry/sdk-node";import{ATTR_SERVICE_INSTANCE_ID as x,ATTR_SERVICE_NAME as T,ATTR_SERVICE_VERSION as A}from"@opentelemetry/semantic-conventions";import{Client as S,request as C}from"undici";import{createHash as O,randomBytes as E,randomUUID as I}from"node:crypto";import{promisify as P}from"node:util";import{accessSync as N}from"node:fs";import{serve as q}from"srvx";import R from"tiny-invariant";import{isIP as j}from"node:net";import{generate as D}from"selfsigned";import{Hono as M}from"hono";import{cors as F}from"hono/cors";import{streamSSE as H}from"hono/streaming";import{events as B}from"fetch-event-stream";import{Tokenizer as L,models as U}from"ai-tokenizer";import*as J from"ai-tokenizer/encoding/claude";const G=i.join(r.homedir(),".local","share","copilot-api"),W={APP_DIR:G,GITHUB_TOKEN_PATH:i.join(G,"github_token"),MACHINE_ID_PATH:i.join(G,"machine_id"),SESSION_ID_PATH:i.join(G,"session_id")};async function z(){await n.mkdir(W.APP_DIR,{recursive:!0}),await K(W.GITHUB_TOKEN_PATH),await K(W.SESSION_ID_PATH)}async function K(e){try{await n.access(e,n.constants.W_OK)}catch{await n.writeFile(e,""),await n.chmod(e,384)}}const V=6e5,Y={accountType:"individual",manualApprove:!1,rateLimitWait:!1,showToken:!1,thinkingEnabled:!1,nativeAnthropicEnabled:!1,timeoutMs:V,connectivity:{probeEndpoints:["https://api.github.com","https://www.google.com","https://1.1.1.1"],fastProbeInterval:5e3,slowProbeInterval:1e4,timeoutMs:5e3,jitterMaxMs:1e3,connectionPooling:!0,dnsCache:!0,h2:!1,h2Keepalive:!1}},X=e=>e>=1e5||e>=1e4?`${Math.round(e/1e3)}K`:e>=1e3?`${(e/1e3).toFixed(1)}K`:e.toString(),Q=(e,t)=>e.padEnd(t),Z=e=>{let t=[];if(e.model){let o=Q(e.model,18);t.push(o)}if(e.tokenUsage){let o=e.tokenUsage,n=(o.inputTokens||0)+(o.outputTokens||0),r=e.model?((e,t)=>{if(!Y.models)return"";let o=Y.models.data.find(e=>e.id===t);if(!o)return"";let n=o.capabilities.limits?.max_context_window_tokens;return n?` (${(e/n*100).toFixed(1)}%)`:""})(n,e.model):"",i=Q(`↑${X(o.inputTokens||0).padStart(5)} │ ↓${X(o.outputTokens||0).padStart(5)}`,18),a=X(n),s=r?`${a}${r.padStart(15-a.length)}`:a.padEnd(15);t.push(`Tokens: ${i} | Context: ${s}`)}else if(e.model){let e=Q("N/A",18),o="N/A".padEnd(15);t.push(`Tokens: ${e} | Context: ${o}`)}if(e._d1){let o=Q(`${Math.round(e._d1)}ms`,8);t.push(`API: ${o}`)}return t.length>0?` | ${t.join(" | ")}`:""},ee={completionCallbacks:new Map,registerCompletion(e,t,o){this.completionCallbacks.set(e,{context:t,startTime:o,requestId:e})},executeCompletion(e){let t=this.completionCallbacks.get(e);t&&(this.logCompletion(t),this.completionCallbacks.delete(e))},logCompletion(e){let{context:t,startTime:n}=e,r=Date.now()-n,i=t.get("requestData"),a=` --\x3e ${Q(t.req.method,4)}${Q(t.req.path,21)}${Q(t.res.status.toString(),3)} ${Q(`${r}ms`,8)}`;i&&(a+=Z(i)),o.info(a),De(h.INFO,"INFO","Request completed",{"http.method":t.req.method,"http.path":t.req.path,"http.status_code":t.res.status,"copilot_api.duration_ms":r,...i?.model&&{"copilot_api.model":i.model},...i?._d1&&{"copilot_api.copilot_duration_ms":Math.round(i._d1)},...i?.tokenUsage?.inputTokens&&{"copilot_api.input_tokens":i.tokenUsage.inputTokens},...i?.tokenUsage?.outputTokens&&{"copilot_api.output_tokens":i.tokenUsage.outputTokens}})},logRateLimit(e,t){let{context:n,startTime:r}=e,i=Date.now()-r,a=(t.headers.get("x-ratelimit-exceeded")||"").split(":")[1]||"unknown",s=t.headers.get("retry-after")||t.headers.get("x-ratelimit-user-retry-after")||"?",l=`⚠ --\x3e ${Q(n.req.method,4)}${Q(n.req.path,21)}${Q("429",3)} ${Q(`${i}ms`,8)}`;l+=` | Rate limited (${s}s retry) | ${a}`;let c=n.get("requestData");if(c?._d1){l+=` | API: ${Q(`${Math.round(c._d1)}ms`,8)}`}o.info(l)},cleanup(){let e=Date.now()-3e5;for(let[t,o]of this.completionCallbacks)o.startTime<e&&this.completionCallbacks.delete(t);if(this.completionCallbacks.size>1e3){let e=Array.from(this.completionCallbacks.entries()).sort(([,e],[,t])=>e.startTime-t.startTime),t=e.slice(0,e.length-1e3);for(let[e]of t)this.completionCallbacks.delete(e)}}};setInterval(()=>ee.cleanup(),6e4);let te,oe,ne=Date.now();const re=process.env.OTEL_EXPORTER_OTLP_ENDPOINT||"https://api.honeycomb.io",ie=process.env.OTEL_EXPORTER_OTLP_ENDPOINT?{}:{"x-honeycomb-team":"hcaik_01km2y7yf1rrn70xvxce5kx9dyz936dwm21b9bgvnwf3pxq0cmqkcwha8n"};const ae=u.getTracer("copilot-api"),se=c.getMeter("copilot-api"),le=g.getLogger("copilot-api"),ce=se.createCounter("copilot_api.requests.total",{unit:"{request}",description:"Total requests received"}),ue=se.createCounter("copilot_api.requests.errors",{unit:"{error}",description:"Total error responses"}),pe=se.createCounter("copilot_api.tokens.input",{unit:"{token}",description:"Total input tokens consumed"}),de=se.createCounter("copilot_api.tokens.output",{unit:"{token}",description:"Total output tokens generated"}),me=se.createCounter("copilot_api.tokens.cached",{unit:"{token}",description:"Total cached prompt tokens"}),fe=se.createCounter("copilot_api.rate_limit.triggers",{unit:"{trigger}",description:"Rate limit trigger count"}),he=se.createCounter("copilot_api.model_validation.errors",{unit:"{error}",description:"Model validation failures"}),ge=se.createCounter("copilot_api.model_mapping.mappings",{unit:"{mapping}",description:"Model name normalizations"}),_e=se.createCounter("copilot_api.token_refresh.attempts",{unit:"{attempt}",description:"Token refresh attempts"}),ye=se.createCounter("copilot_api.token_refresh.failures",{unit:"{failure}",description:"Token refresh final failures"}),ke=se.createCounter("copilot_api.connectivity.checks",{unit:"{check}",description:"Connectivity probe results"}),be=se.createCounter("copilot_api.connectivity.transitions",{unit:"{transition}",description:"Connectivity state transitions"}),we=se.createCounter("copilot_api.upstream.requests",{unit:"{request}",description:"Upstream API calls"}),ve=se.createCounter("copilot_api.stream.chunks",{unit:"{chunk}",description:"Total SSE chunks sent"}),$e=se.createCounter("copilot_api.approval.decisions",{unit:"{decision}",description:"Manual approval decisions"}),xe=se.createCounter("copilot_api.h2_keepalive.pings",{unit:"{ping}",description:"HTTP/2 keepalive pings sent"}),Te=se.createCounter("copilot_api.h2.connections",{unit:"{connection}",description:"HTTP/2 connection lifecycle events"}),Ae=se.createHistogram("copilot_api.request.duration",{unit:"ms",description:"Total request duration"}),Se=se.createHistogram("copilot_api.copilot.duration",{unit:"ms",description:"Upstream Copilot API call duration"}),Ce=se.createHistogram("copilot_api.stream.duration",{unit:"ms",description:"Duration of SSE streaming phase"}),Oe=se.createHistogram("copilot_api.rate_limit.wait_duration",{unit:"ms",description:"Duration of rate limit waits"}),Ee=se.createHistogram("copilot_api.translation.duration",{unit:"ms",description:"Translation layer processing time"}),Ie=se.createHistogram("copilot_api.token_refresh.duration",{unit:"ms",description:"Token refresh duration"}),Pe=se.createHistogram("copilot_api.connectivity.probe_duration",{unit:"ms",description:"Individual connectivity probe duration"}),Ne=se.createHistogram("copilot_api.tokens.per_request.input",{unit:"{token}",description:"Input tokens per request distribution"}),qe=se.createHistogram("copilot_api.tokens.per_request.output",{unit:"{token}",description:"Output tokens per request distribution"}),Re=se.createHistogram("copilot_api.stream.chunks_per_request",{unit:"{chunk}",description:"Chunks per streaming request"}),je=se.createHistogram("copilot_api.approval.wait_duration",{unit:"ms",description:"Time waiting for manual approval"});function De(e,t,o,n){let r=u.getActiveSpan()?.spanContext();le.emit({severityNumber:e,severityText:t,body:o,attributes:{...n,...r&&{"trace.id":r.traceId,"span.id":r.spanId}}})}function Me(e,t=""){let o={};if(null==e)return o;if("object"!=typeof e)return("string"==typeof e||"number"==typeof e||"boolean"==typeof e)&&t&&(o[t]=e),o;if(Array.isArray(e))return t&&(o[t]=JSON.stringify(e)),o;for(let[n,r]of Object.entries(e)){let e=t?`${t}.${n}`:n;void 0===r||"function"==typeof r||(null===r?o[e]="null":"object"!=typeof r||Array.isArray(r)?Array.isArray(r)?o[e]=JSON.stringify(r):("string"==typeof r||"number"==typeof r||"boolean"==typeof r)&&(o[e]=r):Object.assign(o,Me(r,e)))}return o}se.createObservableGauge("copilot_api.connectivity.status",{unit:"{status}",description:"1 = online, 0 = offline"}).addCallback(e=>{e.observe(Ue.getConnectivityStats().isOnline?1:0)}),se.createObservableGauge("copilot_api.connectivity.consecutive_failures",{unit:"{failure}",description:"Current consecutive connectivity failure count"}).addCallback(e=>{e.observe(Ue.getConnectivityStats().consecutiveFailures)}),se.createObservableGauge("copilot_api.models.available",{unit:"{model}",description:"Number of available models"}).addCallback(e=>{e.observe(Y.models?.data.length??0)}),se.createObservableGauge("copilot_api.completion_logger.pending",{unit:"{callback}",description:"Number of pending completion callbacks"}).addCallback(e=>{e.observe(ee.completionCallbacks.size)}),se.createObservableGauge("copilot_api.uptime",{unit:"s",description:"Server uptime in seconds"}).addCallback(e=>{e.observe((Date.now()-ne)/1e3)});const Fe=new Set(["authorization","cookie","set-cookie","x-honeycomb-team","x-api-key","proxy-authorization"]);function He(e,t,o){for(let[n,r]of Object.entries(o)){let o=n.toLowerCase();Fe.has(o)||e.setAttribute(`http.${t}.header.${o}`,r)}}async function Be(e){let{spanName:t,url:o,target:n,method:r="GET",headers:i,body:l,signal:c,extraAttributes:u}=e,p=ae.startSpan(t,{kind:a.CLIENT,attributes:{"http.method":r,"url.full":o,"copilot_api.target":n,...u}});i&&He(p,"request",i);try{let e=await fetch(o,{method:r,headers:i,body:l,signal:c});return p.setAttribute("http.response.status_code",e.status),function(e,t){t.headers.forEach((t,o)=>{let n=o.toLowerCase();Fe.has(n)||e.setAttribute(`http.response.header.${n}`,t)})}(p,e),we.add(1,{target:n,status_code:String(e.status)}),e.ok||p.setStatus({code:s.ERROR,message:`HTTP ${e.status}`}),{response:e,span:p}}catch(e){let t=e instanceof Error?e:Error(String(e));throw p.setStatus({code:s.ERROR,message:t.message}),p.recordException(t),p.end(),e}}async function Le(e){let{spanName:t,url:o,target:n,method:r="POST",headers:i,body:l,signal:c,headersTimeout:u,bodyTimeout:p,extraAttributes:d,dispatcher:m}=e,f=ae.startSpan(t,{kind:a.CLIENT,attributes:{"http.method":r,"url.full":o,"copilot_api.target":n,"copilot_api.h2.enabled":void 0!==m,...d}});He(f,"request",i);try{let{statusCode:e,headers:t,body:a}=await C(o,{method:r,headers:i,body:l,signal:c,headersTimeout:u,bodyTimeout:p,dispatcher:m});f.setAttribute("http.response.status_code",e);for(let[e,o]of Object.entries(t)){let t=e.toLowerCase();void 0!==o&&!Fe.has(t)&&f.setAttribute(`http.response.header.${t}`,Array.isArray(o)?o.join(", "):o)}return we.add(1,{target:n,status_code:String(e)}),e>=400&&f.setStatus({code:s.ERROR,message:`HTTP ${e}`}),{statusCode:e,headers:t,body:a,span:f}}catch(e){let t=e instanceof Error?e:Error(String(e));throw f.setStatus({code:s.ERROR,message:t.message}),f.recordException(t),f.end(),e}}const Ue=new class extends EventTarget{isOnline=!0;lastChecked=(new Date).toISOString();consecutiveFailures=0;lastErrorType;lastErrorMessage;lastSuccessfulEndpoint;endpointFailureStats={};checkInterval;abortController;on(e,t){return this.addEventListener(e,t),this}off(e,t){return this.removeEventListener(e,t),this}start(){o.debug("Starting connectivity monitor",{probeEndpoints:Y.connectivity.probeEndpoints,fastInterval:Y.connectivity.fastProbeInterval}),this.scheduleNextCheck()}stop(){o.debug("Stopping connectivity monitor"),this.checkInterval&&=void clearTimeout(this.checkInterval),this.abortController&&=void this.abortController.abort()}scheduleNextCheck(){this.checkInterval&&clearTimeout(this.checkInterval);let e=(this.isOnline?Y.connectivity.slowProbeInterval:Y.connectivity.fastProbeInterval)+Math.random()*Y.connectivity.jitterMaxMs;this.checkInterval=setTimeout(()=>{this.performConnectivityCheck().catch(e=>{o.error("Connectivity check failed:",e)})},e)}async performConnectivityCheck(){let e=ae.startSpan("copilot_api.connectivity.probe");this.abortController=new AbortController;let t=setTimeout(()=>this.abortController?.abort(),Y.connectivity.timeoutMs);try{let n=!1;for(let e of Y.connectivity.probeEndpoints)try{let t=performance.now(),o=await fetch(e,{method:"HEAD",signal:this.abortController.signal,headers:{"User-Agent":"copilot-api-connectivity-monitor/1.0",...Y.connectivity.dnsCache&&{"Cache-Control":"max-age=300"}}}),r=performance.now()-t;if(o.ok){n=!0,this.lastSuccessfulEndpoint=e,Pe.record(r,{endpoint:e,result:"success"});break}Pe.record(r,{endpoint:e,result:"failed"})}catch(t){this.endpointFailureStats[e]=(this.endpointFailureStats[e]||0)+1,o.debug(`Probe failed for ${e}:`,t)}this.updateConnectivityState(n);let r=n?"online":"offline";e.setAttribute("copilot_api.connectivity.result",r),e.setAttribute("copilot_api.connectivity.consecutive_failures",this.consecutiveFailures),this.lastSuccessfulEndpoint&&e.setAttribute("copilot_api.connectivity.successful_endpoint",this.lastSuccessfulEndpoint),ke.add(1,{result:n?"online":"offline"})}catch(e){this.handleConnectivityError(e)}finally{clearTimeout(t),e.end(),this.scheduleNextCheck()}}updateConnectivityState(e){let t=this.isOnline;if(this.isOnline=e,this.lastChecked=(new Date).toISOString(),e){let e=this.consecutiveFailures;this.consecutiveFailures>0&&o.info(`Connectivity restored after ${this.consecutiveFailures} failures`),this.consecutiveFailures=0,this.lastErrorType=void 0,this.lastErrorMessage=void 0,t||(this.dispatchEvent(new CustomEvent("online")),be.add(1,{from:"offline",to:"online"}),De(h.INFO,"INFO","Connectivity restored",{"copilot_api.connectivity.consecutive_failures_before_recovery":e}))}else this.consecutiveFailures++,t&&(o.warn("Connectivity lost"),this.dispatchEvent(new CustomEvent("offline")),be.add(1,{from:"online",to:"offline"}),De(h.WARN,"WARN","Connectivity lost",{"copilot_api.connectivity.consecutive_failures":this.consecutiveFailures}))}handleConnectivityError(e){this.lastErrorType=e.name,this.lastErrorMessage=e.message,o.error("Connectivity check failed:",e),this.updateConnectivityState(!1)}getConnectivityStats(){return{isOnline:this.isOnline,lastChecked:this.lastChecked,consecutiveFailures:this.consecutiveFailures,lastErrorType:this.lastErrorType,lastErrorMessage:this.lastErrorMessage}}getPerformanceStats(){let e=this.isOnline?Y.connectivity.slowProbeInterval:Y.connectivity.fastProbeInterval;return{currentInterval:e,nextCheckEstimate:new Date(Date.now()+e+Math.random()*Y.connectivity.jitterMaxMs).toISOString(),lastSuccessfulEndpoint:this.lastSuccessfulEndpoint,endpointFailureStats:{...this.endpointFailureStats},jitterEnabled:Y.connectivity.jitterMaxMs>0,connectionPooling:Y.connectivity.connectionPooling,dnsCache:Y.connectivity.dnsCache}}},Je=()=>({"content-type":"application/json",accept:"application/json"}),Ge="0.43.2026040705",We=`copilot-chat/${Ge}`,ze=`GitHubCopilotChat/${Ge}`,Ke=async e=>{let t=(e=>{let t=e.replaceAll(/[^\w.-]/g,"_").trim();if(0===t.length||"."===t||".."===t||/^[_.]+$/.test(t))throw Error("Invalid GitHub username: cannot be empty or consist only of special characters after sanitization");return`${W.MACHINE_ID_PATH}_${t}`})(e);try{let e=await n.readFile(t,"utf8");if(e.trim())return e.trim()}catch{}let o=(e=>{let t=O("sha256");return t.update(process.platform),t.update(process.arch),t.update(process.env.USER||process.env.USERNAME||"anonymous"),t.update(r.hostname()),t.update(e),t.update(Date.now().toString()),t.update(E(16)),t.digest("hex")})(e);return await n.writeFile(t,o),await n.chmod(t,384),o},Ve=async(e,t)=>{e.machineId||=await Ke(t),e.sessionId||=await(async()=>{try{let e=await n.readFile(W.SESSION_ID_PATH,"utf8");if(e.trim())return e.trim()}catch{}let e=I();return await n.writeFile(W.SESSION_ID_PATH,e),await n.chmod(W.SESSION_ID_PATH,384),e})()},Ye=e=>"individual"===e.accountType?"https://api.githubcopilot.com":`https://api.${e.accountType}.githubcopilot.com`,Xe=(e,t=!1)=>{if(!e.machineId||!e.sessionId)throw Error("VSCode identifiers not initialized. Call initializeVSCodeIdentifiers() during startup.");let o=I(),n={Authorization:`Bearer ${e._t1}`,"Content-Type":"application/json",accept:"*/*","accept-encoding":"br, gzip, deflate","accept-language":"*","sec-fetch-mode":"cors","Copilot-Integration-Id":"vscode-chat","Editor-Version":`vscode/${e._v1}`,"Editor-Plugin-Version":We,"User-Agent":ze,"VScode-MachineId":e.machineId,"VScode-SessionId":e.sessionId,"OpenAI-Intent":"conversation-agent","X-Interaction-Type":"conversation-agent","X-Agent-Task-Id":o,"X-VSCode-User-Agent-Library-Version":"node-fetch","X-GitHub-Api-Version":"2025-05-01","X-Interaction-Id":I(),"X-Request-Id":o};return t&&(n["copilot-vision-request"]="true"),n},Qe=["interleaved-thinking","context-management","advanced-tool-use"];const Ze=(e,t)=>{let o=Xe(e);if(delete o["Copilot-Integration-Id"],o["anthropic-version"]=t?.anthropicVersion??"2023-06-01",t?.anthropicBeta){let e=function(e){let t=e.split(",").map(e=>e.trim()).filter(e=>e&&Qe.some(t=>e.startsWith(`${t}-`)));return t.length>0?t.join(","):void 0}(t.anthropicBeta);e&&(o["anthropic-beta"]=e)}return o},et="https://api.github.com",tt=e=>({"content-type":"application/json",accept:"application/json",authorization:`token ${e._t2}`,"editor-version":`vscode/${e._v1}`,"editor-plugin-version":We,"user-agent":ze,"x-github-api-version":"2025-04-01","x-vscode-user-agent-library-version":"node-fetch"}),ot="https://github.com",nt="01ab8ac9400c4e429b23",rt=["user:email"].join(" ");var it=class extends Error{response;constructor(e,t){super(e),this.response=t}};function at(e){return e.req.path.startsWith("/v1/messages")}function st(e,t){if(at(t)){try{let t=JSON.parse(e);if("message"in t&&"string"==typeof t.message&&!("error"in t))return{type:"error",error:{type:"invalid_request_error",message:t.message}};if("error"in t&&"object"==typeof t.error){let e=t.error;return{type:"error",error:{type:"string"==typeof e.type&&e.type||"api_error",message:"string"==typeof e.message&&e.message||"Unknown error"}}}}catch{}return{type:"error",error:{type:"api_error",message:e}}}try{return JSON.parse(e)}catch{return{error:{message:e,type:"error"}}}}async function lt(e,t){let n=u.getActiveSpan();if(t instanceof it&&429===t.response.status){let o=e.get("requestId"),r=ee.completionCallbacks.get(o);r&&(ee.logRateLimit(r,t.response),ee.completionCallbacks.delete(o)),fe.add(1,{action:"rejected",source:"upstream"});let i=st(await t.response.text(),e);return n?.setStatus({code:s.ERROR,message:"Rate limited by upstream"}),n?.setAttribute("copilot_api.error_type","rate_limit_upstream"),De(h.WARN,"WARN","Upstream rate limit hit",{"copilot_api.status_code":429,"http.path":e.req.path,"copilot_api.error_type":"rate_limit_upstream"}),e.json(i,429)}if(o.error("Error occurred:",t),t instanceof it){let r=st(await t.response.text(),e);return o.error("HTTP error:",r),n?.setStatus({code:s.ERROR,message:t.message}),n?.recordException(t),n?.setAttribute("copilot_api.error_type","HTTPError"),De(h.ERROR,"ERROR",`HTTP error: ${t.message}`,{"copilot_api.status_code":t.response.status,"http.path":e.req.path,"copilot_api.error_type":"HTTPError"}),e.json(r,t.response.status)}let r=t instanceof Error?t:Error(String(t));n?.setStatus({code:s.ERROR,message:r.message}),n?.recordException(r),n?.setAttribute("copilot_api.error_type",r.name),De(h.ERROR,"ERROR",`Unhandled error: ${r.message}`,{"copilot_api.status_code":500,"http.path":e.req.path,"copilot_api.error_type":r.name});let i=at(e)?{type:"error",error:{type:"api_error",message:r.message}}:{error:{message:r.message,type:"error"}};return e.json(i,500)}const ct=async()=>{let e=`${et}/copilot_internal/v2/token`,t=Y.timeoutMs,o=new AbortController,n=setTimeout(()=>o.abort(),t);try{let{response:t,span:n}=await Be({spanName:"github GET /copilot_internal/v2/token",url:e,target:"copilot_token",headers:tt(Y),signal:o.signal});if(!t.ok)throw n.end(),new it("Failed to get Service token",t);let r=await t.json();return n.end(),r}finally{clearTimeout(n)}};async function ut(){let e=`${et}/user`,t=Y.timeoutMs,o=new AbortController,n=setTimeout(()=>o.abort(),t);try{let{response:t,span:n}=await Be({spanName:"github GET /user",url:e,target:"github_user",headers:{authorization:`token ${Y._t2}`,"content-type":"application/json",accept:"application/json"},signal:o.signal});if(!t.ok)throw n.end(),new it("Failed to get GitHub user",t);let r=await t.json();return n.end(),r}finally{clearTimeout(n)}}const pt=e=>new Promise(t=>{setTimeout(t,e)}),dt=e=>null==e;async function mt(){Y.models=await(async()=>{let e=`${Ye(Y)}/models`,t=Xe(Y),o=Y.timeoutMs,n=new AbortController,r=setTimeout(()=>n.abort(),o);try{let{response:o,span:r}=await Be({spanName:"copilot GET /models",url:e,target:"models",headers:t,signal:n.signal});if(!o.ok)throw r.end(),new it("Failed to get models",o);let i=await o.json();return r.setAttribute("copilot_api.models_count",i.data.length),r.end(),i}finally{clearTimeout(r)}})()}var ft=class extends Error{constructor(e){super(e),this.name="AuthorizationError"}};let ht,gt,_t,yt=!1;const kt=()=>n.readFile(W.GITHUB_TOKEN_PATH,"utf8"),bt=e=>n.writeFile(W.GITHUB_TOKEN_PATH,e);const wt=async()=>{let{token:e,refresh_in:t}=await ct();Y._t1=e,o.debug("Service token fetched successfully!"),Y.showToken&&o.info("Service token:",e);let n=async(e=5,t=1e3,n="scheduled")=>{if(!yt)return yt=!0,ae.startActiveSpan("copilot_api.token.refresh",async r=>{let i=performance.now();r.setAttribute("copilot_api.token_refresh.reason",n),r.setAttribute("copilot_api.token_refresh.max_retries",e);try{for(let a=1;a<=e;a++)try{r.setAttribute("copilot_api.token_refresh.attempt",a),o.debug(`Refreshing Service token (${n}, attempt ${a}/${e})`);let{token:t}=await ct();return Y._t1=t,o.debug("Service token refreshed successfully"),Y.showToken&&o.info("Refreshed Service token:",t),r.setAttribute("copilot_api.token_refresh.success",!0),_e.add(1,{reason:n,success:"true"}),Ie.record(performance.now()-i,{reason:n}),void De(h.INFO,"INFO",`Token refreshed successfully (${n})`,{"copilot_api.token_refresh.reason":n,"copilot_api.token_refresh.attempt":a})}catch(l){let c=a===e;if(o.error(`Failed to refresh Service token (attempt ${a}/${e}):`,l),_e.add(1,{reason:n,success:"false"}),c){o.error("All refresh attempts failed. May be unavailable until next scheduled refresh.");let t=l instanceof Error?l:Error(String(l));return r.setAttribute("copilot_api.token_refresh.success",!1),r.setStatus({code:s.ERROR,message:t.message}),r.recordException(t),ye.add(1,{reason:n}),Ie.record(performance.now()-i,{reason:n}),void De(h.ERROR,"ERROR",`Token refresh failed after ${e} attempts (${n})`,{"copilot_api.token_refresh.reason":n,"copilot_api.token_refresh.attempts":e})}let u=t*2**(a-1);o.debug(`Retrying token refresh in ${u}ms...`),await new Promise(e=>setTimeout(e,u))}}finally{r.end(),yt=!1}});o.debug("Refresh already in progress, skipping")};ht=setInterval(()=>{n(5,1e3,"scheduled").catch(e=>{o.error("Unexpected error in scheduled token refresh:",e)})},1e3*(t-60)),Ue.start(),gt=()=>{o.debug("Network connectivity restored, attempting immediate token refresh"),n(3,500,"network-restored").catch(e=>{o.error("Unexpected error in network-restored token refresh:",e)})},_t=()=>{o.debug("Network connectivity lost")},Ue.on("online",gt),Ue.on("offline",_t)};async function vt(e){try{let t=await kt();if(t&&!e?.force)return Y._t2=t,Y.showToken&&o.info("Auth token:",t),void await $t();o.info("Authentication required");let n=await async function(){let e=new AbortController,t=Y.timeoutMs,o=setTimeout(()=>{e.abort()},t);try{let t=await fetch(`${ot}/login/device/code`,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify({client_id:nt,scope:rt}),signal:e.signal});if(!t.ok)throw new it("Failed to get device code",t);return await t.json()}finally{clearTimeout(o)}}();o.debug("Device code response:",n),o.info(`Please enter the code "${n.user_code}" at ${n.verification_uri}`);try{p.writeSync(n.user_code),o.success("Code copied to clipboard — opening browser...")}catch{o.info("Open the link above and enter the code to authenticate")}!function(e){try{let t,o=f.platform;t="darwin"===o?"open":"win32"===o?"start":"xdg-open",d(t,[e],()=>{})}catch{}}(n.verification_uri);let r=await async function(e){let t=1e3*(e.interval+1);o.debug(`Polling access token with interval of ${t}ms`),o.start("Waiting for authorization...");let n=Date.now(),r=1e3*e.expires_in;for(;;){if(Date.now()-n>=r)throw new ft("Authorization timed out — the code expired. Please run the command again.");let i=new AbortController,a=Y.timeoutMs,s=setTimeout(()=>{i.abort()},a);try{let n=await fetch(`${ot}/login/oauth/access_token`,{method:"POST",headers:Je(),body:JSON.stringify({client_id:nt,device_code:e.device_code,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}),signal:i.signal});if(!n.ok){await pt(t),o.error("Failed to poll access token:",await n.text());continue}let r=await n.json();if(o.debug("Polling access token response:",r),r.error){if("expired_token"===r.error)throw new ft("Authorization timed out — the code expired. Please run the command again.");if("access_denied"===r.error)throw new ft("Authorization was denied. Please run the command again and approve the request.");"authorization_pending"!==r.error&&"slow_down"!==r.error&&o.warn(`Unexpected auth error: ${r.error}`),await pt(t);continue}if(r.access_token)return r.access_token;await pt(t)}catch(e){if(e instanceof ft)throw e;if(e instanceof Error&&"AbortError"===e.name){o.error("Access token polling timed out"),await pt(t);continue}throw e}finally{clearTimeout(s)}}}(n);await bt(r),Y._t2=r,Y.showToken&&o.info("Auth token:",r),await $t()}catch(e){throw e instanceof it?(o.error("Failed to get Auth token:",await e.response.json()),e):(o.error("Failed to get Auth token:",e),e)}}async function $t(){let e=await ut();o.success(`Authenticated as ${e.login}`)}async function xt(e){e.verbose&&(o.level=5,o.info("Verbose logging enabled")),Y.showToken=e.showToken,await z(),await vt({force:!0}),console.log([""," Get started:",""," $ npx copilot-api-node20@latest start --claude-code"," $ npx copilot-api-node20@latest start --codex",""," Full docs: https://www.npmjs.com/package/copilot-api-node20",""].join("\n")),process.exit(0)}const Tt=e({meta:{name:"auth",description:"Run authentication flow"},args:{verbose:{alias:"v",type:"boolean",default:!1,description:"Enable verbose logging"},"show-token":{type:"boolean",default:!1,description:"Show token on auth"}},run:({args:e})=>xt({verbose:e.verbose,showToken:e["show-token"]})}),At=async()=>{let e=`${et}/copilot_internal/user`,t=Y.timeoutMs,o=new AbortController,n=setTimeout(()=>o.abort(),t);try{let{response:t,span:n}=await Be({spanName:"github GET /copilot_internal/user",url:e,target:"usage",headers:tt(Y),signal:o.signal});if(!t.ok)throw n.end(),new it("Failed to get usage",t);let r=await t.json();return n.end(),r}finally{clearTimeout(n)}},St=e({meta:{name:"check-usage",description:"Show current usage/quota information"},async run(){await z(),await vt();try{let e=await At(),t=e.quota_snapshots.premium_interactions,n=t.entitlement,r=n-t.remaining,i=n>0?r/n*100:0,a=t.percent_remaining;function s(e,t){if(!t)return`${e}: N/A`;let o=t.entitlement,n=o-t.remaining,r=o>0?n/o*100:0,i=t.percent_remaining;return`${e}: ${n}/${o} used (${r.toFixed(1)}% used, ${i.toFixed(1)}% remaining)`}let l=`Premium: ${r}/${n} used (${i.toFixed(1)}% used, ${a.toFixed(1)}% remaining)`,c=s("Chat",e.quota_snapshots.chat),u=s("Completions",e.quota_snapshots.completions);o.box(`Usage (plan: ${e.copilot_plan})\nQuota resets: ${e.quota_reset_date}\n\nQuotas:\n ${l}\n ${c}\n ${u}`)}catch(p){o.error("Failed to fetch usage:",p),process.exit(1)}}}),Ct=P(d);async function Ot(){let e="win32"===f.platform?"where.exe":"which";try{return await Ct(e,["tailscale"]),!0}catch{return!1}}async function Et(){try{let{stdout:e}=await Ct("tailscale",["status","--self","--json"]);return JSON.parse(e).Self}catch{return}}function It(e){return e.replace(/\.$/,"")}async function Pt(){let e=await Et();if(e?.Online)return It(e.DNSName)}const Nt=P(d),qt=e=>`[1m${e}[0m`,Rt=e=>`[2m${e}[0m`,jt=e=>`[36m${e}[0m`,Dt=e=>`[32m${e}[0m`,Mt=e=>`[31m${e}[0m`,Ft=e=>`[33m${e}[0m`,Ht=Rt(" ─────────────────────────────────────────────────────────────"),Bt=i.join(W.APP_DIR,"certs","tailscale"),Lt=i.join(Bt,"cert.pem"),Ut=i.join(Bt,"key.pem"),Jt={certDir:Bt,certPath:Lt,keyPath:Ut};function Gt(){switch(f.platform){case"darwin":return[` ${Rt("Install Tailscale for macOS:")}`,` ${jt("https://tailscale.com/download/mac")}`,` ${Rt("(Use the Mac App Store or .pkg download — not brew)")}`,"",` ${Rt("After installing, open the Tailscale app and sign in.")}`,` ${Rt("Then re-run this command.")}`].join("\n");case"linux":return[` ${Rt("Install Tailscale for Linux:")}`,` ${jt("curl -fsSL https://tailscale.com/install.sh | sh")}`,` ${jt("sudo tailscale up")}`,` ${Rt("or")} ${jt("https://tailscale.com/download/linux")}`].join("\n");case"win32":return[` ${Rt("Install Tailscale for Windows:")}`,` ${jt("https://tailscale.com/download/windows")}`,"",` ${Rt("After installing, open the Tailscale app and sign in.")}`].join("\n");default:return` ${Rt("Install Tailscale:")} ${jt("https://tailscale.com/download")}`}}function Wt(){let e=[` ${Mt("Tailscale is not running.")}`];return"darwin"===f.platform?e.push(` ${Rt("Open the Tailscale app from Applications and sign in.")}`,` ${Rt("Download:")} ${jt("https://tailscale.com/download/mac")}`):"win32"===f.platform?e.push(` ${Rt("Open the Tailscale app and sign in.")}`,` ${Rt("Download:")} ${jt("https://tailscale.com/download/windows")}`):e.push(` ${Rt("Connect with:")} ${jt("sudo tailscale up")}`),e.push("",` ${Rt("Then re-run this command.")}`),e.join("\n")}async function zt(){try{return await n.access(Lt),await n.access(Ut),!0}catch{return!1}}function Kt(e){console.log(""),console.log(Ht),console.log(` ${qt("Claude Cowork Setup")} ${Rt("— Diagnostic")}`),console.log(Ht),console.log("");for(let t of function(e){let t=[];for(let[o,n]of Object.entries(e)){let e;e="ok"===n.status?Dt("✅"):"missing"===n.status?Mt("❌"):Ft("❓");let r=n.detail?Rt(` ${n.detail}`):"";t.push(` ${e} ${o}${r}`)}return t}(e))console.log(t);console.log("");let t=Object.values(e).filter(e=>"missing"===e.status);0===t.length?console.log(` ${Dt("All checks passed.")}`):console.log(` ${Mt(`${t.length} issue(s).`)} Run ${jt("copilot-api cowork-setup install")} to fix.`),console.log("")}const Vt={alias:"y",type:"boolean",default:!1,description:"Skip confirmation prompts (non-interactive mode)"},Yt=e({meta:{name:"cowork-setup",description:"Set up Tailscale-based HTTPS for Claude Cowork to reach the proxy."},subCommands:{doctor:e({meta:{name:"doctor",description:"Diagnose Tailscale + cert status"},async run(){await async function(){let e={},t=await Ot();if(e["tailscale-installed"]=t?{status:"ok"}:{status:"missing",detail:"tailscale not found in PATH"},!t)return Kt(e),console.log(""),console.log(Gt()),void console.log("");let o=await Et();if(!o||!o.Online)return e["tailscale-running"]={status:"missing",detail:"not connected"},Kt(e),console.log(Wt()),void console.log("");let n=It(o.DNSName);e["tailscale-running"]={status:"ok",detail:n};let r=await zt();e["tailscale-cert"]=r?{status:"ok",detail:Lt}:{status:"missing",detail:'Run "copilot-api cowork-setup install" to generate'},r&&(e.ready={status:"ok",detail:`https://${n}:<port>`}),Kt(e)}(),f.exit(0)}}),install:e({meta:{name:"install",description:"Generate a Tailscale TLS certificate for Cowork (interactive, or pass --yes)"},args:{yes:Vt},async run({args:e}){await async function(e){if(console.log(""),console.log(Ht),console.log(` ${qt("Claude Cowork Setup")} ${Rt("— Install")}`),console.log(Ht),console.log(""),!await Ot())return console.log(` ${Mt("Tailscale is not installed.")}`),console.log(""),console.log(Gt()),console.log(""),console.log(` ${Rt("After installing, run")} ${jt("tailscale up")} ${Rt("to connect, then re-run this command.")}`),void console.log("");let t=await Et();if(!t||!t.Online)return console.log(Wt()),void console.log("");let r=It(t.DNSName);if(console.log(` ${Rt("Tailscale hostname:")} ${qt(r)}`),console.log(""),console.log(` ${qt("Generating TLS certificate via Tailscale…")}`),console.log(` ${Rt("This requests a real Let's Encrypt cert for your Tailscale hostname.")}`),console.log(` ${jt(`$ tailscale cert --cert-file ${Lt} --key-file ${Ut} ${r}`)}`),console.log(""),e||await o.prompt("Generate the certificate?",{type:"confirm",initial:!0})){try{await n.mkdir(Bt,{recursive:!0}),o.start("Generating certificate (this may take a few seconds)…"),await Nt("tailscale",["cert","--cert-file",Lt,"--key-file",Ut,r]),console.log(` ${Dt("✓ Certificate generated")}`)}catch(e){let t=e instanceof Error?e.message:String(e);return void o.error(`Failed to generate cert: ${t}`)}console.log(""),console.log(Ht),console.log(` ${qt("Next steps")}`),console.log(Ht),console.log(""),console.log(` ${qt("1.")} Start the proxy:`),console.log(` ${jt("copilot-api start --claude-cowork")}`),console.log(""),console.log(` ${qt("2.")} In Cowork ${Rt("→")} Settings ${Rt("→")} Inference Provider, set:`),console.log(` ${qt("inferenceGatewayBaseUrl")} = ${jt(`https://${r}:<port>`)}`),console.log(` ${Rt("(replace <port> with the port you start the proxy on, default 4141)")}`),console.log(""),console.log(` ${qt("3.")} Restart Cowork ${Rt("(Cmd+Q and reopen)")}`),console.log(""),console.log(` ${Rt("For Cowork's own configuration docs, see:")}`),console.log(` ${jt("https://claude.com/docs/cowork/3p/installation")}`),console.log("")}else o.info("Skipped.")}(e.yes),f.exit(0)}}),revert:e({meta:{name:"revert",description:"Remove the generated Tailscale cert files"},args:{yes:Vt},async run({args:e}){await async function(e){if(console.log(""),console.log(Ht),console.log(` ${qt("Claude Cowork Setup")} ${Rt("— Revert")}`),console.log(Ht),console.log(""),!await zt())return console.log(` ${Rt("No Tailscale cert found. Nothing to revert.")}`),void console.log("");if(console.log(` ${qt("Remove Tailscale cert files:")}`),console.log(` ${Rt(Lt)}`),console.log(` ${Rt(Ut)}`),console.log(""),e||await o.prompt("Delete these files?",{type:"confirm",initial:!0})){try{await n.rm(Bt,{recursive:!0}),console.log(` ${Dt("✓ Cert files removed.")}`)}catch(e){let t=e instanceof Error?e.message:String(e);o.warn(`Could not remove: ${t}`)}console.log(""),console.log(` ${Rt("Don't forget to update Cowork's inferenceGatewayBaseUrl setting.")}`),console.log("")}else o.info("Skipped.")}(e.yes),f.exit(0)}})}});async function Xt(){try{let e=new URL("../package.json",import.meta.url).pathname,t=await n.readFile(e);return JSON.parse(t.toString()).version}catch{return"unknown"}}function Qt(){let e=typeof Bun<"u";return{name:e?"bun":"node",version:e?Bun.version:process.version.slice(1),platform:r.platform(),arch:r.arch()}}async function Zt(){try{return!!(await n.stat(W.GITHUB_TOKEN_PATH)).isFile()&&(await n.readFile(W.GITHUB_TOKEN_PATH,"utf8")).trim().length>0}catch{return!1}}async function eo(e){let t=await async function(){let[e,t]=await Promise.all([Xt(),Zt()]);return{version:e,runtime:Qt(),paths:{APP_DIR:W.APP_DIR,GITHUB_TOKEN_PATH:W.GITHUB_TOKEN_PATH},tokenExists:t}}();e.json?function(e){console.log(JSON.stringify(e,null,2))}(t):function(e){o.info(`service debug\n\nVersion: ${e.version}\nRuntime: ${e.runtime.name} ${e.runtime.version} (${e.runtime.platform} ${e.runtime.arch})\n\nPaths:\n- APP_DIR: ${e.paths.APP_DIR}\n- GITHUB_TOKEN_PATH: ${e.paths.GITHUB_TOKEN_PATH}\n\nToken exists: ${e.tokenExists?"Yes":"No"}`)}(t)}const to=e({meta:{name:"debug",description:"Print debug information about the application"},args:{json:{type:"boolean",default:!1,description:"Output debug information as JSON"}},run:({args:e})=>eo({json:e.json})}),oo="copilot-api-node20",no=`https://registry.npmjs.org/${oo}/latest`,ro=e=>`[1m${e}[0m`,io=e=>`[33m${e}[0m`;async function ao(){let e=new AbortController,t=setTimeout(()=>e.abort(),5e3);"object"==typeof t&&"unref"in t&&t.unref();try{let t=await fetch(no,{signal:e.signal});return t.ok?(await t.json()).version??null:null}catch{return null}finally{clearTimeout(t)}}function so(e,t){let o=Math.max(0,t-function(e){return e.replaceAll(/\x1b\[[0-9;]*m/g,"").length}(e));return e+" ".repeat(o)}const lo=new Map,co=new Map,uo=new Set;let po,mo,fo;function ho(e){return!e.closed&&!e.destroyed}function go(e){o.debug(`Creating HTTP/2 client for ${e}`);let t=new S(e,{allowH2:!0,pipelining:0,keepAliveTimeout:6e4,initialWindowSize:4194304,connectionWindowSize:16777216});return lo.set(t,Date.now()),Te.add(1,{event:"created",origin:e}),De(h.INFO,"INFO",`HTTP/2 client created for ${e}`,{"copilot_api.h2.event":"created","copilot_api.h2.origin":e}),t.on("connect",()=>{o.debug(`HTTP/2 client connected to ${e}`)}),t.on("error",t=>{o.debug(`HTTP/2 client error for ${e}:`,t.message)}),t.on("disconnect",(n,r,i)=>{o.debug(`HTTP/2 client disconnected from ${e}:`,i.message),Te.add(1,{event:"goaway",origin:e}),De(h.WARN,"WARN",`HTTP/2 client disconnected from ${e}: ${i.message}`,{"copilot_api.h2.event":"goaway","copilot_api.h2.origin":e,"copilot_api.h2.error":i.message}),co.delete(t),uo.delete(t),lo.delete(t),ho(t)&&t.close().catch(e=>{o.debug("Error closing GOAWAY'd HTTP/2 client:",e)})}),t}function _o(e){if(!Y.connectivity.h2)return;po&&po!==e&&function(){for(let e of[...co.keys(),...uo])ho(e)&&e.close().catch(e=>{o.debug("Error closing HTTP/2 pool entry:",e)});co.clear(),uo.clear(),lo.clear()}(),po=e;let t=Date.now();for(let[n]of co)if(t-(lo.get(n)??0)>=6e5)co.delete(n),lo.delete(n),ho(n)&&n.close().catch(e=>{o.debug("Error closing rotated HTTP/2 client:",e)}),Te.add(1,{event:"rotated",origin:e}),De(h.INFO,"INFO",`HTTP/2 client rotated for ${e} (max lifetime reached)`,{"copilot_api.h2.event":"rotated","copilot_api.h2.origin":e});else{if(ho(n))return co.delete(n),uo.add(n),n;co.delete(n),lo.delete(n)}let n=go(e);return uo.add(n),n}function yo(e){e&&uo.delete(e)&&(ho(e)?co.set(e,Date.now()):lo.delete(e))}function ko(){fo||(fo=setInterval(()=>{!function(){let e=Date.now(),t=Y.connectivity.h2Keepalive,n=co.size;for(let[r,i]of co)e-i<6e4||t&&n<=1||(co.delete(r),lo.delete(r),n--,ho(r)&&r.close().catch(e=>{o.debug("Error closing idle HTTP/2 client:",e)}),Te.add(1,{event:"idle_reaped",origin:po??""}),De(h.INFO,"INFO",`HTTP/2 idle connection reaped for ${po}`,{"copilot_api.h2.event":"idle_reaped","copilot_api.h2.origin":po??""}))}()},3e4),fo.unref())}function bo(){mo||(o.debug("Starting HTTP/2 keepalive (every 45s)"),mo=setInterval(()=>{(async function(){if(0===co.size&&0===uo.size){if(po){let e=go(po);co.set(e,Date.now())}return}let e=[...co.keys()];await Promise.allSettled(e.map(async e=>{if(!ho(e))return co.delete(e),void lo.delete(e);try{let{statusCode:t,body:n}=await e.request({path:"/models",method:"GET",headers:Xe(Y)});await n.dump(),xe.add(1,{result:"success"}),o.debug(`HTTP/2 keepalive: GET /models → ${t}`),co.set(e,Date.now())}catch(t){xe.add(1,{result:"error"}),o.warn("HTTP/2 keepalive failed:",t instanceof Error?t.message:t),Te.add(1,{event:"error",origin:po??""}),co.delete(e),lo.delete(e),ho(e)&&e.close().catch(e=>{o.debug("Error closing broken HTTP/2 client:",e)})}}))})().catch(e=>{o.debug("Unexpected error in HTTP/2 keepalive:",e)})},45e3),mo.unref(),ko())}function wo(e,t=""){let o,n=function(){let{platform:e,ppid:t,env:o}=f;if("win32"===e){try{if(m(`wmic process get ParentProcessId,Name | findstr "${t}"`,{stdio:"pipe"}).toString().toLowerCase().includes("powershell.exe"))return"powershell"}catch{return"cmd"}return"cmd"}{let e=o.SHELL;if(e){if(e.endsWith("zsh"))return"zsh";if(e.endsWith("fish"))return"fish";if(e.endsWith("bash"))return"bash"}return"sh"}}(),r=Object.entries(e).filter(([,e])=>void 0!==e);switch(n){case"powershell":o=r.map(([e,t])=>`$env:${e} = ${t}`).join("; ");break;case"cmd":o=r.map(([e,t])=>`set ${e}=${t}`).join(" & ");break;case"fish":o=r.map(([e,t])=>`set -gx ${e} ${t}`).join("; ");break;default:{let e=r.map(([e,t])=>`${e}=${t}`).join(" ");o=r.length>0?`export ${e}`:"";break}}return o&&t?`${o}${"cmd"===n?" & ":" && "}${t}`:o||t}const vo=e=>`[1m${e}[0m`,$o=e=>`[2m${e}[0m`,xo=e=>`[36m${e}[0m`,To=e=>`[32m${e}[0m`,Ao=e=>`[33m${e}[0m`,So=e=>`[4m${e}[0m`,Co=(e,t)=>`]8;;${e}\\${t}]8;;\\`,Oo="?utm_source=copilot-cli&utm_medium=terminal&utm_campaign=startup_banner",Eo=$o(" ─────────────────────────────────────────────────────────────");function Io(e){return void 0===e?"":e>=1e6?`${(e/1e6).toFixed(0)}M`:`${(e/1e3).toFixed(0)}K`}const Po=[{title:"The 5-Hour Quota, Boris's Tweet, and What the Source Code Actually Reveals",teaser:"Claude Code's caching story — decoded from the source.",url:"https://barazany.dev/blog/claude-code-token-caching"},{title:"Claude Code's Compaction Engine: What the Source Code Actually Reveals",teaser:"What's actually running beneath every long session.",url:"https://barazany.dev/blog/claude-codes-compaction-engine"},{title:"We Were About to Buy an Automation Platform. We Already Had One.",teaser:"Governance spirals over n8n. The answer was already deployed.",url:"https://barazany.dev/blog/we-already-had-the-automation-platform"}];function No(e){if(0===e.length)return[];let t=["",Eo,` ${vo("BARAZANY.DEV")} ${$o("— Recent Posts")}`,Eo,""];for(let[o,n]of e.entries()){let e=Co(`${n.url}${Oo}`,vo(So(`[${o+1}]`)));t.push(` ${e} ${xo(n.title)}`,` ${$o("→")} ${$o(n.teaser)}`,"")}return t.push(Eo,` ${Co(`https://barazany.dev/blog${Oo}`,"barazany.dev/blog")}`,Eo),t}function qo(e){let t=[];Y.connectivity.h2Keepalive?t.push("HTTP/2 keepalive"):Y.connectivity.h2&&t.push("HTTP/2"),t.push(`timeout ${e.timeout/1e3}s`);let o=e.webSearch?`Tavily ${To("✓")}`:$o("off"),n=["",` ${vo("COPILOT-API")} ${$o(`v${e.version}`)}`,Eo,` ${$o("Runtime")} ${e.runtime.name} ${e.runtime.version} (${e.runtime.platform}-${e.runtime.arch})`,` ${$o("User")} ${e.user} ${$o("·")} ${e.accountType}`];return Y._v1&&n.push(` ${$o("Client")} VSCode ${Y._v1}`),n.push(` ${$o("Network")} ${t.join($o(" · "))}`,` ${$o("Search")} ${o}`),e.clipboardCopied&&n.push(` ${$o("Clipboard")} Claude Code command ${To("✓")}`),n.push(Eo),n}function Ro(e){if(!e.model&&!e.smallModel)return[];let t=["",` ${vo("Active")}`];if(e.model){let o=Y.models?.data.find(t=>t.id===e.model),n=Io(o?.capabilities.limits?.max_context_window_tokens);t.push(` ${xo(e.model.padEnd(32))} ${$o("ctx")} ${vo(n.padStart(5))} ${Ao("← main")}`)}if(e.smallModel){let o=Y.models?.data.find(t=>t.id===e.smallModel),n=Io(o?.capabilities.limits?.max_context_window_tokens);t.push(` ${e.smallModel.padEnd(32)} ${$o("ctx")} ${n.padStart(5)} ${Ao("← small")}`)}return t}function jo(e){let t=[];for(let[o,n]of function(){let e=[],t=[],o=[],n=[];for(let r of Y.models?.data??[]){let i=r.capabilities.limits?.max_context_window_tokens,a={id:r.id,ctx:i};r.id.startsWith("text-embedding")?n.push(a):"Anthropic"===r.vendor?e.push(a):"Google"===r.vendor?o.push(a):t.push(a)}return[["Claude",e],["OpenAI",t],["Gemini",o],["Embedding",n]]}())if(0!==n.length){t.push("",` ${vo(o)}`);for(let o of n){let n=o.id===e.model||o.id===e.smallModel,r=n?xo("●"):$o("·"),i=n?xo(o.id.padEnd(34)):o.id.padEnd(34),a=o.ctx?Io(o.ctx).padStart(5):"";t.push(` ${r} ${i} ${$o(a)}`)}}return t}function Do(e){if(!e.endpoints)return[];let{scheme:t,port:o,hostname:n}=e.endpoints,r=n?`${t}://${n}:${o}`:`${t}://<your-tailscale-hostname>:${o}`,i=["",Eo,` ${vo("Claude Cowork")} ${$o("— Settings → Inference Provider")}`,Eo,"",` ${$o("Paste into")} ${vo("inferenceGatewayBaseUrl")}${$o(":")}`,` ${vo(xo(r))}`];return n||i.push("",` ${$o("Your Tailscale hostname is shown by:")} ${xo("tailscale status --self")}`),i.push("",` ${$o("Docs:")} ${xo("https://claude.com/docs/cowork/3p/installation")}`),i}function Mo(e){if(!e.https||!e.https.selfSigned)return[];let{certPath:t}=e.https,o=["",Eo,` ${vo("HTTPS")} ${$o("— self-signed cert")}`,Eo,"",` ${$o("Cert")} ${t}`];switch(o.push("",` ${vo("Trust this cert")} ${$o("(one-time setup)")}`),f.platform){case"darwin":o.push(` ${$o("macOS:")}`,` ${xo("sudo security add-trusted-cert -d -r trustRoot \\")}`,` ${xo(`-k /Library/Keychains/System.keychain "${t}"`)}`);break;case"win32":o.push(` ${$o("Windows (PowerShell as Administrator):")}`,` ${xo(`Import-Certificate -FilePath "${t}" \``)}`,` ${xo("-CertStoreLocation Cert:\\LocalMachine\\Root")}`);break;case"linux":o.push(` ${$o("Linux (Debian/Ubuntu):")}`,` ${xo(`sudo cp "${t}" /usr/local/share/ca-certificates/copilot-api.crt`)}`,` ${xo("sudo update-ca-certificates")}`,` ${$o("Linux (Fedora/RHEL/Arch):")}`,` ${xo(`sudo cp "${t}" /etc/pki/ca-trust/source/anchors/copilot-api.crt`)}`,` ${xo("sudo update-ca-trust")}`);break;default:o.push(` ${$o("(Unknown platform — see Node fallback below.)")}`)}return o.push("",` ${$o("Or, for Node CLIs only (no admin needed):")}`,` ${xo(`export NODE_EXTRA_CA_CERTS="${t}"`)}`,Eo),o}function Fo(e){let t=Math.floor(e/1e3),o=Math.floor(t/3600),n=Math.floor(t%3600/60);return o>0?`${o}h ${n}m`:n>0?`${n}m`:`${t}s`}const Ho=i.join(W.APP_DIR,"certs"),Bo=i.join(Ho,"cert.pem"),Lo=i.join(Ho,"key.pem"),Uo=i.join(Ho,"cert.meta.json");async function Jo(e){try{return await n.readFile(e,"utf8")}catch{return}}async function Go(e){let t=await Jo(Bo),o=await Jo(Lo),n=await async function(){let e=await Jo(Uo);if(e)try{let t=JSON.parse(e);return Array.isArray(t.hosts)&&"string"==typeof t.notAfter?t:void 0}catch{return}}();if(!t||!o||!n)return!1;let r=new Set(n.hosts);for(let t of e)if(!r.has(t))return!1;let i=Date.parse(n.notAfter);return!Number.isNaN(i)&&i-Date.now()>2592e6}function Wo(e){return 0!==j(e)}async function zo(e){await n.mkdir(Ho,{recursive:!0});let t=new Date,o=new Date;o.setDate(o.getDate()+825);let r=["127.0.0.1","::1"],i=new Set(["localhost"]),a=new Set(r);for(let t of e)Wo(t)?a.add(t):i.add(t);let s=await D([{name:"commonName",value:"localhost"},{name:"organizationName",value:"copilot-api"}],{keyType:"ec",curve:"P-256",algorithm:"sha256",notBeforeDate:t,notAfterDate:o,extensions:[{name:"basicConstraints",cA:!1},{name:"keyUsage",digitalSignature:!0,keyEncipherment:!0,critical:!0},{name:"extKeyUsage",serverAuth:!0,clientAuth:!0},{name:"subjectAltName",altNames:[...[...i].map(e=>({type:2,value:e})),...[...a].map(e=>({type:7,ip:e}))]}]});return await n.writeFile(Bo,s.cert,{mode:420}),await n.writeFile(Lo,s.private,{mode:384}),await async function(e){await n.writeFile(Uo,JSON.stringify(e,null,2),{mode:420})}({hosts:[...i,...a].sort(),notAfter:o.toISOString()}),{cert:s.cert,key:s.private,certPath:Bo,keyPath:Lo,generated:!0}}function Ko(e){(function(e){let{c:t,start:o,span:n}=e,r=t.get("requestData"),i=t.res.status,a=r?.model??"unknown",l=r?.streaming??!1,c=Date.now()-o;if(n.setAttribute("http.status_code",i),n.setAttribute("copilot_api.model",a),n.setAttribute("copilot_api.streaming",l),n.setAttribute("copilot_api.duration_ms",c),r?._d1&&n.setAttribute("copilot_api.copilot_duration_ms",r._d1),r?.tokenUsage){let e=r.tokenUsage;n.setAttribute("copilot_api.input_tokens",e.inputTokens),n.setAttribute("copilot_api.output_tokens",e.outputTokens),n.setAttribute("copilot_api.total_tokens",e.totalTokens),e.cachedTokens&&n.setAttribute("copilot_api.cached_tokens",e.cachedTokens),e.estimatedCost&&n.setAttribute("copilot_api.estimated_cost",e.estimatedCost)}t.res.headers.forEach((e,t)=>{let o=t.toLowerCase();Fe.has(o)||n.setAttribute(`http.response.header.${o}`,e)}),i>=400&&n.setStatus({code:s.ERROR,message:`HTTP ${i}`}),n.end()})(e),function(e){let{c:t,start:o,method:n,path:r,endpointType:i,requestId:a}=e,s=Date.now()-o,l=t.get("requestData"),c=t.res.status,u=l?.model??"unknown",p=l?.streaming??!1,d={method:n,path:r,status_code:String(c),model:u,streaming:String(p),endpoint_type:i};if(ce.add(1,d),Ae.record(s,d),c>=400&&ue.add(1,{method:n,path:r,status_code:String(c),error_type:c>=500?"server_error":"client_error"}),l?.tokenUsage){let e=l.tokenUsage,t={model:u,endpoint_type:i};e.inputTokens&&(pe.add(e.inputTokens,t),Ne.record(e.inputTokens,t)),e.outputTokens&&(de.add(e.outputTokens,t),qe.record(e.outputTokens,t)),e.cachedTokens&&me.add(e.cachedTokens,{model:u})}!p&&l?.tokenUsage&&ee.executeCompletion(a)}(e)}const Vo=async()=>ae.startActiveSpan("copilot_api.approval.await",async e=>{let t=performance.now();try{let n=await o.prompt("Accept incoming request?",{type:"confirm"}),r=performance.now()-t;if(e.setAttribute("copilot_api.approval.wait_duration_ms",r),je.record(r),!n)throw e.setAttribute("copilot_api.approval.result","rejected"),$e.add(1,{result:"rejected"}),new it("Request rejected",Response.json({message:"Request rejected"},{status:403}));e.setAttribute("copilot_api.approval.result","approved"),$e.add(1,{result:"approved"})}finally{e.end()}}),Yo=3e-6,Xo=15e-6;function Qo(e){let t=e.prompt_tokens||0,o=e.completion_tokens||0;return{inputTokens:t,outputTokens:o,totalTokens:e.total_tokens||t+o,estimatedCost:t*Yo+o*Xo,cachedTokens:e.prompt_tokens_details?.cached_tokens,acceptedPredictionTokens:e.completion_tokens_details?.accepted_prediction_tokens,rejectedPredictionTokens:e.completion_tokens_details?.rejected_prediction_tokens}}function Zo(e,t){void 0!==t.prompt_tokens&&e.setAttribute("copilot_api.input_tokens",t.prompt_tokens),void 0!==t.completion_tokens&&e.setAttribute("copilot_api.output_tokens",t.completion_tokens),void 0!==t.total_tokens&&e.setAttribute("copilot_api.total_tokens",t.total_tokens)}const en=[{pattern:/haiku/i,family:"haiku"},{pattern:/sonnet[.-]?4[.-]6/i,family:"sonnet-4.6"},{pattern:/(sonnet-4[.-]5|[.-]?3[.-]5[.-]?sonnet|[.-]?3[.-]7[.-]?sonnet)/i,family:"sonnet-4.5"},{pattern:/sonnet-4(?![.-]5|[.-]6|[.-]1)/i,family:"sonnet-4"},{pattern:/opus[.-]?4[.-]7/i,family:"opus-4.7"},{pattern:/opus[.-]?4[.-]6/i,family:"opus-4.6"},{pattern:/opus[.-]?4[.-]5/i,family:"opus-4.5"},{pattern:/opus/i,family:"opus"}],tn={haiku:"claude-haiku-4.5","sonnet-4.6":"claude-sonnet-4.6","sonnet-4.5":"claude-sonnet-4.5","sonnet-4":"claude-sonnet-4","opus-4.7":"claude-opus-4.7","opus-4.6":"claude-opus-4.6","opus-4.5":"claude-opus-4.5",opus:"claude-opus-4.5"};function on(e,t){let o=function(e){return e.startsWith("anthropic/")?e.slice(10):e}(e),[n,r]=function(e){let t=e.lastIndexOf("["),o=e.lastIndexOf("]");return-1!==t&&o===e.length-1&&o>t?[e.slice(0,t),e.slice(t+1,o)]:[e,null]}(o);if(t.includes(o))return o;if(r){let e=`${n}-${r}`.replaceAll(/(\d)-(\d)\b/g,"$1.$2");if(t.includes(e))return e}let i=function(e){for(let t of en)if(t.pattern.test(e))return t.family;return null}(n);if(!i)return null;let a=n.replace(/-\d{8}(?::.*)?$/,""),s=r?`-${r}`:"";for(let e of t){let t=e.replace(/-\d{8}(?::.*)?$/,""),o=`${a}${s}`.toLowerCase().replaceAll(/(\d)-(\d)\b/g,"$1.$2");if(t.toLowerCase().replaceAll(/(\d)-(\d)\b/g,"$1.$2")===o)return e}return function(e,t,o=null){let n=tn[e];if(!n)return null;if(o){let e=`${n}-${o}`;if(t.includes(e))return e}if(t.includes(n))return n;if("sonnet-4.5"===e)for(let e of["claude-3.5-sonnet"]){let n=o?`${e}-${o}`:e;if(t.includes(n))return n}return null}(i,t,r)}var nn=class extends Error{statusCode;constructor(e,t=400){super(e),this.name="ModelValidationError",this.statusCode=t}};function rn(e){if(!e||"string"!=typeof e)throw new nn("Model name is required and must be a string");if(!Y.models?.data)throw new nn("Models not available. Please try again later.",503);let t=Y.models.data.map(e=>e.id);if(t.includes(e))return e;let o=on(e,t);if(!o)throw he.add(1,{requested_model:e}),new nn(`Invalid model: '${e}'. Available services: ${t.join(", ")}`);return o}async function an(e){if(void 0===e.rateLimitSeconds)return;let t=e.rateLimitSeconds;return ae.startActiveSpan("copilot_api.rate_limit.check",async n=>{try{let r=Date.now();if(n.setAttribute("copilot_api.rate_limit.configured_seconds",t),!e.lastRequestTimestamp)return e.lastRequestTimestamp=r,void n.setAttribute("copilot_api.rate_limit.action","allowed");let i=(r-e.lastRequestTimestamp)/1e3;if(n.setAttribute("copilot_api.rate_limit.elapsed_seconds",i),i>t)return e.lastRequestTimestamp=r,void n.setAttribute("copilot_api.rate_limit.action","allowed");let a=Math.ceil(t-i);if(n.setAttribute("copilot_api.rate_limit.wait_seconds",a),!e.rateLimitWait)throw n.setAttribute("copilot_api.rate_limit.action","rejected"),fe.add(1,{action:"rejected",source:"local"}),o.warn(`Rate limit exceeded. Need to wait ${a} more seconds.`),new it("Rate limit exceeded",Response.json({message:"Rate limit exceeded"},{status:429}));let s=1e3*a;n.setAttribute("copilot_api.rate_limit.action","waited"),fe.add(1,{action:"waited",source:"local"}),Oe.record(s,{source:"local"}),o.warn(`Rate limit reached. Waiting ${a} seconds before proceeding...`),await pt(s),e.lastRequestTimestamp=r,o.info("Rate limit wait completed, proceeding with request")}finally{n.end()}})}function sn(e){if("number"==typeof e){if(!Number.isFinite(e))return null;let t=Math.floor(e);return t>0?t:null}if("string"==typeof e){let t=e.trim();if(!t)return null;let o=Number(t);if(!Number.isFinite(o))return null;let n=Math.floor(o);return n>0?n:null}return null}function ln(e,t,o){return Math.min(Math.max(e,t),o)}function cn(e,t=0){if(t>5||!e||"object"!=typeof e)return null;let o=e.error;if(!o||"object"!=typeof o)return null;let n=o.code;if("string"==typeof n)return n;let r=o.message;if("string"!=typeof r)return null;try{return cn(JSON.parse(r),t+1)}catch{return null}}function un(e,t){let o=e?.data.find(e=>e.id===t);if(!o)return null;let n=sn(o.capabilities.supports.min_thinking_budget),r=sn(o.capabilities.supports.max_thinking_budget);return!n||!r||r<=n?null:{bounds:{min:n,max:r-1},maxOutputTokens:sn(o.capabilities.limits?.max_output_tokens)??void 0}}function pn(e){let{config:t}=e,o=t.bounds.min,n=t.bounds.max,r=ln(sn(e.requestedBudget)??o,o,n),i=sn(e.maxTokens);if(i||=r+1,t.maxOutputTokens&&i>t.maxOutputTokens&&(i=t.maxOutputTokens),i<=r){let e=Math.min(r,i-1);if(e>=o)r=e;else{let e=o+1;if(t.maxOutputTokens&&e>t.maxOutputTokens)return{thinkingBudget:null,maxTokens:i};i=e,r=o}}return i<=r?{thinkingBudget:null,maxTokens:i}:{thinkingBudget:r,maxTokens:i}}function dn(e,t,o){if(dt(e.thinking_budget))return e;if(!1===o?.enabled)return{...e,thinking_budget:void 0};let n=un(t,e.model);if(!n)return{...e,thinking_budget:void 0};let r=pn({requestedBudget:e.thinking_budget,maxTokens:e.max_tokens,config:n});return null===r.thinkingBudget?{...e,max_tokens:r.maxTokens,thinking_budget:void 0}:{...e,max_tokens:r.maxTokens,thinking_budget:r.thinkingBudget}}function mn(e){return"invalid_thinking_budget"===cn(e)}async function fn(e){let{payload:t,error:o,models:n,errorBodyText:r}=e;if(dt(t.thinking_budget)||!(o instanceof Error))return null;let i,a,s=o;if(!(s.response instanceof Response)||400!==s.response.status)return null;if(void 0!==r)i=r;else try{i=await s.response.clone().text()}catch{return null}try{a=JSON.parse(i)}catch{return null}if(!mn(a))return null;let l=un(n,t.model);return l?function(e,t){let o=pn({requestedBudget:e.thinking_budget,maxTokens:e.max_tokens,config:t});if(null===o.thinkingBudget)return{...e,max_tokens:o.maxTokens,thinking_budget:void 0};let n=o.thinkingBudget,r=sn(e.thinking_budget);if(r&&r===o.thinkingBudget){let e=n+1;e<=t.bounds.max&&(!o.maxTokens||e<o.maxTokens)&&(n=e)}let i=o.maxTokens;if((!i||i<=n)&&(i=n+1),t.maxOutputTokens&&i>t.maxOutputTokens){if(!(t.maxOutputTokens>n))return{...e,max_tokens:t.maxOutputTokens,thinking_budget:void 0};i=t.maxOutputTokens}return{...e,max_tokens:i,thinking_budget:n}}(t,l):{...t,thinking_budget:void 0}}function hn(e){if(!(e instanceof Error))return!1;let t=e.code;return(!t||"UND_ERR_SOCKET"===t)&&/GOAWAY/i.test(e.message)}async function gn(){return new Promise(e=>setTimeout(e,100))}function _n(e){if("string"==typeof e)return function(e){let t=e,o=String.fromCodePoint(27),n=t.split(o);if(n.length>1){t=n[0];for(let e=1;e<n.length;e++){let r=n[e],i=r.match(/^\[[0-9;]*[a-z]/i);t+=i?r.slice(i[0].length):o+r}}return t.replaceAll(/[\u200B-\u200D\uFEFF]/g,"").replaceAll(/[\u2060-\u2064]/g,"").replaceAll(/[\u206A-\u206F]/g,"").replaceAll(/[\u180E\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/g,"").replaceAll(/[\uFFF0-\uFFFF]/g,"").replaceAll(/[\x00-\x08\v\f\x0E-\x1F]/g,"")}(e);if(Array.isArray(e))return e.map(e=>_n(e));if(e&&"object"==typeof e){let t={};for(let[o,n]of Object.entries(e))t[o]=_n(n);return"object"===t.type&&!("properties"in t)&&(t.properties={}),t}return e}const yn=async e=>{let t=_n(e);try{return await kn(t)}catch(e){let n;if(e instanceof it)try{n=await e.response.clone().text()}catch{n=void 0}let r=await fn({payload:t,error:e,models:Y.models,errorBodyText:n});if(r)return e instanceof it&&void 0!==n&&o.warn(`Upstream rejected thinking_budget (status ${e.response.status}): ${n.slice(0,500)}`),o.warn("Adjusting thinking_budget payload and retrying once..."),await kn(_n(r));throw e}},kn=async e=>{if(!Y._t1)throw Error("Service token not found");let t=e.messages.some(e=>"string"!=typeof e.content&&e.content?.some(e=>"image_url"===e.type)),n=e.messages.some(e=>["assistant","tool"].includes(e.role)),r={...Xe(Y,t),"X-Initiator":n?"agent":"user"},i=Ye(Y),a=`${i}/chat/completions`,s=Y.timeoutMs,l=JSON.stringify(e),c={"copilot_api.model":e.model,"copilot_api.streaming":!!e.stream,"copilot_api.timeout_ms":s,"copilot_api.has_tools":!!e.tools?.length,"copilot_api.tool_count":e.tools?.length??0,"copilot_api.message_count":e.messages.length,"copilot_api.max_tokens":e.max_tokens??0,"copilot_api.vision_enabled":t,"copilot_api.initiator":n?"agent":"user"};for(let t=0;t<=1;t++){let n=_o(i),u=new AbortController,p=setTimeout(()=>u.abort(),s);try{let{statusCode:o,headers:i,body:p,span:d}=await Le({spanName:"copilot POST /chat/completions",url:a,target:"chat_completions",headers:r,body:l,signal:u.signal,headersTimeout:s,bodyTimeout:3*s,extraAttributes:{...c,"copilot_api.h2.retry_attempt":t},dispatcher:n}),m=new Response(p,{status:o,headers:i});if(!m.ok)throw d.end(),new it("Failed to create chat completions",m);if(e.stream)return{events:B(m),span:d,release:()=>yo(n)};let f=await m.json();return f.id&&d.setAttribute("copilot_api.response.id",f.id),f.usage&&Zo(d,f.usage),d.end(),yo(n),f}catch(e){if(yo(n),hn(e)&&t<1){o.warn(`HTTP/2 GOAWAY during chat completions, retrying (attempt ${t+1})`),await gn();continue}throw e}finally{clearTimeout(p)}}throw Error("Unexpected: exhausted GOAWAY retries without result")};function bn(e,t){if(!e.data)return e;try{let o=JSON.parse(e.data);if(o.usage&&t(o.usage),void 0!==o.usage?.prompt_tokens_details?.cached_tokens)return{...e,data:JSON.stringify({...o,usage:{...o.usage,prompt_tokens_details:void 0}})}}catch(t){o.warn("Failed to parse streaming chunk:",e.data.slice(0,200),t)}return e}async function wn(e){await an(Y);let t=await e.req.json();o.debug("Request payload:",JSON.stringify(t).slice(-400));try{t=function(e){return ae.startActiveSpan("copilot_api.model.validate",t=>{try{t.setAttribute("copilot_api.model.requested",e.model);let n=rn(e.model);return t.setAttribute("copilot_api.model.normalized",n),n===e.model?(t.setAttribute("copilot_api.model.was_mapped",!1),e):(t.setAttribute("copilot_api.model.was_mapped",!0),ge.add(1,{from_model:e.model,to_model:n}),o.debug(`Normalized model from '${e.model}' to '${n}'`),{...e,model:n})}finally{t.end()}})}(t)}catch(t){if(t instanceof nn)return e.json({error:{message:t.message,type:"invalid_request_error",code:"invalid_model"}},t.statusCode);throw t}if(e.set("requestData",{model:t.model,streaming:!!t.stream}),Y.manualApprove&&await Vo(),dt(t.max_tokens)){let e=Y.models?.data.find(e=>e.id===t.model);t={...t,max_tokens:e?.capabilities.limits?.max_output_tokens},o.debug("Set max_tokens to:",JSON.stringify(t.max_tokens))}t=dn(t,Y.models,{enabled:Y.thinkingEnabled}),dt(t.thinking_budget)||o.debug("Normalized thinking_budget to:",JSON.stringify(t.thinking_budget));let n=performance.now(),r=await yn(t),i=performance.now()-n;if(Se.record(i,{model:t.model,target:"chat_completions",streaming:String(!!t.stream)}),vn(r)){let t=e.get("requestData")||{};return r.usage&&(t.tokenUsage=Qo(r.usage)),t._d1=i,e.set("requestData",t),o.debug("Non-streaming response:",JSON.stringify(r)),e.json(r)}let{events:a,span:s,release:l}=r;return H(e,async o=>{let n={value:null},r=0,c=performance.now();try{try{for await(let s of a){let a=s;s.data&&"[DONE]"!==s.data&&(r++,ve.add(1,{model:t.model,endpoint_type:"openai"}),a=bn(s,t=>{n.value=t;let o=e.get("requestData")||{};o.tokenUsage=Qo(t),o._d1=i,e.set("requestData",o)})),await o.writeSSE(a)}let s=performance.now()-c,l={model:t.model,endpoint_type:"openai"};if(Ce.record(s,l),Re.record(r,l),n.value){let t=e.get("requestData")||{};t.tokenUsage||(t.tokenUsage=Qo(n.value),t._d1=i,e.set("requestData",t))}}finally{n.value&&Zo(s,n.value),s.end(),l()}let u=e.get("requestId");u&&ee.executeCompletion(u)}finally{e.get("resolveStreamComplete")?.()}})}const vn=e=>Object.hasOwn(e,"choices"),$n=new M;$n.post("/",async e=>{try{return await wn(e)}catch(t){return await lt(e,t)}});const xn=new M;xn.post("/",async e=>{try{let t=await e.req.json();try{rn(t.model)}catch(t){if(t instanceof nn)return e.json({error:{message:t.message,type:"invalid_request_error",code:"invalid_model"}},t.statusCode);throw t}e.set("requestData",{model:t.model});let o=performance.now(),n=await(async e=>{if(!Y._t1)throw Error("Service token not found");let t=`${Ye(Y)}/embeddings`,o=Xe(Y),n=Y.timeoutMs,r=new AbortController,i=setTimeout(()=>r.abort(),n);try{let{response:n,span:i}=await Be({spanName:"copilot POST /embeddings",url:t,target:"embeddings",method:"POST",headers:o,body:JSON.stringify(e),signal:r.signal,extraAttributes:{"copilot_api.model":e.model,"copilot_api.input_count":Array.isArray(e.input)?e.input.length:1}});if(!n.ok)throw i.end(),new it("Failed to create embeddings",n);let a=await n.json();return i.end(),a}finally{clearTimeout(i)}})(t),r=performance.now()-o;Se.record(r,{model:t.model,target:"embeddings",streaming:"false"});let i=e.get("requestData")||{};return i.tokenUsage=Qo(n.usage),i._d1=r,e.set("requestData",i),e.json(n)}catch(t){return await lt(e,t)}});const Tn=new L(J),An={...U["anthropic/claude-sonnet-4"].tokens,baseOverhead:4,perTool:27};function Sn(e){return Tn.encode(e).length}function Cn(e){let t=0;for(let o of e)switch(o.type){case"text":t+=Sn(o.text)*An.contentMultiplier;break;case"tool_use":t+=Sn(o.name+JSON.stringify(o.input))*An.contentMultiplier;break;case"tool_result":o.content&&(t+=Sn("string"==typeof o.content?o.content:JSON.stringify(o.content))*An.contentMultiplier);break;case"thinking":t+=Sn(o.thinking)*An.contentMultiplier;break;case"image":t+=1600}return t}function On(e){let t=0,o=e.properties;if(!o)return t;let n=Object.entries(o);for(let[e,[o,r]]of n.entries()){if(t+=0===e?An.perFirstProp:An.perAdditionalProp,t+=Sn(o),r.description&&(t+=An.perPropDesc+Sn(r.description)),r.enum&&Array.isArray(r.enum)){t+=An.perEnum;for(let e of r.enum)t+=Sn(String(e))}if("object"===r.type&&r.properties&&(t+=An.perNestedObject,t+=On(r)),"array"===r.type&&r.items){let e=r.items;"object"===e.type&&e.properties&&(t+=An.perArrayOfObjects,t+=On(e))}}return t}const En=async(e,t)=>{if(!Y._t1)throw Error("Service token not found");let{metadata:n,...r}=_n(e),i={...Ze(Y,t),"X-Initiator":"agent"},a=Ye(Y),s=`${a}/v1/messages`,l=Y.timeoutMs,c=JSON.stringify(r),u={"copilot_api.model":r.model,"copilot_api.streaming":!!r.stream,"copilot_api.timeout_ms":l,"copilot_api.has_tools":!!r.tools?.length,"copilot_api.tool_count":r.tools?.length||0,"copilot_api.max_tokens":r.max_tokens||0,"copilot_api.api_type":"anthropic_passthrough"};for(let e=0;e<=1;e++){let t=_o(a),p=new AbortController,d=setTimeout(()=>p.abort(),l);try{let{statusCode:o,headers:n,body:a,span:d}=await Le({spanName:"copilot POST /v1/messages",url:s,target:"anthropic_messages",headers:i,body:c,signal:p.signal,headersTimeout:l,bodyTimeout:3*l,extraAttributes:{...u,"copilot_api.h2.retry_attempt":e},dispatcher:t}),m=new Response(a,{status:o,headers:n});if(!m.ok)throw d.end(),new it("Failed to create anthropic messages",m);if(r.stream)return{events:B(m),span:d,release:()=>yo(t)};let f=await m.json();"string"==typeof f.id&&d.setAttribute("copilot_api.response.id",f.id);let h=f.usage;return h&&Zo(d,{prompt_tokens:h.input_tokens??0,completion_tokens:h.output_tokens??0,total_tokens:(h.input_tokens??0)+(h.output_tokens??0)}),d.end(),yo(t),f}catch(n){if(yo(t),hn(n)&&e<1){o.warn(`HTTP/2 GOAWAY during anthropic messages, retrying (attempt ${e+1})`),await gn();continue}throw n}finally{clearTimeout(d)}}throw Error("Unexpected: exhausted GOAWAY retries without result")},In=async e=>{if(!Y._t1)throw Error("Service token not found");let t=_n(e),n={...Xe(Y),"X-Initiator":"agent"},r=Ye(Y),i=`${r}/responses`,a=Y.timeoutMs,s=JSON.stringify(t),l={"copilot_api.model":t.model,"copilot_api.streaming":!!t.stream,"copilot_api.timeout_ms":a,"copilot_api.has_tools":!!t.tools?.length,"copilot_api.tool_count":t.tools?.length??0,"copilot_api.max_output_tokens":t.max_output_tokens??0,"copilot_api.api_type":"responses"};for(let e=0;e<=1;e++){let c=_o(r),u=new AbortController,p=setTimeout(()=>u.abort(),a);try{let{statusCode:o,headers:r,body:p,span:d}=await Le({spanName:"copilot POST /responses",url:i,target:"responses",headers:n,body:s,signal:u.signal,headersTimeout:a,bodyTimeout:3*a,extraAttributes:{...l,"copilot_api.h2.retry_attempt":e},dispatcher:c}),m=new Response(p,{status:o,headers:r});if(!m.ok)throw d.end(),new it("Failed to create responses",m);if(t.stream)return{events:B(m),span:d,release:()=>yo(c)};let f=await m.json();return f.id&&d.setAttribute("copilot_api.response.id",f.id),f.usage&&Zo(d,{prompt_tokens:f.usage.input_tokens,completion_tokens:f.usage.output_tokens,total_tokens:f.usage.total_tokens}),d.end(),yo(c),f}catch(t){if(yo(c),hn(t)&&e<1){o.warn(`HTTP/2 GOAWAY during responses, retrying (attempt ${e+1})`),await gn();continue}throw t}finally{clearTimeout(p)}}throw Error("Unexpected: exhausted GOAWAY retries without result")};function Pn(e){return null===e?null:{stop:"end_turn",length:"max_tokens",tool_calls:"tool_use",content_filter:"end_turn"}[e]}function Nn(e,t){let o={model:e.model,messages:qn(e.messages,e.system),max_tokens:e.max_tokens,stop:e.stop_sequences,stream:e.stream,temperature:e.temperature,top_p:e.top_p,user:e.metadata?.user_id,tools:Fn(e.tools),tool_choice:Hn(e.tool_choice)},n=e.thinking;if("enabled"===n?.type||"adaptive"===n?.type){let r=un(t,o.model);if(r){let i="enabled"===n.type&&"number"==typeof n.budget_tokens?n.budget_tokens:function(e,t,o){let n=function(e,t){return"max"===e?t:"high"===e?16e3:"medium"===e?8e3:1024}(e,o.max),r=sn(t),i=r&&r>1?r-1:o.min;return ln(Math.min(n,i),o.min,o.max)}(e.output_config?.effort??"high",o.max_tokens,r.bounds);o=dn({...o,thinking_budget:i},t)}}return o}function qn(e,t){let o=function(e){return e?"string"==typeof e?[{role:"system",content:Rn(e)}]:[{role:"system",content:Rn(e.map(e=>e.text).join("\n\n"))}]:[]}(t),n=e.flatMap(e=>"user"===e.role?function(e){let t=[];if(Array.isArray(e.content)){let o=e.content.filter(e=>"tool_result"===e.type),n=e.content.filter(e=>"tool_result"!==e.type);for(let e of o)t.push({role:"tool",tool_call_id:e.tool_use_id,content:Mn(e.content)});n.length>0&&t.push({role:"user",content:Mn(n)})}else t.push({role:"user",content:Mn(e.content)});return t}(e):function(e){let t=function(e){return{reasoning_text:Dn(e.reasoning_text),reasoning_opaque:Dn(e.reasoning_opaque)}}(e);if(!Array.isArray(e.content))return[{role:"assistant",content:Mn(e.content),...t}];let o=e.content.filter(e=>"tool_use"===e.type),n=e.content.filter(e=>"text"===e.type),r=e.content.filter(e=>"thinking"===e.type),i=[...n.map(e=>e.text),...r.map(e=>e.thinking)].join("\n\n");return o.length>0?[{role:"assistant",content:i||null,...t,tool_calls:o.map(e=>({id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.input)}}))}]:[{role:"assistant",content:Mn(e.content),...t}]}(e));return[...o,...n]}function Rn(e){return e.startsWith("x-anthropic-billing-header")?e.replace(/^x-_an1-billing-header:[^\n]*\n+/,""):e}const jn=32768;function Dn(e){if("string"==typeof e)return e.length<=jn?e:e.slice(0,jn)}function Mn(e){if("string"==typeof e)return e;if(!Array.isArray(e))return null;if(!e.some(e=>"image"===e.type))return e.filter(e=>"text"===e.type||"thinking"===e.type).map(e=>"text"===e.type?e.text:e.thinking).join("\n\n");let t=[];for(let o of e)switch(o.type){case"text":t.push({type:"text",text:o.text});break;case"thinking":t.push({type:"text",text:o.thinking});break;case"image":t.push({type:"image_url",image_url:{url:`data:${o.source.media_type};base64,${o.source.data}`}})}return t}function Fn(e){if(e)return e.map(e=>({type:"function",function:{name:e.name,description:e.description,parameters:e.input_schema}}))}function Hn(e){if(e)switch(e.type){case"auto":return"auto";case"any":return"required";case"tool":return e.name?{type:"function",function:{name:e.name}}:void 0;case"none":return"none";default:return}}function Bn(e){return"string"==typeof e?[{type:"text",text:e}]:Array.isArray(e)?e.filter(e=>"text"===e.type).map(e=>({type:"text",text:e.text})):[]}function Ln(e){return e.reasoning_text?[{type:"thinking",thinking:e.reasoning_text}]:[]}function Un(e){return e?e.map(e=>({type:"tool_use",id:e.id,name:e.function.name,input:JSON.parse(e.function.arguments)})):[]}function Jn(e){let t={model:e.model,input:Wn(e.messages),max_output_tokens:Math.max(e.max_tokens,16),stream:e.stream,temperature:e.temperature,top_p:e.top_p,store:!1,user:e.metadata?.user_id?.slice(0,64)},o=function(e){return e?function(e){return e.startsWith("x-anthropic-billing-header")?e.replace(/^x-_an1-billing-header:[^\n]*\n+/,""):e}("string"==typeof e?e:e.map(e=>e.text).join("\n\n")):null}(e.system);return o&&(t.instructions=o),e.tools?.length&&(t.tools=e.tools.map(e=>({type:"function",name:e.name,description:e.description,parameters:e.input_schema}))),e.tool_choice&&(t.tool_choice=function(e){switch(e.type){case"auto":return"auto";case"any":return"required";case"none":return"none";case"tool":return e.name?{type:"function",name:e.name}:void 0;default:return}}(e.tool_choice)),"adaptive"===e.thinking?.type?t.reasoning={effort:Gn(e.output_config?.effort??"high")}:"enabled"===e.thinking?.type&&e.thinking.budget_tokens&&(t.reasoning=function(e){return e<5e3?{effort:"low"}:e<2e4?{effort:"medium"}:e<32e3?{effort:"high"}:{effort:"xhigh"}}(e.thinking.budget_tokens)),t}function Gn(e){switch(e){case"low":return"low";case"medium":return"medium";case"max":return"xhigh";default:return"high"}}function Wn(e){let t=[];for(let o of e)"user"===o.role?t.push(...zn(o)):t.push(...Vn(o));return t}function zn(e){if("string"==typeof e.content)return[{type:"message",role:"user",content:e.content}];let t=[],o=e.content.filter(e=>"tool_result"===e.type),n=e.content.filter(e=>"tool_result"!==e.type);for(let e of o)t.push(Kn(e));if(n.length>0)if(n.some(e=>"image"===e.type)){let e=[];for(let t of n)"text"===t.type?e.push({type:"input_text",text:t.text}):e.push({type:"input_image",image_url:`data:${t.source.media_type};base64,${t.source.data}`});t.push({type:"message",role:"user",content:e})}else{let e=n.filter(e=>"text"===e.type).map(e=>e.text).join("\n\n");e&&t.push({type:"message",role:"user",content:e})}return t}function Kn(e){let t;return t="string"==typeof e.content?e.content:Array.isArray(e.content)?e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"):"",e.is_error&&(t=`[ERROR] ${t}`),{type:"function_call_output",call_id:e.tool_use_id,output:t}}function Vn(e){if("string"==typeof e.content)return[{type:"message",role:"assistant",content:e.content}];let t=[],o=e.content.filter(e=>"text"===e.type),n=e.content.filter(e=>"thinking"===e.type),r=e.content.filter(e=>"tool_use"===e.type),i=[...o.map(e=>e.text),...n.map(e=>e.thinking)].join("\n\n");i&&t.push({type:"message",role:"assistant",content:i});for(let e of r)t.push({type:"function_call",call_id:e.id,name:e.name,arguments:JSON.stringify(e.input)});return t}function Yn(e,t){if(t)return"tool_use";switch(e){case"completed":case"cancelled":case"failed":return"end_turn";case"incomplete":return"max_tokens";default:return null}}function Xn(e,t){e.contentBlockOpen&&=(t.push({type:"content_block_stop",index:e.contentBlockIndex}),e.contentBlockIndex++,!1)}function Qn(e,t,o){e.messageStartSent||=(e.responseId=o?.responseId??e.responseId,e.model=o?.model??e.model,t.push({type:"message_start",message:{id:e.responseId,type:"message",role:"assistant",content:[],model:e.model,stop_reason:null,stop_sequence:null,usage:{input_tokens:0,output_tokens:0}}}),!0)}function Zn(e,t){let o=[];switch(e.type){case"response.created":Qn(t,o,{responseId:e.response.id,model:e.response.model});break;case"response.in_progress":case"response.output_text.done":case"response.function_call_arguments.done":case"response.refusal.done":case"response.reasoning_summary_text.delta":case"response.reasoning_summary_text.done":default:break;case"response.output_item.added":if("function_call"===e.item.type){Qn(t,o),Xn(t,o);let n=e.item;t.toolCalls[e.output_index]={call_id:n.call_id,name:n.name,_bi1:t.contentBlockIndex},o.push({type:"content_block_start",index:t.contentBlockIndex,content_block:{type:"tool_use",id:n.call_id,name:n.name,input:{}}}),t.contentBlockOpen=!0}break;case"response.content_part.added":Qn(t,o),Xn(t,o),o.push({type:"content_block_start",index:t.contentBlockIndex,content_block:{type:"text",text:""}}),t.contentBlockOpen=!0;break;case"response.output_text.delta":o.push({type:"content_block_delta",index:t.contentBlockIndex,delta:{type:"text_delta",text:e.delta}});break;case"response.content_part.done":Xn(t,o);break;case"response.function_call_arguments.delta":{let n=t.toolCalls[e.output_index];n&&o.push({type:"content_block_delta",index:n._bi1,delta:{type:"input_json_delta",partial_json:e.delta}});break}case"response.output_item.done":if("function_call"===e.item.type){let n=t.toolCalls[e.output_index];n&&t.contentBlockOpen&&(o.push({type:"content_block_stop",index:n._bi1}),t.contentBlockIndex++,t.contentBlockOpen=!1)}break;case"response.completed":{Xn(t,o);let n=e.response.output.some(e=>"function_call"===e.type),r=e.response.usage;o.push({type:"message_delta",delta:{stop_reason:Yn(e.response.status,n),stop_sequence:null},usage:{input_tokens:r?.input_tokens??0,output_tokens:r?.output_tokens??0}},{type:"message_stop"});break}case"response.incomplete":{Qn(t,o),Xn(t,o);let n=e.response.usage;o.push({type:"message_delta",delta:{stop_reason:"max_tokens",stop_sequence:null},usage:{input_tokens:n?.input_tokens??0,output_tokens:n?.output_tokens??0}},{type:"message_stop"});break}case"response.failed":Qn(t,o),Xn(t,o),o.push({type:"error",error:{type:e.response.error?.code??"api_error",message:e.response.error?.message??"Response generation failed"}});break;case"response.cancelled":Qn(t,o),Xn(t,o),o.push({type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{input_tokens:0,output_tokens:0}},{type:"message_stop"});break;case"response.refusal.delta":Qn(t,o),t.contentBlockOpen||=(o.push({type:"content_block_start",index:t.contentBlockIndex,content_block:{type:"text",text:""}}),!0),o.push({type:"content_block_delta",index:t.contentBlockIndex,delta:{type:"text_delta",text:e.delta}})}return o}function er(e,t){e.thinkingBlockOpen||(e.contentBlockOpen&&=(t.push({type:"content_block_stop",index:e.contentBlockIndex}),e.contentBlockIndex++,!1),t.push({type:"content_block_start",index:e.contentBlockIndex,content_block:{type:"thinking",thinking:""}}),e.thinkingBlockOpen=!0,e.contentBlockOpen=!0)}function tr(e,t){e.thinkingBlockOpen&&(t.push({type:"content_block_stop",index:e.contentBlockIndex}),e.contentBlockIndex++,e.thinkingBlockOpen=!1,e.contentBlockOpen=!1)}function or(e,t){let o=[];if(0===e.choices.length)return o;let n=e.choices[0],{delta:r}=n;if(t.messageStartSent||=(o.push({type:"message_start",message:{id:e.id,type:"message",role:"assistant",content:[],model:e.model,stop_reason:null,stop_sequence:null,usage:{input_tokens:e.usage?.prompt_tokens??0,output_tokens:0}}}),!0),"string"==typeof r.reasoning_text&&""!==r.reasoning_text&&(er(t,o),o.push({type:"content_block_delta",index:t.contentBlockIndex,delta:{type:"thinking_delta",thinking:r.reasoning_text}})),"string"==typeof r.reasoning_opaque&&""!==r.reasoning_opaque&&(er(t,o),o.push({type:"content_block_delta",index:t.contentBlockIndex,delta:{type:"signature_delta",signature:r.reasoning_opaque}}),tr(t,o)),r.content&&(tr(t,o),function(e){return!!e.contentBlockOpen&&Object.values(e.toolCalls).some(t=>t._bi1===e.contentBlockIndex)}(t)&&(o.push({type:"content_block_stop",index:t.contentBlockIndex}),t.contentBlockIndex++,t.contentBlockOpen=!1),t.contentBlockOpen||=(o.push({type:"content_block_start",index:t.contentBlockIndex,content_block:{type:"text",text:""}}),!0),o.push({type:"content_block_delta",index:t.contentBlockIndex,delta:{type:"text_delta",text:r.content}})),r.tool_calls){tr(t,o);for(let e of r.tool_calls){if(e.id&&e.function?.name){t.contentBlockOpen&&=(o.push({type:"content_block_stop",index:t.contentBlockIndex}),t.contentBlockIndex++,!1);let n=t.contentBlockIndex;t.toolCalls[e.index]={id:e.id,name:e.function.name,_bi1:n},o.push({type:"content_block_start",index:n,content_block:{type:"tool_use",id:e.id,name:e.function.name,input:{}}}),t.contentBlockOpen=!0}if(e.function?.arguments){let n=t.toolCalls[e.index];n&&o.push({type:"content_block_delta",index:n._bi1,delta:{type:"input_json_delta",partial_json:e.function.arguments}})}}}return n.finish_reason&&(tr(t,o),t.contentBlockOpen&&=(o.push({type:"content_block_stop",index:t.contentBlockIndex}),!1),o.push({type:"message_delta",delta:{stop_reason:Pn(n.finish_reason),stop_sequence:null},usage:{input_tokens:e.usage?.prompt_tokens??0,output_tokens:e.usage?.completion_tokens??0}},{type:"message_stop"})),o}async function nr(e,t,n){let r={query:t,max_results:n?.maxResults??5};n?.includeDomains?.length&&(r.include_domains=n.includeDomains),n?.excludeDomains?.length&&(r.exclude_domains=n.excludeDomains),o.debug("Tavily search request:",JSON.stringify(r));let i=await fetch("https://api.tavily.com/search",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(r)});if(!i.ok){let e=await i.text();throw o.error(`Tavily API error (${i.status}):`,e),Error(`Tavily API error: ${i.status} ${e}`)}let a=await i.json();return o.debug(`Tavily returned ${a.results.length} results`),a.results}function rr(){let e="";for(let t=0;t<24;t++)e+="abcdefghijklmnopqrstuvwxyz0123456789"[Math.floor(36*Math.random())];return e}async function ir(e,t){let n=function(e){let t,o=e.messages[0];if(!o||"user"!==o.role)return null;if("string"==typeof o.content)t=o.content;else{if(!Array.isArray(o.content))return null;{let e=o.content.find(e=>"text"===e.type);if(!e)return null;t=e.text}}return t.startsWith("Perform a web search for the query: ")?t.slice(36).trim():t.trim()||null}(t);if(!n)return e.json({type:"error",error:{type:"invalid_request_error",message:"Could not extract search query from web search request"}},400);let r=function(e){let t=e.tools?.[0];return{maxResults:"number"==typeof t?.max_uses?t.max_uses:5,allowedDomains:t?.allowed_domains,blockedDomains:t?.blocked_domains}}(t);o.info(`Web search intercepted: "${n}"`);let i=[];try{let e=Y.tavilyApiKey;if(!e)throw Error("No Tavily API key configured");i=(await nr(e,n,{maxResults:Math.min(r.maxResults,10),includeDomains:r.allowedDomains,excludeDomains:r.blockedDomains})).map(e=>({type:"web_search_result",url:e.url,title:e.title,encrypted_content:Buffer.from(e.content).toString("base64"),page_age:null}))}catch(e){o.error("Tavily search failed:",e)}let a={query:n,results:i,model:t.model};if(!t.stream)return e.json(function(e){let{query:t,results:o,model:n}=e,r=`srvtoolu_${rr()}`,i=[{type:"text",text:"I'll search for that."},{type:"server_tool_use",id:r,name:"web_search",input:{query:t}},{type:"web_search_tool_result",tool_use_id:r,content:o}];return{id:`msg_tavily_${rr()}`,type:"message",role:"assistant",model:n,content:i,stop_reason:"end_turn",stop_sequence:null,usage:{input_tokens:0,output_tokens:0}}}(a));let s=function(e){let{query:t,results:o,model:n}=e,r=`srvtoolu_${rr()}`,i=`msg_tavily_${rr()}`,a=[];return a.push({type:"message_start",message:{id:i,type:"message",role:"assistant",content:[],model:n,stop_reason:null,stop_sequence:null,usage:{input_tokens:0,output_tokens:0}}},{type:"content_block_start",index:0,content_block:{type:"text",text:""}},{type:"content_block_delta",index:0,delta:{type:"text_delta",text:"I'll search for that."}},{type:"content_block_stop",index:0},{type:"content_block_start",index:1,content_block:{type:"server_tool_use",id:r,name:"web_search",input:{}}},{type:"content_block_delta",index:1,delta:{type:"input_json_delta",partial_json:JSON.stringify({query:t})}},{type:"content_block_stop",index:1},{type:"content_block_start",index:2,content_block:{type:"web_search_tool_result",tool_use_id:r,content:o}},{type:"content_block_stop",index:2},{type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{output_tokens:0}},{type:"message_stop"}),a}(a);return H(e,async e=>{for(let t of s)await e.writeSSE({event:t.type,data:JSON.stringify(t)})})}function ar(e){return function(e){let t=e.thinking;if(null==t)return null;if("object"!=typeof t)return"thinking must be an object";let o=t,n=new Set(["enabled","adaptive","disabled"]);return"string"==typeof o.type&&n.has(o.type)?"enabled"!==o.type||void 0===o.budget_tokens||"number"==typeof o.budget_tokens&&Number.isFinite(o.budget_tokens)&&!(o.budget_tokens<=0)&&Number.isInteger(o.budget_tokens)?null:"thinking.budget_tokens must be a positive integer":"thinking.type must be one of: enabled, adaptive, disabled"}(e)??function(e){let t=e.output_config;if(null==t)return null;if("object"!=typeof t)return"output_config must be an object";let o=t;if(void 0===o.effort)return null;let n=new Set(["low","medium","high","max"]);return"string"==typeof o.effort&&n.has(o.effort)?null:"output_config.effort must be one of: low, medium, high, max"}(e)}async function sr(e){let t=await e.req.json();if(function(e){let t=e.tools;if(!t||1!==t.length)return!1;let o=t[0].type;return"string"==typeof o&&o.startsWith("web_search")}(t))return ir(e,t);await an(Y),o.debug("Anthropic request payload:",JSON.stringify(t));let n=e.req.header("anthropic-beta")??"",r=/context-1m/i.test(n);if(r&&/\u0063\u006c\u0061\u0075\u0064\u0065/i.test(t.model)){let e=t.model;t={...t,model:`${t.model}-1m`},o.debug(`Detected context-1m beta flag, rewriting model: '${e}' → '${t.model}'`)}let i=function(e,t){return ae.startActiveSpan("copilot_api.model.validate",n=>{try{n.setAttribute("copilot_api.model.requested",t.model);let r=rn(t.model);n.setAttribute("copilot_api.model.normalized",r);let i=ar(t);return i?{ok:!1,response:e.json({type:"error",error:{type:"invalid_request_error",message:i}},400)}:r===t.model?(n.setAttribute("copilot_api.model.was_mapped",!1),{ok:!0,payload:t}):(n.setAttribute("copilot_api.model.was_mapped",!0),ge.add(1,{from_model:t.model,to_model:r}),o.debug(`Model mapping: '${t.model}' → '${r}'`),{ok:!0,payload:{...t,model:r}})}catch(t){if(t instanceof nn)return{ok:!1,response:e.json({type:"error",error:{type:"invalid_request_error",message:t.message}},t.statusCode)};throw t}finally{n.end()}})}(e,t);if(!i.ok)return i.response;if(t=i.payload,function(e){return/gpt-[\d.]+-codex/i.test(e)}(t.model))return async function(e,t){let n=performance.now(),r=ae.startActiveSpan("copilot_api.translate.anthropic_to_responses",e=>{try{return e.setAttribute("copilot_api.translation.direction","anthropic_to_responses"),e.setAttribute("copilot_api.translation.message_count",t.messages.length),Jn(t)}finally{e.end()}});Ee.record(performance.now()-n,{direction:"anthropic_to_responses"}),o.debug("Translated Responses API payload:",JSON.stringify(r)),e.set("requestData",{model:r.model,streaming:!!r.stream}),Y.manualApprove&&await Vo();let i=performance.now(),a=await In(r),s=performance.now()-i;if(Se.record(s,{model:r.model,target:"responses",streaming:String(!!r.stream)}),ur(a)){let t=e.get("requestData")||{};if(a.usage&&(t.tokenUsage=Qo({prompt_tokens:a.usage.input_tokens,completion_tokens:a.usage.output_tokens,total_tokens:a.usage.total_tokens})),t._d1=s,e.set("requestData",t),o.debug("Non-streaming Responses API response:",JSON.stringify(a).slice(-400)),"failed"===a.status)return e.json({type:"error",error:{type:a.error?.code??"api_error",message:a.error?.message??"Response generation failed"}},500);let n=performance.now(),r=ae.startActiveSpan("copilot_api.translate.responses_to_anthropic",e=>{try{return e.setAttribute("copilot_api.translation.direction","responses_to_anthropic"),function(e){let t=[],o=!1;for(let n of e.output)if("message"===n.type)for(let e of n.content)e.text&&t.push({type:"text",text:e.text});else if("function_call"===n.type){o=!0;let e={};try{e=JSON.parse(n.arguments)}catch{}t.push({type:"tool_use",id:n.call_id,name:n.name,input:e})}return{id:e.id,type:"message",role:"assistant",model:e.model,content:t,stop_reason:Yn(e.status,o),stop_sequence:null,usage:{input_tokens:e.usage?.input_tokens??0,output_tokens:e.usage?.output_tokens??0}}}(a)}finally{e.end()}});return Ee.record(performance.now()-n,{direction:"responses_to_anthropic"}),e.json(r)}o.debug("Streaming Responses API response");let{events:l,span:c,release:u}=a;return H(e,async t=>{let n=null,i=0,a=performance.now(),p={messageStartSent:!1,contentBlockIndex:0,contentBlockOpen:!1,responseId:"",model:"",toolCalls:{}};try{try{for await(let a of l){if(o.debug("Responses API raw stream event:",JSON.stringify(a)),!a.data)continue;let l;try{l=JSON.parse(a.data)}catch(e){o.warn("Failed to parse streaming chunk:",a.data.slice(0,200),e);continue}i++,ve.add(1,{model:r.model,endpoint_type:"responses"});let c=lr(l);if(c){n=c;let t=e.get("requestData")||{};t.tokenUsage=Qo(n),t._d1=s,e.set("requestData",t)}let u=Zn(l,p);for(let e of u)o.debug("Translated Anthropic event:",JSON.stringify(e)),await t.writeSSE({event:e.type,data:JSON.stringify(e)})}let c=performance.now()-a,u={model:r.model,endpoint_type:"responses"};Ce.record(c,u),Re.record(i,u)}finally{n&&Zo(c,n),c.end(),u()}let d=e.get("requestId");d&&ee.executeCompletion(d)}finally{e.get("resolveStreamComplete")?.()}})}(e,t);if(Y.nativeAnthropicEnabled&&function(e){return e.toLowerCase().startsWith("claude-")}(t.model))return async function(e,t){let o={anthropicBeta:e.req.header("anthropic-beta"),anthropicVersion:e.req.header("anthropic-version")};return e.set("requestData",{model:t.model,streaming:!!t.stream}),Y.manualApprove&&await Vo(),ae.startActiveSpan("copilot_api.anthropic_passthrough",async n=>{n.setAttribute("copilot_api.route","anthropic_passthrough"),n.setAttribute("copilot_api.model",t.model),n.setAttribute("copilot_api.streaming",!!t.stream);let r=performance.now(),i=await En(t,o),a=performance.now()-r;if(Se.record(a,{model:t.model,target:"anthropic_messages",streaming:String(!!t.stream)}),!t.stream){let t=i,o=t.usage;if(o){let t={input_tokens:o.input_tokens||0,output_tokens:o.output_tokens||0,cache_read_input_tokens:o.cache_read_input_tokens||0,cache_creation_input_tokens:o.cache_creation_input_tokens||0},n=e.get("requestData")||{};n.tokenUsage=Qo(pr(t)),n._d1=a,e.set("requestData",n)}return n.end(),e.json(t)}let{events:s,span:l,release:c}=i;return H(e,async o=>{let i=0,a=performance.now(),u={input_tokens:0,output_tokens:0,cache_read_input_tokens:0,cache_creation_input_tokens:0},p=!1;try{try{for await(let e of s)e.data&&"[DONE]"!==e.data?(i++,ve.add(1,{model:t.model,endpoint_type:"anthropic_messages"}),dr(e.data,u)&&(p=!0),await o.writeSSE(e)):await o.writeSSE(e);let e=performance.now()-a,n={model:t.model,endpoint_type:"anthropic_messages"};Ce.record(e,n),Re.record(i,n)}finally{if(p){let t=pr(u);Zo(l,t);let o=e.get("requestData")||{};o.tokenUsage=Qo(t),o._d1=performance.now()-r,e.set("requestData",o)}l.end(),c()}let n=e.get("requestId");n&&ee.executeCompletion(n)}finally{n.end(),e.get("resolveStreamComplete")?.()}})})}(e,t);let a=performance.now(),s=ae.startActiveSpan("copilot_api.translate.anthropic_to_openai",e=>{try{e.setAttribute("copilot_api.translation.direction","anthropic_to_openai"),e.setAttribute("copilot_api.translation.message_count",t.messages.length),e.setAttribute("copilot_api.translation.has_tools",!!t.tools?.length),e.setAttribute("copilot_api.translation.has_system",!!t.system),e.setAttribute("copilot_api.translation.context_1m_beta",r);let o=t.messages.some(e=>Array.isArray(e.content)&&e.content.some(e=>"image"===e.type)),n=t.messages.some(e=>Array.isArray(e.content)&&e.content.some(e=>"thinking"===e.type));return e.setAttribute("copilot_api.translation.has_images",o),e.setAttribute("copilot_api.translation.has_thinking",n),Nn(t,Y.models)}finally{e.end()}});Ee.record(performance.now()-a,{direction:"anthropic_to_openai"}),s=dn(s,Y.models,{enabled:Y.thinkingEnabled}),o.debug("Translated OpenAI request payload:",JSON.stringify(s)),e.set("requestData",{model:s.model,streaming:!!s.stream});let l=performance.now();Y.manualApprove&&await Vo();let c=await yn(s),u=performance.now()-l;if(Se.record(u,{model:s.model,target:"chat_completions",streaming:String(!!s.stream)}),cr(c)){let t=e.get("requestData")||{};c.usage&&(t.tokenUsage=Qo(c.usage)),t._d1=u,e.set("requestData",t),o.debug("Non-streaming response:",JSON.stringify(c).slice(-400));let n=performance.now(),r=ae.startActiveSpan("copilot_api.translate.openai_to_anthropic",e=>{try{e.setAttribute("copilot_api.translation.direction","openai_to_anthropic");let t=function(e){let t=[],o=[],n=[],r=null;r=e.choices[0]?.finish_reason??r;for(let i of e.choices){let e=Ln(i.message),a=Bn(i.message.content),s=Un(i.message.tool_calls);t.push(...e),o.push(...a),n.push(...s),("tool_calls"===i.finish_reason||"stop"===r)&&(r=i.finish_reason)}return{id:e.id,type:"message",role:"assistant",model:e.model,content:[...t,...o,...n],stop_reason:Pn(r),stop_sequence:null,usage:{input_tokens:e.usage?.prompt_tokens??0,output_tokens:e.usage?.completion_tokens??0}}}(c);return e.setAttribute("copilot_api.translation.content_blocks",t.content.length),e.setAttribute("copilot_api.translation.stop_reason",t.stop_reason??"null"),e.setAttribute("copilot_api.translation.has_tool_use",t.content.some(e=>"tool_use"===e.type)),t}finally{e.end()}});return Ee.record(performance.now()-n,{direction:"openai_to_anthropic"}),o.debug("Translated Anthropic response:",JSON.stringify(r)),e.json(r)}o.debug("Streaming response from service");let{events:p,span:d,release:m}=c;return H(e,async t=>{let n=null,r=0,i=performance.now(),a={messageStartSent:!1,contentBlockIndex:0,contentBlockOpen:!1,thinkingBlockOpen:!1,toolCalls:{}};try{try{for await(let i of p){if(o.debug("Raw stream event:",JSON.stringify(i)),"[DONE]"===i.data)break;if(!i.data)continue;let l;try{l=JSON.parse(i.data)}catch(e){o.warn("Failed to parse streaming chunk:",i.data.slice(0,200),e);continue}if(r++,ve.add(1,{model:s.model,endpoint_type:"anthropic"}),l.usage){n=l.usage;let t=e.get("requestData")||{};t.tokenUsage=Qo(n),t._d1=u,e.set("requestData",t)}let c=or(l,a);for(let e of c)o.debug("Translated Anthropic event:",JSON.stringify(e)),await t.writeSSE({event:e.type,data:JSON.stringify(e)})}let l=performance.now()-i,c={model:s.model,endpoint_type:"anthropic"};if(Ce.record(l,c),Re.record(r,c),n){let t=e.get("requestData")||{};t.tokenUsage||(t.tokenUsage=Qo(n),t._d1=u,e.set("requestData",t))}}finally{n&&Zo(d,n),d.end(),m()}let l=e.get("requestId");l&&ee.executeCompletion(l)}finally{e.get("resolveStreamComplete")?.()}})}function lr(e){if("response.completed"!==e.type&&"response.incomplete"!==e.type)return null;let t=e.response.usage;return t?{prompt_tokens:t.input_tokens,completion_tokens:t.output_tokens,total_tokens:t.total_tokens}:null}const cr=e=>Object.hasOwn(e,"choices"),ur=e=>Object.hasOwn(e,"output");function pr(e){let t=e.input_tokens+e.cache_read_input_tokens+e.cache_creation_input_tokens;return{prompt_tokens:t,completion_tokens:e.output_tokens,total_tokens:t+e.output_tokens,prompt_tokens_details:{cached_tokens:e.cache_read_input_tokens}}}function dr(e,t){try{let o=JSON.parse(e);if("message_start"===o.type){let e=o.message?.usage;if(e)return t.input_tokens=e.input_tokens||0,t.cache_read_input_tokens=e.cache_read_input_tokens||0,t.cache_creation_input_tokens=e.cache_creation_input_tokens||0,!0}if("message_delta"===o.type){let e=o.usage;if(e)return t.output_tokens=e.output_tokens||0,!0}}catch{}return!1}const mr=new M;mr.post("/",async e=>{try{return await sr(e)}catch(t){return await lt(e,t)}});const fr=new M;function hr(e,t){let o=function(e){try{let t=JSON.parse(e);if(("response.completed"===t.type||"response.incomplete"===t.type)&&t.response?.usage){let e=t.response.usage;return{prompt_tokens:e.input_tokens,completion_tokens:e.output_tokens,total_tokens:e.total_tokens}}}catch{}return null}(e);if(!o)return;t.usageRef.value=o;let n=t.c.get("requestData")||{};n.tokenUsage=Qo(o),n._d1=t._d1,t.c.set("requestData",n)}fr.get("/",async e=>{try{Y.models||await mt();let t=Y.models?.data.map(e=>({id:e.id,object:"model",type:"model",created:0,created_at:new Date(0).toISOString(),owned_by:e.vendor,display_name:e.name,context_length:e.capabilities.limits?.max_context_window_tokens}));return e.json({object:"list",data:t,has_more:!1})}catch(t){return await lt(e,t)}});const gr=new Set(["message","function_call","function_call_output"]),_r=new Set(["type","name","description","parameters"]);async function yr(e){if(!e)return!1;let t=e.sources;if(t&&t.length>0)return!1;let n=e.query??e.queries?.[0];return!(!n||!Y.tavilyApiKey)&&(o.info(`Enriching web search: "${n}"`),e.sources=(await nr(Y.tavilyApiKey,n,{maxResults:5})).map(e=>({type:"url",url:e.url,title:e.title,content:e.content})),!0)}async function kr(e){if(Y.tavilyApiKey)try{for(let t of e.output){let e=t;"web_search_call"===e.type&&await yr(e.action)}}catch(e){o.error("Failed to enrich non-streaming web search:",e)}}async function br(e){if(!Y.tavilyApiKey)return e;try{let t=JSON.parse(e);if("response.output_item.done"===t.type){let e=t.item;if("web_search_call"===e?.type&&await yr(e.action))return JSON.stringify(t)}}catch(e){o.error("Failed to enrich web search:",e)}return e}function wr(e,t){if("function_call"!==e.type||!t.has(e.name))return!1;if(e.type="custom_tool_call","string"==typeof e.arguments){try{e.input=JSON.parse(e.arguments).input??e.arguments}catch{e.input=e.arguments}delete e.arguments}return!0}function vr(e,t){if(0===t.size)return e;try{let o=JSON.parse(e),n=o.type;if("response.output_item.added"===n||"response.output_item.done"===n){let e=o.item;if(e&&wr(e,t))return JSON.stringify(o)}if("response.completed"===n){let n=o.response?.output;if(!n)return e;let r=!1;for(let e of n)wr(e,t)&&(r=!0);if(r)return JSON.stringify(o)}}catch{}return e}function $r(e){return null!=e}function xr(e){let t=e.input,o="string"==typeof t?t:t.map(e=>function(e){switch(e.type){case"custom_tool_call":{let t=e.input;return{type:"function_call",call_id:e.call_id,name:e.name,arguments:JSON.stringify("string"==typeof t?{input:t}:t)}}case"custom_tool_call_output":return{type:"function_call_output",call_id:e.call_id,output:e.output};default:return gr.has(e.type)||"web_search_call"===e.type?e:null}}(e)).filter(e=>null!==e),n={model:e.model,input:o};for(let t of["instructions","max_output_tokens","temperature","top_p","stream","store","tool_choice","parallel_tool_calls","user"])$r(e[t])&&(n[t]=e[t]);let r=new Set;if($r(e.tools)){let t=function(e){let t=new Set;return{tools:e.filter(e=>{let t=e.type;return"function"===t||"custom"===t||"web_search"===t||t.startsWith("web_search_")}).map(e=>{let o=e.type;if("web_search"===o||o.startsWith("web_search_"))return{type:e.type};let n={};for(let t of Object.keys(e))_r.has(t)&&(n[t]=e[t]);return"custom"===n.type&&(n.type="function",t.add(n.name),n.parameters||={type:"object",properties:{input:{type:"string",description:"The freeform tool input content"}},required:["input"],additionalProperties:!1}),n}),customToolNames:t}}(e.tools);n.tools=t.tools,r=t.customToolNames}if($r(e.reasoning)&&"object"==typeof e.reasoning){let t=e.reasoning;n.reasoning={},$r(t.effort)&&(n.reasoning.effort=t.effort),$r(t.summary)&&(n.reasoning.summary=t.summary)}if($r(e.text)&&"object"==typeof e.text){let t=e.text;$r(t.format)&&(n.text={format:t.format})}return{payload:n,customToolNames:r}}async function Tr(e){await an(Y);let{payload:t,customToolNames:n}=xr(await e.req.json()),r=t;o.debug(`Responses API [${Array.isArray(r.input)?r.input.length:1} items]`),n.size>0&&o.debug(`Custom tools detected: ${[...n].join(", ")}`);try{r=function(e){return ae.startActiveSpan("copilot_api.model.validate",t=>{try{t.setAttribute("copilot_api.model.requested",e.model);let n=rn(e.model);return t.setAttribute("copilot_api.model.normalized",n),n===e.model?(t.setAttribute("copilot_api.model.was_mapped",!1),e):(t.setAttribute("copilot_api.model.was_mapped",!0),ge.add(1,{from_model:e.model,to_model:n}),o.debug(`Normalized model from '${e.model}' to '${n}'`),{...e,model:n})}finally{t.end()}})}(r)}catch(t){if(t instanceof nn)return e.json({error:{message:t.message,type:"invalid_request_error",code:"invalid_model"}},t.statusCode);throw t}e.set("requestData",{model:r.model,streaming:!!r.stream}),Y.manualApprove&&await Vo();let i=performance.now(),a=await In(r),s=performance.now()-i;if(Se.record(s,{model:r.model,target:"responses",streaming:String(!!r.stream)}),Ar(a))return async function(e,t,o){await kr(t);let n=e.get("requestData")||{};return t.usage&&(n.tokenUsage=Qo({prompt_tokens:t.usage.input_tokens,completion_tokens:t.usage.output_tokens,total_tokens:t.usage.total_tokens})),n._d1=o,e.set("requestData",n),e.json(t)}(e,a,s);let{events:l,span:c,release:u}=a;return H(e,async t=>{let o={value:null},i=0,a=performance.now();try{try{for await(let a of l)if(a.data&&"[DONE]"!==a.data){i++;let l=vr(a.data,n);l=await br(l);let c=l===a.data?a:{...a,data:l};ve.add(1,{model:r.model,endpoint_type:"responses"}),hr(l,{usageRef:o,c:e,_d1:s}),await t.writeSSE(c)}else await t.writeSSE(a);let c=performance.now()-a,u={model:r.model,endpoint_type:"responses"};Ce.record(c,u),Re.record(i,u)}finally{o.value&&Zo(c,o.value),c.end(),u()}let p=e.get("requestId");p&&ee.executeCompletion(p)}finally{e.get("resolveStreamComplete")?.()}})}const Ar=e=>Object.hasOwn(e,"output"),Sr=new M;Sr.post("/",async e=>{try{return await Tr(e)}catch(t){return await lt(e,t)}});const Cr=new M;Cr.get("/",e=>{try{return e.json({token:Y._t1})}catch(t){return o.error("Error fetching token:",t),e.json({error:"Failed to fetch token",token:null},500)}});const Or=new M;Or.get("/",async e=>{try{let t=await At();return e.json(t)}catch(t){return o.error("Error fetching usage:",t),e.json({error:"Failed to fetch usage"},500)}});const Er=new M;Er.use(async(e,t)=>{let n=Date.now(),r=`req_${Date.now()}_${Math.random().toString(36).slice(2,11)}`,i=e.req.method,c=e.req.path,p=function(e){return e.includes("/messages")?"anthropic":e.includes("/chat/completions")?"openai":e.includes("/embeddings")?"embeddings":e.includes("/models")?"models":e.includes("/usage")?"usage":e.includes("/token")?"token":"unknown"}(c);e.set("requestId",r),e.header("x-request-id",r);let d=ae.startSpan("copilot_api.handle_request",{kind:a.SERVER,attributes:{"http.method":i,"http.url":e.req.url,"http.route":c,"copilot_api.request_id":r,"copilot_api.endpoint_type":p}});for(let[t,o]of Object.entries(e.req.header())){let e=t.toLowerCase();Fe.has(e)||d.setAttribute(`http.request.header.${e}`,o)}let m,f=new Promise(e=>{m=e});e.set("streamComplete",f),e.set("resolveStreamComplete",m);let h=u.setSpan(l.active(),d);await l.with(h,async()=>{ee.registerCompletion(r,e,n);try{await t()}catch(e){let t=e instanceof Error?e:Error(String(e));throw d.setStatus({code:s.ERROR,message:t.message}),d.recordException(t),e}});let g=e.get("requestData"),_={c:e,start:n,method:i,path:c,endpointType:p,requestId:r,span:d};g?.streaming?f.then(()=>Ko(_)).catch(e=>{o.debug("Error finalizing streaming request:",e),d.end()}):Ko(_)}),Er.use(F()),Er.get("/",e=>e.text("Server running")),Er.route("/chat/completions",$n),Er.route("/models",fr),Er.route("/embeddings",xn),Er.route("/usage",Or),Er.route("/token",Cr),Er.route("/v1/chat/completions",$n),Er.route("/v1/models",fr),Er.route("/v1/embeddings",xn),Er.route("/v1/messages",mr),Er.post("/v1/messages/count_tokens",async function(e){let t;try{t=await e.req.json()}catch{return e.json({error:{type:"invalid_request_error",message:"Invalid JSON"}},400)}if(!Array.isArray(t.messages))return e.json({error:{type:"invalid_request_error",message:"messages is required"}},400);let o=An.baseOverhead;if(t.system){let e="string"==typeof t.system?t.system:t.system.map(e=>e.text).join("\n\n");o+=An.perMessage+Sn(e)*An.contentMultiplier}for(let e of t.messages)o+=An.perMessage,o+=Sn(e.role),"string"==typeof e.content?o+=Sn(e.content)*An.contentMultiplier:Array.isArray(e.content)&&(o+=Cn(e.content));return t.tools&&t.tools.length>0&&(o+=function(e){let t=An.toolsExist;for(let[o,n]of e.entries())o>0&&(t+=An.perTool),t+=Sn(n.name),n.description&&(t+=An.perDesc+Sn(n.description)),t+=On(n.input_schema);return t}(t.tools)),e.json({input_tokens:Math.round(o)})}),Er.route("/v1/responses",Sr),Er.route("/responses",Sr);const Ir=[],Pr=Date.now();let Nr="";function qr(){let e=async(e,t=0)=>{let n=ae.startSpan("copilot_api.server.shutdown",{kind:a.INTERNAL,attributes:{"copilot_api.shutdown.reason":e,"copilot_api.shutdown.exit_code":t,"copilot_api.uptime_seconds":(Date.now()-Pr)/1e3}});for(let t of Ir)try{await t()}catch(e){o.error("Error during cleanup:",e)}n.end(),function(e,t){let o=Co("https://barazany.dev?utm_source=copilot-cli&utm_medium=terminal&utm_campaign=goodbye_banner","barazany.dev"),n=["",Eo,` ${vo("COPILOT-API")} ${$o(`v${e}`)} ${$o("·")} ${Fo(t)} uptime`,Eo,""," Check in from time to time on",` ${xo(o)}`,"",Eo,""];console.log(n.join("\n"))}(Nr,Date.now()-Pr),f.exit(t)};f.on("SIGINT",()=>e("SIGINT")),f.on("SIGTERM",()=>e("SIGTERM")),f.on("uncaughtException",t=>{o.error("Uncaught exception:",t),e("uncaughtException",1)}),f.on("unhandledRejection",(t,n)=>{o.error("Unhandled promise rejection at:",n,"reason:",t),e("unhandledRejection",1)})}function Rr(e){let{options:t,version:o,runtime:n,_u1:r}=e,i=ae.startSpan("copilot_api.server.startup",{kind:a.INTERNAL,attributes:Me({config:{version:o,port:t.port,accountType:t.accountType,verbose:t.verbose,manualApprove:t.manual,rateLimitSeconds:t.rateLimit??0,rateLimitWait:t.rateLimitWait,timeoutMs:t.timeout,showToken:t.showToken,_cc1:t._cc1,model:t.model,smallModel:t.smallModel,_t3:t._t2?"cli_arg":"stored",enableThinking:t.enableThinking,nativeAnthropic:t.nativeAnthropic},runtime:n,identity:{_u1:r.login,machineId:Y.machineId,sessionId:Y.sessionId,_v1:Y._v1},connectivity:Y.connectivity,modelsCount:Y.models?.data.length??0,startupDurationMs:Date.now()-Pr},"copilot_api")});if(Y.models?.data)for(let e of Y.models.data)i.addEvent("copilot_api.model.available",Me(e,"model"));i.end(),De(h.INFO,"INFO","Server started",Me({version:o,port:t.port,accountType:t.accountType,_u1:r.login,modelsCount:Y.models?.data.length??0,startupDurationMs:Date.now()-Pr},"copilot_api"))}async function jr(e){if(e.https){if(e.httpsCert&&e.httpsKey)return async function(e,t){let[o,r]=await Promise.all([n.readFile(e,"utf8"),n.readFile(t,"utf8")]);return{cert:o,key:r,certPath:e,keyPath:t,generated:!1}}(e.httpsCert,e.httpsKey);if(e.httpsCert||e.httpsKey)throw Error("Both --https-cert and --https-key must be provided together");return async function(e=[]){if(await Go(e)){let e=await Jo(Bo),t=await Jo(Lo);if(e&&t)return{cert:e,key:t,certPath:Bo,keyPath:Lo,generated:!1}}return o.info("Generating new self-signed TLS certificate…"),zo(e)}(e.httpsHosts)}}async function Dr(e){let t=function(e){if(!e.claudeCowork)return e;if(e.httpsCert&&e.httpsKey)return{...e,https:!0};let{certPath:t,keyPath:n}=Jt;try{N(t),N(n)}catch{throw o.error("Tailscale cert not found. Run `copilot-api cowork-setup install` first."),Error("Tailscale cert not found")}return{...e,https:!0,httpsCert:t,httpsKey:n}}(e);if(qr(),Ir.push(()=>{o.debug("Cleaning up connectivity monitor"),Ue.stop()},()=>{o.debug("Cleaning up token management"),o.debug("Cleaning up token management"),ht&&=void clearInterval(ht),gt&&=void Ue.off("online",gt),_t&&=void Ue.off("offline",_t)},async()=>{o.debug("Cleaning up HTTP/2 client"),await async function(){o.debug("Stopping HTTP/2 pool"),mo&&=void clearInterval(mo),fo&&=void clearInterval(fo);let e=[...co.keys(),...uo];co.clear(),uo.clear(),lo.clear(),po=void 0;for(let t of e)ho(t)&&(Te.add(1,{event:"closed"}),await t.close())}()},async()=>{o.debug("Shutting down OTel SDK"),await async function(){te&&await te.shutdown()}()}),t.verbose&&(o.level=5,o.info("Verbose logging enabled")),t._cc1&&t.codex)throw Error("Cannot use --claude-code and --codex together");Y.accountType=t.accountType,Y.manualApprove=t.manual,Y.rateLimitSeconds=t.rateLimit,Y.rateLimitWait=t.rateLimitWait,Y.showToken=t.showToken,Y.timeoutMs=t.timeout,Y.thinkingEnabled=t.enableThinking,Y.nativeAnthropicEnabled=t.nativeAnthropic,t.tavilyApiKey&&(Y.tavilyApiKey=t.tavilyApiKey),function(){let e="1"===f.env.COPILOT_H2_KEEPALIVE||"true"===f.env.COPILOT_H2_KEEPALIVE,t=e||"1"===f.env.COPILOT_H2||"true"===f.env.COPILOT_H2;Y.connectivity.h2=t,Y.connectivity.h2Keepalive=e}(),await z(),Y._v1="1.116.0-insider";let n=await Xt();Nr=n;let r,i=Qt();(function(e,t){t&&(ne=t),oe=crypto.randomUUID(),te=new $({resource:b({[T]:"copilot-api",[A]:e,[x]:oe}),traceExporter:new k({url:`${re}/v1/traces`,headers:ie}),metricReader:new v({exporter:new y({url:`${re}/v1/metrics`,headers:ie}),exportIntervalMillis:15e3}),logRecordProcessors:[new w(new _({url:`${re}/v1/logs`,headers:ie}))],instrumentations:[]}),te.start()})(n,Pr),t._t2?(Y._t2=t._t2,o.info("Using provided Auth token")):await vt();try{r=await ut(),await Ve(Y,r.login)}catch(e){throw o.error("Failed to get user info for machine ID generation:",e),Error("Cannot proceed without user information",{cause:e})}await wt(),await mt();let a=function(e=18e5){let t=setInterval(()=>{mt().then(()=>o.debug("Model list refreshed successfully")).catch(e=>{o.warn("Failed to refresh model list; keeping existing cache:",e)})},e);return t.unref(),()=>{clearInterval(t)}}();Ir.push(()=>{o.debug("Cleaning up model refresh interval"),a()}),Y.connectivity.h2&&(yo(_o(Ye(Y))),Y.connectivity.h2Keepalive&&bo()),Rr({options:t,version:n,runtime:i,_u1:r});let s=await jr(t),l=`${s?"https":"http"}://localhost:${t.port}`,c=await async function(e,t,n){if(!e._cc1)return!1;let r,i;if(R(Y.models,"Models should be loaded by now"),e.model&&e.smallModel){let t=Y.models.data.map(e=>e.id);if(!t.includes(e.model))throw o.info(`Available services: \n${t.join("\n")}`),Error(`Invalid model: ${e.model}`);if(!t.includes(e.smallModel))throw o.info(`Available services: \n${t.join("\n")}`),Error(`Invalid small model: ${e.smallModel}`);r=e.model,i=e.smallModel}else{if(e.model||e.smallModel)throw Error("Both --model and --small-model must be specified for model selection");r=await o.prompt("Select a model to use",{type:"select",options:Y.models.data.map(e=>e.id)}),i=await o.prompt("Select a small model to use",{type:"select",options:Y.models.data.map(e=>e.id)})}let a=wo({ANTHROPIC_BASE_URL:t,ANTHROPIC_AUTH_TOKEN:"dummy",ANTHROPIC_MODEL:r,ANTHROPIC_SMALL_FAST_MODEL:i,NODE_EXTRA_CA_CERTS:n?.certPath},"claude");try{return p.writeSync(a),!0}catch{return o.warn("Failed to copy to clipboard. Here is the command:"),o.log(a),!1}}(t,l,s)||await async function(e,t,n){if(!e.codex)return!1;let r;if(R(Y.models,"Models should be loaded by now"),e.model){let t=Y.models.data.map(e=>e.id);if(!t.includes(e.model))throw o.info(`Available services: \n${t.join("\n")}`),Error(`Invalid model: ${e.model}`);r=e.model}else r=await o.prompt("Select a model to use with Codex CLI",{type:"select",options:Y.models.data.map(e=>e.id)});let i=wo({OPENAI_BASE_URL:t,OPENAI_API_KEY:"dummy",NODE_EXTRA_CA_CERTS:n?.certPath},`codex --model ${r}`);try{return p.writeSync(i),!0}catch{return o.warn("Failed to copy to clipboard. Here is the Codex CLI command:"),o.log(i),!1}}(t,l,s);(function(e){let t=[...qo(e),...Ro(e),...jo(e),"",...No(Po),...Do(e),...Mo(e),""];console.log(t.join("\n"))})(await async function(e){let{options:t,version:o,runtime:n,user:r,clipboardCopied:i,tls:a}=e,s=a?"https":"http";return{version:o,runtime:n,user:r,accountType:t.accountType,port:t.port,timeout:t.timeout,webSearch:!!t.tavilyApiKey,model:t.model,smallModel:t.smallModel,clipboardCopied:i,https:a?{certPath:a.certPath,keyPath:a.keyPath,generated:a.generated,selfSigned:!t.httpsCert}:void 0,endpoints:t.claudeCowork?{scheme:s,port:t.port,hostname:await Pt()}:void 0}}({options:t,version:n,runtime:i,user:r.login,clipboardCopied:c,tls:s})),q({fetch:Er.fetch,port:t.port,tls:s?{cert:s.cert,key:s.key}:void 0,bun:{idleTimeout:255}})}function Mr(e,t){let o=Number.parseInt(e,10);if(Number.isNaN(o))throw Error(`${t} must be a number, got: "${e}"`);return o}const Fr=e({meta:{name:"start",description:"Start the API server"},args:{port:{alias:"p",type:"string",default:"4141",description:"Port to listen on"},verbose:{alias:"v",type:"boolean",default:!1,description:"Enable verbose logging"},"account-type":{alias:"a",type:"string",default:"individual",description:"Account type (individual, business, enterprise)"},manual:{type:"boolean",default:!1,description:"Enable manual request approval"},"rate-limit":{alias:"r",type:"string",description:"Rate limit in seconds between requests"},wait:{alias:"w",type:"boolean",default:!1,description:"Wait instead of error when rate limit is hit. Has no effect if rate limit is not set"},"github-token":{alias:"g",type:"string",description:"Provide auth token directly (must be generated using the `auth` subcommand)"},"claude-code":{alias:"c",type:"boolean",default:!1,description:"Generate a command to launch with API config"},codex:{type:"boolean",default:!1,description:"Generate a command to launch Codex CLI with Copilot API config"},model:{alias:"m",type:"string",description:"Model to use (with --claude-code or --codex)"},"small-model":{alias:"s",type:"string",description:"Small/fast model to use (requires --claude-code)"},"show-token":{type:"boolean",default:!1,description:"Show tokens on fetch and refresh"},timeout:{alias:"t",type:"string",description:"API timeout in milliseconds (default: 600000)"},"tavily-api-key":{type:"string",description:"Tavily API key for web search support (or set TAVILY_API_KEY env var)"},"enable-thinking":{type:"boolean",default:!1,description:"Enable forwarding of thinking_budget / Anthropic thinking config to upstream. Off by default to avoid accidentally triggering reasoning behaviour."},"native-anthropic":{type:"boolean",default:!1,description:"Route Claude models directly to Copilot's native /v1/messages endpoint instead of translating through OpenAI format."},https:{type:"boolean",default:!1,description:"Serve over HTTPS using a self-signed certificate (auto-generated and persisted)"},"https-cert":{type:"string",description:"Path to a PEM-encoded TLS certificate (use with --https-key to bring your own cert)"},"https-key":{type:"string",description:"Path to a PEM-encoded TLS private key (use with --https-cert to bring your own cert)"},"https-hosts":{type:"string",description:"Extra hostnames or IPs to include in the self-signed cert's SANs (comma-separated). Example: --https-hosts host.docker.internal,192.168.1.42"},"claude-cowork":{type:"boolean",default:!1,description:"Print Claude Cowork-specific setup hints (inference endpoint URLs to paste into Cowork's apiHost setting)"}},run({args:e}){let t=e["rate-limit"],o=void 0===t?void 0:Mr(t,"--rate-limit"),n=e.timeout,r=void 0===n?V:Mr(n,"--timeout"),i=e["https-hosts"],a=i?i.split(",").map(e=>e.trim()).filter(Boolean):[];return Dr({port:Mr(e.port,"--port"),verbose:e.verbose,accountType:e["account-type"],manual:e.manual,rateLimit:o,rateLimitWait:e.wait,_t2:e["github-token"],_cc1:e["claude-code"],codex:e.codex,model:e.model,smallModel:e["small-model"],showToken:e["show-token"],timeout:r,tavilyApiKey:e["tavily-api-key"]||f.env.TAVILY_API_KEY,enableThinking:e["enable-thinking"],nativeAnthropic:e["native-anthropic"],https:e.https,httpsCert:e["https-cert"],httpsKey:e["https-key"],httpsHosts:a,claudeCowork:e["claude-cowork"]})}});await async function(){try{if("1"===process.env.COPILOT_API_SKIP_UPDATE_CHECK)return;let[e,t]=await Promise.all([Xt(),ao()]);if("unknown"===e||!t||!function(e,t){let o=e.split(".").map(Number),n=t.split(".").map(Number),r=Math.max(o.length,n.length);for(let e=0;e<r;e++){let t=o[e]??0,r=n[e]??0;if(t<r)return!0;if(t>r)return!1}return!1}(e,t))return;!function(e,t){let o=`npx ${oo}@latest`,n=io("│"),r=` ${ro("Update available!")} ${(e=>`[2m${e}[0m`)(e)} → ${(e=>`[32m${e}[0m`)(t)}`,i=` Run ${ro(o)} to update`,a=" ".repeat(54),s=io(`╭${"─".repeat(54)}╮`),l=io(`╰${"─".repeat(54)}╯`),c=["",s,`${n}${a}${n}`,`${n}${so(r,54)}${n}`,`${n}${a}${n}`,`${n}${so(i,54)}${n}`,`${n}${a}${n}`,l,""];console.log(c.join("\n"))}(e,t)}catch{}}(),await t(e({meta:{name:"copilot-api",description:"API proxy server for tool integration."},subCommands:{auth:Tt,start:Fr,"check-usage":St,debug:to,"cowork-setup":Yt}}));export{};
|
|
2
|
+
import{defineCommand as e,runMain as t}from"citty";import o from"consola";import n from"node:fs/promises";import r from"node:os";import a from"node:path";import{SpanKind as i,SpanStatusCode as s,context as l,metrics as c,trace as u}from"@opentelemetry/api";import p from"clipboardy";import{execFile as d,execSync as m}from"node:child_process";import f from"node:process";import{SeverityNumber as h,logs as g}from"@opentelemetry/api-logs";import{OTLPLogExporter as _}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as y}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as k}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as w}from"@opentelemetry/resources";import{BatchLogRecordProcessor as b}from"@opentelemetry/sdk-logs";import{PeriodicExportingMetricReader as v}from"@opentelemetry/sdk-metrics";import{NodeSDK as x}from"@opentelemetry/sdk-node";import{ATTR_SERVICE_INSTANCE_ID as $,ATTR_SERVICE_NAME as T,ATTR_SERVICE_VERSION as A}from"@opentelemetry/semantic-conventions";import{Client as S,request as C}from"undici";import{createHash as O,randomBytes as E,randomUUID as I}from"node:crypto";import{promisify as P}from"node:util";import{accessSync as N}from"node:fs";import{serve as q}from"srvx";import{isIP as R}from"node:net";import{generate as j}from"selfsigned";import{Hono as D}from"hono";import{cors as M}from"hono/cors";import{streamSSE as H}from"hono/streaming";import{events as F}from"fetch-event-stream";import{Tokenizer as B,models as L}from"ai-tokenizer";import*as U from"ai-tokenizer/encoding/claude";const J=a.join(r.homedir(),".local","share","copilot-api"),G={APP_DIR:J,GITHUB_TOKEN_PATH:a.join(J,"github_token"),MACHINE_ID_PATH:a.join(J,"machine_id"),SESSION_ID_PATH:a.join(J,"session_id")};async function K(){await n.mkdir(G.APP_DIR,{recursive:!0}),await W(G.GITHUB_TOKEN_PATH),await W(G.SESSION_ID_PATH)}async function W(e){try{await n.access(e,n.constants.W_OK)}catch{await n.writeFile(e,""),await n.chmod(e,384)}}const z=6e5,V={accountType:"individual",manualApprove:!1,rateLimitWait:!1,showToken:!1,thinkingEnabled:!1,nativeAnthropicEnabled:!1,timeoutMs:z,connectivity:{probeEndpoints:["https://api.github.com","https://www.google.com","https://1.1.1.1"],fastProbeInterval:5e3,slowProbeInterval:1e4,timeoutMs:5e3,jitterMaxMs:1e3,connectionPooling:!0,dnsCache:!0,h2:!1,h2Keepalive:!1}},Y=e=>e>=1e5||e>=1e4?`${Math.round(e/1e3)}K`:e>=1e3?`${(e/1e3).toFixed(1)}K`:e.toString(),X=(e,t)=>e.padEnd(t),Q=e=>{let t=[];if(e.model){let o=X(e.model,18);t.push(o)}if(e.tokenUsage){let o=e.tokenUsage,n=(o.inputTokens||0)+(o.outputTokens||0),r=e.model?((e,t)=>{if(!V.models)return"";let o=V.models.data.find(e=>e.id===t);if(!o)return"";let n=o.capabilities.limits?.max_context_window_tokens;return n?` (${(e/n*100).toFixed(1)}%)`:""})(n,e.model):"",a=X(`↑${Y(o.inputTokens||0).padStart(5)} │ ↓${Y(o.outputTokens||0).padStart(5)}`,18),i=Y(n),s=r?`${i}${r.padStart(15-i.length)}`:i.padEnd(15);t.push(`Tokens: ${a} | Context: ${s}`)}else if(e.model){let e=X("N/A",18),o="N/A".padEnd(15);t.push(`Tokens: ${e} | Context: ${o}`)}if(e._d1){let o=X(`${Math.round(e._d1)}ms`,8);t.push(`API: ${o}`)}return t.length>0?` | ${t.join(" | ")}`:""},Z={completionCallbacks:new Map,registerCompletion(e,t,o){this.completionCallbacks.set(e,{context:t,startTime:o,requestId:e})},executeCompletion(e){let t=this.completionCallbacks.get(e);t&&(this.logCompletion(t),this.completionCallbacks.delete(e))},logCompletion(e){let{context:t,startTime:n}=e,r=Date.now()-n,a=t.get("requestData"),i=` --\x3e ${X(t.req.method,4)}${X(t.req.path,21)}${X(t.res.status.toString(),3)} ${X(`${r}ms`,8)}`;a&&(i+=Q(a)),o.info(i),je(h.INFO,"INFO","Request completed",{"http.method":t.req.method,"http.path":t.req.path,"http.status_code":t.res.status,"copilot_api.duration_ms":r,...a?.model&&{"copilot_api.model":a.model},...a?._d1&&{"copilot_api.copilot_duration_ms":Math.round(a._d1)},...a?.tokenUsage?.inputTokens&&{"copilot_api.input_tokens":a.tokenUsage.inputTokens},...a?.tokenUsage?.outputTokens&&{"copilot_api.output_tokens":a.tokenUsage.outputTokens}},t.get("requestTraceContext"))},logRateLimit(e,t){let{context:n,startTime:r}=e,a=Date.now()-r,i=(t.headers.get("x-ratelimit-exceeded")||"").split(":")[1]||"unknown",s=t.headers.get("retry-after")||t.headers.get("x-ratelimit-user-retry-after")||"?",l=`⚠ --\x3e ${X(n.req.method,4)}${X(n.req.path,21)}${X("429",3)} ${X(`${a}ms`,8)}`;l+=` | Rate limited (${s}s retry) | ${i}`;let c=n.get("requestData");if(c?._d1){l+=` | API: ${X(`${Math.round(c._d1)}ms`,8)}`}o.info(l)},cleanup(){let e=Date.now()-3e5;for(let[t,o]of this.completionCallbacks)o.startTime<e&&this.completionCallbacks.delete(t);if(this.completionCallbacks.size>1e3){let e=Array.from(this.completionCallbacks.entries()).sort(([,e],[,t])=>e.startTime-t.startTime),t=e.slice(0,e.length-1e3);for(let[e]of t)this.completionCallbacks.delete(e)}}};setInterval(()=>Z.cleanup(),6e4);let ee,te,oe=Date.now();const ne={"x-honeycomb-team":"hcaik_01km2y7yf1rrn70xvxce5kx9dyz936dwm21b9bgvnwf3pxq0cmqkcwha8n"};function re(){let e=process.env.OTEL_EXPORTER_OTLP_ENDPOINT??"https://api.honeycomb.io",t=process.env.OTEL_EXPORTER_OTLP_HEADERS?function(e){return e?Object.fromEntries(e.split(",").map(e=>e.trim()).filter(Boolean).map(e=>{let t=e.indexOf("=");return-1===t?[e,""]:[decodeURIComponent(e.slice(0,t)),decodeURIComponent(e.slice(t+1))]})):{}}(process.env.OTEL_EXPORTER_OTLP_HEADERS):ne;return{endpoint:e.replace(/\/$/,""),headers:t}}const ae=u.getTracer("copilot-api"),ie=c.getMeter("copilot-api"),se=g.getLogger("copilot-api"),le=ie.createCounter("copilot_api.requests.total",{unit:"{request}",description:"Total requests received"}),ce=ie.createCounter("copilot_api.requests.errors",{unit:"{error}",description:"Total error responses"}),ue=ie.createCounter("copilot_api.tokens.input",{unit:"{token}",description:"Total input tokens consumed"}),pe=ie.createCounter("copilot_api.tokens.output",{unit:"{token}",description:"Total output tokens generated"}),de=ie.createCounter("copilot_api.tokens.cached",{unit:"{token}",description:"Total cached prompt tokens"}),me=ie.createCounter("copilot_api.rate_limit.triggers",{unit:"{trigger}",description:"Rate limit trigger count"}),fe=ie.createCounter("copilot_api.model_validation.errors",{unit:"{error}",description:"Model validation failures"}),he=ie.createCounter("copilot_api.model_mapping.mappings",{unit:"{mapping}",description:"Model name normalizations"}),ge=ie.createCounter("copilot_api.token_refresh.attempts",{unit:"{attempt}",description:"Token refresh attempts"}),_e=ie.createCounter("copilot_api.token_refresh.failures",{unit:"{failure}",description:"Token refresh final failures"}),ye=ie.createCounter("copilot_api.connectivity.checks",{unit:"{check}",description:"Connectivity probe results"}),ke=ie.createCounter("copilot_api.connectivity.transitions",{unit:"{transition}",description:"Connectivity state transitions"}),we=ie.createCounter("copilot_api.upstream.requests",{unit:"{request}",description:"Upstream API calls"}),be=ie.createCounter("copilot_api.stream.chunks",{unit:"{chunk}",description:"Total SSE chunks sent"}),ve=ie.createCounter("copilot_api.approval.decisions",{unit:"{decision}",description:"Manual approval decisions"}),xe=ie.createCounter("copilot_api.h2_keepalive.pings",{unit:"{ping}",description:"HTTP/2 keepalive pings sent"}),$e=ie.createCounter("copilot_api.h2.connections",{unit:"{connection}",description:"HTTP/2 connection lifecycle events"}),Te=ie.createHistogram("copilot_api.request.duration",{unit:"ms",description:"Total request duration"}),Ae=ie.createHistogram("copilot_api.copilot.duration",{unit:"ms",description:"Upstream Copilot API call duration"}),Se=ie.createHistogram("copilot_api.stream.duration",{unit:"ms",description:"Duration of SSE streaming phase"}),Ce=ie.createHistogram("copilot_api.rate_limit.wait_duration",{unit:"ms",description:"Duration of rate limit waits"}),Oe=ie.createHistogram("copilot_api.translation.duration",{unit:"ms",description:"Translation layer processing time"}),Ee=ie.createHistogram("copilot_api.token_refresh.duration",{unit:"ms",description:"Token refresh duration"}),Ie=ie.createHistogram("copilot_api.connectivity.probe_duration",{unit:"ms",description:"Individual connectivity probe duration"}),Pe=ie.createHistogram("copilot_api.tokens.per_request.input",{unit:"{token}",description:"Input tokens per request distribution"}),Ne=ie.createHistogram("copilot_api.tokens.per_request.output",{unit:"{token}",description:"Output tokens per request distribution"}),qe=ie.createHistogram("copilot_api.stream.chunks_per_request",{unit:"{chunk}",description:"Chunks per streaming request"}),Re=ie.createHistogram("copilot_api.approval.wait_duration",{unit:"ms",description:"Time waiting for manual approval"});function je(e,t,o,n,r){let a=u.getActiveSpan()?.spanContext()??r;se.emit({severityNumber:e,severityText:t,body:o,attributes:{...n,...a&&{"trace.id":a.traceId,"span.id":a.spanId}}})}function De(e,t,o){let n=t instanceof Error?t:Error(String(t));e.setStatus({code:s.ERROR,message:o??n.message}),e.recordException(n)}function Me(e,t,o){De(e,o),t&&t!==e&&De(t,o)}function He(e,t=""){let o={};if(null==e)return o;if("object"!=typeof e)return("string"==typeof e||"number"==typeof e||"boolean"==typeof e)&&t&&(o[t]=e),o;if(Array.isArray(e))return t&&(o[t]=JSON.stringify(e)),o;for(let[n,r]of Object.entries(e)){let e=t?`${t}.${n}`:n;void 0===r||"function"==typeof r||(null===r?o[e]="null":"object"!=typeof r||Array.isArray(r)?Array.isArray(r)?o[e]=JSON.stringify(r):("string"==typeof r||"number"==typeof r||"boolean"==typeof r)&&(o[e]=r):Object.assign(o,He(r,e)))}return o}ie.createObservableGauge("copilot_api.connectivity.status",{unit:"{status}",description:"1 = online, 0 = offline"}).addCallback(e=>{e.observe(Je.getConnectivityStats().isOnline?1:0)}),ie.createObservableGauge("copilot_api.connectivity.consecutive_failures",{unit:"{failure}",description:"Current consecutive connectivity failure count"}).addCallback(e=>{e.observe(Je.getConnectivityStats().consecutiveFailures)}),ie.createObservableGauge("copilot_api.models.available",{unit:"{model}",description:"Number of available models"}).addCallback(e=>{e.observe(V.models?.data.length??0)}),ie.createObservableGauge("copilot_api.completion_logger.pending",{unit:"{callback}",description:"Number of pending completion callbacks"}).addCallback(e=>{e.observe(Z.completionCallbacks.size)}),ie.createObservableGauge("copilot_api.uptime",{unit:"s",description:"Server uptime in seconds"}).addCallback(e=>{e.observe((Date.now()-oe)/1e3)});const Fe=new Set(["authorization","cookie","set-cookie","x-honeycomb-team","x-api-key","proxy-authorization"]);function Be(e,t,o){for(let[n,r]of Object.entries(o)){let o=n.toLowerCase();Fe.has(o)||e.setAttribute(`http.${t}.header.${o}`,r)}}async function Le(e){let{spanName:t,url:o,target:n,method:r="GET",headers:a,body:l,signal:c,extraAttributes:u}=e,p=ae.startSpan(t,{kind:i.CLIENT,attributes:{"http.method":r,"url.full":o,"copilot_api.target":n,...u}});a&&Be(p,"request",a);try{let e=await fetch(o,{method:r,headers:a,body:l,signal:c});return p.setAttribute("http.response.status_code",e.status),function(e,t){t.headers.forEach((t,o)=>{let n=o.toLowerCase();Fe.has(n)||e.setAttribute(`http.response.header.${n}`,t)})}(p,e),we.add(1,{target:n,status_code:String(e.status)}),e.ok||p.setStatus({code:s.ERROR,message:`HTTP ${e.status}`}),{response:e,span:p}}catch(e){throw De(p,e),p.end(),e}}async function Ue(e){let{spanName:t,url:o,target:n,method:r="POST",headers:a,body:l,signal:c,headersTimeout:u,bodyTimeout:p,extraAttributes:d,dispatcher:m}=e,f=ae.startSpan(t,{kind:i.CLIENT,attributes:{"http.method":r,"url.full":o,"copilot_api.target":n,"copilot_api.h2.enabled":void 0!==m,...d}});Be(f,"request",a);try{let{statusCode:e,headers:t,body:i}=await C(o,{method:r,headers:a,body:l,signal:c,headersTimeout:u,bodyTimeout:p,dispatcher:m});f.setAttribute("http.response.status_code",e);for(let[e,o]of Object.entries(t)){let t=e.toLowerCase();void 0!==o&&!Fe.has(t)&&f.setAttribute(`http.response.header.${t}`,Array.isArray(o)?o.join(", "):o)}return we.add(1,{target:n,status_code:String(e)}),e>=400&&f.setStatus({code:s.ERROR,message:`HTTP ${e}`}),{statusCode:e,headers:t,body:i,span:f}}catch(e){throw De(f,e),f.end(),e}}const Je=new class extends EventTarget{isOnline=!0;lastChecked=(new Date).toISOString();consecutiveFailures=0;lastErrorType;lastErrorMessage;lastSuccessfulEndpoint;endpointFailureStats={};checkInterval;abortController;on(e,t){return this.addEventListener(e,t),this}off(e,t){return this.removeEventListener(e,t),this}start(){o.debug("Starting connectivity monitor",{probeEndpoints:V.connectivity.probeEndpoints,fastInterval:V.connectivity.fastProbeInterval}),this.scheduleNextCheck()}stop(){o.debug("Stopping connectivity monitor"),this.checkInterval&&=void clearTimeout(this.checkInterval),this.abortController&&=void this.abortController.abort()}scheduleNextCheck(){this.checkInterval&&clearTimeout(this.checkInterval);let e=(this.isOnline?V.connectivity.slowProbeInterval:V.connectivity.fastProbeInterval)+Math.random()*V.connectivity.jitterMaxMs;this.checkInterval=setTimeout(()=>{this.performConnectivityCheck().catch(e=>{o.error("Connectivity check failed:",e)})},e)}async performConnectivityCheck(){let e=ae.startSpan("copilot_api.connectivity.probe");this.abortController=new AbortController;let t=setTimeout(()=>this.abortController?.abort(),V.connectivity.timeoutMs);try{let n=!1;for(let e of V.connectivity.probeEndpoints)try{let t=performance.now(),o=await fetch(e,{method:"HEAD",signal:this.abortController.signal,headers:{"User-Agent":"copilot-api-connectivity-monitor/1.0",...V.connectivity.dnsCache&&{"Cache-Control":"max-age=300"}}}),r=performance.now()-t;if(o.ok){n=!0,this.lastSuccessfulEndpoint=e,Ie.record(r,{endpoint:e,result:"success"});break}Ie.record(r,{endpoint:e,result:"failed"})}catch(t){this.endpointFailureStats[e]=(this.endpointFailureStats[e]||0)+1,o.debug(`Probe failed for ${e}:`,t)}this.updateConnectivityState(n);let r=n?"online":"offline";e.setAttribute("copilot_api.connectivity.result",r),e.setAttribute("copilot_api.connectivity.consecutive_failures",this.consecutiveFailures),this.lastSuccessfulEndpoint&&e.setAttribute("copilot_api.connectivity.successful_endpoint",this.lastSuccessfulEndpoint),ye.add(1,{result:n?"online":"offline"})}catch(e){this.handleConnectivityError(e)}finally{clearTimeout(t),e.end(),this.scheduleNextCheck()}}updateConnectivityState(e){let t=this.isOnline;if(this.isOnline=e,this.lastChecked=(new Date).toISOString(),e){let e=this.consecutiveFailures;this.consecutiveFailures>0&&o.info(`Connectivity restored after ${this.consecutiveFailures} failures`),this.consecutiveFailures=0,this.lastErrorType=void 0,this.lastErrorMessage=void 0,t||(this.dispatchEvent(new CustomEvent("online")),ke.add(1,{from:"offline",to:"online"}),je(h.INFO,"INFO","Connectivity restored",{"copilot_api.connectivity.consecutive_failures_before_recovery":e}))}else this.consecutiveFailures++,t&&(o.warn("Connectivity lost"),this.dispatchEvent(new CustomEvent("offline")),ke.add(1,{from:"online",to:"offline"}),je(h.WARN,"WARN","Connectivity lost",{"copilot_api.connectivity.consecutive_failures":this.consecutiveFailures}))}handleConnectivityError(e){this.lastErrorType=e.name,this.lastErrorMessage=e.message,o.error("Connectivity check failed:",e),this.updateConnectivityState(!1)}getConnectivityStats(){return{isOnline:this.isOnline,lastChecked:this.lastChecked,consecutiveFailures:this.consecutiveFailures,lastErrorType:this.lastErrorType,lastErrorMessage:this.lastErrorMessage}}getPerformanceStats(){let e=this.isOnline?V.connectivity.slowProbeInterval:V.connectivity.fastProbeInterval;return{currentInterval:e,nextCheckEstimate:new Date(Date.now()+e+Math.random()*V.connectivity.jitterMaxMs).toISOString(),lastSuccessfulEndpoint:this.lastSuccessfulEndpoint,endpointFailureStats:{...this.endpointFailureStats},jitterEnabled:V.connectivity.jitterMaxMs>0,connectionPooling:V.connectivity.connectionPooling,dnsCache:V.connectivity.dnsCache}}},Ge=()=>({"content-type":"application/json",accept:"application/json"}),Ke="0.43.2026040705",We=`copilot-chat/${Ke}`,ze=`GitHubCopilotChat/${Ke}`,Ve=async e=>{let t=(e=>{let t=e.replaceAll(/[^\w.-]/g,"_").trim();if(0===t.length||"."===t||".."===t||/^[_.]+$/.test(t))throw Error("Invalid GitHub username: cannot be empty or consist only of special characters after sanitization");return`${G.MACHINE_ID_PATH}_${t}`})(e);try{let e=await n.readFile(t,"utf8");if(e.trim())return e.trim()}catch{}let o=(e=>{let t=O("sha256");return t.update(process.platform),t.update(process.arch),t.update(process.env.USER||process.env.USERNAME||"anonymous"),t.update(r.hostname()),t.update(e),t.update(Date.now().toString()),t.update(E(16)),t.digest("hex")})(e);return await n.writeFile(t,o),await n.chmod(t,384),o},Ye=async(e,t)=>{e.machineId||=await Ve(t),e.sessionId||=await(async()=>{try{let e=await n.readFile(G.SESSION_ID_PATH,"utf8");if(e.trim())return e.trim()}catch{}let e=I();return await n.writeFile(G.SESSION_ID_PATH,e),await n.chmod(G.SESSION_ID_PATH,384),e})()},Xe=e=>"individual"===e.accountType?"https://api.githubcopilot.com":`https://api.${e.accountType}.githubcopilot.com`,Qe=(e,t=!1)=>{if(!e.machineId||!e.sessionId)throw Error("VSCode identifiers not initialized. Call initializeVSCodeIdentifiers() during startup.");let o=I(),n={Authorization:`Bearer ${e._t1}`,"Content-Type":"application/json",accept:"*/*","accept-encoding":"br, gzip, deflate","accept-language":"*","sec-fetch-mode":"cors","Copilot-Integration-Id":"vscode-chat","Editor-Version":`vscode/${e._v1}`,"Editor-Plugin-Version":We,"User-Agent":ze,"VScode-MachineId":e.machineId,"VScode-SessionId":e.sessionId,"OpenAI-Intent":"conversation-agent","X-Interaction-Type":"conversation-agent","X-Agent-Task-Id":o,"X-VSCode-User-Agent-Library-Version":"node-fetch","X-GitHub-Api-Version":"2025-05-01","X-Interaction-Id":I(),"X-Request-Id":o};return t&&(n["copilot-vision-request"]="true"),n},Ze=["interleaved-thinking","context-management","advanced-tool-use"];const et=(e,t)=>{let o=Qe(e);if(delete o["Copilot-Integration-Id"],o["anthropic-version"]=t?.anthropicVersion??"2023-06-01",t?.anthropicBeta){let e=function(e){let t=e.split(",").map(e=>e.trim()).filter(e=>e&&Ze.some(t=>e.startsWith(`${t}-`)));return t.length>0?t.join(","):void 0}(t.anthropicBeta);e&&(o["anthropic-beta"]=e)}return o},tt="https://api.github.com",ot=e=>({"content-type":"application/json",accept:"application/json",authorization:`token ${e._t2}`,"editor-version":`vscode/${e._v1}`,"editor-plugin-version":We,"user-agent":ze,"x-github-api-version":"2025-04-01","x-vscode-user-agent-library-version":"node-fetch"}),nt="https://github.com",rt="01ab8ac9400c4e429b23",at=["user:email"].join(" ");var it=class extends Error{response;constructor(e,t){super(e),this.response=t}};function st(e){return e.req.path.startsWith("/v1/messages")}function lt(e,t){if(st(t)){try{let t=JSON.parse(e);if("message"in t&&"string"==typeof t.message&&!("error"in t))return{type:"error",error:{type:"invalid_request_error",message:t.message}};if("error"in t&&"object"==typeof t.error){let e=t.error;return{type:"error",error:{type:"string"==typeof e.type&&e.type||"api_error",message:"string"==typeof e.message&&e.message||"Unknown error"}}}}catch{}return{type:"error",error:{type:"api_error",message:e}}}try{return JSON.parse(e)}catch{return{error:{message:e,type:"error"}}}}async function ct(e,t){let n=u.getActiveSpan();if(t instanceof it&&429===t.response.status){let o=e.get("requestId"),r=Z.completionCallbacks.get(o);r&&(Z.logRateLimit(r,t.response),Z.completionCallbacks.delete(o)),me.add(1,{action:"rejected",source:"upstream"});let a=lt(await t.response.text(),e);return n?.setStatus({code:s.ERROR,message:"Rate limited by upstream"}),n?.setAttribute("copilot_api.error_type","rate_limit_upstream"),je(h.WARN,"WARN","Upstream rate limit hit",{"copilot_api.status_code":429,"http.path":e.req.path,"copilot_api.error_type":"rate_limit_upstream"}),e.json(a,429)}if(o.error("Error occurred:",t),t instanceof it){let r=lt(await t.response.text(),e);return o.error("HTTP error:",r),n?.setStatus({code:s.ERROR,message:t.message}),n?.recordException(t),n?.setAttribute("copilot_api.error_type","HTTPError"),je(h.ERROR,"ERROR",`HTTP error: ${t.message}`,{"copilot_api.status_code":t.response.status,"http.path":e.req.path,"copilot_api.error_type":"HTTPError"}),e.json(r,t.response.status)}let r=t instanceof Error?t:Error(String(t));n?.setStatus({code:s.ERROR,message:r.message}),n?.recordException(r),n?.setAttribute("copilot_api.error_type",r.name),je(h.ERROR,"ERROR",`Unhandled error: ${r.message}`,{"copilot_api.status_code":500,"http.path":e.req.path,"copilot_api.error_type":r.name});let a=st(e)?{type:"error",error:{type:"api_error",message:r.message}}:{error:{message:r.message,type:"error"}};return e.json(a,500)}const ut=async()=>{let e=`${tt}/copilot_internal/v2/token`,t=V.timeoutMs,o=new AbortController,n=setTimeout(()=>o.abort(),t);try{let{response:t,span:n}=await Le({spanName:"github GET /copilot_internal/v2/token",url:e,target:"copilot_token",headers:ot(V),signal:o.signal});try{if(!t.ok)throw new it("Failed to get Service token",t);return await t.json()}catch(e){throw De(n,e),e}finally{n.end()}}finally{clearTimeout(n)}};async function pt(){let e=`${tt}/user`,t=V.timeoutMs,o=new AbortController,n=setTimeout(()=>o.abort(),t);try{let{response:t,span:n}=await Le({spanName:"github GET /user",url:e,target:"github_user",headers:{authorization:`token ${V._t2}`,"content-type":"application/json",accept:"application/json"},signal:o.signal});try{if(!t.ok)throw new it("Failed to get GitHub user",t);return await t.json()}catch(e){throw De(n,e),e}finally{n.end()}}finally{clearTimeout(n)}}const dt=e=>new Promise(t=>{setTimeout(t,e)}),mt=e=>null==e;async function ft(){V.models=await(async()=>{let e=`${Xe(V)}/models`,t=Qe(V),o=V.timeoutMs,n=new AbortController,r=setTimeout(()=>n.abort(),o);try{let{response:o,span:r}=await Le({spanName:"copilot GET /models",url:e,target:"models",headers:t,signal:n.signal});try{if(!o.ok)throw new it("Failed to get models",o);let e=await o.json();return r.setAttribute("copilot_api.models_count",e.data.length),e}catch(e){throw De(r,e),e}finally{r.end()}}finally{clearTimeout(r)}})()}var ht=class extends Error{constructor(e){super(e),this.name="AuthorizationError"}};let gt,_t,yt,kt=!1;const wt=()=>n.readFile(G.GITHUB_TOKEN_PATH,"utf8"),bt=e=>n.writeFile(G.GITHUB_TOKEN_PATH,e);const vt=async()=>{let{token:e,refresh_in:t}=await ut();V._t1=e,o.debug("Service token fetched successfully!"),V.showToken&&o.info("Service token:",e);let n=async(e=5,t=1e3,n="scheduled")=>{if(!kt)return kt=!0,ae.startActiveSpan("copilot_api.token.refresh",async r=>{let a=performance.now();r.setAttribute("copilot_api.token_refresh.reason",n),r.setAttribute("copilot_api.token_refresh.max_retries",e);try{for(let i=1;i<=e;i++)try{r.setAttribute("copilot_api.token_refresh.attempt",i),o.debug(`Refreshing Service token (${n}, attempt ${i}/${e})`);let{token:t}=await ut();return V._t1=t,o.debug("Service token refreshed successfully"),V.showToken&&o.info("Refreshed Service token:",t),r.setAttribute("copilot_api.token_refresh.success",!0),ge.add(1,{reason:n,success:"true"}),Ee.record(performance.now()-a,{reason:n}),void je(h.INFO,"INFO",`Token refreshed successfully (${n})`,{"copilot_api.token_refresh.reason":n,"copilot_api.token_refresh.attempt":i})}catch(l){let c=i===e;if(o.error(`Failed to refresh Service token (attempt ${i}/${e}):`,l),ge.add(1,{reason:n,success:"false"}),c){o.error("All refresh attempts failed. May be unavailable until next scheduled refresh.");let t=l instanceof Error?l:Error(String(l));return r.setAttribute("copilot_api.token_refresh.success",!1),r.setStatus({code:s.ERROR,message:t.message}),r.recordException(t),_e.add(1,{reason:n}),Ee.record(performance.now()-a,{reason:n}),void je(h.ERROR,"ERROR",`Token refresh failed after ${e} attempts (${n})`,{"copilot_api.token_refresh.reason":n,"copilot_api.token_refresh.attempts":e})}let u=t*2**(i-1);o.debug(`Retrying token refresh in ${u}ms...`),await new Promise(e=>setTimeout(e,u))}}finally{r.end(),kt=!1}});o.debug("Refresh already in progress, skipping")};gt=setInterval(()=>{n(5,1e3,"scheduled").catch(e=>{o.error("Unexpected error in scheduled token refresh:",e)})},1e3*(t-60)),Je.start(),_t=()=>{o.debug("Network connectivity restored, attempting immediate token refresh"),n(3,500,"network-restored").catch(e=>{o.error("Unexpected error in network-restored token refresh:",e)})},yt=()=>{o.debug("Network connectivity lost")},Je.on("online",_t),Je.on("offline",yt)};async function xt(e){try{let t=await wt();if(t&&!e?.force)return V._t2=t,V.showToken&&o.info("Auth token:",t),void await $t();o.info("Authentication required");let n=await async function(){let e=new AbortController,t=V.timeoutMs,o=setTimeout(()=>{e.abort()},t);try{let t=await fetch(`${nt}/login/device/code`,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify({client_id:rt,scope:at}),signal:e.signal});if(!t.ok)throw new it("Failed to get device code",t);return await t.json()}finally{clearTimeout(o)}}();o.debug("Device code response:",n),o.info(`Please enter the code "${n.user_code}" at ${n.verification_uri}`);try{p.writeSync(n.user_code),o.success("Code copied to clipboard — opening browser...")}catch{o.info("Open the link above and enter the code to authenticate")}!function(e){try{let t,o=f.platform;t="darwin"===o?"open":"win32"===o?"start":"xdg-open",d(t,[e],()=>{})}catch{}}(n.verification_uri);let r=await async function(e){let t=1e3*(e.interval+1);o.debug(`Polling access token with interval of ${t}ms`),o.start("Waiting for authorization...");let n=Date.now(),r=1e3*e.expires_in;for(;;){if(Date.now()-n>=r)throw new ht("Authorization timed out — the code expired. Please run the command again.");let a=new AbortController,i=V.timeoutMs,s=setTimeout(()=>{a.abort()},i);try{let n=await fetch(`${nt}/login/oauth/access_token`,{method:"POST",headers:Ge(),body:JSON.stringify({client_id:rt,device_code:e.device_code,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}),signal:a.signal});if(!n.ok){await dt(t),o.error("Failed to poll access token:",await n.text());continue}let r=await n.json();if(o.debug("Polling access token response:",r),r.error){if("expired_token"===r.error)throw new ht("Authorization timed out — the code expired. Please run the command again.");if("access_denied"===r.error)throw new ht("Authorization was denied. Please run the command again and approve the request.");"authorization_pending"!==r.error&&"slow_down"!==r.error&&o.warn(`Unexpected auth error: ${r.error}`),await dt(t);continue}if(r.access_token)return r.access_token;await dt(t)}catch(e){if(e instanceof ht)throw e;if(e instanceof Error&&"AbortError"===e.name){o.error("Access token polling timed out"),await dt(t);continue}throw e}finally{clearTimeout(s)}}}(n);await bt(r),V._t2=r,V.showToken&&o.info("Auth token:",r),await $t()}catch(e){throw e instanceof it?(o.error("Failed to get Auth token:",await e.response.json()),e):(o.error("Failed to get Auth token:",e),e)}}async function $t(){let e=await pt();o.success(`Authenticated as ${e.login}`)}async function Tt(e){e.verbose&&(o.level=5,o.info("Verbose logging enabled")),V.showToken=e.showToken,await K(),await xt({force:!0}),console.log([""," Get started:",""," $ npx copilot-api-node20@latest start --claude-code"," $ npx copilot-api-node20@latest start --codex",""," Full docs: https://www.npmjs.com/package/copilot-api-node20",""].join("\n")),process.exit(0)}const At=e({meta:{name:"auth",description:"Run authentication flow"},args:{verbose:{alias:"v",type:"boolean",default:!1,description:"Enable verbose logging"},"show-token":{type:"boolean",default:!1,description:"Show token on auth"}},run:({args:e})=>Tt({verbose:e.verbose,showToken:e["show-token"]})}),St=async()=>{let e=`${tt}/copilot_internal/user`,t=V.timeoutMs,o=new AbortController,n=setTimeout(()=>o.abort(),t);try{let{response:t,span:n}=await Le({spanName:"github GET /copilot_internal/user",url:e,target:"usage",headers:ot(V),signal:o.signal});try{if(!t.ok)throw new it("Failed to get usage",t);return await t.json()}catch(e){throw De(n,e),e}finally{n.end()}}finally{clearTimeout(n)}},Ct=e({meta:{name:"check-usage",description:"Show current usage/quota information"},async run(){await K(),await xt();try{let e=await St(),t=e.quota_snapshots.premium_interactions,n=t.entitlement,r=n-t.remaining,a=n>0?r/n*100:0,i=t.percent_remaining;function s(e,t){if(!t)return`${e}: N/A`;let o=t.entitlement,n=o-t.remaining,r=o>0?n/o*100:0,a=t.percent_remaining;return`${e}: ${n}/${o} used (${r.toFixed(1)}% used, ${a.toFixed(1)}% remaining)`}let l=`Premium: ${r}/${n} used (${a.toFixed(1)}% used, ${i.toFixed(1)}% remaining)`,c=s("Chat",e.quota_snapshots.chat),u=s("Completions",e.quota_snapshots.completions);o.box(`Usage (plan: ${e.copilot_plan})\nQuota resets: ${e.quota_reset_date}\n\nQuotas:\n ${l}\n ${c}\n ${u}`)}catch(p){o.error("Failed to fetch usage:",p),process.exit(1)}}}),Ot=P(d);async function Et(){let e="win32"===f.platform?"where.exe":"which";try{return await Ot(e,["tailscale"]),!0}catch{return!1}}async function It(){try{let{stdout:e}=await Ot("tailscale",["status","--self","--json"]);return JSON.parse(e).Self}catch{return}}function Pt(e){return e.replace(/\.$/,"")}async function Nt(){let e=await It();if(e?.Online)return Pt(e.DNSName)}const qt=P(d),Rt=e=>`[1m${e}[0m`,jt=e=>`[2m${e}[0m`,Dt=e=>`[36m${e}[0m`,Mt=e=>`[32m${e}[0m`,Ht=e=>`[31m${e}[0m`,Ft=e=>`[33m${e}[0m`,Bt=jt(" ─────────────────────────────────────────────────────────────"),Lt=a.join(G.APP_DIR,"certs","tailscale"),Ut=a.join(Lt,"cert.pem"),Jt=a.join(Lt,"key.pem"),Gt={certDir:Lt,certPath:Ut,keyPath:Jt};function Kt(){switch(f.platform){case"darwin":return[` ${jt("Install Tailscale for macOS:")}`,` ${Dt("https://tailscale.com/download/mac")}`,` ${jt("(Use the Mac App Store or .pkg download — not brew)")}`,"",` ${jt("After installing, open the Tailscale app and sign in.")}`,` ${jt("Then re-run this command.")}`].join("\n");case"linux":return[` ${jt("Install Tailscale for Linux:")}`,` ${Dt("curl -fsSL https://tailscale.com/install.sh | sh")}`,` ${Dt("sudo tailscale up")}`,` ${jt("or")} ${Dt("https://tailscale.com/download/linux")}`].join("\n");case"win32":return[` ${jt("Install Tailscale for Windows:")}`,` ${Dt("https://tailscale.com/download/windows")}`,"",` ${jt("After installing, open the Tailscale app and sign in.")}`].join("\n");default:return` ${jt("Install Tailscale:")} ${Dt("https://tailscale.com/download")}`}}function Wt(){let e=[` ${Ht("Tailscale is not running.")}`];return"darwin"===f.platform?e.push(` ${jt("Open the Tailscale app from Applications and sign in.")}`,` ${jt("Download:")} ${Dt("https://tailscale.com/download/mac")}`):"win32"===f.platform?e.push(` ${jt("Open the Tailscale app and sign in.")}`,` ${jt("Download:")} ${Dt("https://tailscale.com/download/windows")}`):e.push(` ${jt("Connect with:")} ${Dt("sudo tailscale up")}`),e.push("",` ${jt("Then re-run this command.")}`),e.join("\n")}async function zt(){try{return await n.access(Ut),await n.access(Jt),!0}catch{return!1}}function Vt(e){console.log(""),console.log(Bt),console.log(` ${Rt("Claude Cowork Setup")} ${jt("— Diagnostic")}`),console.log(Bt),console.log("");for(let t of function(e){let t=[];for(let[o,n]of Object.entries(e)){let e;e="ok"===n.status?Mt("✅"):"missing"===n.status?Ht("❌"):Ft("❓");let r=n.detail?jt(` ${n.detail}`):"";t.push(` ${e} ${o}${r}`)}return t}(e))console.log(t);console.log("");let t=Object.values(e).filter(e=>"missing"===e.status);0===t.length?console.log(` ${Mt("All checks passed.")}`):console.log(` ${Ht(`${t.length} issue(s).`)} Run ${Dt("copilot-api cowork-setup install")} to fix.`),console.log("")}const Yt={alias:"y",type:"boolean",default:!1,description:"Skip confirmation prompts (non-interactive mode)"},Xt=e({meta:{name:"cowork-setup",description:"Set up Tailscale-based HTTPS for Claude Cowork to reach the proxy."},subCommands:{doctor:e({meta:{name:"doctor",description:"Diagnose Tailscale + cert status"},async run(){await async function(){let e={},t=await Et();if(e["tailscale-installed"]=t?{status:"ok"}:{status:"missing",detail:"tailscale not found in PATH"},!t)return Vt(e),console.log(""),console.log(Kt()),void console.log("");let o=await It();if(!o||!o.Online)return e["tailscale-running"]={status:"missing",detail:"not connected"},Vt(e),console.log(Wt()),void console.log("");let n=Pt(o.DNSName);e["tailscale-running"]={status:"ok",detail:n};let r=await zt();e["tailscale-cert"]=r?{status:"ok",detail:Ut}:{status:"missing",detail:'Run "copilot-api cowork-setup install" to generate'},r&&(e.ready={status:"ok",detail:`https://${n}:<port>`}),Vt(e)}(),f.exit(0)}}),install:e({meta:{name:"install",description:"Generate a Tailscale TLS certificate for Cowork (interactive, or pass --yes)"},args:{yes:Yt},async run({args:e}){await async function(e){if(console.log(""),console.log(Bt),console.log(` ${Rt("Claude Cowork Setup")} ${jt("— Install")}`),console.log(Bt),console.log(""),!await Et())return console.log(` ${Ht("Tailscale is not installed.")}`),console.log(""),console.log(Kt()),console.log(""),console.log(` ${jt("After installing, run")} ${Dt("tailscale up")} ${jt("to connect, then re-run this command.")}`),void console.log("");let t=await It();if(!t||!t.Online)return console.log(Wt()),void console.log("");let r=Pt(t.DNSName);if(console.log(` ${jt("Tailscale hostname:")} ${Rt(r)}`),console.log(""),console.log(` ${Rt("Generating TLS certificate via Tailscale…")}`),console.log(` ${jt("This requests a real Let's Encrypt cert for your Tailscale hostname.")}`),console.log(` ${Dt(`$ tailscale cert --cert-file ${Ut} --key-file ${Jt} ${r}`)}`),console.log(""),e||await o.prompt("Generate the certificate?",{type:"confirm",initial:!0})){try{await n.mkdir(Lt,{recursive:!0}),o.start("Generating certificate (this may take a few seconds)…"),await qt("tailscale",["cert","--cert-file",Ut,"--key-file",Jt,r]),console.log(` ${Mt("✓ Certificate generated")}`)}catch(e){let t=e instanceof Error?e.message:String(e);return void o.error(`Failed to generate cert: ${t}`)}console.log(""),console.log(Bt),console.log(` ${Rt("Next steps")}`),console.log(Bt),console.log(""),console.log(` ${Rt("1.")} Start the proxy:`),console.log(` ${Dt("copilot-api start --claude-cowork")}`),console.log(""),console.log(` ${Rt("2.")} In Cowork ${jt("→")} Settings ${jt("→")} Inference Provider, set:`),console.log(` ${Rt("inferenceGatewayBaseUrl")} = ${Dt(`https://${r}:<port>`)}`),console.log(` ${jt("(replace <port> with the port you start the proxy on, default 4141)")}`),console.log(""),console.log(` ${Rt("3.")} Restart Cowork ${jt("(Cmd+Q and reopen)")}`),console.log(""),console.log(` ${jt("For Cowork's own configuration docs, see:")}`),console.log(` ${Dt("https://claude.com/docs/cowork/3p/installation")}`),console.log("")}else o.info("Skipped.")}(e.yes),f.exit(0)}}),revert:e({meta:{name:"revert",description:"Remove the generated Tailscale cert files"},args:{yes:Yt},async run({args:e}){await async function(e){if(console.log(""),console.log(Bt),console.log(` ${Rt("Claude Cowork Setup")} ${jt("— Revert")}`),console.log(Bt),console.log(""),!await zt())return console.log(` ${jt("No Tailscale cert found. Nothing to revert.")}`),void console.log("");if(console.log(` ${Rt("Remove Tailscale cert files:")}`),console.log(` ${jt(Ut)}`),console.log(` ${jt(Jt)}`),console.log(""),e||await o.prompt("Delete these files?",{type:"confirm",initial:!0})){try{await n.rm(Lt,{recursive:!0}),console.log(` ${Mt("✓ Cert files removed.")}`)}catch(e){let t=e instanceof Error?e.message:String(e);o.warn(`Could not remove: ${t}`)}console.log(""),console.log(` ${jt("Don't forget to update Cowork's inferenceGatewayBaseUrl setting.")}`),console.log("")}else o.info("Skipped.")}(e.yes),f.exit(0)}})}});async function Qt(){try{let e=new URL("../package.json",import.meta.url).pathname,t=await n.readFile(e);return JSON.parse(t.toString()).version}catch{return"unknown"}}function Zt(){let e=typeof Bun<"u";return{name:e?"bun":"node",version:e?Bun.version:process.version.slice(1),platform:r.platform(),arch:r.arch()}}async function eo(){try{return!!(await n.stat(G.GITHUB_TOKEN_PATH)).isFile()&&(await n.readFile(G.GITHUB_TOKEN_PATH,"utf8")).trim().length>0}catch{return!1}}async function to(e){let t=await async function(){let[e,t]=await Promise.all([Qt(),eo()]);return{version:e,runtime:Zt(),paths:{APP_DIR:G.APP_DIR,GITHUB_TOKEN_PATH:G.GITHUB_TOKEN_PATH},tokenExists:t}}();e.json?function(e){console.log(JSON.stringify(e,null,2))}(t):function(e){o.info(`service debug\n\nVersion: ${e.version}\nRuntime: ${e.runtime.name} ${e.runtime.version} (${e.runtime.platform} ${e.runtime.arch})\n\nPaths:\n- APP_DIR: ${e.paths.APP_DIR}\n- GITHUB_TOKEN_PATH: ${e.paths.GITHUB_TOKEN_PATH}\n\nToken exists: ${e.tokenExists?"Yes":"No"}`)}(t)}const oo=e({meta:{name:"debug",description:"Print debug information about the application"},args:{json:{type:"boolean",default:!1,description:"Output debug information as JSON"}},run:({args:e})=>to({json:e.json})}),no="copilot-api-node20",ro=`https://registry.npmjs.org/${no}/latest`,ao=e=>`[1m${e}[0m`,io=e=>`[33m${e}[0m`;async function so(){let e=new AbortController,t=setTimeout(()=>e.abort(),5e3);"object"==typeof t&&"unref"in t&&t.unref();try{let t=await fetch(ro,{signal:e.signal});return t.ok?(await t.json()).version??null:null}catch{return null}finally{clearTimeout(t)}}function lo(e,t){let o=Math.max(0,t-function(e){return e.replaceAll(/\x1b\[[0-9;]*m/g,"").length}(e));return e+" ".repeat(o)}const co=new Map,uo=new Map,po=new Set;let mo,fo,ho;function go(e){return!e.closed&&!e.destroyed}function _o(e){o.debug(`Creating HTTP/2 client for ${e}`);let t=new S(e,{allowH2:!0,pipelining:0,keepAliveTimeout:6e4,initialWindowSize:4194304,connectionWindowSize:16777216});return co.set(t,Date.now()),$e.add(1,{event:"created",origin:e}),je(h.INFO,"INFO",`HTTP/2 client created for ${e}`,{"copilot_api.h2.event":"created","copilot_api.h2.origin":e}),t.on("connect",()=>{o.debug(`HTTP/2 client connected to ${e}`)}),t.on("error",t=>{o.debug(`HTTP/2 client error for ${e}:`,t.message)}),t.on("disconnect",(n,r,a)=>{o.debug(`HTTP/2 client disconnected from ${e}:`,a.message),$e.add(1,{event:"goaway",origin:e}),je(h.WARN,"WARN",`HTTP/2 client disconnected from ${e}: ${a.message}`,{"copilot_api.h2.event":"goaway","copilot_api.h2.origin":e,"copilot_api.h2.error":a.message}),uo.delete(t),po.delete(t),co.delete(t),go(t)&&t.close().catch(e=>{o.debug("Error closing GOAWAY'd HTTP/2 client:",e)})}),t}function yo(e){if(!V.connectivity.h2)return;mo&&mo!==e&&function(){for(let e of[...uo.keys(),...po])go(e)&&e.close().catch(e=>{o.debug("Error closing HTTP/2 pool entry:",e)});uo.clear(),po.clear(),co.clear()}(),mo=e;let t=Date.now();for(let[n]of uo)if(t-(co.get(n)??0)>=6e5)uo.delete(n),co.delete(n),go(n)&&n.close().catch(e=>{o.debug("Error closing rotated HTTP/2 client:",e)}),$e.add(1,{event:"rotated",origin:e}),je(h.INFO,"INFO",`HTTP/2 client rotated for ${e} (max lifetime reached)`,{"copilot_api.h2.event":"rotated","copilot_api.h2.origin":e});else{if(go(n))return uo.delete(n),po.add(n),n;uo.delete(n),co.delete(n)}let n=_o(e);return po.add(n),n}function ko(e){e&&po.delete(e)&&(go(e)?uo.set(e,Date.now()):co.delete(e))}function wo(){ho||(ho=setInterval(()=>{!function(){let e=Date.now(),t=V.connectivity.h2Keepalive,n=uo.size;for(let[r,a]of uo)e-a<6e4||t&&n<=1||(uo.delete(r),co.delete(r),n--,go(r)&&r.close().catch(e=>{o.debug("Error closing idle HTTP/2 client:",e)}),$e.add(1,{event:"idle_reaped",origin:mo??""}),je(h.INFO,"INFO",`HTTP/2 idle connection reaped for ${mo}`,{"copilot_api.h2.event":"idle_reaped","copilot_api.h2.origin":mo??""}))}()},3e4),ho.unref())}function bo(){fo||(o.debug("Starting HTTP/2 keepalive (every 45s)"),fo=setInterval(()=>{(async function(){if(0===uo.size&&0===po.size){if(mo){let e=_o(mo);uo.set(e,Date.now())}return}let e=[...uo.keys()];await Promise.allSettled(e.map(async e=>{if(!go(e))return uo.delete(e),void co.delete(e);try{let{statusCode:t,body:n}=await e.request({path:"/models",method:"GET",headers:Qe(V)});await n.dump(),xe.add(1,{result:"success"}),o.debug(`HTTP/2 keepalive: GET /models → ${t}`),uo.set(e,Date.now())}catch(t){xe.add(1,{result:"error"}),o.warn("HTTP/2 keepalive failed:",t instanceof Error?t.message:t),$e.add(1,{event:"error",origin:mo??""}),uo.delete(e),co.delete(e),go(e)&&e.close().catch(e=>{o.debug("Error closing broken HTTP/2 client:",e)})}}))})().catch(e=>{o.debug("Unexpected error in HTTP/2 keepalive:",e)})},45e3),fo.unref(),wo())}function vo(e,t=""){let o,n=function(){let{platform:e,ppid:t,env:o}=f;if("win32"===e){try{if(m(`wmic process get ParentProcessId,Name | findstr "${t}"`,{stdio:"pipe"}).toString().toLowerCase().includes("powershell.exe"))return"powershell"}catch{return"cmd"}return"cmd"}{let e=o.SHELL;if(e){if(e.endsWith("zsh"))return"zsh";if(e.endsWith("fish"))return"fish";if(e.endsWith("bash"))return"bash"}return"sh"}}(),r=Object.entries(e).filter(([,e])=>void 0!==e);switch(n){case"powershell":o=r.map(([e,t])=>`$env:${e} = ${t}`).join("; ");break;case"cmd":o=r.map(([e,t])=>`set ${e}=${t}`).join(" & ");break;case"fish":o=r.map(([e,t])=>`set -gx ${e} ${t}`).join("; ");break;default:{let e=r.map(([e,t])=>`${e}=${t}`).join(" ");o=r.length>0?`export ${e}`:"";break}}return o&&t?`${o}${"cmd"===n?" & ":" && "}${t}`:o||t}const xo=e=>`[1m${e}[0m`,$o=e=>`[2m${e}[0m`,To=e=>`[36m${e}[0m`,Ao=e=>`[32m${e}[0m`,So=e=>`[33m${e}[0m`,Co=e=>`[4m${e}[0m`,Oo=(e,t)=>`]8;;${e}\\${t}]8;;\\`,Eo="?utm_source=copilot-cli&utm_medium=terminal&utm_campaign=startup_banner",Io=$o(" ─────────────────────────────────────────────────────────────");function Po(e){return void 0===e?"":e>=1e6?`${(e/1e6).toFixed(0)}M`:`${(e/1e3).toFixed(0)}K`}const No=[{title:"The 5-Hour Quota, Boris's Tweet, and What the Source Code Actually Reveals",teaser:"Claude Code's caching story — decoded from the source.",url:"https://barazany.dev/blog/claude-code-token-caching"},{title:"Claude Code's Compaction Engine: What the Source Code Actually Reveals",teaser:"What's actually running beneath every long session.",url:"https://barazany.dev/blog/claude-codes-compaction-engine"},{title:"We Were About to Buy an Automation Platform. We Already Had One.",teaser:"Governance spirals over n8n. The answer was already deployed.",url:"https://barazany.dev/blog/we-already-had-the-automation-platform"}];function qo(e){if(0===e.length)return[];let t=["",Io,` ${xo("BARAZANY.DEV")} ${$o("— Recent Posts")}`,Io,""];for(let[o,n]of e.entries()){let e=Oo(`${n.url}${Eo}`,xo(Co(`[${o+1}]`)));t.push(` ${e} ${To(n.title)}`,` ${$o("→")} ${$o(n.teaser)}`,"")}return t.push(Io,` ${Oo(`https://barazany.dev/blog${Eo}`,"barazany.dev/blog")}`,Io),t}function Ro(e){let t=[];V.connectivity.h2Keepalive?t.push("HTTP/2 keepalive"):V.connectivity.h2&&t.push("HTTP/2"),t.push(`timeout ${e.timeout/1e3}s`);let o=e.webSearch?`Tavily ${Ao("✓")}`:$o("off"),n=["",` ${xo("COPILOT-API")} ${$o(`v${e.version}`)}`,Io,` ${$o("Runtime")} ${e.runtime.name} ${e.runtime.version} (${e.runtime.platform}-${e.runtime.arch})`,` ${$o("User")} ${e.user} ${$o("·")} ${e.accountType}`];return V._v1&&n.push(` ${$o("Client")} VSCode ${V._v1}`),n.push(` ${$o("Network")} ${t.join($o(" · "))}`,` ${$o("Search")} ${o}`),e.clipboardCopied&&n.push(` ${$o("Clipboard")} Claude Code command ${Ao("✓")}`),n.push(Io),n}function jo(e){if(!e.model&&!e.smallModel)return[];let t=["",` ${xo("Active")}`];if(e.model){let o=V.models?.data.find(t=>t.id===e.model),n=Po(o?.capabilities.limits?.max_context_window_tokens);t.push(` ${To(e.model.padEnd(32))} ${$o("ctx")} ${xo(n.padStart(5))} ${So("← main")}`)}if(e.smallModel){let o=V.models?.data.find(t=>t.id===e.smallModel),n=Po(o?.capabilities.limits?.max_context_window_tokens);t.push(` ${e.smallModel.padEnd(32)} ${$o("ctx")} ${n.padStart(5)} ${So("← small")}`)}return t}function Do(e){let t=[];for(let[o,n]of function(){let e=[],t=[],o=[],n=[];for(let r of V.models?.data??[]){let a=r.capabilities.limits?.max_context_window_tokens,i={id:r.id,ctx:a};r.id.startsWith("text-embedding")?n.push(i):"Anthropic"===r.vendor?e.push(i):"Google"===r.vendor?o.push(i):t.push(i)}return[["Claude",e],["OpenAI",t],["Gemini",o],["Embedding",n]]}())if(0!==n.length){t.push("",` ${xo(o)}`);for(let o of n){let n=o.id===e.model||o.id===e.smallModel,r=n?To("●"):$o("·"),a=n?To(o.id.padEnd(34)):o.id.padEnd(34),i=o.ctx?Po(o.ctx).padStart(5):"";t.push(` ${r} ${a} ${$o(i)}`)}}return t}function Mo(e){if(!e.endpoints)return[];let{scheme:t,port:o,hostname:n}=e.endpoints,r=n?`${t}://${n}:${o}`:`${t}://<your-tailscale-hostname>:${o}`,a=["",Io,` ${xo("Claude Cowork")} ${$o("— Settings → Inference Provider")}`,Io,"",` ${$o("Paste into")} ${xo("inferenceGatewayBaseUrl")}${$o(":")}`,` ${xo(To(r))}`];return n||a.push("",` ${$o("Your Tailscale hostname is shown by:")} ${To("tailscale status --self")}`),a.push("",` ${$o("Docs:")} ${To("https://claude.com/docs/cowork/3p/installation")}`),a}function Ho(e){if(!e.https||!e.https.selfSigned)return[];let{certPath:t}=e.https,o=["",Io,` ${xo("HTTPS")} ${$o("— self-signed cert")}`,Io,"",` ${$o("Cert")} ${t}`];switch(o.push("",` ${xo("Trust this cert")} ${$o("(one-time setup)")}`),f.platform){case"darwin":o.push(` ${$o("macOS:")}`,` ${To("sudo security add-trusted-cert -d -r trustRoot \\")}`,` ${To(`-k /Library/Keychains/System.keychain "${t}"`)}`);break;case"win32":o.push(` ${$o("Windows (PowerShell as Administrator):")}`,` ${To(`Import-Certificate -FilePath "${t}" \``)}`,` ${To("-CertStoreLocation Cert:\\LocalMachine\\Root")}`);break;case"linux":o.push(` ${$o("Linux (Debian/Ubuntu):")}`,` ${To(`sudo cp "${t}" /usr/local/share/ca-certificates/copilot-api.crt`)}`,` ${To("sudo update-ca-certificates")}`,` ${$o("Linux (Fedora/RHEL/Arch):")}`,` ${To(`sudo cp "${t}" /etc/pki/ca-trust/source/anchors/copilot-api.crt`)}`,` ${To("sudo update-ca-trust")}`);break;default:o.push(` ${$o("(Unknown platform — see Node fallback below.)")}`)}return o.push("",` ${$o("Or, for Node CLIs only (no admin needed):")}`,` ${To(`export NODE_EXTRA_CA_CERTS="${t}"`)}`,Io),o}function Fo(e){let t=Math.floor(e/1e3),o=Math.floor(t/3600),n=Math.floor(t%3600/60);return o>0?`${o}h ${n}m`:n>0?`${n}m`:`${t}s`}const Bo=a.join(G.APP_DIR,"certs"),Lo=a.join(Bo,"cert.pem"),Uo=a.join(Bo,"key.pem"),Jo=a.join(Bo,"cert.meta.json");async function Go(e){try{return await n.readFile(e,"utf8")}catch{return}}async function Ko(e){let t=await Go(Lo),o=await Go(Uo),n=await async function(){let e=await Go(Jo);if(e)try{let t=JSON.parse(e);return Array.isArray(t.hosts)&&"string"==typeof t.notAfter?t:void 0}catch{return}}();if(!t||!o||!n)return!1;let r=new Set(n.hosts);for(let t of e)if(!r.has(t))return!1;let a=Date.parse(n.notAfter);return!Number.isNaN(a)&&a-Date.now()>2592e6}function Wo(e){return 0!==R(e)}async function zo(e){await n.mkdir(Bo,{recursive:!0});let t=new Date,o=new Date;o.setDate(o.getDate()+825);let r=["127.0.0.1","::1"],a=new Set(["localhost"]),i=new Set(r);for(let t of e)Wo(t)?i.add(t):a.add(t);let s=await j([{name:"commonName",value:"localhost"},{name:"organizationName",value:"copilot-api"}],{keyType:"ec",curve:"P-256",algorithm:"sha256",notBeforeDate:t,notAfterDate:o,extensions:[{name:"basicConstraints",cA:!1},{name:"keyUsage",digitalSignature:!0,keyEncipherment:!0,critical:!0},{name:"extKeyUsage",serverAuth:!0,clientAuth:!0},{name:"subjectAltName",altNames:[...[...a].map(e=>({type:2,value:e})),...[...i].map(e=>({type:7,ip:e}))]}]});return await n.writeFile(Lo,s.cert,{mode:420}),await n.writeFile(Uo,s.private,{mode:384}),await async function(e){await n.writeFile(Jo,JSON.stringify(e,null,2),{mode:420})}({hosts:[...a,...i].sort(),notAfter:o.toISOString()}),{cert:s.cert,key:s.private,certPath:Lo,keyPath:Uo,generated:!0}}function Vo(e){(function(e){let{c:t,start:o,span:n}=e,r=t.get("requestData"),a=t.res.status,i=r?.model??"unknown",l=r?.streaming??!1,c=Date.now()-o;if(n.setAttribute("http.status_code",a),n.setAttribute("copilot_api.model",i),n.setAttribute("copilot_api.streaming",l),n.setAttribute("copilot_api.duration_ms",c),r?._d1&&n.setAttribute("copilot_api.copilot_duration_ms",r._d1),r?.tokenUsage){let e=r.tokenUsage;n.setAttribute("copilot_api.input_tokens",e.inputTokens),n.setAttribute("copilot_api.output_tokens",e.outputTokens),n.setAttribute("copilot_api.total_tokens",e.totalTokens),e.cachedTokens&&n.setAttribute("copilot_api.cached_tokens",e.cachedTokens),e.estimatedCost&&n.setAttribute("copilot_api.estimated_cost",e.estimatedCost)}t.res.headers.forEach((e,t)=>{let o=t.toLowerCase();Fe.has(o)||n.setAttribute(`http.response.header.${o}`,e)}),a>=400&&n.setStatus({code:s.ERROR,message:`HTTP ${a}`}),n.end()})(e),function(e){let{c:t,start:o,method:n,path:r,endpointType:a,requestId:i}=e,s=Date.now()-o,l=t.get("requestData"),c=t.res.status,u=l?.model??"unknown",p=l?.streaming??!1,d={method:n,path:r,status_code:String(c),model:u,streaming:String(p),endpoint_type:a};if(le.add(1,d),Te.record(s,d),c>=400&&ce.add(1,{method:n,path:r,status_code:String(c),error_type:c>=500?"server_error":"client_error"}),l?.tokenUsage){let e=l.tokenUsage,t={model:u,endpoint_type:a};e.inputTokens&&(ue.add(e.inputTokens,t),Pe.record(e.inputTokens,t)),e.outputTokens&&(pe.add(e.outputTokens,t),Ne.record(e.outputTokens,t)),e.cachedTokens&&de.add(e.cachedTokens,{model:u})}!p&&l?.tokenUsage&&Z.executeCompletion(i)}(e)}const Yo=async()=>ae.startActiveSpan("copilot_api.approval.await",async e=>{let t=performance.now();try{let n=await o.prompt("Accept incoming request?",{type:"confirm"}),r=performance.now()-t;if(e.setAttribute("copilot_api.approval.wait_duration_ms",r),Re.record(r),!n)throw e.setAttribute("copilot_api.approval.result","rejected"),ve.add(1,{result:"rejected"}),new it("Request rejected",Response.json({message:"Request rejected"},{status:403}));e.setAttribute("copilot_api.approval.result","approved"),ve.add(1,{result:"approved"})}finally{e.end()}}),Xo=3e-6,Qo=15e-6;function Zo(e){let t=e.prompt_tokens||0,o=e.completion_tokens||0;return{inputTokens:t,outputTokens:o,totalTokens:e.total_tokens||t+o,estimatedCost:t*Xo+o*Qo,cachedTokens:e.prompt_tokens_details?.cached_tokens,acceptedPredictionTokens:e.completion_tokens_details?.accepted_prediction_tokens,rejectedPredictionTokens:e.completion_tokens_details?.rejected_prediction_tokens}}function en(e,t){void 0!==t.prompt_tokens&&e.setAttribute("copilot_api.input_tokens",t.prompt_tokens),void 0!==t.completion_tokens&&e.setAttribute("copilot_api.output_tokens",t.completion_tokens),void 0!==t.total_tokens&&e.setAttribute("copilot_api.total_tokens",t.total_tokens)}const tn=[{pattern:/haiku/i,family:"haiku"},{pattern:/sonnet[.-]?4[.-]6/i,family:"sonnet-4.6"},{pattern:/(sonnet-4[.-]5|[.-]?3[.-]5[.-]?sonnet|[.-]?3[.-]7[.-]?sonnet)/i,family:"sonnet-4.5"},{pattern:/sonnet-4(?![.-]5|[.-]6|[.-]1)/i,family:"sonnet-4"},{pattern:/opus[.-]?4[.-]7/i,family:"opus-4.7"},{pattern:/opus[.-]?4[.-]6/i,family:"opus-4.6"},{pattern:/opus[.-]?4[.-]5/i,family:"opus-4.5"},{pattern:/opus/i,family:"opus"}],on={haiku:"claude-haiku-4.5","sonnet-4.6":"claude-sonnet-4.6","sonnet-4.5":"claude-sonnet-4.5","sonnet-4":"claude-sonnet-4","opus-4.7":"claude-opus-4.7","opus-4.6":"claude-opus-4.6","opus-4.5":"claude-opus-4.5",opus:"claude-opus-4.5"};function nn(e,t){let o=function(e){return e.startsWith("anthropic/")?e.slice(10):e}(e),[n,r]=function(e){let t=e.lastIndexOf("["),o=e.lastIndexOf("]");return-1!==t&&o===e.length-1&&o>t?[e.slice(0,t),e.slice(t+1,o)]:[e,null]}(o);if(t.includes(o))return o;if(r){let e=`${n}-${r}`.replaceAll(/(\d)-(\d)\b/g,"$1.$2");if(t.includes(e))return e}let a=function(e){for(let t of tn)if(t.pattern.test(e))return t.family;return null}(n);if(!a)return null;let i=n.replace(/-\d{8}(?::.*)?$/,""),s=r?`-${r}`:"";for(let e of t){let t=e.replace(/-\d{8}(?::.*)?$/,""),o=`${i}${s}`.toLowerCase().replaceAll(/(\d)-(\d)\b/g,"$1.$2");if(t.toLowerCase().replaceAll(/(\d)-(\d)\b/g,"$1.$2")===o)return e}return function(e,t,o=null){let n=on[e];if(!n)return null;if(o){let e=`${n}-${o}`;if(t.includes(e))return e}if(t.includes(n))return n;if("sonnet-4.5"===e)for(let e of["claude-3.5-sonnet"]){let n=o?`${e}-${o}`:e;if(t.includes(n))return n}return null}(a,t,r)}var rn=class extends Error{statusCode;constructor(e,t=400){super(e),this.name="ModelValidationError",this.statusCode=t}};function an(e){if(!e||"string"!=typeof e)throw new rn("Model name is required and must be a string");if(!V.models?.data)throw new rn("Models not available. Please try again later.",503);let t=V.models.data.map(e=>e.id);if(t.includes(e))return e;let o=nn(e,t);if(!o)throw fe.add(1,{requested_model:e}),new rn(`Invalid model: '${e}'. Available services: ${t.join(", ")}`);return o}async function sn(e){if(void 0===e.rateLimitSeconds)return;let t=e.rateLimitSeconds;return ae.startActiveSpan("copilot_api.rate_limit.check",async n=>{try{let r=Date.now();if(n.setAttribute("copilot_api.rate_limit.configured_seconds",t),!e.lastRequestTimestamp)return e.lastRequestTimestamp=r,void n.setAttribute("copilot_api.rate_limit.action","allowed");let a=(r-e.lastRequestTimestamp)/1e3;if(n.setAttribute("copilot_api.rate_limit.elapsed_seconds",a),a>t)return e.lastRequestTimestamp=r,void n.setAttribute("copilot_api.rate_limit.action","allowed");let i=Math.ceil(t-a);if(n.setAttribute("copilot_api.rate_limit.wait_seconds",i),!e.rateLimitWait)throw n.setAttribute("copilot_api.rate_limit.action","rejected"),me.add(1,{action:"rejected",source:"local"}),o.warn(`Rate limit exceeded. Need to wait ${i} more seconds.`),new it("Rate limit exceeded",Response.json({message:"Rate limit exceeded"},{status:429}));let s=1e3*i;n.setAttribute("copilot_api.rate_limit.action","waited"),me.add(1,{action:"waited",source:"local"}),Ce.record(s,{source:"local"}),o.warn(`Rate limit reached. Waiting ${i} seconds before proceeding...`),await dt(s),e.lastRequestTimestamp=r,o.info("Rate limit wait completed, proceeding with request")}finally{n.end()}})}function ln(e){if("number"==typeof e){if(!Number.isFinite(e))return null;let t=Math.floor(e);return t>0?t:null}if("string"==typeof e){let t=e.trim();if(!t)return null;let o=Number(t);if(!Number.isFinite(o))return null;let n=Math.floor(o);return n>0?n:null}return null}function cn(e,t,o){return Math.min(Math.max(e,t),o)}function un(e,t=0){if(t>5||!e||"object"!=typeof e)return null;let o=e.error;if(!o||"object"!=typeof o)return null;let n=o.code;if("string"==typeof n)return n;let r=o.message;if("string"!=typeof r)return null;try{return un(JSON.parse(r),t+1)}catch{return null}}function pn(e,t){let o=e?.data.find(e=>e.id===t);if(!o)return null;let n=ln(o.capabilities.supports.min_thinking_budget),r=ln(o.capabilities.supports.max_thinking_budget);return!n||!r||r<=n?null:{bounds:{min:n,max:r-1},maxOutputTokens:ln(o.capabilities.limits?.max_output_tokens)??void 0}}function dn(e){let{config:t}=e,o=t.bounds.min,n=t.bounds.max,r=cn(ln(e.requestedBudget)??o,o,n),a=ln(e.maxTokens);if(a||=r+1,t.maxOutputTokens&&a>t.maxOutputTokens&&(a=t.maxOutputTokens),a<=r){let e=Math.min(r,a-1);if(e>=o)r=e;else{let e=o+1;if(t.maxOutputTokens&&e>t.maxOutputTokens)return{thinkingBudget:null,maxTokens:a};a=e,r=o}}return a<=r?{thinkingBudget:null,maxTokens:a}:{thinkingBudget:r,maxTokens:a}}function mn(e,t,o){if(mt(e.thinking_budget))return e;if(!1===o?.enabled)return{...e,thinking_budget:void 0};let n=pn(t,e.model);if(!n)return{...e,thinking_budget:void 0};let r=dn({requestedBudget:e.thinking_budget,maxTokens:e.max_tokens,config:n});return null===r.thinkingBudget?{...e,max_tokens:r.maxTokens,thinking_budget:void 0}:{...e,max_tokens:r.maxTokens,thinking_budget:r.thinkingBudget}}function fn(e){return"invalid_thinking_budget"===un(e)}async function hn(e){let{payload:t,error:o,models:n,errorBodyText:r}=e;if(mt(t.thinking_budget)||!(o instanceof Error))return null;let a,i,s=o;if(!(s.response instanceof Response)||400!==s.response.status)return null;if(void 0!==r)a=r;else try{a=await s.response.clone().text()}catch{return null}try{i=JSON.parse(a)}catch{return null}if(!fn(i))return null;let l=pn(n,t.model);return l?function(e,t){let o=dn({requestedBudget:e.thinking_budget,maxTokens:e.max_tokens,config:t});if(null===o.thinkingBudget)return{...e,max_tokens:o.maxTokens,thinking_budget:void 0};let n=o.thinkingBudget,r=ln(e.thinking_budget);if(r&&r===o.thinkingBudget){let e=n+1;e<=t.bounds.max&&(!o.maxTokens||e<o.maxTokens)&&(n=e)}let a=o.maxTokens;if((!a||a<=n)&&(a=n+1),t.maxOutputTokens&&a>t.maxOutputTokens){if(!(t.maxOutputTokens>n))return{...e,max_tokens:t.maxOutputTokens,thinking_budget:void 0};a=t.maxOutputTokens}return{...e,max_tokens:a,thinking_budget:n}}(t,l):{...t,thinking_budget:void 0}}function gn(e){if(!(e instanceof Error))return!1;let t=e.code;return(!t||"UND_ERR_SOCKET"===t)&&/GOAWAY/i.test(e.message)}async function _n(){return new Promise(e=>setTimeout(e,100))}function yn(e){if("string"==typeof e)return function(e){let t=e,o=String.fromCodePoint(27),n=t.split(o);if(n.length>1){t=n[0];for(let e=1;e<n.length;e++){let r=n[e],a=r.match(/^\[[0-9;]*[a-z]/i);t+=a?r.slice(a[0].length):o+r}}return t.replaceAll(/[\u200B-\u200D\uFEFF]/g,"").replaceAll(/[\u2060-\u2064]/g,"").replaceAll(/[\u206A-\u206F]/g,"").replaceAll(/[\u180E\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/g,"").replaceAll(/[\uFFF0-\uFFFF]/g,"").replaceAll(/[\x00-\x08\v\f\x0E-\x1F]/g,"")}(e);if(Array.isArray(e))return e.map(e=>yn(e));if(e&&"object"==typeof e){let t={};for(let[o,n]of Object.entries(e))t[o]=yn(n);return"object"===t.type&&!("properties"in t)&&(t.properties={}),t}return e}async function kn(e,t){try{if(!e.ok)throw new it("Failed to create chat completions",e);let o=await e.json();return o.id&&t.setAttribute("copilot_api.response.id",o.id),o.usage&&en(t,o.usage),o}catch(e){throw De(t,e),e}finally{t.end()}}const wn=async e=>{let t=yn(e);try{return await bn(t)}catch(e){let n;if(e instanceof it)try{n=await e.response.clone().text()}catch{n=void 0}let r=await hn({payload:t,error:e,models:V.models,errorBodyText:n});if(r)return e instanceof it&&void 0!==n&&o.warn(`Upstream rejected thinking_budget (status ${e.response.status}): ${n.slice(0,500)}`),o.warn("Adjusting thinking_budget payload and retrying once..."),await bn(yn(r));throw e}},bn=async e=>{if(!V._t1)throw Error("Service token not found");let t=e.messages.some(e=>"string"!=typeof e.content&&e.content?.some(e=>"image_url"===e.type)),n=e.messages.some(e=>["assistant","tool"].includes(e.role)),r={...Qe(V,t),"X-Initiator":n?"agent":"user"},a=Xe(V),i=`${a}/chat/completions`,s=V.timeoutMs,l=JSON.stringify(e),c={"copilot_api.model":e.model,"copilot_api.streaming":!!e.stream,"copilot_api.timeout_ms":s,"copilot_api.has_tools":!!e.tools?.length,"copilot_api.tool_count":e.tools?.length??0,"copilot_api.message_count":e.messages.length,"copilot_api.max_tokens":e.max_tokens??0,"copilot_api.vision_enabled":t,"copilot_api.initiator":n?"agent":"user"};for(let t=0;t<=1;t++){let n=yo(a),u=new AbortController,p=setTimeout(()=>u.abort(),s);try{let{statusCode:o,headers:a,body:p,span:d}=await Ue({spanName:"copilot POST /chat/completions",url:i,target:"chat_completions",headers:r,body:l,signal:u.signal,headersTimeout:s,bodyTimeout:3*s,extraAttributes:{...c,"copilot_api.h2.retry_attempt":t},dispatcher:n}),m=new Response(p,{status:o,headers:a});if(e.stream){if(!m.ok)throw d.end(),new it("Failed to create chat completions",m);return{events:F(m),span:d,release:()=>ko(n)}}try{return await kn(m,d)}finally{ko(n)}}catch(e){if(ko(n),gn(e)&&t<1){o.warn(`HTTP/2 GOAWAY during chat completions, retrying (attempt ${t+1})`),await _n();continue}throw e}finally{clearTimeout(p)}}throw Error("Unexpected: exhausted GOAWAY retries without result")};function vn(e,t){if(!e.data)return e;try{let o=JSON.parse(e.data);if(o.usage&&t(o.usage),void 0!==o.usage?.prompt_tokens_details?.cached_tokens)return{...e,data:JSON.stringify({...o,usage:{...o.usage,prompt_tokens_details:void 0}})}}catch(t){o.warn("Failed to parse streaming chunk:",e.data.slice(0,200),t)}return e}async function xn(e){await sn(V);let t=await e.req.json();o.debug("Request payload:",JSON.stringify(t).slice(-400));try{t=function(e){return ae.startActiveSpan("copilot_api.model.validate",t=>{try{t.setAttribute("copilot_api.model.requested",e.model);let n=an(e.model);return t.setAttribute("copilot_api.model.normalized",n),n===e.model?(t.setAttribute("copilot_api.model.was_mapped",!1),e):(t.setAttribute("copilot_api.model.was_mapped",!0),he.add(1,{from_model:e.model,to_model:n}),o.debug(`Normalized model from '${e.model}' to '${n}'`),{...e,model:n})}finally{t.end()}})}(t)}catch(t){if(t instanceof rn)return e.json({error:{message:t.message,type:"invalid_request_error",code:"invalid_model"}},t.statusCode);throw t}if(e.set("requestData",{model:t.model,streaming:!!t.stream}),V.manualApprove&&await Yo(),mt(t.max_tokens)){let e=V.models?.data.find(e=>e.id===t.model);t={...t,max_tokens:e?.capabilities.limits?.max_output_tokens},o.debug("Set max_tokens to:",JSON.stringify(t.max_tokens))}t=mn(t,V.models,{enabled:V.thinkingEnabled}),mt(t.thinking_budget)||o.debug("Normalized thinking_budget to:",JSON.stringify(t.thinking_budget));let n=performance.now(),r=await wn(t),a=performance.now()-n;if(Ae.record(a,{model:t.model,target:"chat_completions",streaming:String(!!t.stream)}),$n(r)){let t=e.get("requestData")||{};return r.usage&&(t.tokenUsage=Zo(r.usage)),t._d1=a,e.set("requestData",t),o.debug("Non-streaming response:",JSON.stringify(r)),e.json(r)}let{events:i,span:s,release:l}=r;return H(e,async o=>{let n={value:null},r=0,c=performance.now();try{try{for await(let s of i){let i=s;s.data&&"[DONE]"!==s.data&&(r++,be.add(1,{model:t.model,endpoint_type:"openai"}),i=vn(s,t=>{n.value=t;let o=e.get("requestData")||{};o.tokenUsage=Zo(t),o._d1=a,e.set("requestData",o)})),await o.writeSSE(i)}let s=performance.now()-c,l={model:t.model,endpoint_type:"openai"};if(Se.record(s,l),qe.record(r,l),n.value){let t=e.get("requestData")||{};t.tokenUsage||(t.tokenUsage=Zo(n.value),t._d1=a,e.set("requestData",t))}}catch(t){throw Me(s,e.get("requestSpan"),t),t}finally{n.value&&en(s,n.value),s.end(),l()}let u=e.get("requestId");u&&Z.executeCompletion(u)}finally{e.get("resolveStreamComplete")?.()}})}const $n=e=>Object.hasOwn(e,"choices"),Tn=new D;Tn.post("/",async e=>{try{return await xn(e)}catch(t){return await ct(e,t)}});const An=new D;An.post("/",async e=>{try{let t=await e.req.json();try{an(t.model)}catch(t){if(t instanceof rn)return e.json({error:{message:t.message,type:"invalid_request_error",code:"invalid_model"}},t.statusCode);throw t}e.set("requestData",{model:t.model});let o=performance.now(),n=await(async e=>{if(!V._t1)throw Error("Service token not found");let t=`${Xe(V)}/embeddings`,o=Qe(V),n=V.timeoutMs,r=new AbortController,a=setTimeout(()=>r.abort(),n);try{let{response:n,span:a}=await Le({spanName:"copilot POST /embeddings",url:t,target:"embeddings",method:"POST",headers:o,body:JSON.stringify(e),signal:r.signal,extraAttributes:{"copilot_api.model":e.model,"copilot_api.input_count":Array.isArray(e.input)?e.input.length:1}});try{if(!n.ok)throw new it("Failed to create embeddings",n);return await n.json()}catch(e){throw De(a,e),e}finally{a.end()}}finally{clearTimeout(a)}})(t),r=performance.now()-o;Ae.record(r,{model:t.model,target:"embeddings",streaming:"false"});let a=e.get("requestData")||{};return a.tokenUsage=Zo(n.usage),a._d1=r,e.set("requestData",a),e.json(n)}catch(t){return await ct(e,t)}});const Sn=new D;let Cn=null,On=null;Sn.get("/",async e=>{let t,o=function(){let e=V._t1;if(!e)return"missing";try{let t=e.split(".");if(t.length<2)return"expired";let o=(t[1]??"").replaceAll("-","+").replaceAll("_","/"),n=JSON.parse(atob(o)),r="object"==typeof n&&n&&"exp"in n&&"number"==typeof n.exp?n.exp:void 0;return void 0!==r&&1e3*r<Date.now()?"expired":"valid"}catch{return"expired"}}(),n=await async function(){let e=Date.now(),t=Cn;return t&&e-t.timestamp<3e4?{result:t.result}:On||(On=(async()=>{let e=new AbortController,t=setTimeout(()=>e.abort(),5e3),o=performance.now();try{let t=`${Xe(V)}/models`,n=await fetch(t,{method:"GET",headers:Qe(V),signal:e.signal}),r=Math.round(performance.now()-o),a=n.ok?"reachable":"unreachable";return Cn={result:a,timestamp:Date.now()},{result:a,latencyMs:r}}catch{let e=Math.round(performance.now()-o);return Cn={result:"unreachable",timestamp:Date.now()},{result:"unreachable",latencyMs:e}}finally{clearTimeout(t),On=null}})(),On)}();t="valid"===o&&"reachable"===n.result?"ok":"valid"!==o&&"reachable"!==n.result?"unhealthy":"degraded";let r={status:t,copilot_token:o,upstream:n.result,version:"0.24.0",timestamp:(new Date).toISOString()};void 0!==n.latencyMs&&(r.upstream_latency_ms=n.latencyMs);let a="ok"===t?200:503;return e.json(r,a)});const En=new B(U),In={...L["anthropic/claude-sonnet-4"].tokens,baseOverhead:4,perTool:27};function Pn(e){return En.encode(e).length}function Nn(e){let t=0;for(let o of e)switch(o.type){case"text":t+=Pn(o.text)*In.contentMultiplier;break;case"tool_use":t+=Pn(o.name+JSON.stringify(o.input))*In.contentMultiplier;break;case"tool_result":o.content&&(t+=Pn("string"==typeof o.content?o.content:JSON.stringify(o.content))*In.contentMultiplier);break;case"thinking":t+=Pn(o.thinking)*In.contentMultiplier;break;case"image":t+=1600}return t}function qn(e){let t=0,o=e.properties;if(!o)return t;let n=Object.entries(o);for(let[e,[o,r]]of n.entries()){if(t+=0===e?In.perFirstProp:In.perAdditionalProp,t+=Pn(o),r.description&&(t+=In.perPropDesc+Pn(r.description)),r.enum&&Array.isArray(r.enum)){t+=In.perEnum;for(let e of r.enum)t+=Pn(String(e))}if("object"===r.type&&r.properties&&(t+=In.perNestedObject,t+=qn(r)),"array"===r.type&&r.items){let e=r.items;"object"===e.type&&e.properties&&(t+=In.perArrayOfObjects,t+=qn(e))}}return t}const Rn=async(e,t)=>{if(!V._t1)throw Error("Service token not found");let{metadata:n,...r}=yn(e),a={...et(V,t),"X-Initiator":"agent"},i=Xe(V),s=`${i}/v1/messages`,l=V.timeoutMs,c=JSON.stringify(r),u={"copilot_api.model":r.model,"copilot_api.streaming":!!r.stream,"copilot_api.timeout_ms":l,"copilot_api.has_tools":!!r.tools?.length,"copilot_api.tool_count":r.tools?.length||0,"copilot_api.max_tokens":r.max_tokens||0,"copilot_api.api_type":"anthropic_passthrough"};for(let e=0;e<=1;e++){let t=yo(i),p=new AbortController,d=setTimeout(()=>p.abort(),l);try{let{statusCode:o,headers:n,body:i,span:d}=await Ue({spanName:"copilot POST /v1/messages",url:s,target:"anthropic_messages",headers:a,body:c,signal:p.signal,headersTimeout:l,bodyTimeout:3*l,extraAttributes:{...u,"copilot_api.h2.retry_attempt":e},dispatcher:t}),m=new Response(i,{status:o,headers:n});if(!m.ok)throw d.end(),new it("Failed to create anthropic messages",m);if(r.stream)return{events:F(m),span:d,release:()=>ko(t)};let f=await m.json();"string"==typeof f.id&&d.setAttribute("copilot_api.response.id",f.id);let h=f.usage;return h&&en(d,{prompt_tokens:h.input_tokens??0,completion_tokens:h.output_tokens??0,total_tokens:(h.input_tokens??0)+(h.output_tokens??0)}),d.end(),ko(t),f}catch(n){if(ko(t),gn(n)&&e<1){o.warn(`HTTP/2 GOAWAY during anthropic messages, retrying (attempt ${e+1})`),await _n();continue}throw n}finally{clearTimeout(d)}}throw Error("Unexpected: exhausted GOAWAY retries without result")};async function jn(e,t){try{if(!e.ok)throw new it("Failed to create responses",e);let o=await e.json();return o.id&&t.setAttribute("copilot_api.response.id",o.id),o.usage&&en(t,{prompt_tokens:o.usage.input_tokens,completion_tokens:o.usage.output_tokens,total_tokens:o.usage.total_tokens}),o}catch(e){throw De(t,e),e}finally{t.end()}}const Dn=async e=>{if(!V._t1)throw Error("Service token not found");let t=yn(e),n={...Qe(V),"X-Initiator":"agent"},r=Xe(V),a=`${r}/responses`,i=V.timeoutMs,s=JSON.stringify(t),l={"copilot_api.model":t.model,"copilot_api.streaming":!!t.stream,"copilot_api.timeout_ms":i,"copilot_api.has_tools":!!t.tools?.length,"copilot_api.tool_count":t.tools?.length??0,"copilot_api.max_output_tokens":t.max_output_tokens??0,"copilot_api.api_type":"responses"};for(let e=0;e<=1;e++){let c=yo(r),u=new AbortController,p=setTimeout(()=>u.abort(),i);try{let{statusCode:o,headers:r,body:p,span:d}=await Ue({spanName:"copilot POST /responses",url:a,target:"responses",headers:n,body:s,signal:u.signal,headersTimeout:i,bodyTimeout:3*i,extraAttributes:{...l,"copilot_api.h2.retry_attempt":e},dispatcher:c}),m=new Response(p,{status:o,headers:r});if(t.stream){if(!m.ok)throw d.end(),new it("Failed to create responses",m);return{events:F(m),span:d,release:()=>ko(c)}}try{return await jn(m,d)}finally{ko(c)}}catch(t){if(ko(c),gn(t)&&e<1){o.warn(`HTTP/2 GOAWAY during responses, retrying (attempt ${e+1})`),await _n();continue}throw t}finally{clearTimeout(p)}}throw Error("Unexpected: exhausted GOAWAY retries without result")};function Mn(e){return null===e?null:{stop:"end_turn",length:"max_tokens",tool_calls:"tool_use",content_filter:"end_turn"}[e]}function Hn(e,t){let o={model:e.model,messages:Fn(e.messages,e.system),max_tokens:e.max_tokens,stop:e.stop_sequences,stream:e.stream,temperature:e.temperature,top_p:e.top_p,user:e.metadata?.user_id,tools:Gn(e.tools),tool_choice:Kn(e.tool_choice)},n=e.thinking;if("enabled"===n?.type||"adaptive"===n?.type){let r=pn(t,o.model);if(r){let a="enabled"===n.type&&"number"==typeof n.budget_tokens?n.budget_tokens:function(e,t,o){let n=function(e,t){return"max"===e?t:"high"===e?16e3:"medium"===e?8e3:1024}(e,o.max),r=ln(t),a=r&&r>1?r-1:o.min;return cn(Math.min(n,a),o.min,o.max)}(e.output_config?.effort??"high",o.max_tokens,r.bounds);o=mn({...o,thinking_budget:a},t)}}return o}function Fn(e,t){let o=function(e){return e?"string"==typeof e?[{role:"system",content:Bn(e)}]:[{role:"system",content:Bn(e.map(e=>e.text).join("\n\n"))}]:[]}(t),n=e.flatMap(e=>"user"===e.role?function(e){let t=[];if(Array.isArray(e.content)){let o=e.content.filter(e=>"tool_result"===e.type),n=e.content.filter(e=>"tool_result"!==e.type);for(let e of o)t.push({role:"tool",tool_call_id:e.tool_use_id,content:Jn(e.content)});n.length>0&&t.push({role:"user",content:Jn(n)})}else t.push({role:"user",content:Jn(e.content)});return t}(e):function(e){let t=function(e){return{reasoning_text:Un(e.reasoning_text),reasoning_opaque:Un(e.reasoning_opaque)}}(e);if(!Array.isArray(e.content))return[{role:"assistant",content:Jn(e.content),...t}];let o=e.content.filter(e=>"tool_use"===e.type),n=e.content.filter(e=>"text"===e.type),r=e.content.filter(e=>"thinking"===e.type),a=[...n.map(e=>e.text),...r.map(e=>e.thinking)].join("\n\n");return o.length>0?[{role:"assistant",content:a||null,...t,tool_calls:o.map(e=>({id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.input)}}))}]:[{role:"assistant",content:Jn(e.content),...t}]}(e));return[...o,...n]}function Bn(e){return e.startsWith("x-anthropic-billing-header")?e.replace(/^x-_an1-billing-header:[^\n]*\n+/,""):e}const Ln=32768;function Un(e){if("string"==typeof e)return e.length<=Ln?e:e.slice(0,Ln)}function Jn(e){if("string"==typeof e)return e;if(!Array.isArray(e))return null;if(!e.some(e=>"image"===e.type))return e.filter(e=>"text"===e.type||"thinking"===e.type).map(e=>"text"===e.type?e.text:e.thinking).join("\n\n");let t=[];for(let o of e)switch(o.type){case"text":t.push({type:"text",text:o.text});break;case"thinking":t.push({type:"text",text:o.thinking});break;case"image":t.push({type:"image_url",image_url:{url:`data:${o.source.media_type};base64,${o.source.data}`}})}return t}function Gn(e){if(e)return e.map(e=>({type:"function",function:{name:e.name,description:e.description,parameters:e.input_schema}}))}function Kn(e){if(e)switch(e.type){case"auto":return"auto";case"any":return"required";case"tool":return e.name?{type:"function",function:{name:e.name}}:void 0;case"none":return"none";default:return}}function Wn(e){return"string"==typeof e?[{type:"text",text:e}]:Array.isArray(e)?e.filter(e=>"text"===e.type).map(e=>({type:"text",text:e.text})):[]}function zn(e){return e.reasoning_text?[{type:"thinking",thinking:e.reasoning_text}]:[]}function Vn(e){return e?e.map(e=>({type:"tool_use",id:e.id,name:e.function.name,input:JSON.parse(e.function.arguments)})):[]}function Yn(e){let t={model:e.model,input:Qn(e.messages),max_output_tokens:Math.max(e.max_tokens,16),stream:e.stream,temperature:e.temperature,top_p:e.top_p,store:!1,user:e.metadata?.user_id?.slice(0,64)},o=function(e){return e?function(e){return e.startsWith("x-anthropic-billing-header")?e.replace(/^x-_an1-billing-header:[^\n]*\n+/,""):e}("string"==typeof e?e:e.map(e=>e.text).join("\n\n")):null}(e.system);return o&&(t.instructions=o),e.tools?.length&&(t.tools=e.tools.map(e=>({type:"function",name:e.name,description:e.description,parameters:e.input_schema}))),e.tool_choice&&(t.tool_choice=function(e){switch(e.type){case"auto":return"auto";case"any":return"required";case"none":return"none";case"tool":return e.name?{type:"function",name:e.name}:void 0;default:return}}(e.tool_choice)),"adaptive"===e.thinking?.type?t.reasoning={effort:Xn(e.output_config?.effort??"high")}:"enabled"===e.thinking?.type&&e.thinking.budget_tokens&&(t.reasoning=function(e){return e<5e3?{effort:"low"}:e<2e4?{effort:"medium"}:e<32e3?{effort:"high"}:{effort:"xhigh"}}(e.thinking.budget_tokens)),t}function Xn(e){switch(e){case"low":return"low";case"medium":return"medium";case"max":return"xhigh";default:return"high"}}function Qn(e){let t=[];for(let o of e)"user"===o.role?t.push(...Zn(o)):t.push(...tr(o));return t}function Zn(e){if("string"==typeof e.content)return[{type:"message",role:"user",content:e.content}];let t=[],o=e.content.filter(e=>"tool_result"===e.type),n=e.content.filter(e=>"tool_result"!==e.type);for(let e of o)t.push(er(e));if(n.length>0)if(n.some(e=>"image"===e.type)){let e=[];for(let t of n)"text"===t.type?e.push({type:"input_text",text:t.text}):e.push({type:"input_image",image_url:`data:${t.source.media_type};base64,${t.source.data}`});t.push({type:"message",role:"user",content:e})}else{let e=n.filter(e=>"text"===e.type).map(e=>e.text).join("\n\n");e&&t.push({type:"message",role:"user",content:e})}return t}function er(e){let t;return t="string"==typeof e.content?e.content:Array.isArray(e.content)?e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"):"",e.is_error&&(t=`[ERROR] ${t}`),{type:"function_call_output",call_id:e.tool_use_id,output:t}}function tr(e){if("string"==typeof e.content)return[{type:"message",role:"assistant",content:e.content}];let t=[],o=e.content.filter(e=>"text"===e.type),n=e.content.filter(e=>"thinking"===e.type),r=e.content.filter(e=>"tool_use"===e.type),a=[...o.map(e=>e.text),...n.map(e=>e.thinking)].join("\n\n");a&&t.push({type:"message",role:"assistant",content:a});for(let e of r)t.push({type:"function_call",call_id:e.id,name:e.name,arguments:JSON.stringify(e.input)});return t}function or(e,t){if(t)return"tool_use";switch(e){case"completed":case"cancelled":case"failed":return"end_turn";case"incomplete":return"max_tokens";default:return null}}function nr(e,t){e.contentBlockOpen&&=(t.push({type:"content_block_stop",index:e.contentBlockIndex}),e.contentBlockIndex++,!1)}function rr(e,t,o){e.messageStartSent||=(e.responseId=o?.responseId??e.responseId,e.model=o?.model??e.model,t.push({type:"message_start",message:{id:e.responseId,type:"message",role:"assistant",content:[],model:e.model,stop_reason:null,stop_sequence:null,usage:{input_tokens:0,output_tokens:0}}}),!0)}function ar(e,t){let o=[];switch(e.type){case"response.created":rr(t,o,{responseId:e.response.id,model:e.response.model});break;case"response.in_progress":case"response.output_text.done":case"response.function_call_arguments.done":case"response.refusal.done":case"response.reasoning_summary_text.delta":case"response.reasoning_summary_text.done":default:break;case"response.output_item.added":if("function_call"===e.item.type){rr(t,o),nr(t,o);let n=e.item;t.toolCalls[e.output_index]={call_id:n.call_id,name:n.name,_bi1:t.contentBlockIndex},o.push({type:"content_block_start",index:t.contentBlockIndex,content_block:{type:"tool_use",id:n.call_id,name:n.name,input:{}}}),t.contentBlockOpen=!0}break;case"response.content_part.added":rr(t,o),nr(t,o),o.push({type:"content_block_start",index:t.contentBlockIndex,content_block:{type:"text",text:""}}),t.contentBlockOpen=!0;break;case"response.output_text.delta":o.push({type:"content_block_delta",index:t.contentBlockIndex,delta:{type:"text_delta",text:e.delta}});break;case"response.content_part.done":nr(t,o);break;case"response.function_call_arguments.delta":{let n=t.toolCalls[e.output_index];n&&o.push({type:"content_block_delta",index:n._bi1,delta:{type:"input_json_delta",partial_json:e.delta}});break}case"response.output_item.done":if("function_call"===e.item.type){let n=t.toolCalls[e.output_index];n&&t.contentBlockOpen&&(o.push({type:"content_block_stop",index:n._bi1}),t.contentBlockIndex++,t.contentBlockOpen=!1)}break;case"response.completed":{nr(t,o);let n=e.response.output.some(e=>"function_call"===e.type),r=e.response.usage;o.push({type:"message_delta",delta:{stop_reason:or(e.response.status,n),stop_sequence:null},usage:{input_tokens:r?.input_tokens??0,output_tokens:r?.output_tokens??0}},{type:"message_stop"});break}case"response.incomplete":{rr(t,o),nr(t,o);let n=e.response.usage;o.push({type:"message_delta",delta:{stop_reason:"max_tokens",stop_sequence:null},usage:{input_tokens:n?.input_tokens??0,output_tokens:n?.output_tokens??0}},{type:"message_stop"});break}case"response.failed":rr(t,o),nr(t,o),o.push({type:"error",error:{type:e.response.error?.code??"api_error",message:e.response.error?.message??"Response generation failed"}});break;case"response.cancelled":rr(t,o),nr(t,o),o.push({type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{input_tokens:0,output_tokens:0}},{type:"message_stop"});break;case"response.refusal.delta":rr(t,o),t.contentBlockOpen||=(o.push({type:"content_block_start",index:t.contentBlockIndex,content_block:{type:"text",text:""}}),!0),o.push({type:"content_block_delta",index:t.contentBlockIndex,delta:{type:"text_delta",text:e.delta}})}return o}function ir(e,t){e.thinkingBlockOpen||(e.contentBlockOpen&&=(t.push({type:"content_block_stop",index:e.contentBlockIndex}),e.contentBlockIndex++,!1),t.push({type:"content_block_start",index:e.contentBlockIndex,content_block:{type:"thinking",thinking:""}}),e.thinkingBlockOpen=!0,e.contentBlockOpen=!0)}function sr(e,t){e.thinkingBlockOpen&&(t.push({type:"content_block_stop",index:e.contentBlockIndex}),e.contentBlockIndex++,e.thinkingBlockOpen=!1,e.contentBlockOpen=!1)}function lr(e,t){let o=[];if(0===e.choices.length)return o;let n=e.choices[0],{delta:r}=n;if(t.messageStartSent||=(o.push({type:"message_start",message:{id:e.id,type:"message",role:"assistant",content:[],model:e.model,stop_reason:null,stop_sequence:null,usage:{input_tokens:e.usage?.prompt_tokens??0,output_tokens:0}}}),!0),"string"==typeof r.reasoning_text&&""!==r.reasoning_text&&(ir(t,o),o.push({type:"content_block_delta",index:t.contentBlockIndex,delta:{type:"thinking_delta",thinking:r.reasoning_text}})),"string"==typeof r.reasoning_opaque&&""!==r.reasoning_opaque&&(ir(t,o),o.push({type:"content_block_delta",index:t.contentBlockIndex,delta:{type:"signature_delta",signature:r.reasoning_opaque}}),sr(t,o)),r.content&&(sr(t,o),function(e){return!!e.contentBlockOpen&&Object.values(e.toolCalls).some(t=>t._bi1===e.contentBlockIndex)}(t)&&(o.push({type:"content_block_stop",index:t.contentBlockIndex}),t.contentBlockIndex++,t.contentBlockOpen=!1),t.contentBlockOpen||=(o.push({type:"content_block_start",index:t.contentBlockIndex,content_block:{type:"text",text:""}}),!0),o.push({type:"content_block_delta",index:t.contentBlockIndex,delta:{type:"text_delta",text:r.content}})),r.tool_calls){sr(t,o);for(let e of r.tool_calls){if(e.id&&e.function?.name){t.contentBlockOpen&&=(o.push({type:"content_block_stop",index:t.contentBlockIndex}),t.contentBlockIndex++,!1);let n=t.contentBlockIndex;t.toolCalls[e.index]={id:e.id,name:e.function.name,_bi1:n},o.push({type:"content_block_start",index:n,content_block:{type:"tool_use",id:e.id,name:e.function.name,input:{}}}),t.contentBlockOpen=!0}if(e.function?.arguments){let n=t.toolCalls[e.index];n&&o.push({type:"content_block_delta",index:n._bi1,delta:{type:"input_json_delta",partial_json:e.function.arguments}})}}}return n.finish_reason&&(sr(t,o),t.contentBlockOpen&&=(o.push({type:"content_block_stop",index:t.contentBlockIndex}),!1),o.push({type:"message_delta",delta:{stop_reason:Mn(n.finish_reason),stop_sequence:null},usage:{input_tokens:e.usage?.prompt_tokens??0,output_tokens:e.usage?.completion_tokens??0}},{type:"message_stop"})),o}var cr=class extends Error{constructor(){super("Tavily web search timed out after 15000ms. The search endpoint may be slow or unreachable."),this.name="TavilyTimeoutError"}};async function ur(e,t,n){let r=function(e,t){let o={query:e,max_results:t?.maxResults??5};return t?.includeDomains?.length&&(o.include_domains=t.includeDomains),t?.excludeDomains?.length&&(o.exclude_domains=t.excludeDomains),o}(t,n);o.debug("Tavily search request:",JSON.stringify(r));let a=new AbortController,i=setTimeout(()=>a.abort(),15e3);try{let{response:t,span:i}=await Le({spanName:"tavily POST /search",url:"https://api.tavily.com/search",target:"tavily_search",method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(r),signal:a.signal,extraAttributes:{"tavily.max_results":n?.maxResults??5,"tavily.has_include_domains":!!n?.includeDomains?.length,"tavily.has_exclude_domains":!!n?.excludeDomains?.length}});try{let e=await async function(e){if(!e.ok){let t=await e.text();throw o.error(`Tavily API error (${e.status}):`,t),Error(`Tavily API error: ${e.status} ${t}`)}return await e.json()}(t);return i.setAttribute("tavily.results_count",e.results.length),o.debug(`Tavily returned ${e.results.length} results`),e.results}catch(e){throw De(i,e),e}finally{i.end()}}catch(e){throw e instanceof DOMException&&"AbortError"===e.name?new cr:e}finally{clearTimeout(i)}}function pr(){let e="";for(let t=0;t<24;t++)e+="abcdefghijklmnopqrstuvwxyz0123456789"[Math.floor(36*Math.random())];return e}async function dr(e,t){let n=function(e){let t,o=e.messages[0];if(!o||"user"!==o.role)return null;if("string"==typeof o.content)t=o.content;else{if(!Array.isArray(o.content))return null;{let e=o.content.find(e=>"text"===e.type);if(!e)return null;t=e.text}}return t.startsWith("Perform a web search for the query: ")?t.slice(36).trim():t.trim()||null}(t);if(!n)return e.json({type:"error",error:{type:"invalid_request_error",message:"Could not extract search query from web search request"}},400);let r=function(e){let t=e.tools?.[0];return{maxResults:"number"==typeof t?.max_uses?t.max_uses:5,allowedDomains:t?.allowed_domains,blockedDomains:t?.blocked_domains}}(t);o.info(`Web search intercepted: "${n}"`);let a=[];try{let e=V.tavilyApiKey;if(!e)throw Error("No Tavily API key configured");a=(await ur(e,n,{maxResults:Math.min(r.maxResults,10),includeDomains:r.allowedDomains,excludeDomains:r.blockedDomains})).map(e=>({type:"web_search_result",url:e.url,title:e.title,encrypted_content:Buffer.from(e.content).toString("base64"),page_age:null}))}catch(e){o.error("Tavily search failed:",e)}let i={query:n,results:a,model:t.model};if(!t.stream)return e.json(function(e){let{query:t,results:o,model:n}=e,r=`srvtoolu_${pr()}`,a=[{type:"text",text:"I'll search for that."},{type:"server_tool_use",id:r,name:"web_search",input:{query:t}},{type:"web_search_tool_result",tool_use_id:r,content:o}];return{id:`msg_tavily_${pr()}`,type:"message",role:"assistant",model:n,content:a,stop_reason:"end_turn",stop_sequence:null,usage:{input_tokens:0,output_tokens:0}}}(i));let s=function(e){let{query:t,results:o,model:n}=e,r=`srvtoolu_${pr()}`,a=`msg_tavily_${pr()}`,i=[];return i.push({type:"message_start",message:{id:a,type:"message",role:"assistant",content:[],model:n,stop_reason:null,stop_sequence:null,usage:{input_tokens:0,output_tokens:0}}},{type:"content_block_start",index:0,content_block:{type:"text",text:""}},{type:"content_block_delta",index:0,delta:{type:"text_delta",text:"I'll search for that."}},{type:"content_block_stop",index:0},{type:"content_block_start",index:1,content_block:{type:"server_tool_use",id:r,name:"web_search",input:{}}},{type:"content_block_delta",index:1,delta:{type:"input_json_delta",partial_json:JSON.stringify({query:t})}},{type:"content_block_stop",index:1},{type:"content_block_start",index:2,content_block:{type:"web_search_tool_result",tool_use_id:r,content:o}},{type:"content_block_stop",index:2},{type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:{output_tokens:0}},{type:"message_stop"}),i}(i);return H(e,async e=>{for(let t of s)await e.writeSSE({event:t.type,data:JSON.stringify(t)})})}function mr(e){return function(e){let t=e.thinking;if(null==t)return null;if("object"!=typeof t)return"thinking must be an object";let o=t,n=new Set(["enabled","adaptive","disabled"]);return"string"==typeof o.type&&n.has(o.type)?"enabled"!==o.type||void 0===o.budget_tokens||"number"==typeof o.budget_tokens&&Number.isFinite(o.budget_tokens)&&!(o.budget_tokens<=0)&&Number.isInteger(o.budget_tokens)?null:"thinking.budget_tokens must be a positive integer":"thinking.type must be one of: enabled, adaptive, disabled"}(e)??function(e){let t=e.output_config;if(null==t)return null;if("object"!=typeof t)return"output_config must be an object";let o=t;if(void 0===o.effort)return null;let n=new Set(["low","medium","high","max"]);return"string"==typeof o.effort&&n.has(o.effort)?null:"output_config.effort must be one of: low, medium, high, max"}(e)}async function fr(e){let t=await e.req.json();if(function(e){let t=e.tools;if(!t||1!==t.length)return!1;let o=t[0].type;return"string"==typeof o&&o.startsWith("web_search")}(t))return dr(e,t);await sn(V),o.debug("Anthropic request payload:",JSON.stringify(t));let n=e.req.header("anthropic-beta")??"",r=/context-1m/i.test(n);if(r&&/\u0063\u006c\u0061\u0075\u0064\u0065/i.test(t.model)){let e=t.model;t={...t,model:`${t.model}-1m`},o.debug(`Detected context-1m beta flag, rewriting model: '${e}' → '${t.model}'`)}let a=function(e,t){return ae.startActiveSpan("copilot_api.model.validate",n=>{try{n.setAttribute("copilot_api.model.requested",t.model);let r=an(t.model);n.setAttribute("copilot_api.model.normalized",r);let a=mr(t);return a?{ok:!1,response:e.json({type:"error",error:{type:"invalid_request_error",message:a}},400)}:r===t.model?(n.setAttribute("copilot_api.model.was_mapped",!1),{ok:!0,payload:t}):(n.setAttribute("copilot_api.model.was_mapped",!0),he.add(1,{from_model:t.model,to_model:r}),o.debug(`Model mapping: '${t.model}' → '${r}'`),{ok:!0,payload:{...t,model:r}})}catch(t){if(t instanceof rn)return{ok:!1,response:e.json({type:"error",error:{type:"invalid_request_error",message:t.message}},t.statusCode)};throw t}finally{n.end()}})}(e,t);if(!a.ok)return a.response;if(t=a.payload,function(e){return/gpt-[\d.]+-codex/i.test(e)}(t.model))return async function(e,t){let n=performance.now(),r=ae.startActiveSpan("copilot_api.translate.anthropic_to_responses",e=>{try{return e.setAttribute("copilot_api.translation.direction","anthropic_to_responses"),e.setAttribute("copilot_api.translation.message_count",t.messages.length),Yn(t)}finally{e.end()}});Oe.record(performance.now()-n,{direction:"anthropic_to_responses"}),o.debug("Translated Responses API payload:",JSON.stringify(r)),e.set("requestData",{model:r.model,streaming:!!r.stream}),V.manualApprove&&await Yo();let a=performance.now(),i=await Dn(r),s=performance.now()-a;if(Ae.record(s,{model:r.model,target:"responses",streaming:String(!!r.stream)}),_r(i)){let t=e.get("requestData")||{};if(i.usage&&(t.tokenUsage=Zo({prompt_tokens:i.usage.input_tokens,completion_tokens:i.usage.output_tokens,total_tokens:i.usage.total_tokens})),t._d1=s,e.set("requestData",t),o.debug("Non-streaming Responses API response:",JSON.stringify(i).slice(-400)),"failed"===i.status)return e.json({type:"error",error:{type:i.error?.code??"api_error",message:i.error?.message??"Response generation failed"}},500);let n=performance.now(),r=ae.startActiveSpan("copilot_api.translate.responses_to_anthropic",e=>{try{return e.setAttribute("copilot_api.translation.direction","responses_to_anthropic"),function(e){let t=[],o=!1;for(let n of e.output)if("message"===n.type)for(let e of n.content)e.text&&t.push({type:"text",text:e.text});else if("function_call"===n.type){o=!0;let e={};try{e=JSON.parse(n.arguments)}catch{}t.push({type:"tool_use",id:n.call_id,name:n.name,input:e})}return{id:e.id,type:"message",role:"assistant",model:e.model,content:t,stop_reason:or(e.status,o),stop_sequence:null,usage:{input_tokens:e.usage?.input_tokens??0,output_tokens:e.usage?.output_tokens??0}}}(i)}finally{e.end()}});return Oe.record(performance.now()-n,{direction:"responses_to_anthropic"}),e.json(r)}o.debug("Streaming Responses API response");let{events:l,span:c,release:u}=i;return H(e,async t=>{let n=null,a=0,i=performance.now(),p={messageStartSent:!1,contentBlockIndex:0,contentBlockOpen:!1,responseId:"",model:"",toolCalls:{}};try{try{for await(let i of l){if(o.debug("Responses API raw stream event:",JSON.stringify(i)),!i.data)continue;let l;try{l=JSON.parse(i.data)}catch(e){o.warn("Failed to parse streaming chunk:",i.data.slice(0,200),e);continue}a++,be.add(1,{model:r.model,endpoint_type:"responses"});let c=hr(l);if(c){n=c;let t=e.get("requestData")||{};t.tokenUsage=Zo(n),t._d1=s,e.set("requestData",t)}let u=ar(l,p);for(let e of u)o.debug("Translated Anthropic event:",JSON.stringify(e)),await t.writeSSE({event:e.type,data:JSON.stringify(e)})}let c=performance.now()-i,u={model:r.model,endpoint_type:"responses"};Se.record(c,u),qe.record(a,u)}catch(t){throw Me(c,e.get("requestSpan"),t),t}finally{n&&en(c,n),c.end(),u()}let d=e.get("requestId");d&&Z.executeCompletion(d)}finally{e.get("resolveStreamComplete")?.()}})}(e,t);if(V.nativeAnthropicEnabled&&function(e){return e.toLowerCase().startsWith("claude-")}(t.model))return async function(e,t){let o={anthropicBeta:e.req.header("anthropic-beta"),anthropicVersion:e.req.header("anthropic-version")};return e.set("requestData",{model:t.model,streaming:!!t.stream}),V.manualApprove&&await Yo(),ae.startActiveSpan("copilot_api.anthropic_passthrough",async n=>{n.setAttribute("copilot_api.route","anthropic_passthrough"),n.setAttribute("copilot_api.model",t.model),n.setAttribute("copilot_api.streaming",!!t.stream);let r=performance.now(),a=await Rn(t,o),i=performance.now()-r;if(Ae.record(i,{model:t.model,target:"anthropic_messages",streaming:String(!!t.stream)}),!t.stream){let t=a,o=t.usage;if(o){let t={input_tokens:o.input_tokens||0,output_tokens:o.output_tokens||0,cache_read_input_tokens:o.cache_read_input_tokens||0,cache_creation_input_tokens:o.cache_creation_input_tokens||0},n=e.get("requestData")||{};n.tokenUsage=Zo(yr(t)),n._d1=i,e.set("requestData",n)}return n.end(),e.json(t)}let{events:s,span:l,release:c}=a;return H(e,async o=>{let a=0,i=performance.now(),u={input_tokens:0,output_tokens:0,cache_read_input_tokens:0,cache_creation_input_tokens:0},p=!1;try{try{for await(let e of s)e.data&&"[DONE]"!==e.data?(a++,be.add(1,{model:t.model,endpoint_type:"anthropic_messages"}),kr(e.data,u)&&(p=!0),await o.writeSSE(e)):await o.writeSSE(e);let e=performance.now()-i,n={model:t.model,endpoint_type:"anthropic_messages"};Se.record(e,n),qe.record(a,n)}finally{if(p){let t=yr(u);en(l,t);let o=e.get("requestData")||{};o.tokenUsage=Zo(t),o._d1=performance.now()-r,e.set("requestData",o)}l.end(),c()}let n=e.get("requestId");n&&Z.executeCompletion(n)}finally{n.end(),e.get("resolveStreamComplete")?.()}})})}(e,t);let i=performance.now(),s=ae.startActiveSpan("copilot_api.translate.anthropic_to_openai",e=>{try{e.setAttribute("copilot_api.translation.direction","anthropic_to_openai"),e.setAttribute("copilot_api.translation.message_count",t.messages.length),e.setAttribute("copilot_api.translation.has_tools",!!t.tools?.length),e.setAttribute("copilot_api.translation.has_system",!!t.system),e.setAttribute("copilot_api.translation.context_1m_beta",r);let o=t.messages.some(e=>Array.isArray(e.content)&&e.content.some(e=>"image"===e.type)),n=t.messages.some(e=>Array.isArray(e.content)&&e.content.some(e=>"thinking"===e.type));return e.setAttribute("copilot_api.translation.has_images",o),e.setAttribute("copilot_api.translation.has_thinking",n),Hn(t,V.models)}finally{e.end()}});Oe.record(performance.now()-i,{direction:"anthropic_to_openai"}),s=mn(s,V.models,{enabled:V.thinkingEnabled}),o.debug("Translated OpenAI request payload:",JSON.stringify(s)),e.set("requestData",{model:s.model,streaming:!!s.stream});let l=performance.now();V.manualApprove&&await Yo();let c=await wn(s),u=performance.now()-l;if(Ae.record(u,{model:s.model,target:"chat_completions",streaming:String(!!s.stream)}),gr(c)){let t=e.get("requestData")||{};c.usage&&(t.tokenUsage=Zo(c.usage)),t._d1=u,e.set("requestData",t),o.debug("Non-streaming response:",JSON.stringify(c).slice(-400));let n=performance.now(),r=ae.startActiveSpan("copilot_api.translate.openai_to_anthropic",e=>{try{e.setAttribute("copilot_api.translation.direction","openai_to_anthropic");let t=function(e){let t=[],o=[],n=[],r=null;r=e.choices[0]?.finish_reason??r;for(let a of e.choices){let e=zn(a.message),i=Wn(a.message.content),s=Vn(a.message.tool_calls);t.push(...e),o.push(...i),n.push(...s),("tool_calls"===a.finish_reason||"stop"===r)&&(r=a.finish_reason)}return{id:e.id,type:"message",role:"assistant",model:e.model,content:[...t,...o,...n],stop_reason:Mn(r),stop_sequence:null,usage:{input_tokens:e.usage?.prompt_tokens??0,output_tokens:e.usage?.completion_tokens??0}}}(c);return e.setAttribute("copilot_api.translation.content_blocks",t.content.length),e.setAttribute("copilot_api.translation.stop_reason",t.stop_reason??"null"),e.setAttribute("copilot_api.translation.has_tool_use",t.content.some(e=>"tool_use"===e.type)),t}finally{e.end()}});return Oe.record(performance.now()-n,{direction:"openai_to_anthropic"}),o.debug("Translated Anthropic response:",JSON.stringify(r)),e.json(r)}o.debug("Streaming response from service");let{events:p,span:d,release:m}=c;return H(e,async t=>{let n=null,r=0,a=performance.now(),i={messageStartSent:!1,contentBlockIndex:0,contentBlockOpen:!1,thinkingBlockOpen:!1,toolCalls:{}};try{try{for await(let a of p){if(o.debug("Raw stream event:",JSON.stringify(a)),"[DONE]"===a.data)break;if(!a.data)continue;let l;try{l=JSON.parse(a.data)}catch(e){o.warn("Failed to parse streaming chunk:",a.data.slice(0,200),e);continue}if(r++,be.add(1,{model:s.model,endpoint_type:"anthropic"}),l.usage){n=l.usage;let t=e.get("requestData")||{};t.tokenUsage=Zo(n),t._d1=u,e.set("requestData",t)}let c=lr(l,i);for(let e of c)o.debug("Translated Anthropic event:",JSON.stringify(e)),await t.writeSSE({event:e.type,data:JSON.stringify(e)})}let l=performance.now()-a,c={model:s.model,endpoint_type:"anthropic"};if(Se.record(l,c),qe.record(r,c),n){let t=e.get("requestData")||{};t.tokenUsage||(t.tokenUsage=Zo(n),t._d1=u,e.set("requestData",t))}}catch(t){throw Me(d,e.get("requestSpan"),t),t}finally{n&&en(d,n),d.end(),m()}let l=e.get("requestId");l&&Z.executeCompletion(l)}finally{e.get("resolveStreamComplete")?.()}})}function hr(e){if("response.completed"!==e.type&&"response.incomplete"!==e.type)return null;let t=e.response.usage;return t?{prompt_tokens:t.input_tokens,completion_tokens:t.output_tokens,total_tokens:t.total_tokens}:null}const gr=e=>Object.hasOwn(e,"choices"),_r=e=>Object.hasOwn(e,"output");function yr(e){let t=e.input_tokens+e.cache_read_input_tokens+e.cache_creation_input_tokens;return{prompt_tokens:t,completion_tokens:e.output_tokens,total_tokens:t+e.output_tokens,prompt_tokens_details:{cached_tokens:e.cache_read_input_tokens}}}function kr(e,t){try{let o=JSON.parse(e);if("message_start"===o.type){let e=o.message?.usage;if(e)return t.input_tokens=e.input_tokens||0,t.cache_read_input_tokens=e.cache_read_input_tokens||0,t.cache_creation_input_tokens=e.cache_creation_input_tokens||0,!0}if("message_delta"===o.type){let e=o.usage;if(e)return t.output_tokens=e.output_tokens||0,!0}}catch{}return!1}const wr=new D;wr.post("/",async e=>{try{return await fr(e)}catch(t){return await ct(e,t)}});const br=new D;function vr(e,t){let o=function(e){try{let t=JSON.parse(e);if(("response.completed"===t.type||"response.incomplete"===t.type)&&t.response?.usage){let e=t.response.usage;return{prompt_tokens:e.input_tokens,completion_tokens:e.output_tokens,total_tokens:e.total_tokens}}}catch{}return null}(e);if(!o)return;t.usageRef.value=o;let n=t.c.get("requestData")||{};n.tokenUsage=Zo(o),n._d1=t._d1,t.c.set("requestData",n)}br.get("/",async e=>{try{V.models||await ft();let t=V.models?.data.map(e=>({id:e.id,object:"model",type:"model",created:0,created_at:new Date(0).toISOString(),owned_by:e.vendor,display_name:e.name,context_length:e.capabilities.limits?.max_context_window_tokens}));return e.json({object:"list",data:t,has_more:!1})}catch(t){return await ct(e,t)}});const xr=new Set(["message","function_call","function_call_output"]),$r=new Set(["type","name","description","parameters"]);async function Tr(e){if(!e)return!1;let t=e.sources;if(t&&t.length>0)return!1;let n=e.query??e.queries?.[0];return!(!n||!V.tavilyApiKey)&&(o.info(`Enriching web search: "${n}"`),e.sources=(await ur(V.tavilyApiKey,n,{maxResults:5})).map(e=>({type:"url",url:e.url,title:e.title,content:e.content})),!0)}async function Ar(e){if(V.tavilyApiKey)try{for(let t of e.output){let e=t;"web_search_call"===e.type&&await Tr(e.action)}}catch(e){o.error("Failed to enrich non-streaming web search:",e)}}async function Sr(e){if(!V.tavilyApiKey)return e;try{let t=JSON.parse(e);if("response.output_item.done"===t.type){let e=t.item;if("web_search_call"===e?.type&&await Tr(e.action))return JSON.stringify(t)}}catch(e){o.error("Failed to enrich web search:",e)}return e}function Cr(e,t){if("function_call"!==e.type||!t.has(e.name))return!1;if(e.type="custom_tool_call","string"==typeof e.arguments){try{e.input=JSON.parse(e.arguments).input??e.arguments}catch{e.input=e.arguments}delete e.arguments}return!0}function Or(e,t){if(0===t.size)return e;try{let o=JSON.parse(e),n=o.type;if("response.output_item.added"===n||"response.output_item.done"===n){let e=o.item;if(e&&Cr(e,t))return JSON.stringify(o)}if("response.completed"===n){let n=o.response?.output;if(!n)return e;let r=!1;for(let e of n)Cr(e,t)&&(r=!0);if(r)return JSON.stringify(o)}}catch{}return e}function Er(e){return null!=e}function Ir(e){let t=e.input,o="string"==typeof t?t:t.map(e=>function(e){switch(e.type){case"custom_tool_call":{let t=e.input;return{type:"function_call",call_id:e.call_id,name:e.name,arguments:JSON.stringify("string"==typeof t?{input:t}:t)}}case"custom_tool_call_output":return{type:"function_call_output",call_id:e.call_id,output:e.output};default:return xr.has(e.type)||"web_search_call"===e.type?e:null}}(e)).filter(e=>null!==e),n={model:e.model,input:o};for(let t of["instructions","max_output_tokens","temperature","top_p","stream","store","tool_choice","parallel_tool_calls","user"])Er(e[t])&&(n[t]=e[t]);let r=new Set;if(Er(e.tools)){let t=function(e){let t=new Set;return{tools:e.filter(e=>{let t=e.type;return"function"===t||"custom"===t||"web_search"===t||t.startsWith("web_search_")}).map(e=>{let o=e.type;if("web_search"===o||o.startsWith("web_search_"))return{type:e.type};let n={};for(let t of Object.keys(e))$r.has(t)&&(n[t]=e[t]);return"custom"===n.type&&(n.type="function",t.add(n.name),n.parameters||={type:"object",properties:{input:{type:"string",description:"The freeform tool input content"}},required:["input"],additionalProperties:!1}),n}),customToolNames:t}}(e.tools);n.tools=t.tools,r=t.customToolNames}if(Er(e.reasoning)&&"object"==typeof e.reasoning){let t=e.reasoning;n.reasoning={},Er(t.effort)&&(n.reasoning.effort=t.effort),Er(t.summary)&&(n.reasoning.summary=t.summary)}if(Er(e.text)&&"object"==typeof e.text){let t=e.text;Er(t.format)&&(n.text={format:t.format})}return{payload:n,customToolNames:r}}async function Pr(e){await sn(V);let{payload:t,customToolNames:n}=Ir(await e.req.json()),r=t;o.debug(`Responses API [${Array.isArray(r.input)?r.input.length:1} items]`),n.size>0&&o.debug(`Custom tools detected: ${[...n].join(", ")}`);try{r=function(e){return ae.startActiveSpan("copilot_api.model.validate",t=>{try{t.setAttribute("copilot_api.model.requested",e.model);let n=an(e.model);return t.setAttribute("copilot_api.model.normalized",n),n===e.model?(t.setAttribute("copilot_api.model.was_mapped",!1),e):(t.setAttribute("copilot_api.model.was_mapped",!0),he.add(1,{from_model:e.model,to_model:n}),o.debug(`Normalized model from '${e.model}' to '${n}'`),{...e,model:n})}finally{t.end()}})}(r)}catch(t){if(t instanceof rn)return e.json({error:{message:t.message,type:"invalid_request_error",code:"invalid_model"}},t.statusCode);throw t}e.set("requestData",{model:r.model,streaming:!!r.stream}),V.manualApprove&&await Yo();let a=performance.now(),i=await Dn(r),s=performance.now()-a;if(Ae.record(s,{model:r.model,target:"responses",streaming:String(!!r.stream)}),Nr(i))return async function(e,t,o){await Ar(t);let n=e.get("requestData")||{};return t.usage&&(n.tokenUsage=Zo({prompt_tokens:t.usage.input_tokens,completion_tokens:t.usage.output_tokens,total_tokens:t.usage.total_tokens})),n._d1=o,e.set("requestData",n),e.json(t)}(e,i,s);let{events:l,span:c,release:u}=i;return H(e,async t=>{let o={value:null},a=0,i=performance.now();try{try{for await(let i of l)if(i.data&&"[DONE]"!==i.data){a++;let l=Or(i.data,n);l=await Sr(l);let c=l===i.data?i:{...i,data:l};be.add(1,{model:r.model,endpoint_type:"responses"}),vr(l,{usageRef:o,c:e,_d1:s}),await t.writeSSE(c)}else await t.writeSSE(i);let c=performance.now()-i,u={model:r.model,endpoint_type:"responses"};Se.record(c,u),qe.record(a,u)}catch(t){throw Me(c,e.get("requestSpan"),t),t}finally{o.value&&en(c,o.value),c.end(),u()}let p=e.get("requestId");p&&Z.executeCompletion(p)}finally{e.get("resolveStreamComplete")?.()}})}const Nr=e=>Object.hasOwn(e,"output"),qr=new D;qr.post("/",async e=>{try{return await Pr(e)}catch(t){return await ct(e,t)}});const Rr=new D;Rr.get("/",e=>{try{return e.json({token:V._t1})}catch(t){return o.error("Error fetching token:",t),e.json({error:"Failed to fetch token",token:null},500)}});const jr=new D;jr.get("/",async e=>{try{let t=await St();return e.json(t)}catch(t){return o.error("Error fetching usage:",t),e.json({error:"Failed to fetch usage"},500)}});const Dr=new D;Dr.use(async(e,t)=>{let n=Date.now(),r=`req_${Date.now()}_${Math.random().toString(36).slice(2,11)}`,a=e.req.method,c=e.req.path,p=function(e){return e.includes("/messages")?"anthropic":e.includes("/chat/completions")?"openai":e.includes("/embeddings")?"embeddings":e.includes("/models")?"models":e.includes("/usage")?"usage":e.includes("/token")?"token":"unknown"}(c);e.set("requestId",r),e.header("x-request-id",r);let d=ae.startSpan("copilot_api.handle_request",{kind:i.SERVER,attributes:{"http.method":a,"http.url":e.req.url,"http.route":c,"copilot_api.request_id":r,"copilot_api.endpoint_type":p}});e.set("requestSpan",d),e.set("requestTraceContext",d.spanContext());for(let[t,o]of Object.entries(e.req.header())){let e=t.toLowerCase();Fe.has(e)||d.setAttribute(`http.request.header.${e}`,o)}let m,f=new Promise(e=>{m=e});e.set("streamComplete",f),e.set("resolveStreamComplete",m);let h=u.setSpan(l.active(),d);await l.with(h,async()=>{Z.registerCompletion(r,e,n);try{await t()}catch(e){let t=e instanceof Error?e:Error(String(e));throw d.setStatus({code:s.ERROR,message:t.message}),d.recordException(t),e}});let g=e.get("requestData"),_={c:e,start:n,method:a,path:c,endpointType:p,requestId:r,span:d};g?.streaming&&e.res.status<400?f.then(()=>Vo(_)).catch(e=>{o.debug("Error finalizing streaming request:",e),d.end()}):Vo(_)}),Dr.use(M()),Dr.get("/",e=>e.text("Server running")),Dr.route("/health",Sn),Dr.route("/chat/completions",Tn),Dr.route("/models",br),Dr.route("/embeddings",An),Dr.route("/usage",jr),Dr.route("/token",Rr),Dr.route("/v1/chat/completions",Tn),Dr.route("/v1/models",br),Dr.route("/v1/embeddings",An),Dr.route("/v1/messages",wr),Dr.post("/v1/messages/count_tokens",async function(e){let t;try{t=await e.req.json()}catch{return e.json({error:{type:"invalid_request_error",message:"Invalid JSON"}},400)}if(!Array.isArray(t.messages))return e.json({error:{type:"invalid_request_error",message:"messages is required"}},400);let o=In.baseOverhead;if(t.system){let e="string"==typeof t.system?t.system:t.system.map(e=>e.text).join("\n\n");o+=In.perMessage+Pn(e)*In.contentMultiplier}for(let e of t.messages)o+=In.perMessage,o+=Pn(e.role),"string"==typeof e.content?o+=Pn(e.content)*In.contentMultiplier:Array.isArray(e.content)&&(o+=Nn(e.content));return t.tools&&t.tools.length>0&&(o+=function(e){let t=In.toolsExist;for(let[o,n]of e.entries())o>0&&(t+=In.perTool),t+=Pn(n.name),n.description&&(t+=In.perDesc+Pn(n.description)),t+=qn(n.input_schema);return t}(t.tools)),e.json({input_tokens:Math.round(o)})}),Dr.route("/v1/responses",qr),Dr.route("/responses",qr);const Mr=[],Hr=Date.now();let Fr="";function Br(){let e=async(e,t=0)=>{let n=ae.startSpan("copilot_api.server.shutdown",{kind:i.INTERNAL,attributes:{"copilot_api.shutdown.reason":e,"copilot_api.shutdown.exit_code":t,"copilot_api.uptime_seconds":(Date.now()-Hr)/1e3}});for(let t of Mr)try{await t()}catch(e){o.error("Error during cleanup:",e)}n.end(),function(e,t){let o=Oo("https://barazany.dev?utm_source=copilot-cli&utm_medium=terminal&utm_campaign=goodbye_banner","barazany.dev"),n=["",Io,` ${xo("COPILOT-API")} ${$o(`v${e}`)} ${$o("·")} ${Fo(t)} uptime`,Io,""," Check in from time to time on",` ${To(o)}`,"",Io,""];console.log(n.join("\n"))}(Fr,Date.now()-Hr),f.exit(t)};f.on("SIGINT",()=>e("SIGINT")),f.on("SIGTERM",()=>e("SIGTERM")),f.on("uncaughtException",t=>{o.error("Uncaught exception:",t),e("uncaughtException",1)}),f.on("unhandledRejection",(t,n)=>{o.error("Unhandled promise rejection at:",n,"reason:",t),e("unhandledRejection",1)})}async function Lr(e,t,n){if(!e._cc1)return!1;let r,a;if(V.models||(o.error("Cannot apply --claude-code defaults: model cache is empty (Copilot API was unreachable at startup). Retry once the network/API is back, or run without --claude-code."),f.exit(1)),e.model&&e.smallModel){let t=V.models.data.map(e=>e.id);if(!t.includes(e.model))throw o.info(`Available services: \n${t.join("\n")}`),Error(`Invalid model: ${e.model}`);if(!t.includes(e.smallModel))throw o.info(`Available services: \n${t.join("\n")}`),Error(`Invalid small model: ${e.smallModel}`);r=e.model,a=e.smallModel}else{if(e.model||e.smallModel)throw Error("Both --model and --small-model must be specified for model selection");r=await o.prompt("Select a model to use",{type:"select",options:V.models.data.map(e=>e.id)}),a=await o.prompt("Select a small model to use",{type:"select",options:V.models.data.map(e=>e.id)})}let i=vo({ANTHROPIC_BASE_URL:t,ANTHROPIC_AUTH_TOKEN:"dummy",ANTHROPIC_MODEL:r,ANTHROPIC_SMALL_FAST_MODEL:a,NODE_EXTRA_CA_CERTS:n?.certPath},"claude");try{return p.writeSync(i),!0}catch{return o.warn("Failed to copy to clipboard. Here is the command:"),o.log(i),!1}}async function Ur(e,t,n){if(!e.codex)return!1;let r;if(V.models||(o.error("Cannot apply --codex defaults: model cache is empty (Copilot API was unreachable at startup). Retry once the network/API is back, or run without --codex."),f.exit(1)),e.model){let t=V.models.data.map(e=>e.id);if(!t.includes(e.model))throw o.info(`Available services: \n${t.join("\n")}`),Error(`Invalid model: ${e.model}`);r=e.model}else r=await o.prompt("Select a model to use with Codex CLI",{type:"select",options:V.models.data.map(e=>e.id)});let a=vo({OPENAI_BASE_URL:t,OPENAI_API_KEY:"dummy",NODE_EXTRA_CA_CERTS:n?.certPath},`codex --model ${r}`);try{return p.writeSync(a),!0}catch{return o.warn("Failed to copy to clipboard. Here is the Codex CLI command:"),o.log(a),!1}}function Jr(e){return e._t2?"cli_arg":f.env.GH_TOKEN?"env_var":"stored"}function Gr(e){let{options:t,version:o,runtime:n,_u1:r}=e,a=ae.startSpan("copilot_api.server.startup",{kind:i.INTERNAL,attributes:He({config:{version:o,port:t.port,accountType:t.accountType,verbose:t.verbose,manualApprove:t.manual,rateLimitSeconds:t.rateLimit??0,rateLimitWait:t.rateLimitWait,timeoutMs:t.timeout,showToken:t.showToken,_cc1:t._cc1,model:t.model,smallModel:t.smallModel,_t3:Jr(t),enableThinking:t.enableThinking,nativeAnthropic:t.nativeAnthropic},runtime:n,identity:{_u1:r.login,machineId:V.machineId,sessionId:V.sessionId,_v1:V._v1},connectivity:V.connectivity,modelsCount:V.models?.data.length??0,startupDurationMs:Date.now()-Hr},"copilot_api")});if(V.models?.data)for(let e of V.models.data)a.addEvent("copilot_api.model.available",He(e,"model"));a.end(),je(h.INFO,"INFO","Server started",He({version:o,port:t.port,accountType:t.accountType,_u1:r.login,modelsCount:V.models?.data.length??0,startupDurationMs:Date.now()-Hr},"copilot_api"))}async function Kr(e){if(e.https){if(e.httpsCert&&e.httpsKey)return async function(e,t){let[o,r]=await Promise.all([n.readFile(e,"utf8"),n.readFile(t,"utf8")]);return{cert:o,key:r,certPath:e,keyPath:t,generated:!1}}(e.httpsCert,e.httpsKey);if(e.httpsCert||e.httpsKey)throw Error("Both --https-cert and --https-key must be provided together");return async function(e=[]){if(await Ko(e)){let e=await Go(Lo),t=await Go(Uo);if(e&&t)return{cert:e,key:t,certPath:Lo,keyPath:Uo,generated:!1}}return o.info("Generating new self-signed TLS certificate…"),zo(e)}(e.httpsHosts)}}async function Wr(e){let t=function(e){if(!e.claudeCowork)return e;if(e.httpsCert&&e.httpsKey)return{...e,https:!0};let{certPath:t,keyPath:n}=Gt;try{N(t),N(n)}catch{throw o.error("Tailscale cert not found. Run `copilot-api cowork-setup install` first."),Error("Tailscale cert not found")}return{...e,https:!0,httpsCert:t,httpsKey:n}}(e);if(Br(),Mr.push(()=>{o.debug("Cleaning up connectivity monitor"),Je.stop()},()=>{o.debug("Cleaning up token management"),o.debug("Cleaning up token management"),gt&&=void clearInterval(gt),_t&&=void Je.off("online",_t),yt&&=void Je.off("offline",yt)},async()=>{o.debug("Cleaning up HTTP/2 client"),await async function(){o.debug("Stopping HTTP/2 pool"),fo&&=void clearInterval(fo),ho&&=void clearInterval(ho);let e=[...uo.keys(),...po];uo.clear(),po.clear(),co.clear(),mo=void 0;for(let t of e)go(t)&&($e.add(1,{event:"closed"}),await t.close())}()},async()=>{o.debug("Shutting down OTel SDK"),await async function(){ee&&await ee.shutdown()}()}),t.verbose&&(o.level=5,o.info("Verbose logging enabled")),t._cc1&&t.codex)throw Error("Cannot use --claude-code and --codex together");V.accountType=t.accountType,V.manualApprove=t.manual,V.rateLimitSeconds=t.rateLimit,V.rateLimitWait=t.rateLimitWait,V.showToken=t.showToken,V.timeoutMs=t.timeout,V.thinkingEnabled=t.enableThinking,V.nativeAnthropicEnabled=t.nativeAnthropic,t.tavilyApiKey&&(V.tavilyApiKey=t.tavilyApiKey),function(){let e="1"===f.env.COPILOT_H2_KEEPALIVE||"true"===f.env.COPILOT_H2_KEEPALIVE,t=e||"1"===f.env.COPILOT_H2||"true"===f.env.COPILOT_H2;V.connectivity.h2=t,V.connectivity.h2Keepalive=e}(),await K(),V._v1="1.116.0-insider";let n=await Qt();Fr=n;let r=Zt();!function(e,t){t&&(oe=t),te=crypto.randomUUID();let o=w({[T]:"copilot-api",[A]:e,[$]:te}),{endpoint:n,headers:r}=re();ee=new x({resource:o,traceExporter:new k({url:`${n}/v1/traces`,headers:r}),metricReader:new v({exporter:new y({url:`${n}/v1/metrics`,headers:r}),exportIntervalMillis:15e3}),logRecordProcessors:[new b(new _({url:`${n}/v1/logs`,headers:r}))],instrumentations:[]}),ee.start()}(n,Hr);let a,i=t._t2||f.env.GH_TOKEN;i?(V._t2=i,o.info("Using provided Auth token")):await xt();try{a=await pt(),await Ye(V,a.login)}catch(e){throw o.error("Failed to get user info for machine ID generation:",e),Error("Cannot proceed without user information",{cause:e})}await vt(),await async function(){try{return await ft(),!0}catch(e){let t="object"==typeof e&&e&&"statusCode"in e&&"number"==typeof e.statusCode?e.statusCode:void 0,n=e instanceof Error?e.message:"Unknown error occurred",r=void 0===t?"":` (HTTP ${t})`;return o.warn(`Could not fetch model list from Copilot${r}: ${n}. This is likely a transient network or authentication issue. The proxy will start anyway; model listing endpoints may return empty until the cache is populated.`),!1}}()||function(e){let t=setTimeout(()=>{ft().then(()=>{o.info("Model cache populated successfully on deferred retry")}).catch(()=>{})},e);t.unref()}(3e4);let s=function(e=18e5){let t=setInterval(()=>{ft().then(()=>o.debug("Model list refreshed successfully")).catch(e=>{o.warn("Failed to refresh model list; keeping existing cache:",e)})},e);return t.unref(),()=>{clearInterval(t)}}();Mr.push(()=>{o.debug("Cleaning up model refresh interval"),s()}),V.connectivity.h2&&(ko(yo(Xe(V))),V.connectivity.h2Keepalive&&bo()),Gr({options:t,version:n,runtime:r,_u1:a});let l=await Kr(t),c=l?"https":"http",u=`${c}://localhost:${t.port}`,p=await Lr(t,u,l)||await Ur(t,u,l);(function(e){let t=[...Ro(e),...jo(e),...Do(e),"",...qo(No),...Mo(e),...Ho(e),""];console.log(t.join("\n"))})(await async function(e){let{options:t,version:o,runtime:n,user:r,clipboardCopied:a,tls:i}=e,s=i?"https":"http";return{version:o,runtime:n,user:r,accountType:t.accountType,port:t.port,timeout:t.timeout,webSearch:!!t.tavilyApiKey,model:t.model,smallModel:t.smallModel,clipboardCopied:a,https:i?{certPath:i.certPath,keyPath:i.keyPath,generated:i.generated,selfSigned:!t.httpsCert}:void 0,endpoints:t.claudeCowork?{scheme:s,port:t.port,hostname:await Nt()}:void 0}}({options:t,version:n,runtime:r,user:a.login,clipboardCopied:p,tls:l})),q({fetch:Dr.fetch,port:t.port,hostname:t.hostname,tls:l?{cert:l.cert,key:l.key}:void 0,bun:{idleTimeout:255}}),function(e,t,n){o.info(`Server listening on ${e}://${t}:${n}`)}(c,t.hostname,t.port)}function zr(e,t){let o=Number.parseInt(e,10);if(Number.isNaN(o))throw Error(`${t} must be a number, got: "${e}"`);return o}const Vr=e({meta:{name:"start",description:"Start the API server"},args:{port:{alias:"p",type:"string",default:"4141",description:"Port to listen on"},hostname:{alias:"H",type:"string",default:"127.0.0.1",description:"Hostname/IP to bind the server to. Defaults to 127.0.0.1 (localhost only) for security. Use 0.0.0.0 only when you intentionally need LAN/network/Docker exposure."},verbose:{alias:"v",type:"boolean",default:!1,description:"Enable verbose logging"},"account-type":{alias:"a",type:"string",default:"individual",description:"Account type (individual, business, enterprise)"},manual:{type:"boolean",default:!1,description:"Enable manual request approval"},"rate-limit":{alias:"r",type:"string",description:"Rate limit in seconds between requests"},wait:{alias:"w",type:"boolean",default:!1,description:"Wait instead of error when rate limit is hit. Has no effect if rate limit is not set"},"github-token":{alias:"g",type:"string",description:"Provide auth token directly (must be generated using the `auth` subcommand)"},"claude-code":{alias:"c",type:"boolean",default:!1,description:"Generate a command to launch with API config"},codex:{type:"boolean",default:!1,description:"Generate a command to launch Codex CLI with Copilot API config"},model:{alias:"m",type:"string",description:"Model to use (with --claude-code or --codex)"},"small-model":{alias:"s",type:"string",description:"Small/fast model to use (requires --claude-code)"},"show-token":{type:"boolean",default:!1,description:"Show tokens on fetch and refresh"},timeout:{alias:"t",type:"string",description:"API timeout in milliseconds (default: 600000)"},"tavily-api-key":{type:"string",description:"Tavily API key for web search support (or set TAVILY_API_KEY env var)"},"enable-thinking":{type:"boolean",default:!1,description:"Enable forwarding of thinking_budget / Anthropic thinking config to upstream. Off by default to avoid accidentally triggering reasoning behaviour."},"native-anthropic":{type:"boolean",default:!1,description:"Route Claude models directly to Copilot's native /v1/messages endpoint instead of translating through OpenAI format."},https:{type:"boolean",default:!1,description:"Serve over HTTPS using a self-signed certificate (auto-generated and persisted)"},"https-cert":{type:"string",description:"Path to a PEM-encoded TLS certificate (use with --https-key to bring your own cert)"},"https-key":{type:"string",description:"Path to a PEM-encoded TLS private key (use with --https-cert to bring your own cert)"},"https-hosts":{type:"string",description:"Extra hostnames or IPs to include in the self-signed cert's SANs (comma-separated). Example: --https-hosts host.docker.internal,192.168.1.42"},"claude-cowork":{type:"boolean",default:!1,description:"Print Claude Cowork-specific setup hints (inference endpoint URLs to paste into Cowork's apiHost setting)"}},run({args:e}){let t=e["rate-limit"],o=void 0===t?void 0:zr(t,"--rate-limit"),n=e.timeout,r=void 0===n?z:zr(n,"--timeout"),a=e["https-hosts"],i=a?a.split(",").map(e=>e.trim()).filter(Boolean):[];return Wr({port:zr(e.port,"--port"),hostname:e.hostname,verbose:e.verbose,accountType:e["account-type"],manual:e.manual,rateLimit:o,rateLimitWait:e.wait,_t2:e["github-token"],_cc1:e["claude-code"],codex:e.codex,model:e.model,smallModel:e["small-model"],showToken:e["show-token"],timeout:r,tavilyApiKey:e["tavily-api-key"]||f.env.TAVILY_API_KEY,enableThinking:e["enable-thinking"],nativeAnthropic:e["native-anthropic"],https:e.https,httpsCert:e["https-cert"],httpsKey:e["https-key"],httpsHosts:i,claudeCowork:e["claude-cowork"]})}});await async function(){try{if("1"===process.env.COPILOT_API_SKIP_UPDATE_CHECK)return;let[e,t]=await Promise.all([Qt(),so()]);if("unknown"===e||!t||!function(e,t){let o=e.split(".").map(Number),n=t.split(".").map(Number),r=Math.max(o.length,n.length);for(let e=0;e<r;e++){let t=o[e]??0,r=n[e]??0;if(t<r)return!0;if(t>r)return!1}return!1}(e,t))return;!function(e,t){let o=`npx ${no}@latest`,n=io("│"),r=` ${ao("Update available!")} ${(e=>`[2m${e}[0m`)(e)} → ${(e=>`[32m${e}[0m`)(t)}`,a=` Run ${ao(o)} to update`,i=" ".repeat(54),s=io(`╭${"─".repeat(54)}╮`),l=io(`╰${"─".repeat(54)}╯`),c=["",s,`${n}${i}${n}`,`${n}${lo(r,54)}${n}`,`${n}${i}${n}`,`${n}${lo(a,54)}${n}`,`${n}${i}${n}`,l,""];console.log(c.join("\n"))}(e,t)}catch{}}(),await t(e({meta:{name:"copilot-api",description:"API proxy server for tool integration."},subCommands:{auth:At,start:Vr,"check-usage":Ct,debug:oo,"cowork-setup":Xt}}));export{};
|