@draht/coding-agent 2026.11.19-1 → 2026.11.19

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.
Files changed (65) hide show
  1. package/dist/bundle/chunks/{anthropic-messages-7PTOA4ZA.js → anthropic-messages-W6HN7XZW.js} +1 -1
  2. package/dist/bundle/chunks/{azure-openai-responses-CDW6FCMN.js → azure-openai-responses-IYU6JN7E.js} +1 -1
  3. package/dist/bundle/chunks/bedrock-converse-stream.js +21 -21
  4. package/dist/bundle/chunks/{chunk-7HQNDYWE.js → chunk-3YSKFWGJ.js} +1 -1
  5. package/dist/bundle/chunks/{chunk-GAABJAG4.js → chunk-5K3TBDND.js} +3 -3
  6. package/dist/bundle/chunks/chunk-6MSE6LZ3.js +6 -0
  7. package/dist/bundle/chunks/{chunk-O2P5SYXT.js → chunk-6QA6EP5G.js} +1 -1
  8. package/dist/bundle/chunks/chunk-736QBNUZ.js +12 -0
  9. package/dist/bundle/chunks/{chunk-CAOOVEOM.js → chunk-AQ4POXF4.js} +1 -1
  10. package/dist/bundle/chunks/chunk-BIBUE2PO.js +2 -0
  11. package/dist/bundle/chunks/chunk-CLONDAPI.js +9 -0
  12. package/dist/bundle/chunks/{chunk-4FPBO5KP.js → chunk-G7DJ6PIU.js} +1 -1
  13. package/dist/bundle/chunks/{chunk-WOIC265R.js → chunk-GRGZRSVX.js} +28 -28
  14. package/dist/bundle/chunks/{chunk-JI5YDTBB.js → chunk-GYCFH7QD.js} +1 -1
  15. package/dist/bundle/chunks/{chunk-3F4OOENR.js → chunk-IRBBJMGW.js} +1 -1
  16. package/dist/bundle/chunks/{chunk-GQXRTK54.js → chunk-ITP6IDBA.js} +2 -2
  17. package/dist/bundle/chunks/{chunk-HKQ3PU5T.js → chunk-J5PACQAM.js} +1 -1
  18. package/dist/bundle/chunks/{chunk-BQMYLQSG.js → chunk-K4FC3EMH.js} +8 -8
  19. package/dist/bundle/chunks/{chunk-6WESOD4H.js → chunk-KVH4HR57.js} +1 -1
  20. package/dist/bundle/chunks/{chunk-KFREX3FS.js → chunk-QVGSXIKT.js} +1 -1
  21. package/dist/bundle/chunks/{chunk-B6OJ7QX4.js → chunk-RHXTTWD5.js} +1 -1
  22. package/dist/bundle/chunks/{chunk-INKDO5TZ.js → chunk-SM2YWAF2.js} +3 -3
  23. package/dist/bundle/chunks/{chunk-YOPX5URH.js → chunk-SYW5VSBL.js} +1 -1
  24. package/dist/bundle/chunks/chunk-TIA2T6EO.js +3 -0
  25. package/dist/bundle/chunks/{chunk-MHNW355A.js → chunk-WZMHLLKP.js} +1 -1
  26. package/dist/bundle/chunks/{chunk-RI7HJ6AF.js → chunk-XY64T2H6.js} +10 -10
  27. package/dist/bundle/chunks/{cli-QUYXUKRF.js → cli-KSFELY3W.js} +1 -1
  28. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-W63EWPDW.js → cloudflare-workers-ai-system-one-WIIL62VL.js} +1 -1
  29. package/dist/bundle/chunks/{execute-KGJOWTPG.js → execute-YOMYOVUT.js} +1 -1
  30. package/dist/bundle/chunks/{google-generative-ai-M5WKK5CW.js → google-generative-ai-NZVCFKM4.js} +1 -1
  31. package/dist/bundle/chunks/{google-vertex-UYNOGPMI.js → google-vertex-BL3BF2VF.js} +1 -1
  32. package/dist/bundle/chunks/https-proxy-agent-O2PVUIOI.js +13 -0
  33. package/dist/bundle/chunks/lib-XOG5PI3Y.js +9 -0
  34. package/dist/bundle/chunks/{llama-cpp-classify-SAUGLDPT.js → llama-cpp-classify-GP2X3HGE.js} +1 -1
  35. package/dist/bundle/chunks/{mistral-conversations-VQ3J6W5K.js → mistral-conversations-2REUBSZJ.js} +1 -1
  36. package/dist/bundle/chunks/{multipart-parser-HMCXZ4BD.js → multipart-parser-AZP5BX2W.js} +1 -1
  37. package/dist/bundle/chunks/{node-DXZFQBEO.js → node-BZAVEWJ3.js} +1 -1
  38. package/dist/bundle/chunks/{node-LBZLUIBE.js → node-C2JGH2OB.js} +1 -1
  39. package/dist/bundle/chunks/{openai-codex-responses-JTGQLYC7.js → openai-codex-responses-7MQGGA7O.js} +1 -1
  40. package/dist/bundle/chunks/{openai-completions-WAW7BG4E.js → openai-completions-MTNKQNK4.js} +1 -1
  41. package/dist/bundle/chunks/{openai-decisions-KHHHHMGW.js → openai-decisions-UYPZJCVG.js} +1 -1
  42. package/dist/bundle/chunks/{openai-responses-GWADST54.js → openai-responses-QVXIRAUW.js} +1 -1
  43. package/dist/bundle/chunks/{openrouter-images-AP626CWG.js → openrouter-images-E6VXUX3T.js} +1 -1
  44. package/dist/bundle/chunks/{pi-messages-H5TYIEJT.js → pi-messages-KPT6QQD4.js} +1 -1
  45. package/dist/bundle/chunks/{runtime-73OLLYOI.js → runtime-3ZSEARRN.js} +1 -1
  46. package/dist/bundle/chunks/{runtime-FZKS2BWI.js → runtime-S5WBSLTE.js} +1 -1
  47. package/dist/bundle/chunks/{settings-manager-CWRQW6PZ.js → settings-manager-H3QEOPQ3.js} +1 -1
  48. package/dist/bundle/chunks/src-TIBHS42X.js +4 -0
  49. package/dist/bundle/chunks/{typesafe-system-one-RLPGOT75.js → typesafe-system-one-5RPPTQ5S.js} +1 -1
  50. package/dist/bundle/chunks/{virtual-modules-5V4G5GQH.js → virtual-modules-HCLXUIRY.js} +1 -1
  51. package/dist/bundle/cli-runtime.js +1 -1
  52. package/dist/bundle/index.js +1 -1
  53. package/dist/bundle/rpc-entry.js +1 -1
  54. package/package.json +9 -9
  55. package/dist/bundle/chunks/chunk-2JZLKNZ4.js +0 -3
  56. package/dist/bundle/chunks/chunk-6M3D4XVD.js +0 -2
  57. package/dist/bundle/chunks/chunk-BIXKXDGW.js +0 -9
  58. package/dist/bundle/chunks/chunk-GBFVS2SF.js +0 -12
  59. package/dist/bundle/chunks/chunk-LO6CVU2L.js +0 -6
  60. package/dist/bundle/chunks/https-proxy-agent-WQIRL24U.js +0 -13
  61. package/dist/bundle/chunks/lib-ULKZYRGD.js +0 -9
  62. package/dist/bundle/chunks/src-KDGO7EGF.js +0 -4
  63. /package/dist/bundle/chunks/{chunk-ATYP3OSV.js → chunk-OPLOTJXH.js} +0 -0
  64. /package/dist/bundle/chunks/{chunk-ITKDPD4D.js → chunk-PX3CDFUB.js} +0 -0
  65. /package/dist/bundle/chunks/{chunk-MOOADNVS.js → chunk-ZZD35WKM.js} +0 -0
@@ -1,4 +1,4 @@
1
1
  import { createRequire as __drahtCreateRequire } from "node:module"; const require = __drahtCreateRequire(import.meta.url);
2
- import{AssistantMessageEventStream,formatThrownValue}from"./chunk-USCN7R2E.js";import{contentText,getOpenCodeSessionHeaders,getSystemMessageText,mergeClientIdentity,ownedSlice}from"./chunk-BIXKXDGW.js";import{__export}from"./chunk-HZ2UHMBT.js";function createInitialSystemMessage(systemPrompt,tools){let hasSystemPrompt=systemPrompt!==void 0&&systemPrompt.length>0,hasTools=tools!==void 0&&tools.length>0;if(!(!hasSystemPrompt&&!hasTools))return{role:"system",content:systemPrompt??"",...hasTools?{toolsAdded:tools}:{},timestamp:0}}function normalizeContext(context){let initialMessage=createInitialSystemMessage(context.systemPrompt,context.tools);return{messages:initialMessage?[initialMessage,...context.messages]:context.messages}}function isSystemMessage(message){return message.role==="system"}function getInitialSystemMessage(messages){let first=messages[0];return first&&isSystemMessage(first)?first:void 0}function withoutInitialSystemMessage(messages){return getInitialSystemMessage(messages)?messages.slice(1):messages}function getCurrentTools(messages){let tools=new Map;for(let message of messages)if(isSystemMessage(message)){for(let tool of message.toolsRemoved??[])tools.delete(tool.name);for(let tool of message.toolsAdded??[])tools.set(tool.name,tool)}return[...tools.values()]}function getCurrentSystemMessage(messages){let content=[],sections=new Map,timestamp;for(let message of messages){if(!isSystemMessage(message))continue;timestamp??=message.timestamp;let text=contentText(message.content);text.length>0&&content.push(text);for(let[name,value]of Object.entries(message.sections??{}))value===null?sections.delete(name):sections.set(name,value)}let tools=getCurrentTools(messages);if(!(timestamp===void 0&&tools.length===0))return{role:"system",content:content.join(`
2
+ import{AssistantMessageEventStream,formatThrownValue}from"./chunk-USCN7R2E.js";import{contentText,getOpenCodeSessionHeaders,getSystemMessageText,mergeClientIdentity,ownedSlice}from"./chunk-CLONDAPI.js";import{__export}from"./chunk-HZ2UHMBT.js";function createInitialSystemMessage(systemPrompt,tools){let hasSystemPrompt=systemPrompt!==void 0&&systemPrompt.length>0,hasTools=tools!==void 0&&tools.length>0;if(!(!hasSystemPrompt&&!hasTools))return{role:"system",content:systemPrompt??"",...hasTools?{toolsAdded:tools}:{},timestamp:0}}function normalizeContext(context){let initialMessage=createInitialSystemMessage(context.systemPrompt,context.tools);return{messages:initialMessage?[initialMessage,...context.messages]:context.messages}}function isSystemMessage(message){return message.role==="system"}function getInitialSystemMessage(messages){let first=messages[0];return first&&isSystemMessage(first)?first:void 0}function withoutInitialSystemMessage(messages){return getInitialSystemMessage(messages)?messages.slice(1):messages}function getCurrentTools(messages){let tools=new Map;for(let message of messages)if(isSystemMessage(message)){for(let tool of message.toolsRemoved??[])tools.delete(tool.name);for(let tool of message.toolsAdded??[])tools.set(tool.name,tool)}return[...tools.values()]}function getCurrentSystemMessage(messages){let content=[],sections=new Map,timestamp;for(let message of messages){if(!isSystemMessage(message))continue;timestamp??=message.timestamp;let text=contentText(message.content);text.length>0&&content.push(text);for(let[name,value]of Object.entries(message.sections??{}))value===null?sections.delete(name):sections.set(name,value)}let tools=getCurrentTools(messages);if(!(timestamp===void 0&&tools.length===0))return{role:"system",content:content.join(`
3
3
 
4
4
  `),...sections.size>0?{sections:Object.fromEntries(sections)}:{},...tools.length>0?{toolsAdded:tools}:{},timestamp:timestamp??0}}function getCurrentSystemPrompt(messages){let message=getCurrentSystemMessage(messages);return message?getSystemMessageText(message):""}function collapseSystemMessages(context){let head=getCurrentSystemMessage(context.messages),messages=context.messages.filter(message=>message.role!=="system");return{messages:head?[head,...messages]:messages}}function resolveTranscript(context,supportsMidConvoSystemMessages){return supportsMidConvoSystemMessages?context:collapseSystemMessages(context)}function toToolDeclaration(tool){return{name:tool.name,description:tool.description,parameters:JSON.parse(JSON.stringify(tool.parameters)),...tool.constrainedSampling===void 0?{}:{constrainedSampling:tool.constrainedSampling}}}function declarationsEqual(left,right){return JSON.stringify(toToolDeclaration(left))===JSON.stringify(toToolDeclaration(right))}function getToolStateChanges(previous,current){let previousTools=new Map(previous.map(tool=>[tool.name,tool])),currentTools=new Map(current.map(tool=>[tool.name,tool]));return{toolsAdded:current.filter(tool=>{let previousTool=previousTools.get(tool.name);return previousTool===void 0||!declarationsEqual(previousTool,tool)}).map(toToolDeclaration),toolsRemoved:previous.filter(tool=>{let currentTool=currentTools.get(tool.name);return currentTool===void 0||!declarationsEqual(tool,currentTool)}).map(tool=>({name:tool.name}))}}function getDeclaredTools(messages){let definitions=new Map;for(let message of messages)if(isSystemMessage(message))for(let tool of message.toolsAdded??[])definitions.set(tool.name,tool);return[...definitions.values()]}function hasToolRedefinitions(messages){let declared=new Map;for(let message of messages)if(isSystemMessage(message))for(let tool of message.toolsAdded??[]){let previous=declared.get(tool.name);if(previous!==void 0&&!declarationsEqual(previous,tool))return!0;declared.set(tool.name,tool)}return!1}function hasNonAdditiveToolChanges(messages){return findLastNonAdditiveToolChange(messages.filter(isSystemMessage))>=0}function findLastNonAdditiveToolChange(systemMessages){let declared=new Set,last=-1;for(let index=0;index<systemMessages.length;index++){let message=systemMessages[index];(message.toolsRemoved?.length??0)>0&&(last=index);for(let tool of message.toolsAdded??[])declared.has(tool.name)&&(last=index),declared.add(tool.name)}return last}function resolveTranscriptTools(messages,support){let systemMessages=messages.filter(isSystemMessage);if(support==="none")return{requestTools:getCurrentTools(systemMessages),foldedSystemMessages:systemMessages.length};if(support==="changes")return{requestTools:[],foldedSystemMessages:0};let folded=Math.max(getInitialSystemMessage(messages)?1:0,findLastNonAdditiveToolChange(systemMessages)+1);return{requestTools:getCurrentTools(systemMessages.slice(0,folded)),foldedSystemMessages:folded}}var models_exports={};__export(models_exports,{AI_TELEMETRY_SCHEMA:()=>AI_TELEMETRY_SCHEMA,ModelsError:()=>ModelsError,calculateCost:()=>calculateCost,clampThinkingLevel:()=>clampThinkingLevel,createModels:()=>createModels,createProvider:()=>createProvider,getModelType:()=>getModelType,getSupportedThinkingLevels:()=>getSupportedThinkingLevels,hasApi:()=>hasApi,isModelType:()=>isModelType,modelsAreEqual:()=>modelsAreEqual,supportsMax:()=>supportsMax,supportsXhigh:()=>supportsXhigh});function createSetupErrorMessage(model2,error,timestamp,stopReason){return{role:"assistant",content:[],api:model2.api,provider:model2.provider,model:model2.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason,errorMessage:error instanceof Error?error.message:String(error),timestamp}}function hasResult(source){return typeof source.result=="function"}async function forwardStream(target,source,observer,observeResult){let result;for await(let event of source)target.push(event),observer?.onEvent?.(event),event.type==="done"?result=event.message:event.type==="error"&&(result=event.error);hasResult(source)&&(result=await source.result()),target.end(result),observeResult(result)}function lazyStream(model2,setup,observer,signal){let startedAt=Date.now(),outer=new AssistantMessageEventStream,observedResult=!1,observeResult=result=>{observedResult||(observedResult=!0,observer?.onResult?.(result))};return setup().then(inner=>forwardStream(outer,inner,observer,observeResult)).catch(error=>{let reason=signal?.aborted?"aborted":"error",message=createSetupErrorMessage(model2,error,startedAt,reason),event={type:"error",reason,error:message};outer.push(event),observer?.onEvent?.(event),outer.end(message),observeResult(message)}),outer}function lazyApi(load,capabilities){let api={stream:(model2,context,options)=>lazyStream(model2,async()=>(await load()).stream(model2,context,options),void 0,options?.signal),streamSimple:(model2,context,options)=>lazyStream(model2,async()=>(await load()).streamSimple(model2,context,options),void 0,options?.signal)};return capabilities?.fetchDeferred&&(api.fetchDeferred=(model2,handle,options)=>lazyStream(model2,async()=>{let implementation=await load();if(!implementation.fetchDeferred)throw new Error("API does not support deferred responses");return implementation.fetchDeferred(model2,handle,options)},void 0,options?.signal)),capabilities?.cancelDeferred&&(api.cancelDeferred=async(model2,handle,options)=>{let implementation=await load();if(!implementation.cancelDeferred)throw new Error("API cannot cancel deferred responses");await implementation.cancelDeferred(model2,handle,options)}),api}var __rewriteRelativeImportExtension=function(path,preserveJsx){return typeof path=="string"&&/^\.\.?\//.test(path)?path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(m,tsx,d,ext,cm){return tsx?preserveJsx?".jsx":".js":d&&(!ext||!cm)?m:d+ext+"."+cm.toLowerCase()+"js"}):path},importNodeModule=specifier=>import(__rewriteRelativeImportExtension(specifier));function getProcessEnv(){return globalThis.process?.env}function defaultProviderAuthContext(){return{async env(name){let value=getProcessEnv()?.[name];return typeof value=="string"&&value.trim().length>0?value:void 0},async fileExists(path){try{let fs=await importNodeModule("node:fs/promises"),resolved=path;return resolved.startsWith("~")&&(resolved=(await importNodeModule("node:os")).homedir()+resolved.slice(1)),await fs.access(resolved),!0}catch{return!1}}}}function abortReason(signal){if(signal.reason!==void 0)return signal.reason;let error=new Error("The operation was aborted");return error.name="AbortError",error}function operationSignal(signal){return signal??new AbortController().signal}function raceWithAbortSignal(operation,signal){return signal.aborted?(operation.catch(()=>{}),Promise.reject(abortReason(signal))):new Promise((resolve,reject)=>{let settled=!1,cleanup=()=>signal.removeEventListener("abort",onAbort),onAbort=()=>{settled||(settled=!0,cleanup(),reject(abortReason(signal)))};signal.addEventListener("abort",onAbort,{once:!0}),operation.then(value=>{settled||(settled=!0,cleanup(),resolve(value))},error=>{settled||(settled=!0,cleanup(),reject(error))}),signal.aborted&&onAbort()})}var InMemoryCredentialStore=class{credentials=new Map;chains=new Map;enqueue(providerId,task,options){let signal=operationSignal(options?.signal),previous=this.chains.get(providerId)??Promise.resolve(),queued=(async()=>(await previous.catch(()=>{}),signal.throwIfAborted(),task()))(),tail=queued.catch(()=>{});return this.chains.set(providerId,tail),tail.then(()=>{this.chains.get(providerId)===tail&&this.chains.delete(providerId)}),raceWithAbortSignal(queued,signal)}async read(providerId,options){return options?.signal?.throwIfAborted(),this.credentials.get(providerId)}async list(options){return options?.signal?.throwIfAborted(),[...this.credentials].map(([providerId,credential])=>({providerId,type:credential.type}))}modify(providerId,fn,options){return this.enqueue(providerId,async()=>{let current=this.credentials.get(providerId),next=await fn(current);return options?.signal?.throwIfAborted(),next!==void 0&&this.credentials.set(providerId,next),next??current},options)}delete(providerId,options){return this.enqueue(providerId,async()=>{this.credentials.delete(providerId)},options)}};var ModelsError=class extends Error{code;constructor(code,message,options){super(withCauseDetail(message,options?.cause),options),this.name="ModelsError",this.code=code}};function withCauseDetail(message,cause){if(cause==null)return message;let detail=formatThrownValue(cause).trim();return!detail||message.includes(detail)?message:`${message}: ${detail}`}function resolveProviderAuth(provider2,credentials,authContext,overrides){let signal=operationSignal(overrides?.signal);return raceWithAbortSignal(resolveProviderAuthWithSignal(provider2,credentials,authContext,overrides,signal),signal)}async function resolveProviderAuthWithSignal(provider2,credentials,authContext,overrides,signal){signal.throwIfAborted();let requestAuthContext=overrides?.env?overlayEnvAuthContext(authContext,overrides.env):authContext;if(overrides?.apiKey!==void 0&&provider2.auth.apiKey)return resolveApiKey(requestAuthContext,provider2.auth.apiKey,provider2.id,{type:"api_key",key:overrides.apiKey,env:overrides.env},signal);let stored=await readCredential(credentials,provider2.id,signal);if(stored){if(stored.type==="oauth"&&provider2.auth.oauth)return resolveStoredOAuth(credentials,provider2.id,provider2.auth.oauth,stored,signal,overrides?.minOAuthValidityMs);if(stored.type==="api_key"&&provider2.auth.apiKey){let credential=overrides?.env?{...stored,env:{...stored.env,...overrides.env}}:stored;return resolveApiKey(requestAuthContext,provider2.auth.apiKey,provider2.id,credential,signal)}return}return provider2.auth.apiKey?resolveApiKey(requestAuthContext,provider2.auth.apiKey,provider2.id,void 0,signal):void 0}function overlayEnvAuthContext(base,env){return{env:async name=>env[name]||await base.env(name),fileExists:path=>base.fileExists(path)}}var DEFAULT_OAUTH_MINIMUM_VALIDITY_MS=300*1e3,DEFAULT_OAUTH_REFRESH_TIMEOUT_MS=15e3;async function refreshStoredOAuthCredential(credentials,providerId,oauth,needsRefresh,signal){let post,lockWait=new AbortController,cancelLockWait=()=>lockWait.abort(signal.reason);signal.addEventListener("abort",cancelLockWait,{once:!0}),signal.aborted&&cancelLockWait();try{post=await credentials.modify(providerId,async current=>{if(signal.removeEventListener("abort",cancelLockWait),signal.throwIfAborted(),current?.type==="oauth"&&needsRefresh(current))try{return await oauth.refresh(current,AbortSignal.timeout(DEFAULT_OAUTH_REFRESH_TIMEOUT_MS))}catch(error){throw new ModelsError("oauth",`OAuth refresh failed for ${providerId}`,{cause:error})}},{signal:lockWait.signal})}catch(error){throw error instanceof ModelsError?error:(signal.throwIfAborted(),new ModelsError("auth",`Credential store modify failed for ${providerId}`,{cause:error}))}finally{signal.removeEventListener("abort",cancelLockWait)}return post?.type==="oauth"?post:void 0}async function resolveStoredOAuth(credentials,providerId,oauth,stored,signal,minOAuthValidityMs){let minimumValidityMs=Math.max(DEFAULT_OAUTH_MINIMUM_VALIDITY_MS,minOAuthValidityMs??0),expiresSoon=credential2=>Date.now()+minimumValidityMs>=credential2.expires,credential=stored;if(expiresSoon(credential)){let post=await refreshStoredOAuthCredential(credentials,providerId,oauth,expiresSoon,signal);if(!post)return;if(credential=post,minOAuthValidityMs!==void 0&&expiresSoon(credential))throw new ModelsError("oauth",`OAuth refresh returned a token that expires too soon for ${providerId}`)}try{return{auth:await oauth.toAuth(credential),source:"OAuth"}}catch(error){throw new ModelsError("oauth",`OAuth auth derivation failed for ${providerId}`,{cause:error})}}async function resolveApiKey(authContext,apiKey,providerId,credential,signal){try{return await apiKey.resolve({ctx:authContext,credential,signal})}catch(error){throw new ModelsError("auth",`API key auth failed for provider ${providerId}`,{cause:error})}}async function readCredential(credentials,providerId,signal){try{return await credentials.read(providerId,{signal})}catch(error){throw new ModelsError("auth",`Credential store read failed for ${providerId}`,{cause:error})}}var InMemoryModelsStore=class{entries=new Map;async read(providerId,options){options?.signal?.throwIfAborted();let entry=this.entries.get(providerId);return entry?structuredClone(entry):void 0}async write(providerId,entry,options){options?.signal?.throwIfAborted(),this.entries.set(providerId,structuredClone(entry))}async delete(providerId,options){options?.signal?.throwIfAborted(),this.entries.delete(providerId)}};function createTypedMetrics(metrics,schemas){let definitions=new Map;for(let schema of schemas)for(let[name,definition]of Object.entries(schema.metrics??{}))definitions.set(name,definition);return{counter:name=>metrics.counter(name,definitions.get(name)),upDownCounter:name=>metrics.upDownCounter(name,definitions.get(name)),histogram:name=>metrics.histogram(name,definitions.get(name))}}async function startNoopSpan(_options,callback){return callback(noopTelemetrySpan)}var noopCounter=Object.freeze({add:()=>{}}),noopUpDownCounter=Object.freeze({add:()=>{}}),noopHistogram=Object.freeze({record:()=>{}}),NOOP_TELEMETRY_METRICS=Object.freeze({counter:()=>noopCounter,upDownCounter:()=>noopUpDownCounter,histogram:()=>noopHistogram}),NOOP_TELEMETRY_PROPAGATION=Object.freeze({inject:()=>{},extract:()=>NOOP_TELEMETRY_CONTEXT}),noopTelemetrySpan={metrics:NOOP_TELEMETRY_METRICS,propagation:NOOP_TELEMETRY_PROPAGATION,startSpan:startNoopSpan,addLink:()=>{},addEvent:()=>{},setAttributes:()=>{},setStatus:()=>{}};Object.freeze(noopTelemetrySpan);var NOOP_TELEMETRY_CONTEXT=noopTelemetrySpan;var anchor=performance.timeOrigin;function bindTypedSpanStarter(telemetryContext){return(name,attributes,callback)=>telemetryContext.startSpan({name,attributes},span=>callback(span,bindTypedSpanStarter(span)))}function createTypedSpanStarter(telemetryContext,_schemas){return bindTypedSpanStarter(telemetryContext)}var provider={type:"string",description:"Provider identifier.",required:!0},model={type:"string",description:"Requested model identifier.",required:!0},stop={type:"string",description:"Normalized stop reason.",values:["pending","stop","length","toolUse","error","aborted","deferred"]},request={description:"One logical model request, including authentication and provider setup.",parents:{kind:"any"},startAttributes:{provider,api:{type:"string",description:"API identifier.",required:!0},model,reasoning:{type:"string",description:"Scalar requested reasoning level.",required:!1}},endAttributes:{stop,"usage.input":{type:"number",description:"Uncached input tokens."},"usage.output":{type:"number",description:"Output tokens."},"usage.cache_read":{type:"number",description:"Cache-read tokens."},"usage.cache_write":{type:"number",description:"Cache-write tokens."},"cost.total":{type:"number",description:"Total request cost in USD."},"response.id":{type:"string",description:"Provider response identifier.",cardinality:"high"}},events:{"pi.ai.first_chunk":{description:"First normalized stream event delivered.",attributes:{}},"pi.ai.block":{description:"A completed content block; content is never recorded.",attributes:{type:{type:"string",description:"Block kind.",values:["text","thinking","tool_call"],required:!0},index:{type:"number",description:"Content block index.",required:!0},chars:{type:"number",description:"UTF-16 character count.",required:!0},tool:{type:"string",description:"Tool name, for tool-call blocks only.",required:!1}}}},status:{default:"ok",errorWhen:"Stop reason is error: provider_error with at most 500 error-message characters. Aborted stays ok."}},AI_TELEMETRY_SCHEMA={version:1,spans:{"pi.ai.request":request,"pi.ai.poll":{...request,description:"One deferred-response poll, not the deferred request's lifetime."}},metrics:{"pi.ai.request.duration":{kind:"histogram",description:"Logical request or poll duration.",unit:"ms",attributes:{provider,model,stop:{...stop,required:!0}}},"pi.ai.first_chunk.duration":{kind:"histogram",description:"Time to the first normalized stream event.",unit:"ms",attributes:{provider,model}},"pi.ai.tokens":{kind:"counter",description:"Reported model token usage; pending and deferred polls are excluded.",unit:"token",attributes:{provider,model,kind:{type:"string",description:"Token usage category.",values:["input","output","cache_read","cache_write"],required:!0}}},"pi.ai.cost":{kind:"counter",description:"Reported model cost; pending and deferred polls are excluded.",unit:"USD",attributes:{provider,model}}}};function createInstruments(adapter){let metrics=createTypedMetrics(adapter,[AI_TELEMETRY_SCHEMA]);return{requestDuration:metrics.histogram("pi.ai.request.duration"),firstChunkDuration:metrics.histogram("pi.ai.first_chunk.duration"),tokens:metrics.counter("pi.ai.tokens"),cost:metrics.counter("pi.ai.cost")}}var instrumentCache=new WeakMap;function observeModelRequest(requestedModel,options,poll){let started=performance.now(),attributes={provider:requestedModel.provider,model:requestedModel.id},adapter=options?.telemetry?.metrics??NOOP_TELEMETRY_METRICS,instruments=instrumentCache.get(adapter);instruments||(instruments=createInstruments(adapter),instrumentCache.set(adapter,instruments));let{requestDuration,firstChunkDuration,tokens,cost}=instruments,span,finish,first=!0,toolChars=new Map,finished=new Promise(resolve=>{finish=resolve}),run=activeSpan=>(span=activeSpan,finished),startAttributes={...attributes,api:requestedModel.api,...typeof options?.reasoning=="string"?{reasoning:options.reasoning}:{}},start=createTypedSpanStarter(options?.telemetry??NOOP_TELEMETRY_CONTEXT,[AI_TELEMETRY_SCHEMA]);return start(poll?"pi.ai.poll":"pi.ai.request",startAttributes,run),{onEvent(event){if(first&&(first=!1,span.addEvent("pi.ai.first_chunk"),firstChunkDuration.record(performance.now()-started,attributes,span)),event.type==="toolcall_delta")toolChars.set(event.contentIndex,(toolChars.get(event.contentIndex)??0)+event.delta.length);else if(event.type==="text_end"||event.type==="thinking_end")span.addEvent("pi.ai.block",{type:event.type==="text_end"?"text":"thinking",index:event.contentIndex,chars:event.content.length});else if(event.type==="toolcall_end"){let chars=toolChars.get(event.contentIndex)??0;toolChars.delete(event.contentIndex),span.addEvent("pi.ai.block",{type:"tool_call",index:event.contentIndex,chars,tool:event.toolCall.name})}},onResult(message){message&&(span.setAttributes({stop:message.stopReason,"usage.input":message.usage.input,"usage.output":message.usage.output,"usage.cache_read":message.usage.cacheRead,"usage.cache_write":message.usage.cacheWrite,"cost.total":message.usage.cost.total,"response.id":message.responseId}),message.stopReason==="error"&&span.setStatus({status:"error",error:{name:"provider_error",message:ownedSlice(message.errorMessage??"",0,500)}}),requestDuration.record(performance.now()-started,{...attributes,stop:message.stopReason},span),(!poll||message.stopReason!=="pending"&&message.stopReason!=="deferred")&&(tokens.add(message.usage.input,{...attributes,kind:"input"}),tokens.add(message.usage.output,{...attributes,kind:"output"}),tokens.add(message.usage.cacheRead,{...attributes,kind:"cache_read"}),tokens.add(message.usage.cacheWrite,{...attributes,kind:"cache_write"}),cost.add(message.usage.cost.total,attributes))),finish()}}}function getModelType(model2){return model2.type??"chat"}function isModelType(model2,type){return getModelType(model2)===type}function assertChatModel(model2){if(!isModelType(model2,"chat"))throw new ModelsError("provider",`Model ${model2.provider}/${model2.id} is not a chat model`)}function assertImageModel(model2){if(!isModelType(model2,"image"))throw new ModelsError("provider",`Model ${model2.provider}/${model2.id} is not an image model`)}function assertClassifierModel(model2){if(!isModelType(model2,"classifier"))throw new ModelsError("provider",`Model ${model2.provider}/${model2.id} is not a classifier model`)}function assertClassifierInputSupported(model2,context){if(context.images?.length&&!model2.input.includes("image"))throw new ModelsError("provider",`Model ${model2.provider}/${model2.id} does not accept image input`)}function imageErrorResult(model2,error,aborted=!1){return{api:model2.api,provider:model2.provider,model:model2.id,output:[],stopReason:aborted?"aborted":"error",errorMessage:error instanceof Error?error.message:String(error),timestamp:Date.now()}}function classifierErrorResult(model2,error,aborted=!1){return{api:model2.api,provider:model2.provider,model:model2.id,answers:{},stopReason:aborted?"aborted":"error",errorMessage:error instanceof Error?error.message:String(error),timestamp:Date.now()}}var KNOWN_MODEL_TYPES={chat:!0,image:!0,classifier:!0};function hasKnownModelType(model2){return Object.hasOwn(KNOWN_MODEL_TYPES,getModelType(model2))}function withKnownModelTypes(entry){return{...entry,models:entry.models.filter(hasKnownModelType)}}function mergeHeaders(base,override){if(!base&&!override)return;let merged={...base};for(let[name,value]of Object.entries(override??{})){let lowerName=name.toLowerCase();for(let existingName of Object.keys(merged))existingName.toLowerCase()===lowerName&&delete merged[existingName];merged[name]=value}return merged}var ModelsImpl=class{providers=new Map;credentials;modelsStore;authContext;identity;refreshGenerations=new Map;refreshControllers=new Map;publicationChains=new Map;constructor(options){this.credentials=options?.credentials??new InMemoryCredentialStore,this.modelsStore=options?.modelsStore??new InMemoryModelsStore,this.authContext=options?.authContext??defaultProviderAuthContext(),this.identity=options?.identity}setProvider(provider2){this.supersedeProviderRefresh(provider2.id),this.providers.set(provider2.id,provider2)}deleteProvider(id){this.supersedeProviderRefresh(id),this.providers.delete(id)}clearProviders(){for(let id of new Set([...this.providers.keys(),...this.refreshControllers.keys()]))this.supersedeProviderRefresh(id);this.providers.clear()}getProviders(){return Array.from(this.providers.values())}getProvider(id){return this.providers.get(id)}getModels(provider2){if(provider2!==void 0){let entry=this.providers.get(provider2);if(!entry)return[];try{return entry.getModels()}catch{return[]}}let models=[];for(let entry of this.providers.values())try{models.push(...entry.getModels())}catch{}return models}getAllModels(provider2){if(provider2!==void 0){let entry=this.providers.get(provider2);if(!entry)return[];try{return entry.getAllModels?.()??entry.getModels()}catch{return[]}}let models=[];for(let entry of this.providers.values())try{models.push(...entry.getAllModels?.()??entry.getModels())}catch{}return models}getModelsOfType(type,provider2){return this.getAllModels(provider2).filter(model2=>isModelType(model2,type))}getModel(provider2,id){return this.getModels(provider2).find(model2=>model2.id===id)}getModelOfType(type,provider2,id){return this.getModelsOfType(type,provider2).find(model2=>model2.id===id)}supersedeProviderRefresh(providerId){let generation=(this.refreshGenerations.get(providerId)??0)+1;this.refreshGenerations.set(providerId,generation);let previous=this.refreshControllers.get(providerId);return previous&&(this.refreshControllers.delete(providerId),previous.abort()),generation}beginProviderRefresh(providerId){let generation=this.supersedeProviderRefresh(providerId),controller=new AbortController;return this.refreshControllers.set(providerId,controller),{generation,controller}}publishProviderModels(providerId,generation,signal,publication){let previous=this.publicationChains.get(providerId)??Promise.resolve(),queued=(async()=>(await previous.catch(()=>{}),signal.aborted||this.refreshGenerations.get(providerId)!==generation||(publication.persist===null?await this.modelsStore.delete(providerId,{signal}):publication.persist!==void 0&&await this.modelsStore.write(providerId,structuredClone(publication.persist),{signal}),signal.aborted||this.refreshGenerations.get(providerId)!==generation)?!1:(publication.update?.(),!0)))(),tail=queued.catch(()=>{});return this.publicationChains.set(providerId,tail),tail.then(()=>{this.publicationChains.get(providerId)===tail&&this.publicationChains.delete(providerId)}),raceWithAbortSignal(queued,signal)}async runProviderRefreshPhase(provider2,credential,allowNetwork,force,generation,signal){let stored=await this.modelsStore.read(provider2.id,{signal});await provider2.refreshModels({credential,stored:stored?withKnownModelTypes(structuredClone(stored)):void 0,publish:publication=>this.publishProviderModels(provider2.id,generation,signal,publication),allowNetwork,force:allowNetwork?force:void 0,signal,baseUrl:provider2.baseUrl})}async refresh(options={}){let allowNetwork=options.allowNetwork??!0,callerSignal=operationSignal(options.signal),errors=new Map;if(callerSignal.aborted)return{aborted:!0,errors};let selected=options.providers?new Set(options.providers):void 0,refreshable=Array.from(this.providers.values()).filter(provider2=>provider2.refreshModels!==void 0&&(!selected||selected.has(provider2.id))),refresh=Promise.all(refreshable.map(async provider2=>{let{generation,controller}=this.beginProviderRefresh(provider2.id),signal=AbortSignal.any([callerSignal,controller.signal]),operation=(async()=>{let storedCredential,credentialError;try{storedCredential=await this.readCredential(provider2.id,signal)}catch(error){credentialError=error}if(await this.runProviderRefreshPhase(provider2,storedCredential,!1,void 0,generation,signal),credentialError!==void 0)throw credentialError;if(!allowNetwork||signal.aborted)return;let network=await this.resolveNetworkRefresh(provider2,storedCredential,signal);network&&await this.runProviderRefreshPhase(provider2,network.credential,!0,options.force,generation,signal)})();try{await raceWithAbortSignal(operation,signal)}catch(error){signal.aborted||errors.set(provider2.id,error instanceof Error?error:new ModelsError("model_source",`Model refresh failed for ${provider2.id}`,{cause:error}))}finally{this.refreshControllers.get(provider2.id)===controller&&this.refreshControllers.delete(provider2.id)}}));try{await raceWithAbortSignal(refresh,callerSignal)}catch(error){if(!callerSignal.aborted)throw error}return{aborted:callerSignal.aborted,errors:new Map(errors)}}async resolveNetworkRefresh(provider2,stored,signal){if(provider2.refreshModelsAuth==="configured")return await this.checkProviderAuth(provider2,stored,signal)?{}:void 0;let credential=await this.resolveRefreshCredential(provider2,stored,signal);return credential?{credential}:void 0}async resolveRefreshCredential(provider2,stored,signal){if(stored?.type==="oauth"){let oauth=provider2.auth.oauth;return oauth?Date.now()<stored.expires?stored:signal.aborted?void 0:refreshStoredOAuthCredential(this.credentials,provider2.id,oauth,current=>Date.now()>=current.expires,signal):void 0}let apiKey=provider2.auth.apiKey;if(!apiKey)return;let credential=stored?.type==="api_key"?stored:void 0,result=await apiKey.resolve({ctx:this.authContext,credential,signal});if(result)return{type:"api_key",key:result.auth.apiKey,env:result.env}}async readCredential(providerId,signal){try{return await this.credentials.read(providerId,{signal})}catch(error){throw new ModelsError("auth",`Credential store read failed for ${providerId}`,{cause:error})}}async checkProviderAuth(provider2,credential,signal){if(credential?.type==="oauth")return provider2.auth.oauth?{source:"OAuth",type:"oauth"}:void 0;let apiKey=provider2.auth.apiKey;if(!apiKey)return;if(apiKey.check)try{return await apiKey.check({ctx:this.authContext,credential:credential?.type==="api_key"?credential:void 0,signal})}catch(error){throw new ModelsError("auth",`API key auth check failed for provider ${provider2.id}`,{cause:error})}let resolution=await resolveProviderAuth(provider2,this.credentials,this.authContext,{signal});return resolution?{source:resolution.source,type:"api_key"}:void 0}checkAuth(providerId,options){let signal=operationSignal(options?.signal),check=(async()=>{signal.throwIfAborted();let provider2=this.providers.get(providerId);if(provider2)return this.checkProviderAuth(provider2,await this.readCredential(providerId,signal),signal)})();return raceWithAbortSignal(check,signal)}async getAuthenticatedProviders(providerId,signal){signal.throwIfAborted();let providers=providerId?[this.providers.get(providerId)].filter(entry=>entry!==void 0):this.getProviders();return(await Promise.all(providers.map(async provider2=>{let credential=await this.readCredential(provider2.id,signal);return{provider:provider2,credential,auth:await this.checkProviderAuth(provider2,credential,signal)}}))).filter(entry=>entry.auth!==void 0)}getAvailable(providerId,options){let signal=operationSignal(options?.signal),available=(async()=>(await this.getAuthenticatedProviders(providerId,signal)).flatMap(({provider:provider2,credential})=>{let models=provider2.getModels();return provider2.filterModels?.(models,credential)??models}))();return raceWithAbortSignal(available,signal)}async getAvailableOfType(type,providerId,options){return(await this.getAllAvailable(providerId,options)).filter(model2=>isModelType(model2,type))}getAllAvailable(providerId,options){let signal=operationSignal(options?.signal),available=(async()=>(await this.getAuthenticatedProviders(providerId,signal)).flatMap(({provider:provider2,credential})=>{let models=provider2.getAllModels?.()??provider2.getModels();if(provider2.filterAllModels)return provider2.filterAllModels(models,credential);if(!provider2.filterModels)return models;let availableChatIds=new Set(provider2.filterModels(provider2.getModels(),credential).map(model2=>model2.id));return models.filter(model2=>!isModelType(model2,"chat")||availableChatIds.has(model2.id))}))();return raceWithAbortSignal(available,signal)}async getAuth(providerOrModel,overrides){let signal=operationSignal(overrides?.signal),providerId=typeof providerOrModel=="string"?providerOrModel:providerOrModel.provider,provider2=this.providers.get(providerId);if(!provider2)return;let result=await resolveProviderAuth(provider2,this.credentials,this.authContext,{...overrides,signal});return!result||typeof providerOrModel=="string"||!providerOrModel.headers?result:{...result,auth:{...result.auth,headers:mergeHeaders(result.auth.headers,providerOrModel.headers)}}}async login(providerId,type,interaction,options){let signal=operationSignal(interaction.signal);signal.throwIfAborted();let provider2=this.providers.get(providerId);if(!provider2)throw new ModelsError("provider",`Unknown provider: ${providerId}`);let method=type==="oauth"?provider2.auth.oauth:provider2.auth.apiKey;if(!method?.login)throw new ModelsError("auth",`${provider2.name} does not support ${type} login`);let loginOperation=method.login({...interaction,signal},options),credential=await raceWithAbortSignal(loginOperation,signal),mutationStarted=!1,markMutationStarted,started=new Promise(resolve=>{markMutationStarted=resolve}),mutation=this.credentials.modify(providerId,async()=>(mutationStarted=!0,markMutationStarted?.(),credential),{signal});mutation.catch(()=>{});try{await new Promise((resolve,reject)=>{let onAbort=()=>{mutationStarted||reject(signal.reason)};signal.addEventListener("abort",onAbort,{once:!0}),Promise.race([started,mutation]).then(()=>{signal.removeEventListener("abort",onAbort),resolve()},error=>{signal.removeEventListener("abort",onAbort),reject(error)}),signal.aborted&&onAbort()}),await mutation}catch(error){throw signal.throwIfAborted(),new ModelsError("auth",`Credential store modify failed for ${providerId}`,{cause:error})}return credential}async logout(providerId,options){let signal=operationSignal(options?.signal);signal.throwIfAborted();try{await this.credentials.delete(providerId,{signal})}catch(error){throw signal.throwIfAborted(),new ModelsError("auth",`Credential store delete failed for ${providerId}`,{cause:error})}}requireProvider(model2){let provider2=this.providers.get(model2.provider);if(!provider2)throw new ModelsError("provider",`Unknown provider: ${model2.provider}`);return provider2}requireChatProvider(model2){return assertChatModel(model2),this.requireProvider(model2)}async applyAuth(model2,options){this.requireProvider(model2);let resolution=await this.getAuth(model2,{apiKey:options?.apiKey,env:options?.env,signal:options?.signal});if(!resolution)throw new ModelsError("auth",`Provider is not configured: ${model2.provider}`);let auth=resolution.auth,apiKey=options?.apiKey??auth.apiKey,requestModel=auth.baseUrl?{...model2,baseUrl:auth.baseUrl}:model2,sessionId=options&&"sessionId"in options&&typeof options.sessionId=="string"?options.sessionId:void 0,headers=mergeHeaders(mergeHeaders(getOpenCodeSessionHeaders(requestModel,sessionId),auth.headers),options?.headers);options?.transformHeaders&&(headers=await options.transformHeaders(headers??{}));let env=resolution.env||options?.env?{...resolution.env??{},...options?.env??{}}:void 0,identity=mergeClientIdentity(this.identity,options?.identity),{transformHeaders:_transformHeaders,...providerOptions}=options??{},requestOptions={...providerOptions,apiKey,headers,env,...identity===void 0?{}:{identity}};return{requestModel,requestOptions}}stream(model2,context,options){let transcript=normalizeContext(context);return lazyStream(model2,async()=>{let provider2=this.requireChatProvider(model2),{requestModel,requestOptions}=await this.applyAuth(model2,options);return provider2.stream(requestModel,transcript,requestOptions)},observeModelRequest(model2,options,!1),options?.signal)}async complete(model2,context,options){return this.stream(model2,context,options).result()}streamSimple(model2,context,options){let transcript=normalizeContext(context);return lazyStream(model2,async()=>{let provider2=this.requireChatProvider(model2),{requestModel,requestOptions}=await this.applyAuth(model2,options);return provider2.streamSimple(requestModel,transcript,requestOptions)},observeModelRequest(model2,options,!1),options?.signal)}async completeSimple(model2,context,options){return this.streamSimple(model2,context,options).result()}streamDeferred(model2,handle,options){return lazyStream(model2,async()=>{let provider2=this.requireChatProvider(model2);if(!provider2.fetchDeferred)throw new ModelsError("provider",`Provider ${model2.provider} does not support deferred responses`);let{requestModel,requestOptions}=await this.applyAuth(model2,options);return provider2.fetchDeferred(requestModel,handle,requestOptions)},observeModelRequest(model2,options,!0),options?.signal)}async fetchDeferred(model2,handle,options){return this.streamDeferred(model2,handle,options).result()}async cancelDeferred(model2,handle,options){let provider2=this.requireChatProvider(model2);if(!provider2.cancelDeferred)throw new ModelsError("provider",`Provider ${model2.provider} does not support deferred responses`);let{requestModel,requestOptions}=await this.applyAuth(model2,options);await provider2.cancelDeferred(requestModel,handle,requestOptions)}async generateImages(model2,context,options){try{assertImageModel(model2);let provider2=this.requireProvider(model2);if(!provider2.generateImages)throw new ModelsError("provider",`Provider ${model2.provider} does not support image generation`);let{requestModel,requestOptions}=await this.applyAuth(model2,options);return await provider2.generateImages(requestModel,context,requestOptions)}catch(error){return imageErrorResult(model2,error,options?.signal?.aborted)}}async classify(model2,context,options){try{assertClassifierModel(model2),assertClassifierInputSupported(model2,context);let provider2=this.requireProvider(model2);if(!provider2.classify)throw new ModelsError("provider",`Provider ${model2.provider} does not support classification`);let{requestModel,requestOptions}=await this.applyAuth(model2,options);return await provider2.classify(requestModel,context,requestOptions)}catch(error){return classifierErrorResult(model2,error,options?.signal?.aborted)}}};function createModels(options){return new ModelsImpl(options)}function createProvider(input){let single=input.api&&typeof input.api.stream=="function"?input.api:void 0,byApi=single||!input.api?void 0:input.api,images=input.images,classifiers=input.classifiers,streams=single?[single]:Object.values(byApi??{}).filter(entry=>entry!==void 0),imageImplementations=Object.values(images??{}).filter(entry=>entry!==void 0),classifierImplementations=Object.values(classifiers??{}).filter(entry=>entry!==void 0);if(streams.length===0&&imageImplementations.length===0&&classifierImplementations.length===0)throw new Error(`Provider ${input.id}: at least one of "api", "images", or "classifiers" is required.`);let baselineModels=input.models,dynamicModels=[],fetchModels=input.fetchModels,currentModels=()=>{let merged=[...baselineModels];for(let model2 of dynamicModels){let index=merged.findIndex(entry=>getModelType(entry)===getModelType(model2)&&entry.id===model2.id);index>=0?merged[index]=model2:merged.push(model2)}return merged},apiFor=model2=>single??byApi?.[model2.api],dispatch=(model2,run,signal)=>{let streams2=apiFor(model2);return streams2?run(streams2):lazyStream(model2,async()=>{throw new ModelsError("stream",`Provider ${input.id} has no API implementation for "${model2.api}"`)},void 0,signal)},provider2={id:input.id,name:input.name??input.id,baseUrl:input.baseUrl,headers:input.headers,auth:input.auth,getModels:()=>currentModels().filter(model2=>isModelType(model2,"chat")),getAllModels:currentModels,refreshModels:fetchModels?async context=>{if(context.stored){let restored=context.stored.models.filter(model2=>model2.provider===input.id).map(model2=>model2);if(!await context.publish({update:()=>{dynamicModels=restored}}))return}if(!context.allowNetwork||context.signal.aborted)return;let fetched=await fetchModels(context);if(context.signal.aborted)return;let refreshed=fetched.filter(hasKnownModelType);await context.publish({persist:{models:refreshed,checkedAt:Date.now()},update:()=>{dynamicModels=refreshed}})}:void 0,filterModels:input.filterModels,filterAllModels:input.filterAllModels,stream:(model2,context,options)=>dispatch(model2,streams2=>streams2.stream(model2,context,options),options?.signal),streamSimple:(model2,context,options)=>dispatch(model2,streams2=>streams2.streamSimple(model2,context,options),options?.signal)};return streams.some(entry=>entry.fetchDeferred!==void 0)&&(provider2.fetchDeferred=(model2,handle,options)=>lazyStream(model2,async()=>{let implementation=apiFor(model2);if(!implementation?.fetchDeferred)throw new ModelsError("provider",`Provider ${input.id} does not support deferred responses for "${model2.api}"`);return implementation.fetchDeferred(model2,handle,options)},void 0,options?.signal)),streams.some(entry=>entry.cancelDeferred!==void 0)&&(provider2.cancelDeferred=async(model2,handle,options)=>{let implementation=apiFor(model2);if(!implementation?.cancelDeferred)throw new ModelsError("provider",`Provider ${input.id} cannot cancel deferred responses for "${model2.api}"`);await implementation.cancelDeferred(model2,handle,options)}),images&&imageImplementations.length>0&&(provider2.generateImages=async(model2,context,options)=>{let implementation=images[model2.api];return implementation?implementation.generateImages(model2,context,options):imageErrorResult(model2,new ModelsError("provider",`Provider ${input.id} has no image generation implementation for "${model2.api}"`))}),classifiers&&classifierImplementations.length>0&&(provider2.classify=async(model2,context,options)=>{let implementation=classifiers[model2.api];return implementation?implementation.classify(model2,context,options):classifierErrorResult(model2,new ModelsError("provider",`Provider ${input.id} has no classifier implementation for "${model2.api}"`))}),provider2}function hasApi(model2,api){return isModelType(model2,"chat")&&model2.api===api}function calculateCost(model2,usage){let inputTokens=usage.input+usage.cacheRead+usage.cacheWrite,rates=model2.cost,matchedThreshold=-1;for(let tier of model2.cost.tiers??[])inputTokens>tier.inputTokensAbove&&tier.inputTokensAbove>matchedThreshold&&(rates=tier,matchedThreshold=tier.inputTokensAbove);let longWrite=usage.cacheWrite1h??0,shortWrite=usage.cacheWrite-longWrite;return usage.cost.input=rates.input/1e6*usage.input,usage.cost.output=rates.output/1e6*usage.output,usage.cost.cacheRead=rates.cacheRead/1e6*usage.cacheRead,usage.cost.cacheWrite=(rates.cacheWrite*shortWrite+rates.input*2*longWrite)/1e6,usage.cost.total=usage.cost.input+usage.cost.output+usage.cost.cacheRead+usage.cost.cacheWrite,usage.cost.totalFromProvider=!1,usage.cost}var EXTENDED_THINKING_LEVELS=["off","minimal","low","medium","high","xhigh","max"];function getSupportedThinkingLevels(model2){return model2.reasoning?EXTENDED_THINKING_LEVELS.filter(level=>{let mapped=model2.thinkingLevelMap?.[level];return mapped===null?!1:level==="xhigh"||level==="max"?mapped!==void 0:!0}):["off"]}function clampThinkingLevel(model2,level){let availableLevels=getSupportedThinkingLevels(model2);if(availableLevels.includes(level))return level;let requestedIndex=EXTENDED_THINKING_LEVELS.indexOf(level);if(requestedIndex===-1)return availableLevels[0]??"off";for(let i=requestedIndex;i<EXTENDED_THINKING_LEVELS.length;i++){let candidate=EXTENDED_THINKING_LEVELS[i];if(availableLevels.includes(candidate))return candidate}for(let i=requestedIndex-1;i>=0;i--){let candidate=EXTENDED_THINKING_LEVELS[i];if(availableLevels.includes(candidate))return candidate}return availableLevels[0]??"off"}function supportsXhigh(model2){return!!(model2.id.includes("gpt-5.2")||model2.id.includes("gpt-5.3")||model2.id.includes("gpt-5.4")||model2.id.includes("opus-4-6")||model2.id.includes("opus-4.6")||model2.id.includes("opus-4-7")||model2.id.includes("opus-4.7")||model2.id.includes("sonnet-4-6")||model2.id.includes("sonnet-4.6")||model2.id.includes("haiku-4-5")||model2.id.includes("haiku-4.5"))}function supportsMax(model2){return model2.id.includes("opus-4-6")||model2.id.includes("opus-4.6")||model2.id.includes("opus-4-7")||model2.id.includes("opus-4.7")}function modelsAreEqual(a,b){return!a||!b?!1:getModelType(a)===getModelType(b)&&a.id===b.id&&a.provider===b.provider}export{lazyStream,lazyApi,defaultProviderAuthContext,InMemoryCredentialStore,ModelsError,InMemoryModelsStore,AI_TELEMETRY_SCHEMA,getModelType,isModelType,assertChatModel,assertImageModel,assertClassifierModel,assertClassifierInputSupported,imageErrorResult,classifierErrorResult,createInitialSystemMessage,normalizeContext,getInitialSystemMessage,withoutInitialSystemMessage,getCurrentTools,getCurrentSystemMessage,getCurrentSystemPrompt,collapseSystemMessages,resolveTranscript,toToolDeclaration,declarationsEqual,getToolStateChanges,getDeclaredTools,hasToolRedefinitions,hasNonAdditiveToolChanges,resolveTranscriptTools,createModels,createProvider,hasApi,calculateCost,getSupportedThinkingLevels,clampThinkingLevel,supportsXhigh,supportsMax,modelsAreEqual,models_exports};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __drahtCreateRequire } from "node:module"; const require = __drahtCreateRequire(import.meta.url);
2
- import{source_default,typebox_exports}from"./chunk-ITKDPD4D.js";import{sanitizeBinaryOutput}from"./chunk-4FPBO5KP.js";import{require_bash,require_c,require_core,require_cpp,require_csharp,require_dart,require_go,require_groovy,require_java,require_javascript,require_json,require_kotlin,require_lua,require_nix,require_perl,require_php,require_python,require_ruby,require_rust,require_scala,require_swift,require_typescript}from"./chunk-LO6CVU2L.js";import{CODEMODE_SOURCE_GRAMMAR,renderToolOutputType,renderToolSample,resolveSchemaRef,toCodemodeIdentifier}from"./chunk-EBTEI43G.js";import{SETTINGS_DEFAULTS}from"./chunk-MXA4WY3C.js";import{getCustomThemesDir,getDocsPath,getThemesDir,resolvePath,shortenHomePath,stripBom}from"./chunk-6M3D4XVD.js";import{__export,__toESM}from"./chunk-HZ2UHMBT.js";var dist_exports={};__export(dist_exports,{Box:()=>Box,CURSOR_MARKER:()=>CURSOR_MARKER,CancellableLoader:()=>CancellableLoader,CombinedAutocompleteProvider:()=>CombinedAutocompleteProvider,Container:()=>Container,Editor:()=>Editor,HStack:()=>HStack,Image:()=>Image,Input:()=>Input,Key:()=>Key,KeybindingsManager:()=>KeybindingsManager,Loader:()=>Loader,Markdown:()=>Markdown,Marked:()=>Marked,MouseRegion:()=>MouseRegion,ProcessTerminal:()=>ProcessTerminal,ScrollView:()=>ScrollView,SelectList:()=>SelectList,SettingsList:()=>SettingsList,Spacer:()=>Spacer,StdinBuffer:()=>StdinBuffer,TUI_KEYBINDINGS:()=>TUI_KEYBINDINGS,Text:()=>Text,TruncatedText:()=>TruncatedText,TuiAltScreen:()=>TuiAltScreen,TuiMainScreen:()=>TuiMainScreen,VStack:()=>VStack,allocateImageId:()=>allocateImageId,backgroundAnsi:()=>backgroundAnsi,calculateImageRows:()=>calculateImageRows,colorToHex:()=>colorToHex,colorToOkhsl:()=>colorToOkhsl,colorToOklch:()=>colorToOklch,colorToRgb:()=>colorToRgb,compositeTuiLine:()=>compositeTuiLine,decodeKittyPrintable:()=>decodeKittyPrintable,deleteAllKittyImages:()=>deleteAllKittyImages,deleteKittyImage:()=>deleteKittyImage,detectCapabilities:()=>detectCapabilities,encodeITerm2:()=>encodeITerm2,encodeKitty:()=>encodeKitty,foregroundAnsi:()=>foregroundAnsi,formatProgramStatus:()=>formatProgramStatus,fuzzyFilter:()=>fuzzyFilter,fuzzyMatch:()=>fuzzyMatch,getCapabilities:()=>getCapabilities,getCellDimensions:()=>getCellDimensions,getGifDimensions:()=>getGifDimensions,getImageDimensions:()=>getImageDimensions,getJpegDimensions:()=>getJpegDimensions,getKeybindings:()=>getKeybindings,getNativeClipboard:()=>getNativeClipboard,getOsc8LinkAtColumn:()=>getOsc8LinkAtColumn,getPngDimensions:()=>getPngDimensions,getSelectPageIndex:()=>getSelectPageIndex,getTerminalColorMode:()=>getTerminalColorMode,getWebpDimensions:()=>getWebpDimensions,hyperlink:()=>hyperlink,imageFallback:()=>imageFallback,indexedColor:()=>indexedColor,isFocusable:()=>isFocusable,isKeyRelease:()=>isKeyRelease,isKeyRepeat:()=>isKeyRepeat,isKittyProtocolActive:()=>isKittyProtocolActive,isViewportTUI:()=>isViewportTUI,matchesKey:()=>matchesKey,mixColors:()=>mixColors,okhslColor:()=>okhslColor,oklabToOkhslLightness:()=>oklabToOkhslLightness,oklchColor:()=>oklchColor,parseColor:()=>parseColor,parseKey:()=>parseKey,parseTerminalColorSchemeReport:()=>parseTerminalColorSchemeReport,renderFakeCursor:()=>renderFakeCursor,renderImage:()=>renderImage,renderLatex:()=>renderLatex,replaceControlCharacters:()=>replaceControlCharacters,resetCapabilitiesCache:()=>resetCapabilitiesCache,rgbColor:()=>rgbColor,setCapabilities:()=>setCapabilities,setCapabilityOverrides:()=>setCapabilityOverrides,setCellDimensions:()=>setCellDimensions,setImageTranscoder:()=>setImageTranscoder,setKeybindings:()=>setKeybindings,setKittyProtocolActive:()=>setKittyProtocolActive,sliceByColumn:()=>sliceByColumn,stripTerminalSequences:()=>stripTerminalSequences,styleText:()=>styleText,styleTextWithAnsi:()=>styleTextWithAnsi,truncateToWidth:()=>truncateToWidth,visibleWidth:()=>visibleWidth,wrapTextWithAnsi:()=>wrapTextWithAnsi});function _getDefaults(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var _defaults=_getDefaults();function changeDefaults(newDefaults){_defaults=newDefaults}var noopTest={exec:()=>null};function edit(regex,opt=""){let source=typeof regex=="string"?regex:regex.source,obj={replace:(name,val)=>{let valSource=typeof val=="string"?val:val.source;return valSource=valSource.replace(other.caret,"$1"),source=source.replace(name,valSource),obj},getRegex:()=>new RegExp(source,opt)};return obj}var other={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] /,listReplaceTask:/^\[[ xX]\] +/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:bull=>new RegExp(`^( {0,3}${bull})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:indent=>new RegExp(`^ {0,${Math.min(3,indent-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:indent=>new RegExp(`^ {0,${Math.min(3,indent-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:indent=>new RegExp(`^ {0,${Math.min(3,indent-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:indent=>new RegExp(`^ {0,${Math.min(3,indent-1)}}#`),htmlBeginRegex:indent=>new RegExp(`^ {0,${Math.min(3,indent-1)}}<(?:[a-z].*>|!--)`,"i")},newline=/^(?:[ \t]*(?:\n|$))+/,blockCode=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,fences=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,hr=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,heading=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,bullet=/(?:[*+-]|\d{1,9}[.)])/,lheadingCore=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,lheading=edit(lheadingCore).replace(/bull/g,bullet).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),lheadingGfm=edit(lheadingCore).replace(/bull/g,bullet).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),_paragraph=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,blockText=/^[^\n]+/,_blockLabel=/(?!\s*\])(?:\\.|[^\[\]\\])+/,def=edit(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",_blockLabel).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),list=edit(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,bullet).getRegex(),_tag="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",_comment=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,html=edit("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",_comment).replace("tag",_tag).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),paragraph=edit(_paragraph).replace("hr",hr).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",_tag).getRegex(),blockquote=edit(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",paragraph).getRegex(),blockNormal={blockquote,code:blockCode,def,fences,heading,hr,html,lheading,list,newline,paragraph,table:noopTest,text:blockText},gfmTable=edit("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",hr).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",_tag).getRegex(),blockGfm={...blockNormal,lheading:lheadingGfm,table:gfmTable,paragraph:edit(_paragraph).replace("hr",hr).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",gfmTable).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",_tag).getRegex()},blockPedantic={...blockNormal,html:edit(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",_comment).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:noopTest,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:edit(_paragraph).replace("hr",hr).replace("heading",` *#{1,6} *[^
2
+ import{source_default,typebox_exports}from"./chunk-PX3CDFUB.js";import{sanitizeBinaryOutput}from"./chunk-G7DJ6PIU.js";import{require_bash,require_c,require_core,require_cpp,require_csharp,require_dart,require_go,require_groovy,require_java,require_javascript,require_json,require_kotlin,require_lua,require_nix,require_perl,require_php,require_python,require_ruby,require_rust,require_scala,require_swift,require_typescript}from"./chunk-6MSE6LZ3.js";import{CODEMODE_SOURCE_GRAMMAR,renderToolOutputType,renderToolSample,resolveSchemaRef,toCodemodeIdentifier}from"./chunk-EBTEI43G.js";import{SETTINGS_DEFAULTS}from"./chunk-MXA4WY3C.js";import{getCustomThemesDir,getDocsPath,getThemesDir,resolvePath,shortenHomePath,stripBom}from"./chunk-BIBUE2PO.js";import{__export,__toESM}from"./chunk-HZ2UHMBT.js";var dist_exports={};__export(dist_exports,{Box:()=>Box,CURSOR_MARKER:()=>CURSOR_MARKER,CancellableLoader:()=>CancellableLoader,CombinedAutocompleteProvider:()=>CombinedAutocompleteProvider,Container:()=>Container,Editor:()=>Editor,HStack:()=>HStack,Image:()=>Image,Input:()=>Input,Key:()=>Key,KeybindingsManager:()=>KeybindingsManager,Loader:()=>Loader,Markdown:()=>Markdown,Marked:()=>Marked,MouseRegion:()=>MouseRegion,ProcessTerminal:()=>ProcessTerminal,ScrollView:()=>ScrollView,SelectList:()=>SelectList,SettingsList:()=>SettingsList,Spacer:()=>Spacer,StdinBuffer:()=>StdinBuffer,TUI_KEYBINDINGS:()=>TUI_KEYBINDINGS,Text:()=>Text,TruncatedText:()=>TruncatedText,TuiAltScreen:()=>TuiAltScreen,TuiMainScreen:()=>TuiMainScreen,VStack:()=>VStack,allocateImageId:()=>allocateImageId,backgroundAnsi:()=>backgroundAnsi,calculateImageRows:()=>calculateImageRows,colorToHex:()=>colorToHex,colorToOkhsl:()=>colorToOkhsl,colorToOklch:()=>colorToOklch,colorToRgb:()=>colorToRgb,compositeTuiLine:()=>compositeTuiLine,decodeKittyPrintable:()=>decodeKittyPrintable,deleteAllKittyImages:()=>deleteAllKittyImages,deleteKittyImage:()=>deleteKittyImage,detectCapabilities:()=>detectCapabilities,encodeITerm2:()=>encodeITerm2,encodeKitty:()=>encodeKitty,foregroundAnsi:()=>foregroundAnsi,formatProgramStatus:()=>formatProgramStatus,fuzzyFilter:()=>fuzzyFilter,fuzzyMatch:()=>fuzzyMatch,getCapabilities:()=>getCapabilities,getCellDimensions:()=>getCellDimensions,getGifDimensions:()=>getGifDimensions,getImageDimensions:()=>getImageDimensions,getJpegDimensions:()=>getJpegDimensions,getKeybindings:()=>getKeybindings,getNativeClipboard:()=>getNativeClipboard,getOsc8LinkAtColumn:()=>getOsc8LinkAtColumn,getPngDimensions:()=>getPngDimensions,getSelectPageIndex:()=>getSelectPageIndex,getTerminalColorMode:()=>getTerminalColorMode,getWebpDimensions:()=>getWebpDimensions,hyperlink:()=>hyperlink,imageFallback:()=>imageFallback,indexedColor:()=>indexedColor,isFocusable:()=>isFocusable,isKeyRelease:()=>isKeyRelease,isKeyRepeat:()=>isKeyRepeat,isKittyProtocolActive:()=>isKittyProtocolActive,isViewportTUI:()=>isViewportTUI,matchesKey:()=>matchesKey,mixColors:()=>mixColors,okhslColor:()=>okhslColor,oklabToOkhslLightness:()=>oklabToOkhslLightness,oklchColor:()=>oklchColor,parseColor:()=>parseColor,parseKey:()=>parseKey,parseTerminalColorSchemeReport:()=>parseTerminalColorSchemeReport,renderFakeCursor:()=>renderFakeCursor,renderImage:()=>renderImage,renderLatex:()=>renderLatex,replaceControlCharacters:()=>replaceControlCharacters,resetCapabilitiesCache:()=>resetCapabilitiesCache,rgbColor:()=>rgbColor,setCapabilities:()=>setCapabilities,setCapabilityOverrides:()=>setCapabilityOverrides,setCellDimensions:()=>setCellDimensions,setImageTranscoder:()=>setImageTranscoder,setKeybindings:()=>setKeybindings,setKittyProtocolActive:()=>setKittyProtocolActive,sliceByColumn:()=>sliceByColumn,stripTerminalSequences:()=>stripTerminalSequences,styleText:()=>styleText,styleTextWithAnsi:()=>styleTextWithAnsi,truncateToWidth:()=>truncateToWidth,visibleWidth:()=>visibleWidth,wrapTextWithAnsi:()=>wrapTextWithAnsi});function _getDefaults(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var _defaults=_getDefaults();function changeDefaults(newDefaults){_defaults=newDefaults}var noopTest={exec:()=>null};function edit(regex,opt=""){let source=typeof regex=="string"?regex:regex.source,obj={replace:(name,val)=>{let valSource=typeof val=="string"?val:val.source;return valSource=valSource.replace(other.caret,"$1"),source=source.replace(name,valSource),obj},getRegex:()=>new RegExp(source,opt)};return obj}var other={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] /,listReplaceTask:/^\[[ xX]\] +/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:bull=>new RegExp(`^( {0,3}${bull})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:indent=>new RegExp(`^ {0,${Math.min(3,indent-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:indent=>new RegExp(`^ {0,${Math.min(3,indent-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:indent=>new RegExp(`^ {0,${Math.min(3,indent-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:indent=>new RegExp(`^ {0,${Math.min(3,indent-1)}}#`),htmlBeginRegex:indent=>new RegExp(`^ {0,${Math.min(3,indent-1)}}<(?:[a-z].*>|!--)`,"i")},newline=/^(?:[ \t]*(?:\n|$))+/,blockCode=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,fences=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,hr=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,heading=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,bullet=/(?:[*+-]|\d{1,9}[.)])/,lheadingCore=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,lheading=edit(lheadingCore).replace(/bull/g,bullet).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),lheadingGfm=edit(lheadingCore).replace(/bull/g,bullet).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),_paragraph=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,blockText=/^[^\n]+/,_blockLabel=/(?!\s*\])(?:\\.|[^\[\]\\])+/,def=edit(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",_blockLabel).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),list=edit(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,bullet).getRegex(),_tag="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",_comment=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,html=edit("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",_comment).replace("tag",_tag).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),paragraph=edit(_paragraph).replace("hr",hr).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",_tag).getRegex(),blockquote=edit(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",paragraph).getRegex(),blockNormal={blockquote,code:blockCode,def,fences,heading,hr,html,lheading,list,newline,paragraph,table:noopTest,text:blockText},gfmTable=edit("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",hr).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",_tag).getRegex(),blockGfm={...blockNormal,lheading:lheadingGfm,table:gfmTable,paragraph:edit(_paragraph).replace("hr",hr).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",gfmTable).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",_tag).getRegex()},blockPedantic={...blockNormal,html:edit(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",_comment).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:noopTest,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:edit(_paragraph).replace("hr",hr).replace("heading",` *#{1,6} *[^
3
3
  ]`).replace("lheading",lheading).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},escape=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,inlineCode=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,br=/^( {2,}|\\)\n(?!\s*$)/,inlineText=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,_punctuation=/[\p{P}\p{S}]/u,_punctuationOrSpace=/[\s\p{P}\p{S}]/u,_notPunctuationOrSpace=/[^\s\p{P}\p{S}]/u,punctuation=edit(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,_punctuationOrSpace).getRegex(),_punctuationGfmStrongEm=/(?!~)[\p{P}\p{S}]/u,_punctuationOrSpaceGfmStrongEm=/(?!~)[\s\p{P}\p{S}]/u,_notPunctuationOrSpaceGfmStrongEm=/(?:[^\s\p{P}\p{S}]|~)/u,blockSkip=/\[[^[\]]*?\]\((?:\\.|[^\\\(\)]|\((?:\\.|[^\\\(\)])*\))*\)|`[^`]*?`|<[^<>]*?>/g,emStrongLDelimCore=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,emStrongLDelim=edit(emStrongLDelimCore,"u").replace(/punct/g,_punctuation).getRegex(),emStrongLDelimGfm=edit(emStrongLDelimCore,"u").replace(/punct/g,_punctuationGfmStrongEm).getRegex(),emStrongRDelimAstCore="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",emStrongRDelimAst=edit(emStrongRDelimAstCore,"gu").replace(/notPunctSpace/g,_notPunctuationOrSpace).replace(/punctSpace/g,_punctuationOrSpace).replace(/punct/g,_punctuation).getRegex(),emStrongRDelimAstGfm=edit(emStrongRDelimAstCore,"gu").replace(/notPunctSpace/g,_notPunctuationOrSpaceGfmStrongEm).replace(/punctSpace/g,_punctuationOrSpaceGfmStrongEm).replace(/punct/g,_punctuationGfmStrongEm).getRegex(),emStrongRDelimUnd=edit("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,_notPunctuationOrSpace).replace(/punctSpace/g,_punctuationOrSpace).replace(/punct/g,_punctuation).getRegex(),anyPunctuation=edit(/\\(punct)/,"gu").replace(/punct/g,_punctuation).getRegex(),autolink=edit(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),_inlineComment=edit(_comment).replace("(?:-->|$)","-->").getRegex(),tag=edit("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",_inlineComment).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),_inlineLabel=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,link=edit(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",_inlineLabel).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),reflink=edit(/^!?\[(label)\]\[(ref)\]/).replace("label",_inlineLabel).replace("ref",_blockLabel).getRegex(),nolink=edit(/^!?\[(ref)\](?:\[\])?/).replace("ref",_blockLabel).getRegex(),reflinkSearch=edit("reflink|nolink(?!\\()","g").replace("reflink",reflink).replace("nolink",nolink).getRegex(),inlineNormal={_backpedal:noopTest,anyPunctuation,autolink,blockSkip,br,code:inlineCode,del:noopTest,emStrongLDelim,emStrongRDelimAst,emStrongRDelimUnd,escape,link,nolink,punctuation,reflink,reflinkSearch,tag,text:inlineText,url:noopTest},inlinePedantic={...inlineNormal,link:edit(/^!?\[(label)\]\((.*?)\)/).replace("label",_inlineLabel).getRegex(),reflink:edit(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",_inlineLabel).getRegex()},inlineGfm={...inlineNormal,emStrongRDelimAst:emStrongRDelimAstGfm,emStrongLDelim:emStrongLDelimGfm,url:edit(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,"i").replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/},inlineBreaks={...inlineGfm,br:edit(br).replace("{2,}","*").getRegex(),text:edit(inlineGfm.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},block={normal:blockNormal,gfm:blockGfm,pedantic:blockPedantic},inline={normal:inlineNormal,gfm:inlineGfm,breaks:inlineBreaks,pedantic:inlinePedantic},escapeReplacements={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},getEscapeReplacement=ch=>escapeReplacements[ch];function escape2(html2,encode){if(encode){if(other.escapeTest.test(html2))return html2.replace(other.escapeReplace,getEscapeReplacement)}else if(other.escapeTestNoEncode.test(html2))return html2.replace(other.escapeReplaceNoEncode,getEscapeReplacement);return html2}function cleanUrl(href){try{href=encodeURI(href).replace(other.percentDecode,"%")}catch{return null}return href}function splitCells(tableRow,count){let row=tableRow.replace(other.findPipe,(match,offset,str2)=>{let escaped=!1,curr=offset;for(;--curr>=0&&str2[curr]==="\\";)escaped=!escaped;return escaped?"|":" |"}),cells=row.split(other.splitPipe),i=0;if(cells[0].trim()||cells.shift(),cells.length>0&&!cells.at(-1)?.trim()&&cells.pop(),count)if(cells.length>count)cells.splice(count);else for(;cells.length<count;)cells.push("");for(;i<cells.length;i++)cells[i]=cells[i].trim().replace(other.slashPipe,"|");return cells}function rtrim(str2,c2,invert){let l=str2.length;if(l===0)return"";let suffLen=0;for(;suffLen<l;){let currChar=str2.charAt(l-suffLen-1);if(currChar===c2&&!invert)suffLen++;else if(currChar!==c2&&invert)suffLen++;else break}return str2.slice(0,l-suffLen)}function findClosingBracket(str2,b){if(str2.indexOf(b[1])===-1)return-1;let level=0;for(let i=0;i<str2.length;i++)if(str2[i]==="\\")i++;else if(str2[i]===b[0])level++;else if(str2[i]===b[1]&&(level--,level<0))return i;return level>0?-2:-1}function outputLink(cap,link2,raw,lexer2,rules){let href=link2.href,title=link2.title||null,text=cap[1].replace(rules.other.outputLinkReplace,"$1");lexer2.state.inLink=!0;let token={type:cap[0].charAt(0)==="!"?"image":"link",raw,href,title,text,tokens:lexer2.inlineTokens(text)};return lexer2.state.inLink=!1,token}function indentCodeCompensation(raw,text,rules){let matchIndentToCode=raw.match(rules.other.indentCodeCompensation);if(matchIndentToCode===null)return text;let indentToCode=matchIndentToCode[1];return text.split(`
4
4
  `).map(node=>{let matchIndentInNode=node.match(rules.other.beginningSpace);if(matchIndentInNode===null)return node;let[indentInNode]=matchIndentInNode;return indentInNode.length>=indentToCode.length?node.slice(indentToCode.length):node}).join(`
5
5
  `)}var _Tokenizer=class{options;rules;lexer;constructor(options2){this.options=options2||_defaults}space(src){let cap=this.rules.block.newline.exec(src);if(cap&&cap[0].length>0)return{type:"space",raw:cap[0]}}code(src){let cap=this.rules.block.code.exec(src);if(cap){let text=cap[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:cap[0],codeBlockStyle:"indented",text:this.options.pedantic?text:rtrim(text,`
@@ -112,7 +112,7 @@ Please report this to https://github.com/markedjs/marked.`,silent){let msg="<p>A
112
112
  `);fs2.mkdirSync(path3.dirname(crashLogPath),{recursive:!0}),fs2.writeFileSync(crashLogPath,crashData),this.stop();let errorMsg=[`Rendered line ${i} exceeds terminal width (${visibleWidth(line)} > ${width}).`,"","This is likely caused by a custom TUI component not truncating its output.","Use visibleWidth() to measure and truncateToWidth() to truncate lines.","",`Debug log written to: ${crashLogPath}`].join(`
113
113
  `);throw new Error(errorMsg)}output.append(line)}let finalCursorRow=renderEnd;if(this.previousLines.length>newLines.length){if(renderEnd<newLines.length-1){let moveDown=newLines.length-1-renderEnd;output.append(`\x1B[${moveDown}B`),finalCursorRow=newLines.length-1}let extraLines=this.previousLines.length-newLines.length;for(let i=newLines.length;i<this.previousLines.length;i++)output.append(`\r
114
114
  \x1B[2K`);output.append(`\x1B[${extraLines}A`)}if(output.append("\x1B[?2026l"),process.env.DRAHT_TUI_DEBUG==="1"){let debugDir="/tmp/tui";fs2.mkdirSync(debugDir,{recursive:!0});let debugPath=path3.join(debugDir,`render-${Date.now()}-${Math.random().toString(36).slice(2)}.log`),debugData=[`firstChanged: ${firstChanged}`,`viewportTop: ${viewportTop}`,`cursorRow: ${this.cursorRow}`,`height: ${height}`,`lineDiff: ${lineDiff}`,`hardwareCursorRow: ${hardwareCursorRow}`,`renderEnd: ${renderEnd}`,`finalCursorRow: ${finalCursorRow}`,`cursorPos: ${JSON.stringify(cursorPos)}`,`newLines.length: ${newLines.length}`,`previousLines.length: ${this.previousLines.length}`,"","=== newLines ===",JSON.stringify(newLines,null,2),"","=== previousLines ===",JSON.stringify(this.previousLines,null,2),"","=== buffer ===",`[${output.length} chars written in bounded chunks]`].join(`
115
- `);fs2.writeFileSync(debugPath,debugData)}output.flush(),this.cursorRow=Math.max(0,newLines.length-1),this.hardwareCursorRow=finalCursorRow,this.maxLinesRendered=Math.max(this.maxLinesRendered,newLines.length),this.previousViewportTop=Math.max(prevViewportTop,finalCursorRow-height+1),this.positionHardwareCursor(cursorPos,newLines.length),this.previousLines=newLines,this.previousKittyImageIds=this.collectKittyImageIds(newLines),this.previousWidth=width,this.previousHeight=height}positionHardwareCursor(cursorPos,totalLines){if(!cursorPos||totalLines<=0){this.terminal.hideCursor();return}let targetRow=Math.max(0,Math.min(cursorPos.row,totalLines-1)),targetCol=Math.max(0,cursorPos.col),rowDelta=targetRow-this.hardwareCursorRow,buffer="";rowDelta>0?buffer+=`\x1B[${rowDelta}B`:rowDelta<0&&(buffer+=`\x1B[${-rowDelta}A`),buffer+=`\x1B[${targetCol+1}G`,buffer&&this.terminal.write(buffer),this.hardwareCursorRow=targetRow,this.getShowHardwareCursor()?this.terminal.showCursor():this.terminal.hideCursor()}};import*as fs3 from"node:fs";import*as path4 from"node:path";import{watch}from"node:fs";var FS_WATCH_RETRY_DELAY_MS=5e3;function closeWatcher(watcher){if(watcher)try{watcher.close()}catch{}}function watchWithErrorHandler(path5,listener,onError){try{let watcher=watch(path5,listener);return watcher.on("error",onError),watcher}catch{return onError(),null}}var import_core=__toESM(require_core(),1),import_bash=__toESM(require_bash(),1),import_c=__toESM(require_c(),1),import_cpp=__toESM(require_cpp(),1),import_csharp=__toESM(require_csharp(),1),import_dart=__toESM(require_dart(),1),import_go=__toESM(require_go(),1),import_groovy=__toESM(require_groovy(),1),import_java=__toESM(require_java(),1),import_javascript=__toESM(require_javascript(),1),import_json=__toESM(require_json(),1),import_kotlin=__toESM(require_kotlin(),1),import_lua=__toESM(require_lua(),1),import_nix=__toESM(require_nix(),1),import_perl=__toESM(require_perl(),1),import_php=__toESM(require_php(),1),import_python=__toESM(require_python(),1),import_ruby=__toESM(require_ruby(),1),import_rust=__toESM(require_rust(),1),import_scala=__toESM(require_scala(),1),import_swift=__toESM(require_swift(),1),import_typescript=__toESM(require_typescript(),1);function decodeCodePoint(codePoint){if(!(!Number.isInteger(codePoint)||codePoint<0||codePoint>1114111))return String.fromCodePoint(codePoint)}function decodeHtmlEntity(entity){switch(entity){case"amp":return"&";case"lt":return"<";case"gt":return">";case"quot":return'"';case"apos":return"'"}if(entity.startsWith("#x")||entity.startsWith("#X"))return decodeCodePoint(Number.parseInt(entity.slice(2),16));if(entity.startsWith("#"))return decodeCodePoint(Number.parseInt(entity.slice(1),10))}function decodeHtmlEntityAt(html2,index){let semicolonIndex=html2.indexOf(";",index+1);if(semicolonIndex===-1||semicolonIndex-index>16)return;let entity=html2.slice(index+1,semicolonIndex),decoded=decodeHtmlEntity(entity);if(decoded!==void 0)return{text:decoded,length:semicolonIndex-index+1}}var eagerLanguages={python:import_python.default,java:import_java.default,go:import_go.default,javascript:import_javascript.default,json:import_json.default,cpp:import_cpp.default,typescript:import_typescript.default,php:import_php.default,ruby:import_ruby.default,c:import_c.default,csharp:import_csharp.default,nix:import_nix.default,bash:import_bash.default,rust:import_rust.default,scala:import_scala.default,kotlin:import_kotlin.default,swift:import_swift.default,dart:import_dart.default,groovy:import_groovy.default,perl:import_perl.default,lua:import_lua.default};for(let[name,language]of Object.entries(eagerLanguages))import_core.default.registerLanguage(name,language);var allLanguagesPromise;function loadAllHighlightLanguages(){return allLanguagesPromise||(allLanguagesPromise=new Promise(resolve=>{setImmediate(()=>{import("./lib-ULKZYRGD.js").then(()=>resolve(),()=>{resolve()})})})),allLanguagesPromise}var SPAN_CLOSE="</span>",HIGHLIGHT_CLASS_PREFIX="hljs-";function getScopeFromSpanTag(tag2){let match=/\sclass\s*=\s*(?:"([^"]*)"|'([^']*)')/.exec(tag2),classValue=match?.[1]??match?.[2];if(classValue){for(let className of classValue.split(/\s+/))if(className.startsWith(HIGHLIGHT_CLASS_PREFIX))return className.slice(HIGHLIGHT_CLASS_PREFIX.length)}}function getScopeFormatter(scope,theme2){let exact=theme2[scope];if(exact)return exact;let dotIndex=scope.indexOf(".");if(dotIndex!==-1){let prefixFormatter=theme2[scope.slice(0,dotIndex)];if(prefixFormatter)return prefixFormatter}let dashIndex=scope.indexOf("-");if(dashIndex!==-1){let prefixFormatter=theme2[scope.slice(0,dashIndex)];if(prefixFormatter)return prefixFormatter}}function getActiveFormatter(scopes,theme2){for(let i=scopes.length-1;i>=0;i--){let scope=scopes[i];if(!scope)continue;let formatter=getScopeFormatter(scope,theme2);if(formatter)return formatter}return theme2.default}function isSpanOpenTagStart(html2,index){if(!html2.startsWith("<span",index))return!1;let nextChar=html2[index+5];return nextChar===">"||nextChar===" "||nextChar===" "||nextChar===`
115
+ `);fs2.writeFileSync(debugPath,debugData)}output.flush(),this.cursorRow=Math.max(0,newLines.length-1),this.hardwareCursorRow=finalCursorRow,this.maxLinesRendered=Math.max(this.maxLinesRendered,newLines.length),this.previousViewportTop=Math.max(prevViewportTop,finalCursorRow-height+1),this.positionHardwareCursor(cursorPos,newLines.length),this.previousLines=newLines,this.previousKittyImageIds=this.collectKittyImageIds(newLines),this.previousWidth=width,this.previousHeight=height}positionHardwareCursor(cursorPos,totalLines){if(!cursorPos||totalLines<=0){this.terminal.hideCursor();return}let targetRow=Math.max(0,Math.min(cursorPos.row,totalLines-1)),targetCol=Math.max(0,cursorPos.col),rowDelta=targetRow-this.hardwareCursorRow,buffer="";rowDelta>0?buffer+=`\x1B[${rowDelta}B`:rowDelta<0&&(buffer+=`\x1B[${-rowDelta}A`),buffer+=`\x1B[${targetCol+1}G`,buffer&&this.terminal.write(buffer),this.hardwareCursorRow=targetRow,this.getShowHardwareCursor()?this.terminal.showCursor():this.terminal.hideCursor()}};import*as fs3 from"node:fs";import*as path4 from"node:path";import{watch}from"node:fs";var FS_WATCH_RETRY_DELAY_MS=5e3;function closeWatcher(watcher){if(watcher)try{watcher.close()}catch{}}function watchWithErrorHandler(path5,listener,onError){try{let watcher=watch(path5,listener);return watcher.on("error",onError),watcher}catch{return onError(),null}}var import_core=__toESM(require_core(),1),import_bash=__toESM(require_bash(),1),import_c=__toESM(require_c(),1),import_cpp=__toESM(require_cpp(),1),import_csharp=__toESM(require_csharp(),1),import_dart=__toESM(require_dart(),1),import_go=__toESM(require_go(),1),import_groovy=__toESM(require_groovy(),1),import_java=__toESM(require_java(),1),import_javascript=__toESM(require_javascript(),1),import_json=__toESM(require_json(),1),import_kotlin=__toESM(require_kotlin(),1),import_lua=__toESM(require_lua(),1),import_nix=__toESM(require_nix(),1),import_perl=__toESM(require_perl(),1),import_php=__toESM(require_php(),1),import_python=__toESM(require_python(),1),import_ruby=__toESM(require_ruby(),1),import_rust=__toESM(require_rust(),1),import_scala=__toESM(require_scala(),1),import_swift=__toESM(require_swift(),1),import_typescript=__toESM(require_typescript(),1);function decodeCodePoint(codePoint){if(!(!Number.isInteger(codePoint)||codePoint<0||codePoint>1114111))return String.fromCodePoint(codePoint)}function decodeHtmlEntity(entity){switch(entity){case"amp":return"&";case"lt":return"<";case"gt":return">";case"quot":return'"';case"apos":return"'"}if(entity.startsWith("#x")||entity.startsWith("#X"))return decodeCodePoint(Number.parseInt(entity.slice(2),16));if(entity.startsWith("#"))return decodeCodePoint(Number.parseInt(entity.slice(1),10))}function decodeHtmlEntityAt(html2,index){let semicolonIndex=html2.indexOf(";",index+1);if(semicolonIndex===-1||semicolonIndex-index>16)return;let entity=html2.slice(index+1,semicolonIndex),decoded=decodeHtmlEntity(entity);if(decoded!==void 0)return{text:decoded,length:semicolonIndex-index+1}}var eagerLanguages={python:import_python.default,java:import_java.default,go:import_go.default,javascript:import_javascript.default,json:import_json.default,cpp:import_cpp.default,typescript:import_typescript.default,php:import_php.default,ruby:import_ruby.default,c:import_c.default,csharp:import_csharp.default,nix:import_nix.default,bash:import_bash.default,rust:import_rust.default,scala:import_scala.default,kotlin:import_kotlin.default,swift:import_swift.default,dart:import_dart.default,groovy:import_groovy.default,perl:import_perl.default,lua:import_lua.default};for(let[name,language]of Object.entries(eagerLanguages))import_core.default.registerLanguage(name,language);var allLanguagesPromise;function loadAllHighlightLanguages(){return allLanguagesPromise||(allLanguagesPromise=new Promise(resolve=>{setImmediate(()=>{import("./lib-XOG5PI3Y.js").then(()=>resolve(),()=>{resolve()})})})),allLanguagesPromise}var SPAN_CLOSE="</span>",HIGHLIGHT_CLASS_PREFIX="hljs-";function getScopeFromSpanTag(tag2){let match=/\sclass\s*=\s*(?:"([^"]*)"|'([^']*)')/.exec(tag2),classValue=match?.[1]??match?.[2];if(classValue){for(let className of classValue.split(/\s+/))if(className.startsWith(HIGHLIGHT_CLASS_PREFIX))return className.slice(HIGHLIGHT_CLASS_PREFIX.length)}}function getScopeFormatter(scope,theme2){let exact=theme2[scope];if(exact)return exact;let dotIndex=scope.indexOf(".");if(dotIndex!==-1){let prefixFormatter=theme2[scope.slice(0,dotIndex)];if(prefixFormatter)return prefixFormatter}let dashIndex=scope.indexOf("-");if(dashIndex!==-1){let prefixFormatter=theme2[scope.slice(0,dashIndex)];if(prefixFormatter)return prefixFormatter}}function getActiveFormatter(scopes,theme2){for(let i=scopes.length-1;i>=0;i--){let scope=scopes[i];if(!scope)continue;let formatter=getScopeFormatter(scope,theme2);if(formatter)return formatter}return theme2.default}function isSpanOpenTagStart(html2,index){if(!html2.startsWith("<span",index))return!1;let nextChar=html2[index+5];return nextChar===">"||nextChar===" "||nextChar===" "||nextChar===`
116
116
  `||nextChar==="\r"}function renderHighlightedHtml(html2,theme2={}){let output="",textBuffer="",scopes=[],flushText=()=>{if(!textBuffer)return;let formatter=getActiveFormatter(scopes,theme2);output+=formatter?textBuffer.split(`
117
117
  `).map(line=>line&&formatter(line)).join(`
118
118
  `):textBuffer,textBuffer=""},index=0;for(;index<html2.length;){if(isSpanOpenTagStart(html2,index)){let tagEndIndex=html2.indexOf(">",index+5);if(tagEndIndex!==-1){flushText();let tag2=html2.slice(index,tagEndIndex+1),scope=getScopeFromSpanTag(tag2);scopes.push(scope),index=tagEndIndex+1;continue}}if(html2.startsWith(SPAN_CLOSE,index)){flushText(),scopes.length>0&&scopes.pop(),index+=SPAN_CLOSE.length;continue}if(html2[index]==="&"){let decoded=decodeHtmlEntityAt(html2,index);if(decoded){textBuffer+=decoded.text,index+=decoded.length;continue}}textBuffer+=html2[index],index++}return flushText(),output}function highlight(code,options2={}){let html2=options2.language?import_core.default.highlight(code,{language:options2.language,ignoreIllegals:options2.ignoreIllegals}).value:import_core.default.highlightAuto(code,options2.languageSubset).value;return renderHighlightedHtml(html2,options2.theme)}function supportsLanguage(name){return import_core.default.getLanguage(name)!==void 0}function getHighlightLanguageCount(){return import_core.default.listLanguages().length}var SYSTEM_THEME_NAME="system",FAMILIES={neutral:{hue:231.49,saturation:{min:.02,max:.08},slot:8},blue:{hue:231.49,saturation:{min:.1,max:.68},slot:4},green:{hue:158.68,saturation:{min:.1,max:.76},slot:2},red:{hue:20,saturation:{min:.1,max:.92},slot:1},yellow:{hue:82.36,saturation:{min:.5,max:1},slot:3},orange:{hue:52,saturation:{min:.12,max:.85},slot:3},violet:{hue:295,saturation:{min:.2,max:.6},slot:5},calamine:{hue:202.43,saturation:{min:.1,max:.74},slot:6},thinkingSlate:{hue:231.49,saturation:{min:.08,max:.2},slot:4},thinkingBlue:{hue:231.49,saturation:{min:.2,max:.45},slot:4},thinkingPeriwinkle:{hue:263.25,saturation:{min:.3,max:.6},slot:6},thinkingViolet:{hue:295,saturation:{min:.4,max:.75},slot:5},thinkingMagenta:{hue:337.5,saturation:{min:.5,max:.85},slot:13},thinkingRed:{hue:20,saturation:{min:.95,max:1},slot:1}},TOKEN_FAMILIES={selectedBg:"blue",searchMatchBg:"orange",userMessageBg:"blue",customMessageBg:"violet",toolPendingBg:"neutral",toolSuccessBg:"green",toolErrorBg:"red",text:"neutral",userMessageText:"neutral",customMessageText:"neutral",toolTitle:"neutral",syntaxOperator:"neutral",syntaxPunctuation:"neutral",muted:"neutral",dim:"neutral",thinkingText:"neutral",toolOutput:"neutral",mdLinkUrl:"neutral",mdQuote:"neutral",mdQuoteBorder:"neutral",mdHr:"neutral",mdCodeBlockBorder:"neutral",toolDiffContext:"neutral",syntaxComment:"neutral",scrollbarTrack:"neutral",scrollbarThumb:"neutral",searchMatchText:"neutral",borderMuted:"neutral",accent:"violet",borderAccent:"violet",customMessageLabel:"violet",mdCode:"violet",mdListBullet:"violet",syntaxType:"violet",border:"blue",mdLink:"blue",syntaxKeyword:"blue",syntaxVariable:"calamine",success:"green",mdCodeBlock:"green",toolDiffAdded:"green",bashMode:"green",syntaxNumber:"green",error:"red",toolDiffRemoved:"red",warning:"yellow",mdHeading:"yellow",syntaxFunction:"yellow",syntaxString:"orange",thinkingOff:"neutral",thinkingMinimal:"thinkingSlate",thinkingLow:"thinkingBlue",thinkingMedium:"thinkingPeriwinkle",thinkingHigh:"thinkingViolet",thinkingXhigh:"thinkingMagenta",thinkingMax:"thinkingRed"},TOKEN_SLOTS={syntaxString:2,syntaxNumber:5,searchMatchBg:3},LEVELS={panel:{dark:{coefficients:[.29131,-.39746,2.33185,-.85524,-1.2076,.86276],reachable:[0,.979]},light:{coefficients:[-3.74073,27.94549,-78.44258,112.6798,-79.60015,22.11277],reachable:[.348,1]}},track:{dark:{coefficients:[.39028,-.23015,.83573,2.43829,-4.38292,2.01582],reachable:[0,.946]},light:{coefficients:[-5.24921,38.37322,-107.28833,152.10005,-106.17127,29.18061],reachable:[.368,1]}},thinking0:{dark:{coefficients:[.52988,-.05809,-.30924,4.63567,-6.52933,2.89108],reachable:[0,.873]},light:{coefficients:[-28.27749,182.85284,-469.62416,603.15916,-384.59976,97.35147],reachable:[.51,1]}},thinking1:{dark:{coefficients:[.55278,-.03667,-.45659,4.95347,-6.90265,3.0706],reachable:[0,.858]},light:{coefficients:[-37.10484,235.86282,-596.62344,754.3633,-474.00763,118.3551],reachable:[.535,1]}},thinking2:{dark:{coefficients:[.57486,-.01765,-.58987,5.25227,-7.27175,3.25532],reachable:[0,.842]},light:{coefficients:[-59.89653,377.05024,-945.07843,1182.03145,-734.96375,181.68658],reachable:[.556,1]}},thinking3:{dark:{coefficients:[.59621,-62e-5,-.71148,5.53588,-7.6392,3.44606],reachable:[0,.827]},light:{coefficients:[-72.07122,445.84082,-1099.57352,1353.88793,-829.53392,202.26164],reachable:[.58,1]}},thinking4:{dark:{coefficients:[.61691,.01462,-.82288,5.80651,-8.00641,3.64333],reachable:[0,.811]},light:{coefficients:[-110.14338,674.21488,-1645.75941,2004.32367,-1215.15899,293.3183],reachable:[.6,1]}},thinking5:{dark:{coefficients:[.63702,.02826,-.92498,6.06465,-8.37246,3.84651],reachable:[0,.795]},light:{coefficients:[-175.47701,1063.54495,-2570.70594,3098.80776,-1860.15527,444.76392],reachable:[.62,1]}},thinking6:{dark:{coefficients:[.65658,.04044,-1.01835,6.30989,-8.73529,4.05439],reachable:[0,.779]},light:{coefficients:[-183.81712,1094.70055,-2602.68539,3088.71276,-1826.91131,430.75931],reachable:[.643,1]}},subtle:{dark:{coefficients:[.56762,-.02475,-.5383,5.12628,-7.10931,3.17324],reachable:[0,.848]},light:{coefficients:[-232.85459,1376.54473,-3249.11801,3827.91186,-2248.29472,526.55751],reachable:[.657,1]}},thumb:{dark:{coefficients:[.60323,.00278,-.73328,5.57157,-7.68067,3.46933],reachable:[0,.823]},light:{coefficients:[-82.89897,511.01355,-1255.98095,1540.76821,-940.68087,228.58523],reachable:[.586,1]}},readable:{dark:{coefficients:[.66937,.04704,-1.06871,6.43941,-8.9332,4.17229],reachable:[0,.77]},light:{coefficients:[-1554.52576,8733.56817,-19604.93507,21977.72696,-12300.99599,2749.81288],reachable:[.751,1]}},emphasis:{dark:{coefficients:[.7303,.07695,-1.31626,7.1681,-10.14436,4.92846],reachable:[0,.712]},light:{coefficients:[-4948.31942,26870.91986,-58334.48399,63280.17197,-34298.01053,7430.30146],reachable:[.811,1]}},textOnPanel:{dark:{coefficients:[.86713,.05232,-.89428,4.79014,-5.5432,1.75023],reachable:[0,.542]},light:{coefficients:[-8570.89457,43954.60805,-90084.00702,92220.6791,-47152.15802,9632.27113],reachable:[.867,1]}},text:{dark:{coefficients:[.89242,.02311,-.44862,2.34417,-.06084,-2.63844],reachable:[0,.5]},light:{coefficients:[-2004.67048,6664.47299,-6060.70202,-1792.61209,5133.82359,-1939.85583],reachable:[.894,1]}}},TOOL_PANELS=["toolPendingBg","toolSuccessBg","toolErrorBg"],MESSAGE_PANELS=["userMessageBg","customMessageBg"],PANELS=["userMessageBg","toolPendingBg","toolSuccessBg","toolErrorBg","selectedBg","searchMatchBg","customMessageBg"],THINKING=["thinkingOff","thinkingMinimal","thinkingLow","thinkingMedium","thinkingHigh","thinkingXhigh","thinkingMax"],THINKING_LEVELS=["thinking0","thinking1","thinking2","thinking3","thinking4","thinking5","thinking6"],each=(tokens,on,level)=>tokens.map(token=>({token,on,level})),RULES=[...each(PANELS,["background"],"panel"),{token:"text",on:["background"],level:"text"},{token:"text",on:["selectedBg"],level:"textOnPanel"},{token:"userMessageText",on:["userMessageBg"],level:"textOnPanel"},{token:"toolTitle",on:TOOL_PANELS,level:"textOnPanel"},...each(["accent","success","error","warning"],["background","selectedBg",...TOOL_PANELS],"readable"),{token:"muted",on:["background","selectedBg","customMessageBg",...TOOL_PANELS],level:"readable"},{token:"dim",on:["background","selectedBg","customMessageBg",...TOOL_PANELS],level:"subtle"},{token:"thinkingText",on:["background"],level:"readable"},{token:"customMessageText",on:["customMessageBg",...TOOL_PANELS],level:"readable"},{token:"customMessageLabel",on:["background","customMessageBg","selectedBg",...TOOL_PANELS],level:"readable"},{token:"toolOutput",on:["background",...TOOL_PANELS],level:"readable"},...each(["mdHeading","mdLink","mdLinkUrl","mdCode","mdQuote","mdCodeBlockBorder","mdListBullet"],["background",...MESSAGE_PANELS],"readable"),{token:"mdCodeBlock",on:["background",...MESSAGE_PANELS,...TOOL_PANELS],level:"readable"},...each(["toolDiffAdded","toolDiffRemoved","toolDiffContext"],["background",...TOOL_PANELS],"readable"),...each(["syntaxComment","syntaxKeyword","syntaxFunction","syntaxVariable","syntaxString","syntaxNumber","syntaxType","syntaxOperator","syntaxPunctuation"],["background",...MESSAGE_PANELS,...TOOL_PANELS],"readable"),{token:"searchMatchText",on:["searchMatchBg"],level:"readable"},...each(["bashMode","border","borderAccent"],["background"],"readable"),{token:"borderMuted",on:["background"],level:"subtle"},...each(["mdQuoteBorder","mdHr"],["background",...MESSAGE_PANELS,...TOOL_PANELS],"readable"),{token:"scrollbarTrack",on:["background"],level:"track"},{token:"scrollbarThumb",on:["scrollbarTrack"],level:"thumb"},...THINKING.map((token,index)=>({token,on:["background"],level:THINKING_LEVELS[index]}))],READABLE_FLOOR={dark:"readable",light:"subtle"},FOREGROUND_LEVEL="emphasis",FOREGROUND_TOKENS=["text","userMessageText","toolTitle"],TEXT_MINIMUM_WCAG_CONTRAST=4.5,SOLVE_ORDER=(()=>{let order=[],visit=token=>{if(!order.includes(token)){for(let rule of RULES)if(rule.token===token)for(let surface of rule.on)surface!=="background"&&visit(surface);order.push(token)}};for(let rule of RULES)visit(rule.token);return order})();function oklabLightness(color){return colorToOklch(rgbColor(color.r,color.g,color.b)).l}function relativeLuminance({r,g,b}){let linear=channel=>{let value=channel/255;return value<=.04045?value/12.92:((value+.055)/1.055)**2.4};return .2126*linear(r)+.7152*linear(g)+.0722*linear(b)}function wcagContrast(first,second){let a=relativeLuminance(first),b=relativeLuminance(second);return(Math.max(a,b)+.05)/(Math.min(a,b)+.05)}function terminalAppearance(background,foreground){let white={r:255,g:255,b:255},black={r:0,g:0,b:0},whiteContrast=wcagContrast(white,background),blackContrast=wcagContrast(black,background);if(foreground){let foregroundL=oklabLightness(foreground),backgroundL=oklabLightness(background);if(Math.abs(foregroundL-backgroundL)>.05){let appearance=foregroundL>backgroundL?"dark":"light";if((appearance==="dark"?whiteContrast:blackContrast)>=TEXT_MINIMUM_WCAG_CONTRAST)return appearance}}return whiteContrast>=blackContrast?"dark":"light"}var clamp2=(value,min,max)=>Math.min(max,Math.max(min,value));function hexOf({r,g,b}){return`#${[r,g,b].map(channel=>Math.round(channel).toString(16).padStart(2,"0")).join("")}`}function bellWeight(lightness){let gaussian=x=>Math.exp(-((x-.5)**2)/.125);return(gaussian(lightness)-gaussian(0))/(1-gaussian(0))}function saturationCurve({saturation:{min,max}},lightness){let floor=max>0?min/max:1;return floor+(1-floor)*bellWeight(lightness)}function levelTarget(level,appearance,surfaceL){let curve=LEVELS[level][appearance];if(!(surfaceL<curve.reachable[0]||surfaceL>curve.reachable[1]))return curve.coefficients.reduce((sum,coefficient,power)=>sum+coefficient*surfaceL**power,0)}function generateSystemThemeColors(input){let saturation=clamp2(input.saturation??1,0,1),{background,foreground}=input;if(!background)return indexedColors(saturation,input.appearanceHint);let palette=input.palette?.length===16?input.palette.map(sourceOf):void 0,appearance=terminalAppearance(background,foreground),lighter=appearance==="dark",extreme=lighter?1:0,backgroundL=oklabLightness(background),paint=(token,oklabL)=>{let lightness=oklabToOkhslLightness(oklabL),family=FAMILIES[TOKEN_FAMILIES[token]];if(!palette){let{min,max}=family.saturation;return okhslColor(family.hue,(min+(max-min)*bellWeight(lightness))*saturation,lightness)}return anchored(palette[TOKEN_SLOTS[token]??family.slot],family,lightness,saturation)},target=(level,surfaceL,t)=>{let reached=levelTarget(level,appearance,surfaceL);if(reached===void 0&&t===0)return;let distance=(reached??extreme)-surfaceL,floor=(levelTarget(READABLE_FLOOR[appearance],appearance,surfaceL)??extreme)-surfaceL,compressed=Math.abs(distance)>Math.abs(floor)?distance-(distance-floor)*Math.min(t,1):distance;return surfaceL+compressed*(1-Math.max(0,t-1))},extremeText=lighter?{r:255,g:255,b:255}:{r:0,g:0,b:0},readable=color=>wcagContrast(extremeText,color)>=TEXT_MINIMUM_WCAG_CONTRAST,limitPanel=(token,l)=>{let color=paint(token,l);if(readable(color))return color;let[low,high]=[backgroundL,l];for(let index=0;index<20;index++){let middle=(low+high)/2;readable(paint(token,middle))?low=middle:high=middle}return paint(token,low)},solve=t=>{let colors2=new Map([["background",background]]);for(let token of SOLVE_ORDER){let targets=[];for(let rule of RULES)if(rule.token===token)for(let surface of rule.on){let value=target(rule.level,oklabLightness(colors2.get(surface)??background),t);if(value===void 0||value<0||value>1)return;targets.push(value)}let l=lighter?Math.max(...targets):Math.min(...targets);colors2.set(token,PANELS.includes(token)?limitPanel(token,l):paint(token,l))}return colors2},relaxation=0,colors=solve(0);if(!colors){let[low,high]=[0,2];colors=solve(high);for(let index=0;index<20;index++){let middle=(low+high)/2,attempt=solve(middle);attempt?[high,colors]=[middle,attempt]:low=middle}relaxation=high}let solved=colors??new Map,surfacesOf=token=>RULES.filter(rule=>rule.token===token).flatMap(rule=>rule.on.map(surface=>solved.get(surface)??background)),result={};for(let token of Object.keys(TOKEN_FAMILIES)){let color=solved.get(token);result[token]=color?hexOf(color):""}for(let token of FOREGROUND_TOKENS){let surfaces=surfacesOf(token),text=solved.get(token);if(foreground){let targets=surfaces.map(surface=>target(FOREGROUND_LEVEL,oklabLightness(surface),relaxation));if(targets.every(value=>value!==void 0&&value>=0&&value<=1)){let needed=lighter?Math.max(...targets):Math.min(...targets),foregroundL=oklabLightness(foreground);if(lighter?foregroundL>=needed:foregroundL<=needed){result[token]="";continue}text=anchored(sourceOf(foreground),FAMILIES.neutral,oklabToOkhslLightness(needed),saturation)}}text&&(result[token]=hexOf(withTextContrast(text,surfaces,lighter)))}return{colors:result,dim:[],appearance}}function okhslOf({r,g,b}){return colorToOkhsl(rgbColor(r,g,b))}function sourceOf(color){return{...okhslOf(color),chroma:colorToOklch(rgbColor(color.r,color.g,color.b)).c}}function anchored(source,family,lightness,saturation){let anchor=saturationCurve(family,source.l),falloff=anchor>0?Math.min(1,saturationCurve(family,lightness)/anchor):1,color=okhslColor(source.h,source.s*falloff*saturation,lightness),cap=source.chroma*falloff*saturation,{l,c:c2}=colorToOklch(color);return c2<=cap?color:colorToRgb(oklchColor(l,cap,source.h))}function withTextContrast(color,surfaces,lighter){let meets=candidate=>surfaces.every(surface=>wcagContrast(candidate,surface)>=TEXT_MINIMUM_WCAG_CONTRAST);if(meets(color))return color;let{h,s,l}=okhslOf(color),at=lightness=>okhslColor(h,s,lightness),extreme=lighter?1:0;if(!meets(at(extreme)))return at(extreme);let[low,high]=[l,extreme];for(let index=0;index<20;index++){let middle=(low+high)/2;meets(at(middle))?high=middle:low=middle}return at(high)}function indexedColors(saturation,appearance){let colors={},dim=[];for(let[token,familyName]of Object.entries(TOKEN_FAMILIES)){if(PANELS.includes(token)){colors[token]="";continue}let neutral=familyName==="neutral";colors[token]=!neutral&&saturation>0?TOKEN_SLOTS[token]??FAMILIES[familyName].slot:"",neutral&&!FOREGROUND_TOKENS.includes(token)&&dim.push(token)}return{colors,dim,appearance}}function defineThemeTokens(tokens){for(let[name,descriptor]of Object.entries(tokens)){if(descriptor.fallback===void 0)continue;let fallback=tokens[descriptor.fallback];if(fallback===void 0)throw new Error(`Theme token ${name} has unknown fallback ${descriptor.fallback}`);if(fallback.slot!==descriptor.slot)throw new Error(`Theme token ${name} has fallback ${descriptor.fallback} in a different color slot`)}return tokens}var THEME_TOKENS=defineThemeTokens({accent:{slot:"foreground",description:"Primary accent color (logo, selected items, cursor)"},border:{slot:"foreground",description:"Normal borders"},borderAccent:{slot:"foreground",description:"Highlighted borders"},borderMuted:{slot:"foreground",description:"Subtle borders"},success:{slot:"foreground",description:"Success states"},error:{slot:"foreground",description:"Error states"},warning:{slot:"foreground",description:"Warning states"},muted:{slot:"foreground",description:"Secondary/dimmed text"},dim:{slot:"foreground",description:"Very dimmed text (more subtle than muted)"},text:{slot:"foreground",description:"Default text color (usually empty string)"},thinkingText:{slot:"foreground",description:"Thinking block text color"},scrollbarTrack:{slot:"foreground",description:"Fullscreen scrollbar track foreground (falls back to muted when omitted)",fallback:"muted"},scrollbarThumb:{slot:"foreground",description:"Fullscreen scrollbar thumb foreground (falls back to text when omitted)",fallback:"text"},selectedBg:{slot:"background",description:"Selected item background"},searchMatchBg:{slot:"background",description:"Transcript search match background and current-match text (falls back to selectedBg when omitted)",fallback:"selectedBg"},searchMatchText:{slot:"foreground",description:"Transcript search match text and current-match background (falls back to text when omitted)",fallback:"text"},userMessageBg:{slot:"background",description:"User message background"},userMessageText:{slot:"foreground",description:"User message text color"},customMessageBg:{slot:"background",description:"Custom message background (hook-injected messages)"},customMessageText:{slot:"foreground",description:"Custom message text color"},customMessageLabel:{slot:"foreground",description:"Custom message type label color"},toolPendingBg:{slot:"background",description:"Tool execution box (pending state)"},toolSuccessBg:{slot:"background",description:"Tool execution box (success state)"},toolErrorBg:{slot:"background",description:"Tool execution box (error state)"},toolTitle:{slot:"foreground",description:"Tool execution box title color"},toolOutput:{slot:"foreground",description:"Tool execution box output text color"},mdHeading:{slot:"foreground",description:"Markdown heading text"},mdLink:{slot:"foreground",description:"Markdown link text"},mdLinkUrl:{slot:"foreground",description:"Markdown link URL"},mdCode:{slot:"foreground",description:"Markdown inline code"},mdCodeBlock:{slot:"foreground",description:"Markdown code block content"},mdCodeBlockBorder:{slot:"foreground",description:"Markdown code block fences"},mdQuote:{slot:"foreground",description:"Markdown blockquote text"},mdQuoteBorder:{slot:"foreground",description:"Markdown blockquote border"},mdHr:{slot:"foreground",description:"Markdown horizontal rule"},mdListBullet:{slot:"foreground",description:"Markdown list bullets/numbers"},toolDiffAdded:{slot:"foreground",description:"Added lines in tool diffs"},toolDiffRemoved:{slot:"foreground",description:"Removed lines in tool diffs"},toolDiffContext:{slot:"foreground",description:"Context lines in tool diffs"},syntaxComment:{slot:"foreground",description:"Syntax highlighting: comments"},syntaxKeyword:{slot:"foreground",description:"Syntax highlighting: keywords"},syntaxFunction:{slot:"foreground",description:"Syntax highlighting: function names"},syntaxVariable:{slot:"foreground",description:"Syntax highlighting: variable names"},syntaxString:{slot:"foreground",description:"Syntax highlighting: string literals"},syntaxNumber:{slot:"foreground",description:"Syntax highlighting: number literals"},syntaxType:{slot:"foreground",description:"Syntax highlighting: type names"},syntaxOperator:{slot:"foreground",description:"Syntax highlighting: operators"},syntaxPunctuation:{slot:"foreground",description:"Syntax highlighting: punctuation"},thinkingOff:{slot:"foreground",description:"Thinking level border: off"},thinkingMinimal:{slot:"foreground",description:"Thinking level border: minimal"},thinkingLow:{slot:"foreground",description:"Thinking level border: low"},thinkingMedium:{slot:"foreground",description:"Thinking level border: medium"},thinkingHigh:{slot:"foreground",description:"Thinking level border: high"},thinkingXhigh:{slot:"foreground",description:"Thinking level border: xhigh"},thinkingMax:{slot:"foreground",description:"Thinking level border: max (falls back to thinkingXhigh when omitted)",fallback:"thinkingXhigh"},bashMode:{slot:"foreground",description:"Editor border color in bash mode"}});var themeJsonValidator;function setThemeJsonValidator(validator){themeJsonValidator=validator}function resolveVarRefs(value,vars,visited=new Set){if(typeof value=="number"||value===""||value.startsWith("#")||/^ok(lch|hsl)\(/i.test(value))return value;if(visited.has(value))throw new Error(`Circular variable reference detected: ${value}`);if(!(value in vars))throw new Error(`Variable reference not found: ${value}`);return visited.add(value),resolveVarRefs(vars[value],vars,visited)}function resolveThemeColors(colors,vars={}){let resolved={};for(let[key,value]of Object.entries(colors))resolved[key]=resolveVarRefs(value,vars);return resolved}function withThemeTokenFallbacks(values){let resolved={...values};for(let[rawName,descriptor]of Object.entries(THEME_TOKENS)){if(!("fallback"in descriptor))continue;let name=rawName;if(resolved[name]!==void 0)continue;let fallback=descriptor.fallback,fallbackValue=resolved[fallback];if(fallbackValue===void 0)throw new Error(`Theme token ${rawName} has unresolved fallback ${descriptor.fallback}`);resolved[name]=fallbackValue}return resolved}var terminalColors={},terminalColorsPending=!1,terminalColorScheme;function setTerminalColors(colors){terminalColors={...colors},terminalColorsPending=!1}function setTerminalColorScheme(scheme){terminalColorScheme=scheme}function markTerminalColorsPending(){terminalColorsPending=!0}var GUESSED_DEFAULT_COLORS={dark:{foreground:parseColor("#e5e5e7"),background:parseColor("#000000")},light:{foreground:parseColor("#000000"),background:parseColor("#ffffff")}};function averageLightness(colors){let fixed=colors.filter(color=>color.kind!=="indexed"||color.index>=16);if(fixed.length!==0)return fixed.reduce((sum,color)=>sum+colorToOklch(color).l,0)/fixed.length}function detectAppearance(foregrounds,backgrounds){let fg=averageLightness(foregrounds),bg=averageLightness(backgrounds);if(fg!==void 0&&bg!==void 0)return bg<fg?"dark":"light";if(bg!==void 0)return bg<.5?"dark":"light";if(fg!==void 0)return fg>.5?"dark":"light"}var Theme=class{name;sourcePath;sourceInfo;mode;fgAnsi=new Map;bgAnsi=new Map;concreteColors={};defaultForegroundTokens=[];defaultBackgroundTokens=[];dimTokens;ownAppearance;resolvedColors;constructor(fgColors,bgColors,mode,options2={}){this.name=options2.name,this.sourcePath=options2.sourcePath,this.sourceInfo=options2.sourceInfo,this.mode=mode,this.dimTokens=new Set(options2.dim);let{fgColors:foregrounds,bgColors:backgrounds}=splitThemeColors(withThemeTokenFallbacks({...fgColors,...bgColors})),concreteForegrounds=[],concreteBackgrounds=[],addToken=(token,value,isBackground)=>{if(value==="")return(isBackground?this.defaultBackgroundTokens:this.defaultForegroundTokens).push(token),isBackground?"\x1B[49m":"\x1B[39m";let color=parseColor(value);return this.concreteColors[token]=color,(isBackground?concreteBackgrounds:concreteForegrounds).push(color),isBackground?backgroundAnsi(color,mode):foregroundAnsi(color,mode)};for(let[token,value]of Object.entries(foregrounds))this.fgAnsi.set(token,addToken(token,value,!1));for(let[token,value]of Object.entries(backgrounds))this.bgAnsi.set(token,addToken(token,value,!0));this.ownAppearance=options2.appearance??detectAppearance(concreteForegrounds,concreteBackgrounds)}get appearance(){return this.ownAppearance??getTerminalTheme()}get colors(){let terminal=terminalColors;if(this.resolvedColors?.terminal!==terminal){let guess=GUESSED_DEFAULT_COLORS[this.appearance],toColor=(rgb,fallback)=>rgb?rgbColor(rgb.r,rgb.g,rgb.b):fallback,foreground=toColor(terminal.foreground,guess.foreground),background=toColor(terminal.background,guess.background),colors={...this.concreteColors};for(let token of this.defaultForegroundTokens)colors[token]=foreground;for(let token of this.defaultBackgroundTokens)colors[token]=background;for(let token of this.dimTokens){let color=colors[token];color&&(colors[token]=mixColors(color,background,.4))}this.resolvedColors={terminal,colors:Object.freeze(colors)}}return this.resolvedColors.colors}style(text,options2){let{fg,bg}=options2;return typeof fg=="string"&&this.dimTokens.has(fg)&&(options2={...options2,dim:!0}),styleTextWithAnsi(text,fg===void 0?void 0:typeof fg=="string"?this.tokenAnsi(this.fgAnsi,fg):foregroundAnsi(fg,this.mode),bg===void 0?void 0:typeof bg=="string"?this.tokenAnsi(this.bgAnsi,bg):backgroundAnsi(bg,this.mode),options2)}fg(color,text){let ansi=this.tokenAnsi(this.fgAnsi,color);return this.dimTokens.has(color)?`${ansi}\x1B[2m${text}\x1B[22;39m`:`${ansi}${text}\x1B[39m`}bg(color,text){return`${this.tokenAnsi(this.bgAnsi,color)}${text}\x1B[49m`}tokenAnsi(ansi,token){let value=ansi.get(token);if(value===void 0)throw new Error(`Unknown theme color: ${token}`);return value}bold(text){return source_default.bold(text)}italic(text){return source_default.italic(text)}underline(text){return source_default.underline(text)}inverse(text){return source_default.inverse(text)}strikethrough(text){return source_default.strikethrough(text)}getFgAnsi(color){let ansi=this.tokenAnsi(this.fgAnsi,color);return this.dimTokens.has(color)?`${ansi}\x1B[2m`:ansi}getBgAnsi(color){return this.tokenAnsi(this.bgAnsi,color)}getColorMode(){return this.mode}getThinkingBorderColor(level){switch(level){case"off":return str2=>this.fg("thinkingOff",str2);case"minimal":return str2=>this.fg("thinkingMinimal",str2);case"low":return str2=>this.fg("thinkingLow",str2);case"medium":return str2=>this.fg("thinkingMedium",str2);case"high":return str2=>this.fg("thinkingHigh",str2);case"xhigh":return str2=>this.fg("thinkingXhigh",str2);case"max":return str2=>this.fg("thinkingMax",str2);default:return str2=>this.fg("thinkingOff",str2)}}getBashModeBorderColor(){return str2=>this.fg("bashMode",str2)}},BUILTIN_THEMES;function getBuiltinThemes(){if(!BUILTIN_THEMES){let themesDir=getThemesDir(),darkPath=path4.join(themesDir,"dark.json"),lightPath=path4.join(themesDir,"light.json");BUILTIN_THEMES={dark:JSON.parse(stripBom(fs3.readFileSync(darkPath,"utf-8"))),light:JSON.parse(stripBom(fs3.readFileSync(lightPath,"utf-8")))}}return BUILTIN_THEMES}function getAvailableThemes(){return getAvailableThemesWithPaths().map(({name})=>name)}function getAvailableThemesWithPaths(){let themesDir=getThemesDir(),result=[],seen=new Set,addTheme=themeInfo=>{seen.has(themeInfo.name)||(seen.add(themeInfo.name),result.push(themeInfo))};addTheme({name:SYSTEM_THEME_NAME,path:void 0});for(let name of Object.keys(getBuiltinThemes()))addTheme({name,path:path4.join(themesDir,`${name}.json`)});for(let themeInfo of getCustomThemeInfos())addTheme(themeInfo);for(let[name,theme2]of registeredThemes.entries())addTheme({name,path:theme2.sourcePath});return result.sort((a,b)=>a.name===SYSTEM_THEME_NAME?-1:b.name===SYSTEM_THEME_NAME?1:a.name.localeCompare(b.name))}function getCustomThemeInfos(){let customThemesDir=getCustomThemesDir(),result=[];if(!fs3.existsSync(customThemesDir))return result;for(let file of fs3.readdirSync(customThemesDir)){if(!file.endsWith(".json"))continue;let themePath=path4.join(customThemesDir,file);try{let customTheme=loadThemeFromPath(themePath);customTheme.name&&result.push({name:customTheme.name,path:themePath})}catch{}}return result}function assertThemeNameIsValid(name){if(name.includes("/"))throw new Error(`Invalid theme name "${name}": theme names cannot contain "/" because it is reserved for automatic light/dark theme settings.`)}function parseThemeJson(label,json2){if(themeJsonValidator)return themeJsonValidator(label,json2);if(typeof json2!="object"||json2===null||!("colors"in json2))throw new Error(`Invalid theme "${label}": expected an object with a "colors" map.`);return json2}function parseThemeJsonContent(label,content){let json2;try{json2=JSON.parse(stripBom(content))}catch(error){throw new Error(`Failed to parse theme ${label}: ${error}`)}return parseThemeJson(label,json2)}function loadThemeJson(name){let builtinThemes=getBuiltinThemes();if(name in builtinThemes)return builtinThemes[name];let registeredTheme=registeredThemes.get(name);if(registeredTheme?.sourcePath){let content2=fs3.readFileSync(registeredTheme.sourcePath,"utf-8");return parseThemeJsonContent(registeredTheme.sourcePath,content2)}if(registeredTheme)throw new Error(`Theme "${name}" does not have a source path for export`);let customThemesDir=getCustomThemesDir(),themePath=path4.join(customThemesDir,`${name}.json`);if(!fs3.existsSync(themePath))throw new Error(`Theme not found: ${name}`);let content=fs3.readFileSync(themePath,"utf-8");return parseThemeJsonContent(name,content)}function splitThemeColors(colors){let fgColors={},bgColors={};for(let[key,value]of Object.entries(colors))THEME_TOKENS[key].slot==="background"?bgColors[key]=value:fgColors[key]=value;return{fgColors,bgColors}}function createTheme(themeJson,mode,sourcePath){let colorMode=mode??getTerminalColorMode(),resolvedColors=withThemeTokenFallbacks(resolveThemeColors(themeJson.colors,themeJson.vars)),{fgColors,bgColors}=splitThemeColors(resolvedColors);return new Theme(fgColors,bgColors,colorMode,{name:themeJson.name,sourcePath,appearance:themeJson.appearance})}function createSystemTheme(mode){let generated=generateSystemThemeColors({...terminalColors,saturation:terminalColorsPending?0:1,appearanceHint:getTerminalTheme()}),{fgColors,bgColors}=splitThemeColors(withThemeTokenFallbacks(generated.colors));return new Theme(fgColors,bgColors,mode??getTerminalColorMode(),{name:SYSTEM_THEME_NAME,appearance:generated.appearance,dim:generated.dim})}function loadThemeFromPath(themePath,mode){let content=fs3.readFileSync(themePath,"utf-8"),themeJson=parseThemeJsonContent(themePath,content);return createTheme(themeJson,mode,themePath)}function loadTheme(name,mode){if(name===SYSTEM_THEME_NAME)return createSystemTheme(mode);let registeredTheme=registeredThemes.get(name);if(registeredTheme)return registeredTheme;let themeJson=loadThemeJson(name);return createTheme(themeJson,mode)}function getThemeByName(name){try{return loadTheme(name)}catch{return}}function parseAutoThemeSetting(themeSetting){if(!themeSetting)return;let slashIndex=themeSetting.indexOf("/");if(slashIndex===-1||themeSetting.indexOf("/",slashIndex+1)!==-1)return;let lightTheme=themeSetting.slice(0,slashIndex).trim(),darkTheme=themeSetting.slice(slashIndex+1).trim();if(!(!lightTheme||!darkTheme))return{lightTheme,darkTheme}}function resolveThemeSetting(themeSetting,terminalTheme){let autoTheme=parseAutoThemeSetting(themeSetting);if(autoTheme)return terminalTheme==="light"?autoTheme.lightTheme:autoTheme.darkTheme;if(!themeSetting?.includes("/")&&typeof themeSetting=="string")return themeSetting}function detectColorFgBgTheme(env=process.env){let bg=env.COLORFGBG?.split(";").at(-1)?.trim();if(!bg||!/^\d{1,2}$/.test(bg))return;let index=Number(bg);if(!(index>15))return index<=6||index===8?"dark":"light"}function detectTerminalTheme(colors={},reportedScheme,env=process.env){let{background,foreground}=colors;return background?terminalAppearance(background,foreground):reportedScheme??detectColorFgBgTheme(env)??"dark"}function getTerminalTheme(){return detectTerminalTheme(terminalColors,terminalColorScheme)}var THEME_KEY=Symbol.for("@draht/coding-agent:theme"),THEME_KEY_OLD=Symbol.for("@draht/coding-agent:theme"),theme=new Proxy({},{get(_target,prop){let t=globalThis[THEME_KEY];if(!t)throw new Error("Theme not initialized. Call initTheme() first.");return t[prop]}});function getGlobalTheme(){return globalThis[THEME_KEY]}function setGlobalTheme(t){globalThis[THEME_KEY]=t,globalThis[THEME_KEY_OLD]=t}var currentThemeName,themeWatcher,themeReloadTimer,onThemeChangeCallback,registeredThemes=new Map;function setRegisteredThemes(themes){registeredThemes.clear();for(let theme2 of themes)theme2.name&&(assertThemeNameIsValid(theme2.name),registeredThemes.set(theme2.name,theme2))}function initTheme(themeName,enableWatcher=!1){let name=themeName??getTerminalTheme();currentThemeName=name;try{setGlobalTheme(loadTheme(name)),enableWatcher&&startThemeWatcher()}catch{let fallback=getTerminalTheme();currentThemeName=fallback,setGlobalTheme(loadTheme(fallback))}}function setTheme(name,enableWatcher=!1){currentThemeName=name;try{return setGlobalTheme(loadTheme(name)),enableWatcher&&startThemeWatcher(),onThemeChangeCallback&&onThemeChangeCallback(),{success:!0}}catch(error){let fallback=getTerminalTheme();return currentThemeName=fallback,setGlobalTheme(loadTheme(fallback)),{success:!1,error:error instanceof Error?error.message:String(error)}}}function setThemeInstance(themeInstance){setGlobalTheme(themeInstance),currentThemeName="<in-memory>",stopThemeWatcher(),onThemeChangeCallback&&onThemeChangeCallback()}function onThemeChange(callback){onThemeChangeCallback=callback}function startThemeWatcher(){if(stopThemeWatcher(),!currentThemeName||currentThemeName==="dark"||currentThemeName==="light"||currentThemeName===SYSTEM_THEME_NAME)return;let customThemesDir=getCustomThemesDir(),watchedThemeName=currentThemeName,watchedFileName=`${watchedThemeName}.json`,themeFile=path4.join(customThemesDir,watchedFileName);if(!fs3.existsSync(themeFile))return;let scheduleReload=()=>{themeReloadTimer&&clearTimeout(themeReloadTimer),themeReloadTimer=setTimeout(()=>{if(themeReloadTimer=void 0,currentThemeName===watchedThemeName&&fs3.existsSync(themeFile))try{let reloadedTheme=loadThemeFromPath(themeFile);registeredThemes.set(watchedThemeName,reloadedTheme),setGlobalTheme(reloadedTheme),onThemeChangeCallback&&onThemeChangeCallback()}catch{}},100)};themeWatcher=watchWithErrorHandler(customThemesDir,(_eventType,filename)=>{if(currentThemeName===watchedThemeName){if(!filename){scheduleReload();return}filename===watchedFileName&&scheduleReload()}},()=>{closeWatcher(themeWatcher),themeWatcher=void 0})??void 0}function stopThemeWatcher(){themeReloadTimer&&(clearTimeout(themeReloadTimer),themeReloadTimer=void 0),closeWatcher(themeWatcher),themeWatcher=void 0}function getResolvedThemeColors(themeName){let colors=loadTheme(themeName??currentThemeName??SYSTEM_THEME_NAME).colors;return Object.fromEntries(Object.entries(colors).map(([token,color])=>[token,colorToHex(color)]))}function getThemeExportColors(themeName){let name=themeName??currentThemeName??SYSTEM_THEME_NAME;if(name===SYSTEM_THEME_NAME)return{};try{let themeJson=loadThemeJson(name),exportSection=themeJson.export;if(!exportSection)return{};let vars=themeJson.vars??{},resolve=value=>{if(value===void 0)return;let resolved=resolveVarRefs(value,vars);if(typeof resolved=="number")return colorToHex(indexedColor(resolved));if(resolved!=="")return/^okhsl\(/i.test(resolved)?colorToHex(parseColor(resolved)):resolved};return{pageBg:resolve(exportSection.pageBg),cardBg:resolve(exportSection.cardBg),infoBg:resolve(exportSection.infoBg)}}catch{return{}}}var cachedHighlightThemeFor,cachedCliHighlightTheme;function buildCliHighlightTheme(t){return{keyword:s=>t.fg("syntaxKeyword",s),built_in:s=>t.fg("syntaxType",s),literal:s=>t.fg("syntaxNumber",s),number:s=>t.fg("syntaxNumber",s),regexp:s=>t.fg("syntaxString",s),string:s=>t.fg("syntaxString",s),subst:s=>t.fg("text",s),comment:s=>t.fg("syntaxComment",s),doctag:s=>t.fg("syntaxComment",s),meta:s=>t.fg("muted",s),function:s=>t.fg("syntaxFunction",s),title:s=>t.fg("syntaxFunction",s),class:s=>t.fg("syntaxType",s),type:s=>t.fg("syntaxType",s),tag:s=>t.fg("syntaxPunctuation",s),name:s=>t.fg("syntaxKeyword",s),attr:s=>t.fg("syntaxVariable",s),variable:s=>t.fg("syntaxVariable",s),params:s=>t.fg("syntaxVariable",s),operator:s=>t.fg("syntaxOperator",s),punctuation:s=>t.fg("syntaxPunctuation",s),emphasis:s=>t.italic(s),strong:s=>t.bold(s),link:s=>t.underline(s),addition:s=>t.fg("toolDiffAdded",s),deletion:s=>t.fg("toolDiffRemoved",s)}}function getCliHighlightTheme(t){return(cachedHighlightThemeFor!==t||!cachedCliHighlightTheme)&&(cachedHighlightThemeFor=t,cachedCliHighlightTheme=buildCliHighlightTheme(t)),cachedCliHighlightTheme}function highlightCode(code,lang){let validLang=lang&&supportsLanguage(lang)?lang:void 0;if(!validLang)return code.split(`
@@ -131,7 +131,7 @@ Searches over deferred tool metadata with BM25 and exposes matching tools for th
131
131
 
132
132
  Some of the tools, such as tools of MCP servers, may not have been provided to you upfront, and you should use this tool (\`${TOOL_SEARCH_TOOL_NAME}\`) to search for the required tools. For MCP tool discovery, always use \`${TOOL_SEARCH_TOOL_NAME}\`.`;function createToolSearchToolDefinition(options2={}){return{name:TOOL_SEARCH_TOOL_NAME,label:TOOL_SEARCH_TOOL_NAME,description:TOOL_SEARCH_DESCRIPTION,promptSnippet:"Search for tools that are not loaded yet and load the matches",parameters:toolSearchSchema,exposure:"model-only",reachesTools:()=>"all",async execute(_toolCallId,{query,limit}){if(query.trim()==="")throw new Error("query must not be empty");let max=limit??DEFAULT_TOOL_SEARCH_LIMIT;if(!Number.isInteger(max)||max<=0)throw new Error("limit must be a positive integer");let tools=options2.tools?searchAndLoad(options2.tools,query,max):[];return{content:[{type:"text",text:tools.length===0?"No matching tools found.":`Loaded ${tools.length} tool${tools.length===1?"":"s"}. They are available from your next call:
133
133
  ${tools.map(tool=>`- ${tool.name}: ${tool.description.trim().split(/\r?\n/)[0]}`).join(`
134
- `)}`}],details:{loaded:tools.map(tool=>tool.name)}}}}}import{join as join8}from"node:path";function wrapToolDefinition(definition,ctxFactory){return{name:definition.name,label:definition.label,description:definition.description,parameters:definition.parameters,outputSchema:definition.outputSchema,constrainedSampling:definition.constrainedSampling,prepareArguments:definition.prepareArguments,executionMode:definition.executionMode,execute:(toolCallId,params,signal,onUpdate,ctx)=>definition.execute(toolCallId,params,signal,onUpdate,ctx??ctxFactory?.(toolCallId,signal))}}function createToolDefinitionFromAgentTool(tool){return{name:tool.name,label:tool.label,description:tool.description,parameters:tool.parameters,outputSchema:tool.outputSchema,constrainedSampling:tool.constrainedSampling,prepareArguments:tool.prepareArguments,executionMode:tool.executionMode,execute:async(toolCallId,params,signal,onUpdate)=>tool.execute(toolCallId,params,signal,onUpdate)}}var loadCodemodeExecutor=()=>import("./execute-KGJOWTPG.js");var CODE_PREVIEW_LINES=10,CALL_PREVIEW_COUNT=8,OUTPUT_PREVIEW_LINES=5,COLLAPSED_ARGS_CHARS2=80,SCRIPT_HEADER=/^Script (completed|failed)\nWall time [\d.]+ seconds\nOutput:\n$/;function expandHint(theme2,hidden,noun){return`${theme2.fg("muted",`... (${hidden} more ${noun},`)} ${keyHint("app.tools.expand","to expand")}${theme2.fg("muted",")")}`}function formatDuration(ms){return ms===void 0?"":ms<1e3?`${Math.round(ms)}ms`:`${(ms/1e3).toFixed(1)}s`}function formatCost(cost){return`$${cost>=.01?cost.toFixed(2):cost.toPrecision(2)}`}function statusIcon(call,theme2){switch(call.status){case"running":return theme2.fg("warning","\u2026");case"ok":return theme2.fg("success","\u2713");case"error":return theme2.fg("error","\u2717");case"cancelled":return theme2.fg("muted","\u2298")}}function formatCall(call,theme2,expanded){let args=!expanded&&call.args.length>COLLAPSED_ARGS_CHARS2?`${call.args.slice(0,COLLAPSED_ARGS_CHARS2-3)}...`:call.args,duration=formatDuration(call.durationMs),line=`${statusIcon(call,theme2)} ${theme2.fg("toolTitle",call.name)}`;return args&&(line+=` ${theme2.fg("muted",args)}`),duration&&(line+=` ${theme2.fg("dim",duration)}`),call.cost&&(line+=` ${theme2.fg("dim",formatCost(call.cost))}`),expanded&&call.error&&(line+=`
134
+ `)}`}],details:{loaded:tools.map(tool=>tool.name)}}}}}import{join as join8}from"node:path";function wrapToolDefinition(definition,ctxFactory){return{name:definition.name,label:definition.label,description:definition.description,parameters:definition.parameters,outputSchema:definition.outputSchema,constrainedSampling:definition.constrainedSampling,prepareArguments:definition.prepareArguments,executionMode:definition.executionMode,execute:(toolCallId,params,signal,onUpdate,ctx)=>definition.execute(toolCallId,params,signal,onUpdate,ctx??ctxFactory?.(toolCallId,signal))}}function createToolDefinitionFromAgentTool(tool){return{name:tool.name,label:tool.label,description:tool.description,parameters:tool.parameters,outputSchema:tool.outputSchema,constrainedSampling:tool.constrainedSampling,prepareArguments:tool.prepareArguments,executionMode:tool.executionMode,execute:async(toolCallId,params,signal,onUpdate)=>tool.execute(toolCallId,params,signal,onUpdate)}}var loadCodemodeExecutor=()=>import("./execute-YOMYOVUT.js");var CODE_PREVIEW_LINES=10,CALL_PREVIEW_COUNT=8,OUTPUT_PREVIEW_LINES=5,COLLAPSED_ARGS_CHARS2=80,SCRIPT_HEADER=/^Script (completed|failed)\nWall time [\d.]+ seconds\nOutput:\n$/;function expandHint(theme2,hidden,noun){return`${theme2.fg("muted",`... (${hidden} more ${noun},`)} ${keyHint("app.tools.expand","to expand")}${theme2.fg("muted",")")}`}function formatDuration(ms){return ms===void 0?"":ms<1e3?`${Math.round(ms)}ms`:`${(ms/1e3).toFixed(1)}s`}function formatCost(cost){return`$${cost>=.01?cost.toFixed(2):cost.toPrecision(2)}`}function statusIcon(call,theme2){switch(call.status){case"running":return theme2.fg("warning","\u2026");case"ok":return theme2.fg("success","\u2713");case"error":return theme2.fg("error","\u2717");case"cancelled":return theme2.fg("muted","\u2298")}}function formatCall(call,theme2,expanded){let args=!expanded&&call.args.length>COLLAPSED_ARGS_CHARS2?`${call.args.slice(0,COLLAPSED_ARGS_CHARS2-3)}...`:call.args,duration=formatDuration(call.durationMs),line=`${statusIcon(call,theme2)} ${theme2.fg("toolTitle",call.name)}`;return args&&(line+=` ${theme2.fg("muted",args)}`),duration&&(line+=` ${theme2.fg("dim",duration)}`),call.cost&&(line+=` ${theme2.fg("dim",formatCost(call.cost))}`),expanded&&call.error&&(line+=`
135
135
  ${theme2.fg("error",call.error.split(`
136
136
  `).join(`
137
137
  `))}`),line}var codemodeRenderers={renderCall(args,theme2,context){startToolTimer(context);let code=str(args?.code),title=theme2.fg("toolTitle",theme2.bold("codemode")),component=context.lastComponent??new Container;if(component.clear(),code===null)return component.addChild(new Text(`${title} ${theme2.fg("error","[invalid arg]")}`,0,0)),component;if(component.addChild(new Text(title,0,0)),code){let state=context.state;state.scriptHighlighter??=new CodeHighlighter;let highlighted=state.scriptHighlighter.highlight(replaceTabs(code.replace(/\r/g,"").trimEnd()),"javascript").join(`