@plusonelabs/cue 0.0.41 → 0.0.43
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cue-v0.0.43.tar.gz +0 -0
- package/dist/cli.mjs +7 -7
- package/package.json +1 -1
- package/cue-v0.0.41.tar.gz +0 -0
|
Binary file
|
package/dist/cli.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { createRequire } from 'module'; const require = createRequire(import.meta.url); global.__CUE_VERSION__ = '0.0.
|
|
2
|
+
import { createRequire } from 'module'; const require = createRequire(import.meta.url); global.__CUE_VERSION__ = '0.0.43';
|
|
3
3
|
var rhe=Object.create;var E5=Object.defineProperty;var she=Object.getOwnPropertyDescriptor;var uhe=Object.getOwnPropertyNames;var lhe=Object.getPrototypeOf,che=Object.prototype.hasOwnProperty;var ct=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var F=(t,e)=>()=>(t&&(e=t(t=0)),e);var ue=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),di=(t,e)=>{for(var n in e)E5(t,n,{get:e[n],enumerable:!0})},hG=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of uhe(e))!che.call(t,a)&&a!==n&&E5(t,a,{get:()=>e[a],enumerable:!(i=she(e,a))||i.enumerable});return t};var we=(t,e,n)=>(n=t!=null?rhe(lhe(t)):{},hG(e||!t||!t.__esModule?E5(n,"default",{value:t,enumerable:!0}):n,t)),gG=t=>hG(E5({},"__esModule",{value:!0}),t);import y5 from"fs";import b_ from"path";function fm(){if(typeof global.__CUE_VERSION__<"u")return global.__CUE_VERSION__;try{let t=process.argv[1],e=b_.join(b_.dirname(t),"..","package.json");if(y5.existsSync(e)){let n=y5.readFileSync(e,"utf-8");return JSON.parse(n).version}}catch{}if(process.argv[1].includes("src/cli.tsx"))try{let t=b_.join(process.cwd(),"package.json");if(y5.existsSync(t)){let e=y5.readFileSync(t,"utf-8");return JSON.parse(e).version}}catch{}return"unknown"}var Q3=F(()=>{"use strict"});function ot(t,e,n,i,a){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!a)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!a:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?a.call(t,n):a?a.value=n:e.set(t,n),n}function he(t,e,n,i){if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?i:n==="a"?i.call(t):i?i.value:e.get(t)}var ld=F(()=>{});var I_,yG=F(()=>{I_=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return I_=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),n=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,i=>(+i^n()&15>>+i/4).toString(16))}});function cd(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var R3,s2=F(()=>{R3=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)}});var ht,so,zo,mm,u2,l2,c2,p2,d2,f2,m2,A2,h2,wl=F(()=>{s2();ht=class extends Error{},so=class t extends ht{constructor(e,n,i,a){super(`${t.makeMessage(e,n,i)}`),this.status=e,this.headers=a,this.requestID=a?.get("request-id"),this.error=n}static makeMessage(e,n,i){let a=n?.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):i;return e&&a?`${e} ${a}`:e?`${e} status code (no body)`:a||"(no status code or body)"}static generate(e,n,i,a){if(!e||!a)return new mm({message:i,cause:R3(n)});let o=n;return e===400?new l2(e,o,i,a):e===401?new c2(e,o,i,a):e===403?new p2(e,o,i,a):e===404?new d2(e,o,i,a):e===409?new f2(e,o,i,a):e===422?new m2(e,o,i,a):e===429?new A2(e,o,i,a):e>=500?new h2(e,o,i,a):new t(e,o,i,a)}},zo=class extends so{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},mm=class extends so{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),n&&(this.cause=n)}},u2=class extends mm{constructor({message:e}={}){super({message:e??"Request timed out."})}},l2=class extends so{},c2=class extends so{},p2=class extends so{},d2=class extends so{},f2=class extends so{},m2=class extends so{},A2=class extends so{},h2=class extends so{}});function w_(t){return typeof t!="object"?{}:t??{}}function CG(t){if(!t)return!0;for(let e in t)return!1;return!0}function bG(t,e){return Object.prototype.hasOwnProperty.call(t,e)}var dhe,vG,S_,x_,IG,v5,PA=F(()=>{wl();dhe=/^[a-z][a-z0-9+.-]*:/i,vG=t=>dhe.test(t),S_=t=>(S_=Array.isArray,S_(t)),x_=S_;IG=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new ht(`${t} must be an integer`);if(e<0)throw new ht(`${t} must be a positive integer`);return e},v5=t=>{try{return JSON.parse(t)}catch{return}}});var SG,xG=F(()=>{SG=t=>new Promise(e=>setTimeout(e,t))});var Am,B_=F(()=>{Am="0.64.0"});function fhe(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}function Ahe(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:n}of t){let i=n.exec(navigator.userAgent);if(i){let a=i[1]||0,o=i[2]||0,u=i[3]||0;return{browser:e,version:`${a}.${o}.${u}`}}}return null}var FG,mhe,wG,BG,_G,TG,__=F(()=>{B_();FG=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";mhe=()=>{let t=fhe();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Am,"X-Stainless-OS":BG(Deno.build.os),"X-Stainless-Arch":wG(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Am,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Am,"X-Stainless-OS":BG(globalThis.process.platform??"unknown"),"X-Stainless-Arch":wG(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Ahe();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Am,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Am,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};wG=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",BG=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown"),TG=()=>_G??(_G=mhe())});function QG(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function F_(...t){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function C5(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return F_({start(){},async pull(n){let{done:i,value:a}=await e.next();i?n.close():n.enqueue(a)},async cancel(){await e.return?.()}})}function N3(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{async next(){try{let n=await e.read();return n?.done&&e.releaseLock(),n}catch(n){throw e.releaseLock(),n}},async return(){let n=e.cancel();return e.releaseLock(),await n,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function RG(t){if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await t[Symbol.asyncIterator]().return?.();return}let e=t.getReader(),n=e.cancel();e.releaseLock(),await n}var g2=F(()=>{});var NG,kG=F(()=>{NG=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)})});function MG(t){let e=0;for(let a of t)e+=a.length;let n=new Uint8Array(e),i=0;for(let a of t)n.set(a,i),i+=a.length;return n}function k3(t){let e;return(OG??(e=new globalThis.TextEncoder,OG=e.encode.bind(e)))(t)}function T_(t){let e;return(UG??(e=new globalThis.TextDecoder,UG=e.decode.bind(e)))(t)}var OG,UG,Q_=F(()=>{});function Dhe(t,e){for(let a=e??0;a<t.length;a++){if(t[a]===10)return{preceding:a,index:a+1,carriage:!1};if(t[a]===13)return{preceding:a,index:a+1,carriage:!0}}return null}function LG(t){for(let i=0;i<t.length-1;i++){if(t[i]===10&&t[i+1]===10||t[i]===13&&t[i+1]===13)return i+2;if(t[i]===13&&t[i+1]===10&&i+3<t.length&&t[i+2]===13&&t[i+3]===10)return i+4}return-1}var Ns,ks,pd,R_=F(()=>{ld();Q_();pd=class{constructor(){Ns.set(this,void 0),ks.set(this,void 0),ot(this,Ns,new Uint8Array,"f"),ot(this,ks,null,"f")}decode(e){if(e==null)return[];let n=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?k3(e):e;ot(this,Ns,MG([he(this,Ns,"f"),n]),"f");let i=[],a;for(;(a=Dhe(he(this,Ns,"f"),he(this,ks,"f")))!=null;){if(a.carriage&&he(this,ks,"f")==null){ot(this,ks,a.index,"f");continue}if(he(this,ks,"f")!=null&&(a.index!==he(this,ks,"f")+1||a.carriage)){i.push(T_(he(this,Ns,"f").subarray(0,he(this,ks,"f")-1))),ot(this,Ns,he(this,Ns,"f").subarray(he(this,ks,"f")),"f"),ot(this,ks,null,"f");continue}let o=he(this,ks,"f")!==null?a.preceding-1:a.preceding,u=T_(he(this,Ns,"f").subarray(0,o));i.push(u),ot(this,Ns,he(this,Ns,"f").subarray(a.index),"f"),ot(this,ks,null,"f")}return i}flush(){return he(this,Ns,"f").length?this.decode(`
|
|
4
4
|
`):[]}};Ns=new WeakMap,ks=new WeakMap;pd.NEWLINE_CHARS=new Set([`
|
|
5
5
|
`,"\r"]);pd.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function O3(){}function b5(t,e,n){return!e||I5[t]>I5[n]?O3:e[t].bind(e)}function uo(t){let e=t.logger,n=t.logLevel??"off";if(!e)return Ehe;let i=PG.get(e);if(i&&i[0]===n)return i[1];let a={error:b5("error",e,n),warn:b5("warn",e,n),info:b5("info",e,n),debug:b5("debug",e,n)};return PG.set(e,[n,a]),a}var I5,N_,Ehe,PG,dd,S5=F(()=>{PA();I5={off:0,error:200,warn:300,info:400,debug:500},N_=(t,e,n)=>{if(t){if(bG(I5,t))return t;uo(n).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(I5))}`)}};Ehe={error:O3,warn:O3,info:O3,debug:O3},PG=new WeakMap;dd=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,n])=>[e,e.toLowerCase()==="x-api-key"||e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":n]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t)});async function*yhe(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new ht("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new ht("Attempted to iterate over a response with no body");let n=new k_,i=new pd,a=N3(t.body);for await(let o of vhe(a))for(let u of i.decode(o)){let p=n.decode(u);p&&(yield p)}for(let o of i.flush()){let u=n.decode(o);u&&(yield u)}}async function*vhe(t){let e=new Uint8Array;for await(let n of t){if(n==null)continue;let i=n instanceof ArrayBuffer?new Uint8Array(n):typeof n=="string"?k3(n):n,a=new Uint8Array(e.length+i.length);a.set(e),a.set(i,e.length),e=a;let o;for(;(o=LG(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}function Che(t,e){let n=t.indexOf(e);return n!==-1?[t.substring(0,n),e,t.substring(n+e.length)]:[t,"",""]}var U3,wc,k_,O_=F(()=>{ld();wl();g2();R_();g2();s2();PA();Q_();S5();wl();wc=class t{constructor(e,n,i){this.iterator=e,U3.set(this,void 0),this.controller=n,ot(this,U3,i,"f")}static fromSSEResponse(e,n,i){let a=!1,o=i?uo(i):console;async function*u(){if(a)throw new ht("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");a=!0;let p=!1;try{for await(let f of yhe(e,n)){if(f.event==="completion")try{yield JSON.parse(f.data)}catch(A){throw o.error("Could not parse message into JSON:",f.data),o.error("From chunk:",f.raw),A}if(f.event==="message_start"||f.event==="message_delta"||f.event==="message_stop"||f.event==="content_block_start"||f.event==="content_block_delta"||f.event==="content_block_stop")try{yield JSON.parse(f.data)}catch(A){throw o.error("Could not parse message into JSON:",f.data),o.error("From chunk:",f.raw),A}if(f.event!=="ping"&&f.event==="error")throw new so(void 0,v5(f.data)??f.data,void 0,e.headers)}p=!0}catch(f){if(cd(f))return;throw f}finally{p||n.abort()}}return new t(u,n,i)}static fromReadableStream(e,n,i){let a=!1;async function*o(){let p=new pd,f=N3(e);for await(let A of f)for(let g of p.decode(A))yield g;for(let A of p.flush())yield A}async function*u(){if(a)throw new ht("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");a=!0;let p=!1;try{for await(let f of o())p||f&&(yield JSON.parse(f));p=!0}catch(f){if(cd(f))return;throw f}finally{p||n.abort()}}return new t(u,n,i)}[(U3=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],n=[],i=this.iterator(),a=o=>({next:()=>{if(o.length===0){let u=i.next();e.push(u),n.push(u)}return o.shift()}});return[new t(()=>a(e),this.controller,he(this,U3,"f")),new t(()=>a(n),this.controller,he(this,U3,"f"))]}toReadableStream(){let e=this,n;return F_({async start(){n=e[Symbol.asyncIterator]()},async pull(i){try{let{value:a,done:o}=await n.next();if(o)return i.close();let u=k3(JSON.stringify(a)+`
|
|
@@ -47,7 +47,7 @@ ${t.codeStyle}
|
|
|
47
47
|
# Cue CLI personal configuration
|
|
48
48
|
.cue
|
|
49
49
|
`;Zhe(i,p,"utf-8"),b.debug("Added .cue directory to git exclude file")}}catch(t){b.debug("Failed to setup .cue git ignore:",{error:String(t)})}}var QF=F(()=>{"use strict";TF();Mt()});var Bq={};di(Bq,{logCacheUsage:()=>o0e});import Sq from"fs/promises";import wq from"path";async function o0e(t,e){if(!t)return;let n=f=>"input_tokens"in f&&"output_tokens"in f,i=n(t)?t.input_tokens:t.prompt_tokens||0,a=n(t)?t.output_tokens:t.completion_tokens||0,o=n(t)&&t.cache_creation_input_tokens||0,u=n(t)&&t.cache_read_input_tokens||0,p={timestamp:new Date().toISOString(),method:e,input_tokens:i,output_tokens:a,cache_creation_input_tokens:o,cache_read_input_tokens:u,cache_hit:u>0,cache_miss:o>0,prompt_caching_enabled:i0e};a0e&&console.log("Cache Usage:",p);try{let f=wq.dirname(xq);await Sq.mkdir(f,{recursive:!0}),await Sq.appendFile(xq,JSON.stringify(p)+`
|
|
50
|
-
`)}catch(f){console.error("Failed to write cache log:",f)}}var i0e,a0e,xq,_q=F(()=>{"use strict";i0e=!process.env.DISABLE_PROMPT_CACHING,a0e=process.env.CACHE_DEBUG==="true",xq=process.env.CACHE_LOG_FILE||wq.join(process.cwd(),"logs/cache_usage.jsonl")});function sE(t){RF=t}async function NF(t){if(RF){let e={timestamp:new Date().toISOString(),cwd:process.cwd(),...t};try{await RF(e)}catch(n){console.error("Session logging failed:",n)}}}function kF(){return process.env.NODE_ENV==="development"||process.env.CUE_LOG_SESSIONS==="true"}async function t7(t,e,n,i,a,o){if(n){let{logCacheUsage:u}=await Promise.resolve().then(()=>(_q(),Bq));await u(n,t)}if(kF()){let u=Date.now()-i,p=g=>"input_tokens"in g&&"output_tokens"in g,f=n?p(n)?n.input_tokens:n.prompt_tokens:void 0,A=n?p(n)?n.output_tokens:n.completion_tokens:void 0;await NF({eventType:"api_call",apiCall:{method:t,model:e,inputTokens:f,outputTokens:A,cacheCreationTokens:n&&p(n)&&n.cache_creation_input_tokens||void 0,cacheReadTokens:n&&p(n)&&n.cache_read_input_tokens||void 0,durationMs:u,conversationContext:{messages:a,systemPrompt:o}}})}}var RF,n7=F(()=>{"use strict";RF=null});async function OF(t,e,n){try{let i=e.find(u=>u.name===t.name);if(!i){let u=new Dd(t.name,"Tool not found",t.input,{availableTools:e.map(p=>p.name)});return b.error("Tool error",{error:u.message}),{type:"tool_result",tool_use_id:t.id,content:`Error: Tool '${t.name}' not found. Available tools: ${e.map(p=>p.name).join(", ")}`,is_error:!0}}if(n?.aborted)throw new Error("Operation cancelled by user");let a=t.input||{};b.debug("Tool execution started",{toolName:t.name,input:a});let o;try{o=await i.call(a,n)}catch(u){let p=new Dd(t.name,`Tool execution failed: ${u instanceof Error?u.message:String(u)}`,t.input,{originalError:u});b.error("Tool error",{error:p.message}),o={success:!1,content:"",error:p.message}}if(o.isImage&&o.imageData&&o.success){let u=["image/jpeg","image/png","image/gif","image/webp"],p=o.imageData.mimeType;if(!u.includes(p)){if(p==="image/svg+xml")return{type:"tool_result",tool_use_id:t.id,content:`SVG image detected at ${o.imageData.path}. SVG format is not directly supported for image display.`,is_error:!1};p="image/png"}return{type:"tool_result",tool_use_id:t.id,content:[{type:"image",source:{type:"base64",data:o.imageData.base64,media_type:p}}],is_error:!1}}return{type:"tool_result",tool_use_id:t.id,content:o.success?o.content:`Error: ${o.error}`,is_error:!o.success}}catch(i){return i instanceof Error&&i.message==="Operation cancelled by user"?{type:"tool_result",tool_use_id:t.id,content:"[Request interrupted by user for tool use]",is_error:!0}:(b.error("Unexpected error in processToolUse",{error:i instanceof Error?i.message:String(i),toolName:t.name,toolId:t.id}),{type:"tool_result",tool_use_id:t.id,content:`Error: Unexpected error processing tool '${t.name}': ${i instanceof Error?i.message:String(i)}`,is_error:!0})}}var Fq=F(()=>{"use strict";F2();Mt()});function U2(t,e){let n=e.provider==="anthropic"?"Anthropic":"OpenAI";if(b.debug(`Handling ${n} API error`,{error:t}),t instanceof Error){let a,o;if("status"in t&&(a=t.status),"response"in t&&(o=t.response),t.message.includes("credit")||t.message.includes("balance")||t.message.includes("quota")){let p=new gd(`Insufficient credits. Please check your ${n} account.`,402,o,{originalError:t.message});return b.error(`${n} API error`,{error:p.message}),p}if(t.message.includes("api key")||t.message.includes("unauthorized")){let p=new gd(`Invalid API key. Please check your ${e.apiKeyEnvVar}.`,401,o,{originalError:t.message});return b.error(`${n} API error`,{error:p.message}),p}if(t.message.includes("rate limit")){let p=new gd("Rate limit exceeded. Please try again later.",429,o,{originalError:t.message});return b.error(`${n} API error`,{error:p.message}),p}let u=new gd(t.message,a,o,{originalError:t.message});return b.error(`${n} API error`,{error:u.message}),u}let i=new gd("An unknown error occurred while communicating with model.",void 0,void 0,{originalError:String(t)});return b.error(`${n} API error`,{error:i.message}),i}var UF=F(()=>{"use strict";F2();Mt()});var i7,Tq=F(()=>{"use strict";Mt();i7=class{accumulatedContent="";toolUseBlocks=[];messageId=null;initialUsage=null;finalUsage=null;model;stopReason=null;tag="AnthropicStreamBuilder";constructor(e){this.model=e}processChunk(e){switch(e.type){case"message_start":return e.message&&(this.messageId=e.message.id,this.initialUsage=e.message.usage||null,this.model=e.message.model||this.model,b.debug(`${this.tag}: Captured message_start`,{messageId:this.messageId,hasUsage:!!this.initialUsage,model:this.model})),{type:"none"};case"content_block_delta":return this.handleContentBlockDelta(e);case"content_block_start":return this.handleContentBlockStart(e);case"message_delta":return e.delta?.stop_reason&&(this.stopReason=e.delta.stop_reason),e.usage&&(this.finalUsage={input_tokens:e.usage.input_tokens||0,output_tokens:e.usage.output_tokens||0,cache_read_input_tokens:e.usage.cache_read_input_tokens||null,cache_creation_input_tokens:e.usage.cache_creation_input_tokens||null,cache_creation:null,server_tool_use:e.usage.server_tool_use||null,service_tier:null},b.debug(`${this.tag}: Captured message_delta usage`,{usage:this.finalUsage,stopReason:this.stopReason})),{type:"none"};case"message_stop":return this.handleMessageStop(e);default:return{type:"none"}}}handleContentBlockDelta(e){return e.delta.type==="text_delta"?(this.accumulatedContent+=e.delta.text,{type:"delta",data:this.buildPartialMessage()}):e.delta.type==="input_json_delta"?(this.handleToolInputDelta(e.delta.partial_json),{type:"delta",data:this.buildPartialMessage()}):{type:"none"}}handleToolInputDelta(e){let n=this.toolUseBlocks.length-1,i=this.toolUseBlocks[n];if(!(!i||!e)){i.input||(i.input={});try{let a=JSON.parse(e);Object.assign(i.input,a),b.debug(`${this.tag}: Merged partial JSON input`,{toolName:i.name,partialInput:a})}catch{this.accumulatePartialJson(i,e)}}}accumulatePartialJson(e,n){let i=e;i._inputBuffer||(i._inputBuffer=""),i._inputBuffer+=n;try{let a=JSON.parse(i._inputBuffer);e.input=a,delete i._inputBuffer,b.debug(`${this.tag}: Successfully parsed accumulated JSON buffer`,{toolName:e.name,parsed:a})}catch{b.debug(`${this.tag}: Buffer still accumulating for tool ${e.name}`)}}handleContentBlockStart(e){if(e.content_block.type==="tool_use"){let n={...e.content_block,input:e.content_block.input||{}};this.toolUseBlocks.push(n),b.debug(`${this.tag}: Tool use block started`,{toolName:n.name,toolId:n.id})}return{type:"none"}}handleMessageStop(e){b.debug(`${this.tag}: MESSAGE_STOP - Building final response`,{accumulatedContentLength:this.accumulatedContent.length,toolUseBlocksCount:this.toolUseBlocks.length});let n=[];this.accumulatedContent&&n.push({type:"text",text:this.accumulatedContent,citations:[]}),n.push(...this.toolUseBlocks);let i=this.finalUsage||this.initialUsage||this.extractUsage(e),a={id:this.messageId||`msg_dirty_${Date.now()}`,type:"message",role:"assistant",content:n,model:this.model,stop_reason:this.stopReason||"end_turn",stop_sequence:null,usage:i};return b.debug(`${this.tag}: Built final message`,{messageId:a.id,stopReason:a.stop_reason,hasUsage:!!i,contentLength:n.length}),{type:"assistantResponse",data:a}}buildPartialMessage(){let e=[];this.accumulatedContent&&e.push({type:"text",text:this.accumulatedContent,citations:[]}),e.push(...this.toolUseBlocks);let n=this.finalUsage||this.initialUsage;return{id:this.messageId||`msg_partial_${Date.now()}`,type:"message",role:"assistant",content:e,model:this.model,stop_reason:this.stopReason,stop_sequence:null,usage:n||{input_tokens:0,output_tokens:0,cache_read_input_tokens:null,cache_creation_input_tokens:null,cache_creation:null,server_tool_use:null,service_tier:null}}}extractUsage(e){let n=e?.message.usage;return n&&typeof n=="object"?{input_tokens:n.input_tokens||0,output_tokens:n.output_tokens||0,cache_read_input_tokens:n.cache_read_input_tokens||null,cache_creation_input_tokens:n.cache_creation_input_tokens||null,cache_creation:n.cache_creation||null,server_tool_use:n.server_tool_use||null,service_tier:n.service_tier||null}:{input_tokens:0,output_tokens:0,cache_read_input_tokens:null,cache_creation_input_tokens:null,cache_creation:null,server_tool_use:null,service_tier:null}}getToolUseBlocks(){return this.toolUseBlocks}getMessageId(){return this.messageId}getInitialUsage(){return this.initialUsage}getFinalUsage(){return this.finalUsage}hasTools(){return this.toolUseBlocks.length>0}reset(){this.accumulatedContent="",this.toolUseBlocks=[],this.messageId=null,this.initialUsage=null,this.finalUsage=null,this.stopReason=null}}});function ae(t,e,n){function i(p,f){var A;Object.defineProperty(p,"_zod",{value:p._zod??{},enumerable:!1}),(A=p._zod).traits??(A.traits=new Set),p._zod.traits.add(t),e(p,f);for(let g in u.prototype)g in p||Object.defineProperty(p,g,{value:u.prototype[g].bind(p)});p._zod.constr=u,p._zod.def=f}let a=n?.Parent??Object;class o extends a{}Object.defineProperty(o,"name",{value:t});function u(p){var f;let A=n?.Parent?new o:this;i(A,p),(f=A._zod).deferred??(f.deferred=[]);for(let g of A._zod.deferred)g();return A}return Object.defineProperty(u,"init",{value:i}),Object.defineProperty(u,Symbol.hasInstance,{value:p=>n?.Parent&&p instanceof n.Parent?!0:p?._zod?.traits?.has(t)}),Object.defineProperty(u,"name",{value:t}),u}function _a(t){return t&&Object.assign(uE,t),uE}var MF,LF,kc,uE,M2=F(()=>{MF=Object.freeze({status:"aborted"});LF=Symbol("zod_brand"),kc=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},uE={}});var qe={};di(qe,{BIGINT_FORMAT_RANGES:()=>VF,Class:()=>zF,NUMBER_FORMAT_RANGES:()=>KF,aborted:()=>JA,allowsEval:()=>$F,assert:()=>c0e,assertEqual:()=>r0e,assertIs:()=>u0e,assertNever:()=>l0e,assertNotEqual:()=>s0e,assignProp:()=>KA,cached:()=>pE,captureStackTrace:()=>o7,cleanEnum:()=>S0e,cleanRegex:()=>dE,clone:()=>ps,cloneDef:()=>d0e,createTransparentProxy:()=>D0e,defineLazy:()=>Bn,esc:()=>a7,escapeRegex:()=>Oc,extend:()=>v0e,finalizeIssue:()=>Us,floatSafeRemainder:()=>jF,getElementAtPath:()=>f0e,getEnumValues:()=>cE,getLengthableOrigin:()=>AE,getParsedType:()=>g0e,getSizableOrigin:()=>mE,isObject:()=>L2,isPlainObject:()=>VA,issue:()=>z2,joinValues:()=>ve,jsonStringifyReplacer:()=>P2,merge:()=>C0e,mergeDefs:()=>Sm,normalizeParams:()=>He,nullish:()=>Im,numKeys:()=>h0e,objectClone:()=>p0e,omit:()=>y0e,optionalKeys:()=>qF,partial:()=>b0e,pick:()=>E0e,prefixIssues:()=>Os,primitiveTypes:()=>GF,promiseAllObject:()=>m0e,propertyKeyTypes:()=>fE,randomString:()=>A0e,required:()=>I0e,shallowClone:()=>HF,stringifyPrimitive:()=>Ve,unwrapMessage:()=>lE});function r0e(t){return t}function s0e(t){return t}function u0e(t){}function l0e(t){throw new Error}function c0e(t){}function cE(t){let e=Object.values(t).filter(i=>typeof i=="number");return Object.entries(t).filter(([i,a])=>e.indexOf(+i)===-1).map(([i,a])=>a)}function ve(t,e="|"){return t.map(n=>Ve(n)).join(e)}function P2(t,e){return typeof e=="bigint"?e.toString():e}function pE(t){return{get value(){{let n=t();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function Im(t){return t==null}function dE(t){let e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function jF(t,e){let n=(t.toString().split(".")[1]||"").length,i=e.toString(),a=(i.split(".")[1]||"").length;if(a===0&&/\d?e-\d?/.test(i)){let f=i.match(/\d?e-(\d?)/);f?.[1]&&(a=Number.parseInt(f[1]))}let o=n>a?n:a,u=Number.parseInt(t.toFixed(o).replace(".","")),p=Number.parseInt(e.toFixed(o).replace(".",""));return u%p/10**o}function Bn(t,e,n){let i;Object.defineProperty(t,e,{get(){if(i!==Qq)return i===void 0&&(i=Qq,i=n()),i},set(a){Object.defineProperty(t,e,{value:a})},configurable:!0})}function p0e(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function KA(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Sm(...t){let e={};for(let n of t){let i=Object.getOwnPropertyDescriptors(n);Object.assign(e,i)}return Object.defineProperties({},e)}function d0e(t){return Sm(t._zod.def)}function f0e(t,e){return e?e.reduce((n,i)=>n?.[i],t):t}function m0e(t){let e=Object.keys(t),n=e.map(i=>t[i]);return Promise.all(n).then(i=>{let a={};for(let o=0;o<e.length;o++)a[e[o]]=i[o];return a})}function A0e(t=10){let e="abcdefghijklmnopqrstuvwxyz",n="";for(let i=0;i<t;i++)n+=e[Math.floor(Math.random()*e.length)];return n}function a7(t){return JSON.stringify(t)}function L2(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function VA(t){if(L2(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let n=e.prototype;return!(L2(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function HF(t){return VA(t)?{...t}:t}function h0e(t){let e=0;for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&e++;return e}function Oc(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ps(t,e,n){let i=new t._zod.constr(e??t._zod.def);return(!e||n?.parent)&&(i._zod.parent=t),i}function He(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function D0e(t){let e;return new Proxy({},{get(n,i,a){return e??(e=t()),Reflect.get(e,i,a)},set(n,i,a,o){return e??(e=t()),Reflect.set(e,i,a,o)},has(n,i){return e??(e=t()),Reflect.has(e,i)},deleteProperty(n,i){return e??(e=t()),Reflect.deleteProperty(e,i)},ownKeys(n){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(n,i){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,i)},defineProperty(n,i,a){return e??(e=t()),Reflect.defineProperty(e,i,a)}})}function Ve(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function qF(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function E0e(t,e){let n=t._zod.def,i=Sm(t._zod.def,{get shape(){let a={};for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(a[o]=n.shape[o])}return KA(this,"shape",a),a},checks:[]});return ps(t,i)}function y0e(t,e){let n=t._zod.def,i=Sm(t._zod.def,{get shape(){let a={...t._zod.def.shape};for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete a[o]}return KA(this,"shape",a),a},checks:[]});return ps(t,i)}function v0e(t,e){if(!VA(e))throw new Error("Invalid input to extend: expected a plain object");let n=Sm(t._zod.def,{get shape(){let i={...t._zod.def.shape,...e};return KA(this,"shape",i),i},checks:[]});return ps(t,n)}function C0e(t,e){let n=Sm(t._zod.def,{get shape(){let i={...t._zod.def.shape,...e._zod.def.shape};return KA(this,"shape",i),i},get catchall(){return e._zod.def.catchall},checks:[]});return ps(t,n)}function b0e(t,e,n){let i=Sm(e._zod.def,{get shape(){let a=e._zod.def.shape,o={...a};if(n)for(let u in n){if(!(u in a))throw new Error(`Unrecognized key: "${u}"`);n[u]&&(o[u]=t?new t({type:"optional",innerType:a[u]}):a[u])}else for(let u in a)o[u]=t?new t({type:"optional",innerType:a[u]}):a[u];return KA(this,"shape",o),o},checks:[]});return ps(e,i)}function I0e(t,e,n){let i=Sm(e._zod.def,{get shape(){let a=e._zod.def.shape,o={...a};if(n)for(let u in n){if(!(u in o))throw new Error(`Unrecognized key: "${u}"`);n[u]&&(o[u]=new t({type:"nonoptional",innerType:a[u]}))}else for(let u in a)o[u]=new t({type:"nonoptional",innerType:a[u]});return KA(this,"shape",o),o},checks:[]});return ps(e,i)}function JA(t,e=0){for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue!==!0)return!0;return!1}function Os(t,e){return e.map(n=>{var i;return(i=n).path??(i.path=[]),n.path.unshift(t),n})}function lE(t){return typeof t=="string"?t:t?.message}function Us(t,e,n){let i={...t,path:t.path??[]};if(!t.message){let a=lE(t.inst?._zod.def?.error?.(t))??lE(e?.error?.(t))??lE(n.customError?.(t))??lE(n.localeError?.(t))??"Invalid input";i.message=a}return delete i.inst,delete i.continue,e?.reportInput||delete i.input,i}function mE(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function AE(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function z2(...t){let[e,n,i]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:i}:{...e}}function S0e(t){return Object.entries(t).filter(([e,n])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Qq,o7,$F,g0e,fE,GF,KF,VF,zF,vt=F(()=>{Qq=Symbol("evaluating");o7="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};$F=pE(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});g0e=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},fE=new Set(["string","number","symbol"]),GF=new Set(["string","number","bigint","boolean","symbol","undefined"]);KF={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},VF={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};zF=class{constructor(...e){}}});function gE(t,e=n=>n.message){let n={},i=[];for(let a of t.issues)a.path.length>0?(n[a.path[0]]=n[a.path[0]]||[],n[a.path[0]].push(e(a))):i.push(e(a));return{formErrors:i,fieldErrors:n}}function DE(t,e){let n=e||function(o){return o.message},i={_errors:[]},a=o=>{for(let u of o.issues)if(u.code==="invalid_union"&&u.errors.length)u.errors.map(p=>a({issues:p}));else if(u.code==="invalid_key")a({issues:u.issues});else if(u.code==="invalid_element")a({issues:u.issues});else if(u.path.length===0)i._errors.push(n(u));else{let p=i,f=0;for(;f<u.path.length;){let A=u.path[f];f===u.path.length-1?(p[A]=p[A]||{_errors:[]},p[A]._errors.push(n(u))):p[A]=p[A]||{_errors:[]},p=p[A],f++}}};return a(t),i}function JF(t,e){let n=e||function(o){return o.message},i={errors:[]},a=(o,u=[])=>{var p,f;for(let A of o.issues)if(A.code==="invalid_union"&&A.errors.length)A.errors.map(g=>a({issues:g},A.path));else if(A.code==="invalid_key")a({issues:A.issues},A.path);else if(A.code==="invalid_element")a({issues:A.issues},A.path);else{let g=[...u,...A.path];if(g.length===0){i.errors.push(n(A));continue}let E=i,I=0;for(;I<g.length;){let v=g[I],x=I===g.length-1;typeof v=="string"?(E.properties??(E.properties={}),(p=E.properties)[v]??(p[v]={errors:[]}),E=E.properties[v]):(E.items??(E.items=[]),(f=E.items)[v]??(f[v]={errors:[]}),E=E.items[v]),x&&E.errors.push(n(A)),I++}}};return a(t),i}function Nq(t){let e=[],n=t.map(i=>typeof i=="object"?i.key:i);for(let i of n)typeof i=="number"?e.push(`[${i}]`):typeof i=="symbol"?e.push(`[${JSON.stringify(String(i))}]`):/[^\w$]/.test(i)?e.push(`[${JSON.stringify(i)}]`):(e.length&&e.push("."),e.push(i));return e.join("")}function YF(t){let e=[],n=[...t.issues].sort((i,a)=>(i.path??[]).length-(a.path??[]).length);for(let i of n)e.push(`\u2716 ${i.message}`),i.path?.length&&e.push(` \u2192 at ${Nq(i.path)}`);return e.join(`
|
|
50
|
+
`)}catch(f){console.error("Failed to write cache log:",f)}}var i0e,a0e,xq,_q=F(()=>{"use strict";i0e=!process.env.DISABLE_PROMPT_CACHING,a0e=process.env.CACHE_DEBUG==="true",xq=process.env.CACHE_LOG_FILE||wq.join(process.cwd(),"logs/cache_usage.jsonl")});function sE(t){RF=t}async function NF(t){if(RF){let e={timestamp:new Date().toISOString(),cwd:process.cwd(),...t};try{await RF(e)}catch(n){console.error("Session logging failed:",n)}}}function kF(){return process.env.NODE_ENV==="development"||process.env.CUE_LOG_SESSIONS==="true"}async function t7(t,e,n,i,a,o){if(n){let{logCacheUsage:u}=await Promise.resolve().then(()=>(_q(),Bq));await u(n,t)}if(kF()){let u=Date.now()-i,p=g=>"input_tokens"in g&&"output_tokens"in g,f=n?p(n)?n.input_tokens:n.prompt_tokens:void 0,A=n?p(n)?n.output_tokens:n.completion_tokens:void 0;await NF({eventType:"api_call",apiCall:{method:t,model:e,inputTokens:f,outputTokens:A,cacheCreationTokens:n&&p(n)&&n.cache_creation_input_tokens||void 0,cacheReadTokens:n&&p(n)&&n.cache_read_input_tokens||void 0,durationMs:u,conversationContext:{messages:a,systemPrompt:o}}})}}var RF,n7=F(()=>{"use strict";RF=null});async function OF(t,e,n){try{let i=e.find(u=>u.name===t.name);if(!i){let u=new Dd(t.name,"Tool not found",t.input,{availableTools:e.map(p=>p.name)});return b.error("Tool error",{error:u.message}),{type:"tool_result",tool_use_id:t.id,content:`Error: Tool '${t.name}' not found. Available tools: ${e.map(p=>p.name).join(", ")}`,is_error:!0}}if(n?.aborted)throw new Error("Operation cancelled by user");let a=t.input||{};b.debug("Tool execution started",{toolName:t.name,input:a});let o;try{o=await i.call(a,n)}catch(u){let p=new Dd(t.name,`Tool execution failed: ${u instanceof Error?u.message:String(u)}`,t.input,{originalError:u});b.error("Tool error",{error:p.message}),o={success:!1,content:"",error:p.message}}if(o.isImage&&o.imageData&&o.success){let u=["image/jpeg","image/png","image/gif","image/webp"],p=o.imageData.mimeType;if(!u.includes(p)){if(p==="image/svg+xml")return{type:"tool_result",tool_use_id:t.id,content:`SVG image detected at ${o.imageData.path}. SVG format is not directly supported for image display.`,is_error:!1};p="image/png"}return{type:"tool_result",tool_use_id:t.id,content:[{type:"image",source:{type:"base64",data:o.imageData.base64,media_type:p}}],is_error:!1}}return{type:"tool_result",tool_use_id:t.id,content:o.success?o.content:`Error: ${o.error}`,is_error:!o.success}}catch(i){return i instanceof Error&&i.message==="Operation cancelled by user"?{type:"tool_result",tool_use_id:t.id,content:"[Request interrupted by user for tool use]",is_error:!0}:(b.error("Unexpected error in processToolUse",{error:i instanceof Error?i.message:String(i),toolName:t.name,toolId:t.id}),{type:"tool_result",tool_use_id:t.id,content:`Error: Unexpected error processing tool '${t.name}': ${i instanceof Error?i.message:String(i)}`,is_error:!0})}}var Fq=F(()=>{"use strict";F2();Mt()});function U2(t,e){let n=e.provider==="anthropic"?"Anthropic":"OpenAI";if(b.debug(`Handling ${n} API error`,{error:t}),t instanceof Error){let a,o;if("status"in t&&(a=t.status),"response"in t&&(o=t.response),t.message.includes("credit")||t.message.includes("balance")||t.message.includes("quota")){let p=new gd(`Insufficient credits. Please check your ${n} account.`,402,o,{originalError:t.message});return b.error(`${n} API error`,{error:p.message}),p}if(t.message.includes("api key")||t.message.includes("unauthorized")){let p=new gd(`Invalid API key. Please check your ${e.apiKeyEnvVar}.`,401,o,{originalError:t.message});return b.error(`${n} API error`,{error:p.message}),p}if(t.message.includes("rate limit")){let p=new gd("Rate limit exceeded. Please try again later.",429,o,{originalError:t.message});return b.error(`${n} API error`,{error:p.message}),p}let u=new gd(t.message,a,o,{originalError:t.message});return b.error(`${n} API error`,{error:u.message}),u}let i=new gd("An unknown error occurred while communicating with model.",void 0,void 0,{originalError:String(t)});return b.error(`${n} API error`,{error:i.message}),i}var UF=F(()=>{"use strict";F2();Mt()});var i7,Tq=F(()=>{"use strict";Mt();i7=class{accumulatedContent="";toolUseBlocks=[];messageId=null;initialUsage=null;finalUsage=null;model;stopReason=null;tag="AnthropicStreamBuilder";constructor(e){this.model=e}processChunk(e){switch(e.type){case"message_start":return e.message&&(this.messageId=e.message.id,this.initialUsage=e.message.usage||null,this.model=e.message.model||this.model,b.debug(`${this.tag}: Captured message_start`,{messageId:this.messageId,hasUsage:!!this.initialUsage,model:this.model})),{type:"none"};case"content_block_delta":return this.handleContentBlockDelta(e);case"content_block_start":return this.handleContentBlockStart(e);case"message_delta":return e.delta?.stop_reason&&(this.stopReason=e.delta.stop_reason),e.usage&&(this.finalUsage={input_tokens:e.usage.input_tokens||0,output_tokens:e.usage.output_tokens||0,cache_read_input_tokens:e.usage.cache_read_input_tokens||null,cache_creation_input_tokens:e.usage.cache_creation_input_tokens||null,cache_creation:null,server_tool_use:e.usage.server_tool_use||null,service_tier:null},b.debug(`${this.tag}: Captured message_delta usage`,{usage:this.finalUsage,stopReason:this.stopReason})),{type:"none"};case"message_stop":return this.handleMessageStop(e);default:return{type:"none"}}}handleContentBlockDelta(e){return e.delta.type==="text_delta"?(this.accumulatedContent+=e.delta.text,{type:"delta",data:this.buildPartialMessage()}):e.delta.type==="input_json_delta"?(this.handleToolInputDelta(e.delta.partial_json),{type:"delta",data:this.buildPartialMessage()}):{type:"none"}}handleToolInputDelta(e){let n=this.toolUseBlocks.length-1,i=this.toolUseBlocks[n];if(!(!i||!e)){i.input||(i.input={});try{let a=JSON.parse(e);Object.assign(i.input,a),b.debug(`${this.tag}: Merged partial JSON input`,{toolName:i.name,partialInput:a})}catch{this.accumulatePartialJson(i,e)}}}accumulatePartialJson(e,n){let i=e;i._inputBuffer||(i._inputBuffer=""),i._inputBuffer+=n;try{let a=JSON.parse(i._inputBuffer);e.input=a,delete i._inputBuffer,b.debug(`${this.tag}: Successfully parsed accumulated JSON buffer`,{toolName:e.name,parsed:a})}catch{b.debug(`${this.tag}: Buffer still accumulating for tool ${e.name}`)}}handleContentBlockStart(e){if(e.content_block.type==="tool_use"){let n={...e.content_block,input:e.content_block.input||{}};this.toolUseBlocks.push(n),b.debug(`${this.tag}: Tool use block started`,{toolName:n.name,toolId:n.id})}return{type:"none"}}handleMessageStop(e){b.debug(`${this.tag}: MESSAGE_STOP - Building final response`,{accumulatedContentLength:this.accumulatedContent.length,toolUseBlocksCount:this.toolUseBlocks.length});let n=[];this.accumulatedContent&&n.push({type:"text",text:this.accumulatedContent,citations:[]});let i=this.toolUseBlocks.map(u=>{let{...p}=u,f=p;return delete f._inputBuffer,p});n.push(...i);let a=this.finalUsage||this.initialUsage||this.extractUsage(e),o={id:this.messageId||`msg_dirty_${Date.now()}`,type:"message",role:"assistant",content:n,model:this.model,stop_reason:this.stopReason||"end_turn",stop_sequence:null,usage:a};return b.debug(`${this.tag}: Built final message`,{messageId:o.id,stopReason:o.stop_reason,hasUsage:!!a,contentLength:n.length}),{type:"assistantResponse",data:o}}buildPartialMessage(){let e=[];this.accumulatedContent&&e.push({type:"text",text:this.accumulatedContent,citations:[]});let n=this.toolUseBlocks.map(o=>{let{...u}=o,p=u;return delete p._inputBuffer,u});e.push(...n);let i=this.finalUsage||this.initialUsage;return{id:this.messageId||`msg_partial_${Date.now()}`,type:"message",role:"assistant",content:e,model:this.model,stop_reason:this.stopReason,stop_sequence:null,usage:i||{input_tokens:0,output_tokens:0,cache_read_input_tokens:null,cache_creation_input_tokens:null,cache_creation:null,server_tool_use:null,service_tier:null}}}extractUsage(e){let n=e?.message.usage;return n&&typeof n=="object"?{input_tokens:n.input_tokens||0,output_tokens:n.output_tokens||0,cache_read_input_tokens:n.cache_read_input_tokens||null,cache_creation_input_tokens:n.cache_creation_input_tokens||null,cache_creation:n.cache_creation||null,server_tool_use:n.server_tool_use||null,service_tier:n.service_tier||null}:{input_tokens:0,output_tokens:0,cache_read_input_tokens:null,cache_creation_input_tokens:null,cache_creation:null,server_tool_use:null,service_tier:null}}getToolUseBlocks(){return this.toolUseBlocks.map(e=>{let{...n}=e,i=n;return delete i._inputBuffer,n})}getMessageId(){return this.messageId}getInitialUsage(){return this.initialUsage}getFinalUsage(){return this.finalUsage}hasTools(){return this.toolUseBlocks.length>0}reset(){this.accumulatedContent="",this.toolUseBlocks=[],this.messageId=null,this.initialUsage=null,this.finalUsage=null,this.stopReason=null}}});function ae(t,e,n){function i(p,f){var A;Object.defineProperty(p,"_zod",{value:p._zod??{},enumerable:!1}),(A=p._zod).traits??(A.traits=new Set),p._zod.traits.add(t),e(p,f);for(let g in u.prototype)g in p||Object.defineProperty(p,g,{value:u.prototype[g].bind(p)});p._zod.constr=u,p._zod.def=f}let a=n?.Parent??Object;class o extends a{}Object.defineProperty(o,"name",{value:t});function u(p){var f;let A=n?.Parent?new o:this;i(A,p),(f=A._zod).deferred??(f.deferred=[]);for(let g of A._zod.deferred)g();return A}return Object.defineProperty(u,"init",{value:i}),Object.defineProperty(u,Symbol.hasInstance,{value:p=>n?.Parent&&p instanceof n.Parent?!0:p?._zod?.traits?.has(t)}),Object.defineProperty(u,"name",{value:t}),u}function _a(t){return t&&Object.assign(uE,t),uE}var MF,LF,kc,uE,M2=F(()=>{MF=Object.freeze({status:"aborted"});LF=Symbol("zod_brand"),kc=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},uE={}});var qe={};di(qe,{BIGINT_FORMAT_RANGES:()=>VF,Class:()=>zF,NUMBER_FORMAT_RANGES:()=>KF,aborted:()=>JA,allowsEval:()=>$F,assert:()=>c0e,assertEqual:()=>r0e,assertIs:()=>u0e,assertNever:()=>l0e,assertNotEqual:()=>s0e,assignProp:()=>KA,cached:()=>pE,captureStackTrace:()=>o7,cleanEnum:()=>S0e,cleanRegex:()=>dE,clone:()=>ps,cloneDef:()=>d0e,createTransparentProxy:()=>D0e,defineLazy:()=>Bn,esc:()=>a7,escapeRegex:()=>Oc,extend:()=>v0e,finalizeIssue:()=>Us,floatSafeRemainder:()=>jF,getElementAtPath:()=>f0e,getEnumValues:()=>cE,getLengthableOrigin:()=>AE,getParsedType:()=>g0e,getSizableOrigin:()=>mE,isObject:()=>L2,isPlainObject:()=>VA,issue:()=>z2,joinValues:()=>ve,jsonStringifyReplacer:()=>P2,merge:()=>C0e,mergeDefs:()=>Sm,normalizeParams:()=>He,nullish:()=>Im,numKeys:()=>h0e,objectClone:()=>p0e,omit:()=>y0e,optionalKeys:()=>qF,partial:()=>b0e,pick:()=>E0e,prefixIssues:()=>Os,primitiveTypes:()=>GF,promiseAllObject:()=>m0e,propertyKeyTypes:()=>fE,randomString:()=>A0e,required:()=>I0e,shallowClone:()=>HF,stringifyPrimitive:()=>Ve,unwrapMessage:()=>lE});function r0e(t){return t}function s0e(t){return t}function u0e(t){}function l0e(t){throw new Error}function c0e(t){}function cE(t){let e=Object.values(t).filter(i=>typeof i=="number");return Object.entries(t).filter(([i,a])=>e.indexOf(+i)===-1).map(([i,a])=>a)}function ve(t,e="|"){return t.map(n=>Ve(n)).join(e)}function P2(t,e){return typeof e=="bigint"?e.toString():e}function pE(t){return{get value(){{let n=t();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function Im(t){return t==null}function dE(t){let e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function jF(t,e){let n=(t.toString().split(".")[1]||"").length,i=e.toString(),a=(i.split(".")[1]||"").length;if(a===0&&/\d?e-\d?/.test(i)){let f=i.match(/\d?e-(\d?)/);f?.[1]&&(a=Number.parseInt(f[1]))}let o=n>a?n:a,u=Number.parseInt(t.toFixed(o).replace(".","")),p=Number.parseInt(e.toFixed(o).replace(".",""));return u%p/10**o}function Bn(t,e,n){let i;Object.defineProperty(t,e,{get(){if(i!==Qq)return i===void 0&&(i=Qq,i=n()),i},set(a){Object.defineProperty(t,e,{value:a})},configurable:!0})}function p0e(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function KA(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Sm(...t){let e={};for(let n of t){let i=Object.getOwnPropertyDescriptors(n);Object.assign(e,i)}return Object.defineProperties({},e)}function d0e(t){return Sm(t._zod.def)}function f0e(t,e){return e?e.reduce((n,i)=>n?.[i],t):t}function m0e(t){let e=Object.keys(t),n=e.map(i=>t[i]);return Promise.all(n).then(i=>{let a={};for(let o=0;o<e.length;o++)a[e[o]]=i[o];return a})}function A0e(t=10){let e="abcdefghijklmnopqrstuvwxyz",n="";for(let i=0;i<t;i++)n+=e[Math.floor(Math.random()*e.length)];return n}function a7(t){return JSON.stringify(t)}function L2(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function VA(t){if(L2(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let n=e.prototype;return!(L2(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function HF(t){return VA(t)?{...t}:t}function h0e(t){let e=0;for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&e++;return e}function Oc(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ps(t,e,n){let i=new t._zod.constr(e??t._zod.def);return(!e||n?.parent)&&(i._zod.parent=t),i}function He(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function D0e(t){let e;return new Proxy({},{get(n,i,a){return e??(e=t()),Reflect.get(e,i,a)},set(n,i,a,o){return e??(e=t()),Reflect.set(e,i,a,o)},has(n,i){return e??(e=t()),Reflect.has(e,i)},deleteProperty(n,i){return e??(e=t()),Reflect.deleteProperty(e,i)},ownKeys(n){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(n,i){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,i)},defineProperty(n,i,a){return e??(e=t()),Reflect.defineProperty(e,i,a)}})}function Ve(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function qF(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function E0e(t,e){let n=t._zod.def,i=Sm(t._zod.def,{get shape(){let a={};for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(a[o]=n.shape[o])}return KA(this,"shape",a),a},checks:[]});return ps(t,i)}function y0e(t,e){let n=t._zod.def,i=Sm(t._zod.def,{get shape(){let a={...t._zod.def.shape};for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete a[o]}return KA(this,"shape",a),a},checks:[]});return ps(t,i)}function v0e(t,e){if(!VA(e))throw new Error("Invalid input to extend: expected a plain object");let n=Sm(t._zod.def,{get shape(){let i={...t._zod.def.shape,...e};return KA(this,"shape",i),i},checks:[]});return ps(t,n)}function C0e(t,e){let n=Sm(t._zod.def,{get shape(){let i={...t._zod.def.shape,...e._zod.def.shape};return KA(this,"shape",i),i},get catchall(){return e._zod.def.catchall},checks:[]});return ps(t,n)}function b0e(t,e,n){let i=Sm(e._zod.def,{get shape(){let a=e._zod.def.shape,o={...a};if(n)for(let u in n){if(!(u in a))throw new Error(`Unrecognized key: "${u}"`);n[u]&&(o[u]=t?new t({type:"optional",innerType:a[u]}):a[u])}else for(let u in a)o[u]=t?new t({type:"optional",innerType:a[u]}):a[u];return KA(this,"shape",o),o},checks:[]});return ps(e,i)}function I0e(t,e,n){let i=Sm(e._zod.def,{get shape(){let a=e._zod.def.shape,o={...a};if(n)for(let u in n){if(!(u in o))throw new Error(`Unrecognized key: "${u}"`);n[u]&&(o[u]=new t({type:"nonoptional",innerType:a[u]}))}else for(let u in a)o[u]=new t({type:"nonoptional",innerType:a[u]});return KA(this,"shape",o),o},checks:[]});return ps(e,i)}function JA(t,e=0){for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue!==!0)return!0;return!1}function Os(t,e){return e.map(n=>{var i;return(i=n).path??(i.path=[]),n.path.unshift(t),n})}function lE(t){return typeof t=="string"?t:t?.message}function Us(t,e,n){let i={...t,path:t.path??[]};if(!t.message){let a=lE(t.inst?._zod.def?.error?.(t))??lE(e?.error?.(t))??lE(n.customError?.(t))??lE(n.localeError?.(t))??"Invalid input";i.message=a}return delete i.inst,delete i.continue,e?.reportInput||delete i.input,i}function mE(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function AE(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function z2(...t){let[e,n,i]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:i}:{...e}}function S0e(t){return Object.entries(t).filter(([e,n])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Qq,o7,$F,g0e,fE,GF,KF,VF,zF,vt=F(()=>{Qq=Symbol("evaluating");o7="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};$F=pE(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});g0e=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},fE=new Set(["string","number","symbol"]),GF=new Set(["string","number","bigint","boolean","symbol","undefined"]);KF={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},VF={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};zF=class{constructor(...e){}}});function gE(t,e=n=>n.message){let n={},i=[];for(let a of t.issues)a.path.length>0?(n[a.path[0]]=n[a.path[0]]||[],n[a.path[0]].push(e(a))):i.push(e(a));return{formErrors:i,fieldErrors:n}}function DE(t,e){let n=e||function(o){return o.message},i={_errors:[]},a=o=>{for(let u of o.issues)if(u.code==="invalid_union"&&u.errors.length)u.errors.map(p=>a({issues:p}));else if(u.code==="invalid_key")a({issues:u.issues});else if(u.code==="invalid_element")a({issues:u.issues});else if(u.path.length===0)i._errors.push(n(u));else{let p=i,f=0;for(;f<u.path.length;){let A=u.path[f];f===u.path.length-1?(p[A]=p[A]||{_errors:[]},p[A]._errors.push(n(u))):p[A]=p[A]||{_errors:[]},p=p[A],f++}}};return a(t),i}function JF(t,e){let n=e||function(o){return o.message},i={errors:[]},a=(o,u=[])=>{var p,f;for(let A of o.issues)if(A.code==="invalid_union"&&A.errors.length)A.errors.map(g=>a({issues:g},A.path));else if(A.code==="invalid_key")a({issues:A.issues},A.path);else if(A.code==="invalid_element")a({issues:A.issues},A.path);else{let g=[...u,...A.path];if(g.length===0){i.errors.push(n(A));continue}let E=i,I=0;for(;I<g.length;){let v=g[I],x=I===g.length-1;typeof v=="string"?(E.properties??(E.properties={}),(p=E.properties)[v]??(p[v]={errors:[]}),E=E.properties[v]):(E.items??(E.items=[]),(f=E.items)[v]??(f[v]={errors:[]}),E=E.items[v]),x&&E.errors.push(n(A)),I++}}};return a(t),i}function Nq(t){let e=[],n=t.map(i=>typeof i=="object"?i.key:i);for(let i of n)typeof i=="number"?e.push(`[${i}]`):typeof i=="symbol"?e.push(`[${JSON.stringify(String(i))}]`):/[^\w$]/.test(i)?e.push(`[${JSON.stringify(i)}]`):(e.length&&e.push("."),e.push(i));return e.join("")}function YF(t){let e=[],n=[...t.issues].sort((i,a)=>(i.path??[]).length-(a.path??[]).length);for(let i of n)e.push(`\u2716 ${i.message}`),i.path?.length&&e.push(` \u2192 at ${Nq(i.path)}`);return e.join(`
|
|
51
51
|
`)}var Rq,hE,j2,WF=F(()=>{M2();vt();Rq=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,P2,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},hE=ae("$ZodError",Rq),j2=ae("$ZodError",Rq,{Parent:Error})});var r7,s7,u7,l7,c7,ZF,p7,XF,d7=F(()=>{M2();WF();vt();r7=t=>(e,n,i,a)=>{let o=i?Object.assign(i,{async:!1}):{async:!1},u=e._zod.run({value:n,issues:[]},o);if(u instanceof Promise)throw new kc;if(u.issues.length){let p=new(a?.Err??t)(u.issues.map(f=>Us(f,o,_a())));throw o7(p,a?.callee),p}return u.value},s7=r7(j2),u7=t=>async(e,n,i,a)=>{let o=i?Object.assign(i,{async:!0}):{async:!0},u=e._zod.run({value:n,issues:[]},o);if(u instanceof Promise&&(u=await u),u.issues.length){let p=new(a?.Err??t)(u.issues.map(f=>Us(f,o,_a())));throw o7(p,a?.callee),p}return u.value},l7=u7(j2),c7=t=>(e,n,i)=>{let a=i?{...i,async:!1}:{async:!1},o=e._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new kc;return o.issues.length?{success:!1,error:new(t??hE)(o.issues.map(u=>Us(u,a,_a())))}:{success:!0,data:o.value}},ZF=c7(j2),p7=t=>async(e,n,i)=>{let a=i?Object.assign(i,{async:!0}):{async:!0},o=e._zod.run({value:n,issues:[]},a);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new t(o.issues.map(u=>Us(u,a,_a())))}:{success:!0,data:o.value}},XF=p7(j2)});var Id={};di(Id,{base64:()=>mT,base64url:()=>f7,bigint:()=>vT,boolean:()=>IT,browserEmail:()=>k0e,cidrv4:()=>dT,cidrv6:()=>fT,cuid:()=>eT,cuid2:()=>tT,date:()=>gT,datetime:()=>ET,domain:()=>U0e,duration:()=>rT,e164:()=>hT,email:()=>uT,emoji:()=>lT,extendedDuration:()=>w0e,guid:()=>sT,hostname:()=>AT,html5Email:()=>T0e,idnEmail:()=>N0e,integer:()=>CT,ipv4:()=>cT,ipv6:()=>pT,ksuid:()=>aT,lowercase:()=>wT,nanoid:()=>oT,null:()=>ST,number:()=>bT,rfc5322Email:()=>Q0e,string:()=>yT,time:()=>DT,ulid:()=>nT,undefined:()=>xT,unicodeEmail:()=>R0e,uppercase:()=>BT,uuid:()=>YA,uuid4:()=>B0e,uuid6:()=>_0e,uuid7:()=>F0e,xid:()=>iT});function lT(){return new RegExp(O0e,"u")}function Oq(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function DT(t){return new RegExp(`^${Oq(t)}$`)}function ET(t){let e=Oq({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let i=`${e}(?:${n.join("|")})`;return new RegExp(`^${kq}T(?:${i})$`)}var eT,tT,nT,iT,aT,oT,rT,w0e,sT,YA,B0e,_0e,F0e,uT,T0e,Q0e,R0e,N0e,k0e,O0e,cT,pT,dT,fT,mT,f7,AT,U0e,hT,kq,gT,yT,vT,CT,bT,IT,ST,xT,wT,BT,m7=F(()=>{eT=/^[cC][^\s-]{8,}$/,tT=/^[0-9a-z]+$/,nT=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,iT=/^[0-9a-vA-V]{20}$/,aT=/^[A-Za-z0-9]{27}$/,oT=/^[a-zA-Z0-9_-]{21}$/,rT=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,w0e=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,sT=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,YA=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,B0e=YA(4),_0e=YA(6),F0e=YA(7),uT=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,T0e=/^[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])?)*$/,Q0e=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,R0e=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,N0e=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,k0e=/^[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])?)*$/,O0e="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";cT=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,pT=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,dT=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,fT=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,mT=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,f7=/^[A-Za-z0-9_-]*$/,AT=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,U0e=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,hT=/^\+(?:[0-9]){6,14}[0-9]$/,kq="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",gT=new RegExp(`^${kq}$`);yT=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},vT=/^\d+n?$/,CT=/^\d+$/,bT=/^-?\d+(?:\.\d+)?/i,IT=/true|false/i,ST=/null/i,xT=/undefined/i,wT=/^[^A-Z]*$/,BT=/^[^a-z]*$/});function Uq(t,e,n){t.issues.length&&e.issues.push(...Os(n,t.issues))}var mi,Mq,A7,h7,_T,FT,TT,QT,RT,NT,kT,OT,UT,$2,MT,LT,PT,zT,jT,$T,HT,GT,qT,g7=F(()=>{M2();m7();vt();mi=ae("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),Mq={number:"number",bigint:"bigint",object:"date"},A7=ae("$ZodCheckLessThan",(t,e)=>{mi.init(t,e);let n=Mq[typeof e.value];t._zod.onattach.push(i=>{let a=i._zod.bag,o=(e.inclusive?a.maximum:a.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<o&&(e.inclusive?a.maximum=e.value:a.exclusiveMaximum=e.value)}),t._zod.check=i=>{(e.inclusive?i.value<=e.value:i.value<e.value)||i.issues.push({origin:n,code:"too_big",maximum:e.value,input:i.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),h7=ae("$ZodCheckGreaterThan",(t,e)=>{mi.init(t,e);let n=Mq[typeof e.value];t._zod.onattach.push(i=>{let a=i._zod.bag,o=(e.inclusive?a.minimum:a.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>o&&(e.inclusive?a.minimum=e.value:a.exclusiveMinimum=e.value)}),t._zod.check=i=>{(e.inclusive?i.value>=e.value:i.value>e.value)||i.issues.push({origin:n,code:"too_small",minimum:e.value,input:i.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),_T=ae("$ZodCheckMultipleOf",(t,e)=>{mi.init(t,e),t._zod.onattach.push(n=>{var i;(i=n._zod.bag).multipleOf??(i.multipleOf=e.value)}),t._zod.check=n=>{if(typeof n.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%e.value===BigInt(0):jF(n.value,e.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:e.value,input:n.value,inst:t,continue:!e.abort})}}),FT=ae("$ZodCheckNumberFormat",(t,e)=>{mi.init(t,e),e.format=e.format||"float64";let n=e.format?.includes("int"),i=n?"int":"number",[a,o]=KF[e.format];t._zod.onattach.push(u=>{let p=u._zod.bag;p.format=e.format,p.minimum=a,p.maximum=o,n&&(p.pattern=CT)}),t._zod.check=u=>{let p=u.value;if(n){if(!Number.isInteger(p)){u.issues.push({expected:i,format:e.format,code:"invalid_type",continue:!1,input:p,inst:t});return}if(!Number.isSafeInteger(p)){p>0?u.issues.push({input:p,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:i,continue:!e.abort}):u.issues.push({input:p,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:i,continue:!e.abort});return}}p<a&&u.issues.push({origin:"number",input:p,code:"too_small",minimum:a,inclusive:!0,inst:t,continue:!e.abort}),p>o&&u.issues.push({origin:"number",input:p,code:"too_big",maximum:o,inst:t})}}),TT=ae("$ZodCheckBigIntFormat",(t,e)=>{mi.init(t,e);let[n,i]=VF[e.format];t._zod.onattach.push(a=>{let o=a._zod.bag;o.format=e.format,o.minimum=n,o.maximum=i}),t._zod.check=a=>{let o=a.value;o<n&&a.issues.push({origin:"bigint",input:o,code:"too_small",minimum:n,inclusive:!0,inst:t,continue:!e.abort}),o>i&&a.issues.push({origin:"bigint",input:o,code:"too_big",maximum:i,inst:t})}}),QT=ae("$ZodCheckMaxSize",(t,e)=>{var n;mi.init(t,e),(n=t._zod.def).when??(n.when=i=>{let a=i.value;return!Im(a)&&a.size!==void 0}),t._zod.onattach.push(i=>{let a=i._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<a&&(i._zod.bag.maximum=e.maximum)}),t._zod.check=i=>{let a=i.value;a.size<=e.maximum||i.issues.push({origin:mE(a),code:"too_big",maximum:e.maximum,input:a,inst:t,continue:!e.abort})}}),RT=ae("$ZodCheckMinSize",(t,e)=>{var n;mi.init(t,e),(n=t._zod.def).when??(n.when=i=>{let a=i.value;return!Im(a)&&a.size!==void 0}),t._zod.onattach.push(i=>{let a=i._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>a&&(i._zod.bag.minimum=e.minimum)}),t._zod.check=i=>{let a=i.value;a.size>=e.minimum||i.issues.push({origin:mE(a),code:"too_small",minimum:e.minimum,input:a,inst:t,continue:!e.abort})}}),NT=ae("$ZodCheckSizeEquals",(t,e)=>{var n;mi.init(t,e),(n=t._zod.def).when??(n.when=i=>{let a=i.value;return!Im(a)&&a.size!==void 0}),t._zod.onattach.push(i=>{let a=i._zod.bag;a.minimum=e.size,a.maximum=e.size,a.size=e.size}),t._zod.check=i=>{let a=i.value,o=a.size;if(o===e.size)return;let u=o>e.size;i.issues.push({origin:mE(a),...u?{code:"too_big",maximum:e.size}:{code:"too_small",minimum:e.size},inclusive:!0,exact:!0,input:i.value,inst:t,continue:!e.abort})}}),kT=ae("$ZodCheckMaxLength",(t,e)=>{var n;mi.init(t,e),(n=t._zod.def).when??(n.when=i=>{let a=i.value;return!Im(a)&&a.length!==void 0}),t._zod.onattach.push(i=>{let a=i._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<a&&(i._zod.bag.maximum=e.maximum)}),t._zod.check=i=>{let a=i.value;if(a.length<=e.maximum)return;let u=AE(a);i.issues.push({origin:u,code:"too_big",maximum:e.maximum,inclusive:!0,input:a,inst:t,continue:!e.abort})}}),OT=ae("$ZodCheckMinLength",(t,e)=>{var n;mi.init(t,e),(n=t._zod.def).when??(n.when=i=>{let a=i.value;return!Im(a)&&a.length!==void 0}),t._zod.onattach.push(i=>{let a=i._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>a&&(i._zod.bag.minimum=e.minimum)}),t._zod.check=i=>{let a=i.value;if(a.length>=e.minimum)return;let u=AE(a);i.issues.push({origin:u,code:"too_small",minimum:e.minimum,inclusive:!0,input:a,inst:t,continue:!e.abort})}}),UT=ae("$ZodCheckLengthEquals",(t,e)=>{var n;mi.init(t,e),(n=t._zod.def).when??(n.when=i=>{let a=i.value;return!Im(a)&&a.length!==void 0}),t._zod.onattach.push(i=>{let a=i._zod.bag;a.minimum=e.length,a.maximum=e.length,a.length=e.length}),t._zod.check=i=>{let a=i.value,o=a.length;if(o===e.length)return;let u=AE(a),p=o>e.length;i.issues.push({origin:u,...p?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:i.value,inst:t,continue:!e.abort})}}),$2=ae("$ZodCheckStringFormat",(t,e)=>{var n,i;mi.init(t,e),t._zod.onattach.push(a=>{let o=a._zod.bag;o.format=e.format,e.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(e.pattern))}),e.pattern?(n=t._zod).check??(n.check=a=>{e.pattern.lastIndex=0,!e.pattern.test(a.value)&&a.issues.push({origin:"string",code:"invalid_format",format:e.format,input:a.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(i=t._zod).check??(i.check=()=>{})}),MT=ae("$ZodCheckRegex",(t,e)=>{$2.init(t,e),t._zod.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),LT=ae("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=wT),$2.init(t,e)}),PT=ae("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=BT),$2.init(t,e)}),zT=ae("$ZodCheckIncludes",(t,e)=>{mi.init(t,e);let n=Oc(e.includes),i=new RegExp(typeof e.position=="number"?`^.{${e.position}}${n}`:n);e.pattern=i,t._zod.onattach.push(a=>{let o=a._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(i)}),t._zod.check=a=>{a.value.includes(e.includes,e.position)||a.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:a.value,inst:t,continue:!e.abort})}}),jT=ae("$ZodCheckStartsWith",(t,e)=>{mi.init(t,e);let n=new RegExp(`^${Oc(e.prefix)}.*`);e.pattern??(e.pattern=n),t._zod.onattach.push(i=>{let a=i._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(n)}),t._zod.check=i=>{i.value.startsWith(e.prefix)||i.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:i.value,inst:t,continue:!e.abort})}}),$T=ae("$ZodCheckEndsWith",(t,e)=>{mi.init(t,e);let n=new RegExp(`.*${Oc(e.suffix)}$`);e.pattern??(e.pattern=n),t._zod.onattach.push(i=>{let a=i._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(n)}),t._zod.check=i=>{i.value.endsWith(e.suffix)||i.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:i.value,inst:t,continue:!e.abort})}});HT=ae("$ZodCheckProperty",(t,e)=>{mi.init(t,e),t._zod.check=n=>{let i=e.schema._zod.run({value:n.value[e.property],issues:[]},{});if(i instanceof Promise)return i.then(a=>Uq(a,n,e.property));Uq(i,n,e.property)}}),GT=ae("$ZodCheckMimeType",(t,e)=>{mi.init(t,e);let n=new Set(e.mime);t._zod.onattach.push(i=>{i._zod.bag.mime=e.mime}),t._zod.check=i=>{n.has(i.value.type)||i.issues.push({code:"invalid_value",values:e.mime,input:i.value.type,inst:t,continue:!e.abort})}}),qT=ae("$ZodCheckOverwrite",(t,e)=>{mi.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}})});var EE,KT=F(()=>{EE=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let i=e.split(`
|
|
52
52
|
`).filter(u=>u),a=Math.min(...i.map(u=>u.length-u.trimStart().length)),o=i.map(u=>u.slice(a)).map(u=>" ".repeat(this.indent*2)+u);for(let u of o)this.content.push(u)}compile(){let e=Function,n=this?.args,a=[...(this?.content??[""]).map(o=>` ${o}`)];return new e(...n,a.join(`
|
|
53
53
|
`))}}});var VT,JT=F(()=>{VT={major:4,minor:0,patch:17}});function hQ(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function Wq(t){if(!f7.test(t))return!1;let e=t.replace(/[-_]/g,i=>i==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return hQ(n)}function Zq(t,e=null){try{let n=t.split(".");if(n.length!==3)return!1;let[i]=n;if(!i)return!1;let a=JSON.parse(atob(i));return!("typ"in a&&a?.typ!=="JWT"||!a.alg||e&&(!("alg"in a)||a.alg!==e))}catch{return!1}}function Pq(t,e,n){t.issues.length&&e.issues.push(...Os(n,t.issues)),e.value[n]=t.value}function D7(t,e,n,i){t.issues.length&&e.issues.push(...Os(n,t.issues)),t.value===void 0?n in i&&(e.value[n]=void 0):e.value[n]=t.value}function zq(t,e,n,i){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;let a=t.filter(o=>!JA(o));return a.length===1?(e.value=a[0].value,a[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:t.map(o=>o.issues.map(u=>Us(u,i,_a())))}),e)}function YT(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(VA(t)&&VA(e)){let n=Object.keys(e),i=Object.keys(t).filter(o=>n.indexOf(o)!==-1),a={...t,...e};for(let o of i){let u=YT(t[o],e[o]);if(!u.valid)return{valid:!1,mergeErrorPath:[o,...u.mergeErrorPath]};a[o]=u.data}return{valid:!0,data:a}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let i=0;i<t.length;i++){let a=t[i],o=e[i],u=YT(a,o);if(!u.valid)return{valid:!1,mergeErrorPath:[i,...u.mergeErrorPath]};n.push(u.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function jq(t,e,n){if(e.issues.length&&t.issues.push(...e.issues),n.issues.length&&t.issues.push(...n.issues),JA(t))return t;let i=YT(e.value,n.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return t.value=i.data,t}function E7(t,e,n){t.issues.length&&e.issues.push(...Os(n,t.issues)),e.value[n]=t.value}function $q(t,e,n,i,a,o,u){t.issues.length&&(fE.has(typeof i)?n.issues.push(...Os(i,t.issues)):n.issues.push({code:"invalid_key",origin:"map",input:a,inst:o,issues:t.issues.map(p=>Us(p,u,_a()))})),e.issues.length&&(fE.has(typeof i)?n.issues.push(...Os(i,e.issues)):n.issues.push({origin:"map",code:"invalid_element",input:a,inst:o,key:i,issues:e.issues.map(p=>Us(p,u,_a()))})),n.value.set(t.value,e.value)}function Hq(t,e){t.issues.length&&e.issues.push(...t.issues),e.value.add(t.value)}function Gq(t,e){return t.issues.length&&e===void 0?{issues:[],value:void 0}:t}function qq(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function Kq(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}function Vq(t,e,n){return t.issues.length?t:e.out._zod.run({value:t.value,issues:t.issues},n)}function Jq(t){return t.value=Object.freeze(t.value),t}function Yq(t,e,n,i){if(!t){let a={code:"custom",input:n,inst:i,path:[...i._zod.def.path??[]],continue:!i._zod.def.abort};i._zod.def.params&&(a.params=i._zod.def.params),e.issues.push(z2(a))}}var Lt,WA,ii,WT,ZT,XT,eQ,tQ,nQ,iQ,aQ,oQ,rQ,sQ,uQ,lQ,cQ,pQ,dQ,fQ,mQ,AQ,gQ,DQ,EQ,yQ,vQ,y7,CQ,yE,v7,bQ,IQ,SQ,xQ,wQ,H2,BQ,_Q,FQ,vE,TQ,C7,QQ,RQ,ZA,NQ,kQ,OQ,UQ,MQ,LQ,CE,PQ,zQ,jQ,$Q,HQ,GQ,qQ,KQ,bE,VQ,JQ,YQ,WQ,ZQ,IE=F(()=>{g7();M2();KT();d7();m7();vt();JT();vt();Lt=ae("$ZodType",(t,e)=>{var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=VT;let i=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&i.unshift(t);for(let a of i)for(let o of a._zod.onattach)o(t);if(i.length===0)(n=t._zod).deferred??(n.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let a=(o,u,p)=>{let f=JA(o),A;for(let g of u){if(g._zod.def.when){if(!g._zod.def.when(o))continue}else if(f)continue;let E=o.issues.length,I=g._zod.check(o);if(I instanceof Promise&&p?.async===!1)throw new kc;if(A||I instanceof Promise)A=(A??Promise.resolve()).then(async()=>{await I,o.issues.length!==E&&(f||(f=JA(o,E)))});else{if(o.issues.length===E)continue;f||(f=JA(o,E))}}return A?A.then(()=>o):o};t._zod.run=(o,u)=>{let p=t._zod.parse(o,u);if(p instanceof Promise){if(u.async===!1)throw new kc;return p.then(f=>a(f,i,u))}return a(p,i,u)}}t["~standard"]={validate:a=>{try{let o=ZF(t,a);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return XF(t,a).then(u=>u.success?{value:u.data}:{issues:u.error?.issues})}},vendor:"zod",version:1}}),WA=ae("$ZodString",(t,e)=>{Lt.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??yT(t._zod.bag),t._zod.parse=(n,i)=>{if(e.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:t}),n}}),ii=ae("$ZodStringFormat",(t,e)=>{$2.init(t,e),WA.init(t,e)}),WT=ae("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=sT),ii.init(t,e)}),ZT=ae("$ZodUUID",(t,e)=>{if(e.version){let i={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(i===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=YA(i))}else e.pattern??(e.pattern=YA());ii.init(t,e)}),XT=ae("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=uT),ii.init(t,e)}),eQ=ae("$ZodURL",(t,e)=>{ii.init(t,e),t._zod.check=n=>{try{let i=n.value.trim(),a=new URL(i);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(a.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:AT.source,input:n.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(a.protocol.endsWith(":")?a.protocol.slice(0,-1):a.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:n.value,inst:t,continue:!e.abort})),e.normalize?n.value=a.href:n.value=i;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:t,continue:!e.abort})}}}),tQ=ae("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=lT()),ii.init(t,e)}),nQ=ae("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=oT),ii.init(t,e)}),iQ=ae("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=eT),ii.init(t,e)}),aQ=ae("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=tT),ii.init(t,e)}),oQ=ae("$ZodULID",(t,e)=>{e.pattern??(e.pattern=nT),ii.init(t,e)}),rQ=ae("$ZodXID",(t,e)=>{e.pattern??(e.pattern=iT),ii.init(t,e)}),sQ=ae("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=aT),ii.init(t,e)}),uQ=ae("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=ET(e)),ii.init(t,e)}),lQ=ae("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=gT),ii.init(t,e)}),cQ=ae("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=DT(e)),ii.init(t,e)}),pQ=ae("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=rT),ii.init(t,e)}),dQ=ae("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=cT),ii.init(t,e),t._zod.onattach.push(n=>{let i=n._zod.bag;i.format="ipv4"})}),fQ=ae("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=pT),ii.init(t,e),t._zod.onattach.push(n=>{let i=n._zod.bag;i.format="ipv6"}),t._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:t,continue:!e.abort})}}}),mQ=ae("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=dT),ii.init(t,e)}),AQ=ae("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=fT),ii.init(t,e),t._zod.check=n=>{let[i,a]=n.value.split("/");try{if(!a)throw new Error;let o=Number(a);if(`${o}`!==a)throw new Error;if(o<0||o>128)throw new Error;new URL(`http://[${i}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:t,continue:!e.abort})}}});gQ=ae("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=mT),ii.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),t._zod.check=n=>{hQ(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});DQ=ae("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=f7),ii.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),t._zod.check=n=>{Wq(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),EQ=ae("$ZodE164",(t,e)=>{e.pattern??(e.pattern=hT),ii.init(t,e)});yQ=ae("$ZodJWT",(t,e)=>{ii.init(t,e),t._zod.check=n=>{Zq(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}}),vQ=ae("$ZodCustomStringFormat",(t,e)=>{ii.init(t,e),t._zod.check=n=>{e.fn(n.value)||n.issues.push({code:"invalid_format",format:e.format,input:n.value,inst:t,continue:!e.abort})}}),y7=ae("$ZodNumber",(t,e)=>{Lt.init(t,e),t._zod.pattern=t._zod.bag.pattern??bT,t._zod.parse=(n,i)=>{if(e.coerce)try{n.value=Number(n.value)}catch{}let a=n.value;if(typeof a=="number"&&!Number.isNaN(a)&&Number.isFinite(a))return n;let o=typeof a=="number"?Number.isNaN(a)?"NaN":Number.isFinite(a)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:a,inst:t,...o?{received:o}:{}}),n}}),CQ=ae("$ZodNumber",(t,e)=>{FT.init(t,e),y7.init(t,e)}),yE=ae("$ZodBoolean",(t,e)=>{Lt.init(t,e),t._zod.pattern=IT,t._zod.parse=(n,i)=>{if(e.coerce)try{n.value=!!n.value}catch{}let a=n.value;return typeof a=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:a,inst:t}),n}}),v7=ae("$ZodBigInt",(t,e)=>{Lt.init(t,e),t._zod.pattern=vT,t._zod.parse=(n,i)=>{if(e.coerce)try{n.value=BigInt(n.value)}catch{}return typeof n.value=="bigint"||n.issues.push({expected:"bigint",code:"invalid_type",input:n.value,inst:t}),n}}),bQ=ae("$ZodBigInt",(t,e)=>{TT.init(t,e),v7.init(t,e)}),IQ=ae("$ZodSymbol",(t,e)=>{Lt.init(t,e),t._zod.parse=(n,i)=>{let a=n.value;return typeof a=="symbol"||n.issues.push({expected:"symbol",code:"invalid_type",input:a,inst:t}),n}}),SQ=ae("$ZodUndefined",(t,e)=>{Lt.init(t,e),t._zod.pattern=xT,t._zod.values=new Set([void 0]),t._zod.optin="optional",t._zod.optout="optional",t._zod.parse=(n,i)=>{let a=n.value;return typeof a>"u"||n.issues.push({expected:"undefined",code:"invalid_type",input:a,inst:t}),n}}),xQ=ae("$ZodNull",(t,e)=>{Lt.init(t,e),t._zod.pattern=ST,t._zod.values=new Set([null]),t._zod.parse=(n,i)=>{let a=n.value;return a===null||n.issues.push({expected:"null",code:"invalid_type",input:a,inst:t}),n}}),wQ=ae("$ZodAny",(t,e)=>{Lt.init(t,e),t._zod.parse=n=>n}),H2=ae("$ZodUnknown",(t,e)=>{Lt.init(t,e),t._zod.parse=n=>n}),BQ=ae("$ZodNever",(t,e)=>{Lt.init(t,e),t._zod.parse=(n,i)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)}),_Q=ae("$ZodVoid",(t,e)=>{Lt.init(t,e),t._zod.parse=(n,i)=>{let a=n.value;return typeof a>"u"||n.issues.push({expected:"void",code:"invalid_type",input:a,inst:t}),n}}),FQ=ae("$ZodDate",(t,e)=>{Lt.init(t,e),t._zod.parse=(n,i)=>{if(e.coerce)try{n.value=new Date(n.value)}catch{}let a=n.value,o=a instanceof Date;return o&&!Number.isNaN(a.getTime())||n.issues.push({expected:"date",code:"invalid_type",input:a,...o?{received:"Invalid Date"}:{},inst:t}),n}});vE=ae("$ZodArray",(t,e)=>{Lt.init(t,e),t._zod.parse=(n,i)=>{let a=n.value;if(!Array.isArray(a))return n.issues.push({expected:"array",code:"invalid_type",input:a,inst:t}),n;n.value=Array(a.length);let o=[];for(let u=0;u<a.length;u++){let p=a[u],f=e.element._zod.run({value:p,issues:[]},i);f instanceof Promise?o.push(f.then(A=>Pq(A,n,u))):Pq(f,n,u)}return o.length?Promise.all(o).then(()=>n):n}});TQ=ae("$ZodObject",(t,e)=>{Lt.init(t,e);let n=pE(()=>{let E=Object.keys(e.shape);for(let v of E)if(!e.shape[v]._zod.traits.has("$ZodType"))throw new Error(`Invalid element at key "${v}": expected a Zod schema`);let I=qF(e.shape);return{shape:e.shape,keys:E,keySet:new Set(E),numKeys:E.length,optionalKeys:new Set(I)}});Bn(t._zod,"propValues",()=>{let E=e.shape,I={};for(let v in E){let x=E[v]._zod;if(x.values){I[v]??(I[v]=new Set);for(let w of x.values)I[v].add(w)}}return I});let i=E=>{let I=new EE(["shape","payload","ctx"]),v=n.value,x=R=>{let M=a7(R);return`shape[${M}]._zod.run({ value: input[${M}], issues: [] }, ctx)`};I.write("const input = payload.value;");let w=Object.create(null),_=0;for(let R of v.keys)w[R]=`key_${_++}`;I.write("const newResult = {}");for(let R of v.keys){let M=w[R],z=a7(R);I.write(`const ${M} = ${x(R)};`),I.write(`
|
|
@@ -163,7 +163,7 @@ Please continue the conversation from where we left it off without asking the us
|
|
|
163
163
|
`).filter(g=>g.trim());b.debug(`[SessionDiscovery] Total lines in JSONL: ${o.length}`);let u=Math.max(0,o.length-n-i),p=o.length-i,f=o.slice(u,p);b.debug(`[SessionDiscovery] Selected lines range: ${u} to ${p} (${f.length} lines)`);let A=[];for(let g=0;g<f.length;g++){let E=f[g];try{let I=Eo.parse(E);if(!I){b.debug(`[SessionDiscovery] Failed to parse line ${g+1}`);continue}if(b.debug(`[SessionDiscovery] Line ${g+1}: Entry type=${I.type}, has message=${!!I.message}, uuid=${I.uuid}`),I.message){let v=I.message.role,x=I.message.content;if(Array.isArray(x)&&x.length>0)b.debug(`[SessionDiscovery] Adding message: role=${v}, content blocks=${x.length}`),A.push({role:v,content:x,contentType:"content_parts",timestamp:I.timestamp||new Date().toISOString(),uuid:I.uuid,messageId:v==="assistant"&&"id"in I.message?I.message.id:void 0});else{let w=Gh(x);w.trim()?(b.debug(`[SessionDiscovery] Adding text message: role=${v}, content length=${w.length}`),A.push({role:v,content:w,contentType:"text",timestamp:I.timestamp||new Date().toISOString(),uuid:I.uuid,messageId:v==="assistant"&&"id"in I.message?I.message.id:void 0})):b.debug(`[SessionDiscovery] Skipping message with empty content: role=${v}`)}}else if(I.content){let v=I.type==="system"?"user":I.type;b.debug(`[SessionDiscovery] Adding ${v} message: type=${I.type}, content length=${I.content.length}`),A.push({role:v,content:I.content,contentType:"text",timestamp:I.timestamp||new Date().toISOString(),uuid:I.uuid,messageId:void 0})}else b.debug(`[SessionDiscovery] Skipping line ${g+1}: no valid message content found (type=${I.type})`)}catch(I){b.error(`[SessionDiscovery] Error parsing JSONL line ${g+1}:`,{parseError:I})}}return b.debug(`[SessionDiscovery] Processed ${A.length} messages from ${f.length} lines`),A}catch(a){return b.error(`[SessionDiscovery] Error reading messages from ${e}:`,{error:a}),[]}}};Fae=new $v});import{existsSync as Hv}from"fs";import{join as Gv}from"path";import{homedir as aP}from"os";import{execSync as OCe}from"child_process";var U6,nx=F(()=>{"use strict";Mt();U6=class{cachedPath=null;async find(){if(this.cachedPath&&Hv(this.cachedPath))return this.cachedPath;let e=await this.searchForExecutable();return e&&(this.cachedPath=e),e}async searchForExecutable(){let e=Gv(aP(),".claude/local/claude");if(Hv(e))return b.debug("Found Claude at local path",{path:e}),e;let n=this.tryWhichCommand();if(n)return n;let i=this.getCommonPaths();for(let o of i)if(Hv(o))return b.debug("Found Claude at path",{path:o}),o;let a=this.getNodeScriptPath();return Hv(a)?(b.debug("Found Claude node script",{path:a}),a):(b.warn("Claude Code not found"),null)}tryWhichCommand(){try{let e=OCe("which claude",{encoding:"utf-8"}).trim();if(e&&Hv(e))return b.debug("Found Claude via which",{path:e}),e}catch{}return null}getCommonPaths(){let e=aP();return["/usr/local/bin/claude","/opt/homebrew/bin/claude",Gv(e,".npm-global/bin/claude"),Gv(e,".volta/bin/claude"),Gv(e,".nvm/versions/node/*/bin/claude")].filter(n=>!n.includes("*"))}getNodeScriptPath(){return Gv(aP(),".npm-global/lib/node_modules/@anthropic-ai/claude-code/dist/index.js")}clearCache(){this.cachedPath=null}}});import{spawn as UCe}from"child_process";import{existsSync as MCe}from"fs";var M6,ix=F(()=>{"use strict";Mt();M6=class{activeProcesses=new Map;spawn(e,n,i={}){let{cwd:a=process.cwd(),env:o=process.env,signal:u}=i,p=this.generateProcessId();b.info("Spawning Claude process",{executable:e,args:n,cwd:a,cwdStartsWithSlash:a?.startsWith("/"),cwdExists:MCe(a),processId:p});let f=UCe(e,n,{cwd:a,stdio:["pipe","pipe","pipe"],env:{...o,CUE_LOG_LEVEL:"ERROR",DISABLE_CUE_DEBUG_LOG:"true"},signal:u});return this.activeProcesses.set(p,f),f.on("exit",A=>{b.debug("Claude process exited",{code:A,processId:p}),this.activeProcesses.delete(p)}),f.on("error",A=>{b.error("Claude process error",{error:A,processId:p}),this.activeProcesses.delete(p)}),{process:f,id:p}}kill(e,n="SIGTERM"){let i=this.activeProcesses.get(e);return i?(i.kill(n),this.activeProcesses.delete(e),b.debug("Killed process",{processId:e,signal:n}),!0):!1}killAll(e="SIGTERM"){for(let[n,i]of this.activeProcesses)i.kill(e),b.debug("Killed process",{processId:n,signal:e});this.activeProcesses.clear()}getProcess(e){return this.activeProcesses.get(e)}getActiveProcessIds(){return Array.from(this.activeProcesses.keys())}isActive(e){return this.activeProcesses.has(e)}generateProcessId(){return`claude-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}}});var L6,oP=F(()=>{"use strict";L6=class{queue=[];waiters=[];isDone=!1;error=null;push(e){if(this.isDone)throw new Error("Cannot push to completed iterable");this.waiters.length>0?this.waiters.shift().resolve({done:!1,value:e}):this.queue.push(e)}end(){if(!this.isDone)for(this.isDone=!0;this.waiters.length>0;)this.waiters.shift().resolve({done:!0,value:void 0})}setError(e){for(this.error=e,this.isDone=!0;this.waiters.length>0;)this.waiters.shift().reject(e)}async next(){if(this.error)throw this.error;return this.queue.length>0?{done:!1,value:this.queue.shift()}:this.isDone?{done:!0,value:void 0}:new Promise((e,n)=>{this.waiters.push({resolve:e,reject:n})})}async return(e){return this.end(),{done:!0,value:void 0}}async throw(e){throw this.setError(e),e}[Symbol.asyncIterator](){return this}}});import{createInterface as Qae}from"readline";var qv,rP=F(()=>{"use strict";Mt();qv=class{async streamToStdin(e,n){if(!n.stdin){b.error("Process has no stdin");return}let i=n.stdin;try{for await(let a of e){let o=JSON.stringify(a)+`
|
|
164
164
|
`;b.debug("Writing to stdin",{type:a.type,contentLength:a.message.content.length}),i.write(o)}}catch(a){b.error("Error streaming to stdin",{error:a})}finally{i.end(),b.debug("Stdin stream closed")}}async readFromStdout(e,n,i){if(!e.stdout){b.error("Process has no stdout"),n.end();return}let a=Qae({input:e.stdout});try{for await(let o of a)o.trim()&&this.processLine(o,n,i)}catch(o){b.error("Error reading from stdout",{error:o}),i?.onError&&i.onError(o),n.setError(o)}finally{a.close(),n.end(),b.debug("Stdout stream closed")}}processLine(e,n,i){try{b.info(`MessageStreamHandler processLine line: ${e}`);let a=JSON.parse(e),o=a;b.info("Received Claude message",{type:a.type,subtype:o.subtype,sessionId:o.session_id}),n.push(a),i?.onMessage&&i.onMessage(a),this.detectSessionId(a,i?.onSessionDetected)}catch(a){b.debug("Failed to parse line as JSON",{line:e.substring(0,100),error:String(a)})}}detectSessionId(e,n){if(!n)return;let i;e.type==="system"&&e.session_id&&(i=e.session_id),i&&(b.debug("Session ID detected",{sessionId:i,messageType:e.type}),n(i))}async readFromStderr(e,n){if(!e.stderr)return;let i=Qae({input:e.stderr});try{for await(let a of i)a.trim()&&(b.debug("Stderr output",{line:a}),n&&n(a))}finally{i.close()}}}});var hr,g1,ax=F(()=>{"use strict";Mt();oP();rP();(function(t){t.INITIALIZING="initializing",t.READY="ready",t.WAITING_FOR_RESPONSE="waiting_for_response",t.CLOSED="closed",t.ERROR="error"})(hr||(hr={}));g1=class{options;id;process;inputStream;outputStream;streamHandler;state=hr.INITIALIZING;detectedSessionId;messageCount=0;constructor(e,n,i={}){this.options=i,this.id=e,this.process=n,this.inputStream=new L6,this.outputStream=new L6,this.streamHandler=new qv,this.initialize()}initialize(){this.streamHandler.streamToStdin(this.inputStream,this.process).catch(e=>{b.error("Error in stdin stream",{error:e,sessionId:this.id}),this.handleError(e)}),this.streamHandler.readFromStdout(this.process,this.outputStream,{onMessage:e=>{this.handleMessage(e),this.options.onMessage&&this.options.onMessage(e)},onSessionDetected:e=>{this.detectedSessionId=e,b.info("Session ID detected",{sessionId:e,originalId:this.id}),this.options.onSessionDetected&&this.options.onSessionDetected(e)},onError:e=>{this.handleError(e)}}),this.streamHandler.readFromStderr(this.process,e=>{b.warn("Claude stderr",{error:e,sessionId:this.id})}),this.process.on("exit",e=>{b.info("Session process exited",{code:e,sessionId:this.id,messageCount:this.messageCount}),this.close()}),this.state=hr.READY}async sendMessage(e){if(this.state===hr.CLOSED)throw new Error(`Session ${this.id} is closed`);if(this.state===hr.ERROR)throw new Error(`Session ${this.id} is in error state`);b.info("Sending message to Claude",{sessionId:this.id,detectedSessionId:this.detectedSessionId,contentLength:e.length,messageNumber:this.messageCount+1,state:this.state,contentPreview:e.substring(0,100)}),this.inputStream.push({type:"user",message:{role:"user",content:e}}),this.messageCount++,this.state=hr.WAITING_FOR_RESPONSE}getOutputStream(){return this.outputStream}handleMessage(e){e.type==="result"&&(this.state=hr.READY,b.debug("Session ready for next message",{sessionId:this.id,totalMessages:this.messageCount}))}handleError(e){b.error("Session error",{error:e.message,sessionId:this.id}),this.state=hr.ERROR,this.options.onError&&this.options.onError(e),this.outputStream.setError(e)}close(){this.state!==hr.CLOSED&&(b.info("Closing session",{sessionId:this.id,messageCount:this.messageCount,detectedSessionId:this.detectedSessionId}),this.state=hr.CLOSED,this.inputStream.end(),this.outputStream.end(),this.process.exitCode===null&&this.process.kill("SIGTERM"))}getInfo(){return{id:this.id,detectedSessionId:this.detectedSessionId,state:this.state,messageCount:this.messageCount,processId:this.process.pid,cwd:this.options.cwd}}isActive(){return this.state===hr.READY||this.state===hr.WAITING_FOR_RESPONSE}getSessionId(){return this.detectedSessionId||this.id}}});var Rae=F(()=>{"use strict";Mt();nx();ix();ax()});import{existsSync as LCe}from"fs";var Zh,Nae=F(()=>{"use strict";Mt();nx();ix();ax();Zh=class{executableFinder=new U6;processManager=new M6;sessions=new Map;sessionMetadata=new Map;maxSessions;sessionTimeout;constructor(e=10,n=1440*60*1e3){this.maxSessions=e,this.sessionTimeout=n}async getOrCreateSession(e,n={}){if(b.info("ClaudeMultiSessionManager.getOrCreateSession",{requestedSessionId:e,currentSessions:this.sessions.size,maxSessions:this.maxSessions}),e){let E=this.sessions.get(e),I=e;if(!E){for(let[v,x]of this.sessions)if(x.getInfo().id===e){E=x,I=v;break}}if(E&&E.isActive())return b.info("Reusing existing live session (HOT RESUME)",{sessionId:I,detectedSessionId:E.getInfo().id,state:E.getInfo().state,messageCount:E.getInfo().messageCount,isHotResume:!0,originalRequestedId:e}),this.updateLastActivity(I),{session:E,isNew:!1,sessionId:I};e&&E&&!E.isActive()&&b.info("Found inactive session, will attempt COLD RESUME",{requestedSessionId:e,foundInactiveSession:!0,state:E?.getInfo().state})}this.sessions.size>=this.maxSessions&&await this.cleanupOldestSession();let i=await this.executableFinder.find();if(!i)throw new Error("Claude Code CLI not found. Please install with: npm install -g @anthropic-ai/claude-code");let a=["--output-format","stream-json","--input-format","stream-json","--verbose","--dangerously-skip-permissions"],o;e?/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)?(o=e,a.push("--resume",e),b.info("\u{1F4C2} Attempting to resume previous session (COLD RESUME)",{sessionId:e,cwd:n.cwd,cwdStartsWithSlash:n.cwd?.startsWith("/"),cwdExists:n.cwd?LCe(n.cwd):!1,isColdResume:!0,explanation:"Session not in memory, Claude will load from disk and may generate new ID"})):b.info("\u{1F195} Creating new Claude session (invalid UUID for resume)",{providedId:e,cwd:n.cwd}):b.info("\u{1F195} Creating new Claude session (NO SESSION ID)",{cwd:n.cwd,isNew:!0});let{process:u,id:p}=this.processManager.spawn(i,a,{cwd:n.cwd||process.cwd(),signal:n.signal});b.info("\u{1F680} Claude process spawned",{processId:p,pid:u.pid,sessionId:e||"new"});let f={sessionId:e,cwd:n.cwd,onMessage:n.onMessage,onSessionDetected:E=>{this.updateSessionMapping(p,E),n.onSessionDetected&&n.onSessionDetected(E)},onError:n.onError,signal:n.signal},A=new g1(p,u,f),g=p;return this.sessions.set(g,A),this.sessionMetadata.set(g,{sessionId:g,internalId:p,state:hr.INITIALIZING,messageCount:0,createdAt:new Date,lastActivityAt:new Date,metadata:n.metadata}),b.info("Created new session, set trackingId as sessionId",{sessionId:g,resumeSessionId:o,totalSessions:this.sessions.size,isNew:!o}),{session:A,isNew:!o,sessionId:g}}async sendMessage(e,n,i=!1){let a=this.sessions.get(e);if(!a){for(let[u,p]of this.sessions)if(p.getSessionId()===e){a=p,e=u;break}}if(!a||!a.isActive()){if(!i)throw new Error(`No active session found: ${e}`);let u=await this.getOrCreateSession(e);a=u.session,e=u.sessionId}await a.sendMessage(n),this.updateLastActivity(e);let o=this.sessionMetadata.get(e);return o&&o.messageCount++,a.getOutputStream()}getActiveSessions(){let e=[];for(let[n,i]of this.sessions)if(i.isActive()){let a=this.sessionMetadata.get(n);a&&e.push({...a,state:i.getInfo().state})}return e.sort((n,i)=>i.lastActivityAt.getTime()-n.lastActivityAt.getTime())}getSession(e){return this.sessions.get(e)}async closeSession(e){let n=this.sessions.get(e);if(n){n.close(),this.sessions.delete(e),this.sessionMetadata.delete(e);let i=n.getSessionId();i!==e&&(this.sessions.delete(i),this.sessionMetadata.delete(i)),b.info("Closed session",{sessionId:e,remainingSessions:this.sessions.size})}}async deleteSession(e,n=!1){return b.info("MultiSessionManager DELETE: Starting",{sessionId:e,deleteFromDisk:n,hasSession:this.sessions.has(e),totalSessions:this.sessions.size}),await this.closeSession(e),n?(b.debug("MultiSessionManager DELETE: Deleting from disk",{sessionId:e}),b.info("MultiSessionManager DELETE: Disk deletion not implemented",{sessionId:e,reason:"SessionStorage removed, disk deletion handled by persistence layer"}),!1):(b.info("MultiSessionManager DELETE: Completed (memory only)",{sessionId:e,remainingSessions:this.sessions.size}),!0)}async cleanupInactiveSessions(){let e=Date.now(),n=[];for(let[i,a]of this.sessionMetadata)e-a.lastActivityAt.getTime()>this.sessionTimeout&&n.push(i);for(let i of n)await this.closeSession(i);return b.info("Cleaned up inactive sessions",{count:n.length,remaining:this.sessions.size}),n.length}async cleanupOldestSession(){let e=null,n=Date.now();for(let[i,a]of this.sessionMetadata)a.lastActivityAt.getTime()<n&&(n=a.lastActivityAt.getTime(),e=i);e&&(b.info("Cleaning up oldest session to make room",{sessionId:e}),await this.closeSession(e))}updateSessionMapping(e,n){let i=this.sessions.get(e),a=this.sessionMetadata.get(e);i&&a&&e!==n&&(this.sessions.delete(e),this.sessions.set(n,i),this.sessionMetadata.delete(e),this.sessionMetadata.set(n,{...a,sessionId:n}),b.debug("Updated session mapping",{from:e,to:n}))}updateLastActivity(e){let n=this.sessionMetadata.get(e);n&&(n.lastActivityAt=new Date)}cleanup(){b.info("Cleaning up all sessions",{count:this.sessions.size});for(let e of this.sessions.values())e.close();this.sessions.clear(),this.sessionMetadata.clear(),this.processManager.killAll(),this.executableFinder.clearCache()}}});var Eo,sP=F(()=>{"use strict";Cv();Eo={parse(t,e){try{let n=JSON.parse(t.trim());return Eo.fromRaw(n)}catch(n){let i=t.length>100?t.substring(0,100)+"...":t;return console.warn(`Failed to parse JSONL line${e?` from ${e}`:""}: ${n instanceof Error?n.message:String(n)}`,`
|
|
165
165
|
Line content: ${i}`),null}},fromRaw(t){let e={uuid:t.uuid,parent_uuid:t.parentUuid,session_id:t.sessionId,timestamp:t.timestamp,cwd:t.cwd,type:t.type,is_sidechain:t.isSidechain,user_type:t.userType,version:t.version,git_branch:t.gitBranch,request_id:t.requestId,tool_use_result:t.toolUseResult,level:t.level,is_meta:t.isMeta,is_compact_summary:t.isCompactSummary};if(t.message){let n=t.message;e.message={id:n.id,type:n.type,role:n.role,model:n.model,content:Eo.parseContent(n.content),stop_reason:n.stop_reason,stop_sequence:n.stop_sequence,usage:n.usage}}return t.content&&typeof t.content=="string"&&(e.content=t.content),t.summary&&typeof t.summary=="string"&&(e.summary=t.summary),t.leafUuid&&typeof t.leafUuid=="string"&&(e.leafUuid=t.leafUuid),e},parseContent(t){return typeof t=="string"?[{type:"text",text:t}]:Array.isArray(t)?t.map(e=>{switch(e.type){case"text":return{type:"text",text:e.text};case"tool_use":return{type:"tool_use",id:e.id,name:e.name,input:e.input||{}};case"tool_call":return{type:"tool_call",id:e.id,function:{name:e.function?.name||"unknown",arguments:e.function?.arguments||"{}"}};case"tool_result":{let n;return typeof e.content=="string"?n=[{type:"text",text:e.content}]:Array.isArray(e.content)?n=e.content.map(i=>{if(typeof i=="string")return{type:"text",text:i};if(typeof i=="object"&&i!==null&&"type"in i){let a=i;return a.type==="text"?{type:"text",text:a.text||""}:a.type==="image"?{type:"image",source:a.source}:{type:"text",text:JSON.stringify(i)}}else return{type:"text",text:JSON.stringify(i)}}):n=[{type:"text",text:""}],{type:"tool_result",tool_use_id:e.tool_use_id||e.id||"",content:n}}default:return{type:"text",text:JSON.stringify(e)}}}):[{type:"text",text:String(t)}]},getPreviewText(t){let e=t;return e.summary?e.summary:t.message?.content?Gh(t.message.content):t.content?Gh(t.content):""},isFirstMessage(t){return t.parent_uuid===null&&t.type==="user"}}});var kae=F(()=>{"use strict";Rae();Nae();ax();nx();ix();rP();oP();sP()});import{readFileSync as PCe,existsSync as uP,readdirSync as zCe,statSync as jCe}from"fs";import{join as ox}from"path";import{homedir as $Ce}from"os";var rx,Oae=F(()=>{"use strict";Mt();sP();rx=class{projectsPath;constructor(){this.projectsPath=ox($Ce(),".cue","projects")}async loadChainedHistory(e,n){try{let i=this.findSessionFile(e,n);if(!i)return{messages:[],lastUuid:null};let o=PCe(i,"utf-8").trim().split(`
|
|
166
|
-
`).filter(v=>v.trim());if(o.length===0)return{messages:[],lastUuid:null};let u=o.map(v=>Eo.parse(v,i)).filter(v=>v!==null),p=new Map;u.forEach(v=>{v.uuid&&p.set(v.uuid,v)});let f=[...u].reverse().find(v=>v.uuid);if(!f||!f.uuid)return{messages:[],lastUuid:null};let A=[],g=f,E=new Set;for(;g&&g.uuid&&!(E.has(g.uuid)||(E.add(g.uuid),A.unshift(g),!g.parent_uuid));)g=p.get(g.parent_uuid);return{messages:A.filter(v=>v.message&&(v.message.role==="user"||v.message.role==="assistant")||v.tool_use_result).map(v=>this.convertToSessionMessage(v)),lastUuid:f.uuid}}catch(i){return b.debug("Failed to load chained history",{sessionId:e,error:i instanceof Error?i.message:String(i)}),{messages:[],lastUuid:null}}}findSessionFile(e,n){if(n){let a=this.getProjectDirName(n),o=ox(this.projectsPath,a,`${e}.jsonl`);if(uP(o))return o}if(!uP(this.projectsPath))return null;let i=zCe(this.projectsPath).filter(a=>{let o=ox(this.projectsPath,a);return jCe(o).isDirectory()});for(let a of i){let o=ox(this.projectsPath,a,`${e}.jsonl`);if(uP(o))return o}return null}getProjectDirName(e){return(e.startsWith("/")?e:`/${e}`).replace(/\//g,"-")}convertToSessionMessage(e){if(e.tool_use_result&&e.message)return{role:e.message.role,content:e.message.content,contentType:typeof e.message.content=="string"?"text":"content_parts",timestamp:e.timestamp||new Date().toISOString(),uuid:e.uuid,messageId:e.message?.id,isToolResult:!0};if(e.tool_use_result)return{role:"tool",content:e.tool_use_result.stdout||e.tool_use_result.stderr||"",contentType:"text",timestamp:e.timestamp||new Date().toISOString(),uuid:e.uuid,isToolResult:!0};let n=e.message.role,i=e.message.content,a;return typeof i=="string"||Array.isArray(i)?a=i:a=String(i),{role:n,content:a,contentType:typeof a=="string"?"text":"content_parts",timestamp:e.timestamp||new Date().toISOString(),uuid:e.uuid,messageId:e.message?.id}}}});function HCe(t){if(!t)return!1;let e=t.toLowerCase();return e.includes("claude")||e.includes("sonnet")||e.includes("opus")||e.includes("haiku")||e.startsWith("claude-")}async function Uae({sessionId:t,cwd:e,conversationHistory:n,model:i}){let a=new rx;b.info("[Session Resume] Attempting to load history for session",{sessionId:t,cwd:e});try{let{messages:o,lastUuid:u}=await a.loadChainedHistory(t,e);if(o.length===0)return{messageCount:0,lastUuid:null};b.info(`[Session Resume] Successfully loaded ${o.length} messages from session history`,{sessionId:t,cwd:e,firstMessage:typeof o[0]?.content=="string"?o[0].content.substring(0,50):"Complex content",lastMessage:o[o.length-1]&&typeof o[o.length-1].content=="string"?o[o.length-1].content.substring(0,50):"Complex content"});let p=HCe(i);for(let f=0;f<o.length;f++){let A=o[f];if(A.isToolResult){if(p){if(A.role==="user"&&A.content&&Array.isArray(A.content)){let I={role:"user",content:A.content};n.addMessage(I),b.debug("Added Claude tool result as user message",{sessionId:t,model:i});continue}b.debug("Skipping legacy tool result for Claude model",{sessionId:t,model:i});continue}let g;for(let I=f-1;I>=0;I--){let v=o[I];if(v.role==="assistant"&&v.content&&Array.isArray(v.content)){let x=v.content.find(w=>w.type==="tool_call");if(x&&"id"in x){g=x.id;break}}}let E={role:"tool",content:A.content,tool_call_id:g||"unknown"};n.addMessage(E)}else if(A.role==="assistant"&&Array.isArray(A.content)){let g=[],E=[];for(let I of A.content)I.type==="tool_call"||I.type==="tool_use"?I.type==="tool_use"?g.push(I):g.push({id:I.id,type:"function",function:I.function}):E.push(I);if(g.length>0)if(p){let I={role:"assistant",content:A.content};n.addMessage(I),b.debug("Loaded assistant message with embedded tool calls for Claude",{sessionId:t,model:i,toolCallsCount:g.length})}else{let I={role:"assistant",content:E.length>0?E.length===1&&E[0].type==="text"?E[0].text:E:null,tool_calls:g};n.addMessage(I),b.debug("Loaded assistant message with tool_calls field for OpenAI",{sessionId:t,toolCallsCount:g.length,hasTextContent:E.length>0})}else{let I={role:"assistant",content:A.content};n.addMessage(I)}}else{let g={role:A.role,content:A.content};n.addMessage(g)}}return u&&($r.setLastParentUuid(t,u),b.info("[Session Resume] Session history loaded with parent chain restored",{sessionId:t,lastParentUuid:u,messageCount:o.length})),{messageCount:o.length,lastUuid:u}}catch(o){return b.error("Failed to load session history",{sessionId:t,error:o instanceof Error?o.message:String(o)}),{messageCount:0,lastUuid:null}}}var Mae=F(()=>{"use strict";Mt();Oae();Pv()});import{EventEmitter as GCe}from"events";import{randomUUID as qCe}from"crypto";var Xh,lP=F(()=>{"use strict";Mt();ZS();kS();tf();ex();Ov();vL();XL();nP();Mae();Xh=class extends GCe{sessionId;processId;options;conversationHistory;state;tokenTracker;persistenceService;compactionService;historyLoadPromise;constructor(e,n,i={}){super(),this.sessionId=e,this.processId=n;let a=i.cwd||process.cwd();this.options={...i,cwd:a},this.conversationHistory=new Js(e),this.tokenTracker=new E6(e),this.compactionService=new k6,this.persistenceService=new R6(e,{enabled:!0,cwd:this.options.cwd}),this.state={status:"idle",abortController:void 0,createdAt:new Date,lastActivityAt:new Date,messageCount:0},b.debug("CueSession created",{sessionId:e,processId:n,cwd:this.options.cwd,model:this.options.model,provider:this.options.provider,useStreamingRunner:this.options.useStreamingRunner}),this.persistenceService.setupEventListeners(this),this.historyLoadPromise=this.loadSessionHistory()}async sendMessage(e,n){if(this.state.status==="closed")throw new Error("Session is closed");if(this.state.status==="streaming"||this.state.status==="processing")throw b.warn("Session busy, cannot process message",{sessionId:this.sessionId,status:this.state.status}),new Error("Session is busy processing another message");if(!n?.isCompactSummary&&this.tokenTracker.shouldAutoCompact()){b.info("Auto-compacting before processing user input",{sessionId:this.sessionId,tokensUsed:this.tokenTracker.getTokenStats().totalTokensUsed,threshold:this.tokenTracker.getMaxTokens(),userMessage:e.substring(0,100)}),this.emit("session-event",{type:gn.UPDATE,sessionId:this.sessionId,data:{role:"system",content:"Compacting conversation history (exceeded 100k tokens)...",isSystemMessage:!0}});try{await this.compact(),b.info("Pre-processing compaction completed",{sessionId:this.sessionId,newTokenCount:this.tokenTracker.getTokenStats().totalTokensUsed})}catch(a){b.error("Pre-processing compaction failed, continuing anyway",{sessionId:this.sessionId,error:a instanceof Error?a.message:String(a)}),this.emit("session-event",{type:gn.UPDATE,sessionId:this.sessionId,data:{role:"system",content:"Warning: Compaction failed. Continuing with full history.",isSystemMessage:!0}})}}if(this.state={...this.state,status:"processing",lastActivityAt:new Date,messageCount:this.state.messageCount+1},!n?.isCompactSummary){let a={role:"user",content:e};this.conversationHistory.addMessage(a),this.emit("session-message",a)}let i=qCe();this.emit("session-event",{type:"turn_start",sessionId:this.sessionId,data:{message:e,uuid:i,cwd:this.options.cwd,timestamp:new Date().toISOString(),isCompactSummary:n?.isCompactSummary}});try{this.state.abortController=new AbortController;let a=N6(this.options),o=(p,f)=>{b.debug("CueSession: Received session event",{eventType:p,...f}),this.emit("session-event",{type:p,sessionId:this.sessionId,data:f})},u=this.createStreamIterator(a,o);return this.state={...this.state,status:"streaming"},u}catch(a){throw this.state={...this.state,status:"error",error:a instanceof Error?a:new Error(String(a))},a}finally{}}async*createStreamIterator(e,n){try{let i={maxSteps:100,maxTokens:4e3,model:this.options.model||"claude-3-5-haiku-20241022",tools:Ql(),systemPrompt:"You are a helpful AI assistant with access to various development tools.",stream:!0},a=i.model.toLowerCase(),o=a.includes("claude")||a.includes("sonnet")||a.includes("opus")||a.includes("haiku")||a.startsWith("claude-")||a==="claude-sonnet-4-20250514"||a==="claude-opus-4-20250514",u=o?e.anthropicModel:e.openaiModel;if(!u)throw new Error(`No ${o?"Anthropic":"OpenAI"} model available from provider for model: ${i.model}`);b.debug("CueSession.createStreamIterator - agent",{...i,providerType:e.config?.type||"unknown",isClaudeModel:o,hasAnthropicModel:!!e.anthropicModel,hasOpenAIModel:!!e.openaiModel,baseUrl:e.config?.type==="cue"?e.config.baseUrl:void 0,isProxy:e.config?.type==="cue",actualModelUsed:o?"anthropic":"openai"});let p={modelBase:u,hooks:{canContinue:async E=>{E.usage&&this.tokenTracker.updateTokenUsage(E.usage.inputTokens,E.usage.outputTokens);let I=this.tokenTracker.getTokenStats();return I.totalTokensUsed>this.tokenTracker.getMaxTokens()&&(b.warn("Token usage exceeds threshold during execution",{sessionId:this.sessionId,tokensUsed:I.totalTokensUsed,threshold:this.tokenTracker.getMaxTokens(),step:E.step,hasToolResults:E.lastStepResult?.nextStep==="runAgain"}),this.emit("session-event",{type:gn.UPDATE,sessionId:this.sessionId,data:{role:"system",content:`Note: Token usage at ${Math.round(I.percentageUsed)}% of limit. Compaction will occur after this response.`,isSystemMessage:!0}})),!0},canExecuteTool:async E=>(b.debug("CueSession: Tool execution check",{toolName:E.toolName,sessionId:E.sessionId}),!0)}},f={usage:{requests:0,inputTokens:0,outputTokens:0,cacheWriteTokens:0,cacheReadInputTokens:0},abortSignal:this.state.abortController?.signal,currentStep:0},A=new sp,g=E=>{let I=E.contentType;if(b.debug("buildMessageFromUpdate - full data:",{...E}),I=="text")return{id:E.uuid??"",content:[D1.text(E.content)],role:E.role,isUser:!1,timestamp:new Date};if(I=="content_parts")return{id:E.uuid??"",content:E.content,role:E.role,isUser:!1,timestamp:new Date};b.debug(`buildMessageFromUpdate - skip type: ${I}`)};if(this.options.useStreamingRunner){let I=A.runStreaming(i,p,f,this.conversationHistory,n).stream.getReader();try{for(;;){let{done:v,value:x}=await I.read();if(v)break;let w=x;if(w.eventType==="session_update"){let _=g(w.data);_&&(yield _)}}}finally{I.releaseLock()}}else{let E=A.run(i,p,f,this.conversationHistory,n);for await(let I of E)if(I.eventType==="session_update"){let v=g(I.data);v&&(yield v)}}this.tokenTracker.shouldAutoCompact()&&(b.info("Compacting after response completion",{sessionId:this.sessionId,tokensUsed:this.tokenTracker.getTokenStats().totalTokensUsed,threshold:this.tokenTracker.getMaxTokens()}),this.emit("session-event",{type:gn.UPDATE,sessionId:this.sessionId,data:{role:"system",content:"Note: Conversation will be compacted before next message (exceeded 100k tokens).",isSystemMessage:!0}}))}finally{this.state={...this.state,status:"idle",lastActivityAt:new Date},b.debug("Stream iterator completed, status reset to idle",{sessionId:this.sessionId})}}getInfo(){return{sessionId:this.sessionId,projectId:this.options.projectId,processId:this.processId,cwd:this.options.cwd,model:this.options.model,provider:this.options.provider,createdAt:this.state.createdAt,lastActivityAt:this.state.lastActivityAt,messageCount:this.state.messageCount,isActive:this.state.status!=="closed"}}getTokenStats(){return this.tokenTracker.getTokenStats()}getConversationHistory(){return this.conversationHistory.getAllMessages()}async waitForHistoryLoad(){await this.historyLoadPromise}isActive(){return this.state.status!=="closed"&&this.state.status!=="error"}abort(){this.state.abortController&&!this.state.abortController.signal.aborted&&(this.state.abortController.abort(),this.state={...this.state,status:"idle"},b.info("Session aborted",{sessionId:this.sessionId}))}close(){this.abort(),this.state={...this.state,status:"closed"},this.persistenceService.cleanup(),this.removeAllListeners(),b.debug("Session closed",{sessionId:this.sessionId,messageCount:this.state.messageCount})}async loadSessionHistory(){let{messageCount:e}=await Uae({sessionId:this.sessionId,cwd:this.options.cwd,conversationHistory:this.conversationHistory,model:this.options.model});e>0?this.state.messageCount=e:b.info("[Session Resume] No existing history found for session",{sessionId:this.sessionId,cwd:this.options.cwd})}async compact(){if(this.state.status==="streaming"||this.state.status==="processing")throw new Error("Cannot compact while processing a message");return this.compactionService.compact({sessionId:this.sessionId,conversationHistory:this.conversationHistory,tokenTracker:this.tokenTracker,options:this.options,eventEmitter:this,abortSignal:this.state.abortController?.signal})}async updateModel(e){if(this.state.status==="streaming"||this.state.status==="processing")throw new Error("Cannot change model while processing a message");let n=this.options.model,i=this.isClaudeModel(n),a=this.isClaudeModel(e);this.options.model=e,b.info("Model changed",{sessionId:this.sessionId,oldModel:n,newModel:e,requiresReload:i!==a}),i!==a&&(b.info("Provider change detected, reloading conversation history",{sessionId:this.sessionId,fromProvider:i?"Claude":"OpenAI",toProvider:a?"Claude":"OpenAI"}),this.conversationHistory=new Js(this.sessionId),await this.loadSessionHistory(),this.emit("session-event",{type:gn.UPDATE,sessionId:this.sessionId,data:{role:"system",content:`Model changed from ${n||"default"} to ${e}. History reloaded for compatibility.`,isSystemMessage:!0}}))}isClaudeModel(e){if(!e)return!1;let n=e.toLowerCase();return n.includes("claude")||n.includes("sonnet")||n.includes("opus")||n.includes("haiku")||n.startsWith("claude-")}}});import{randomUUID as KCe}from"crypto";var uf,Lae=F(()=>{"use strict";Mt();lP();uf=class{sessions=new Map;sessionAccessTime=new Map;maxSessions;sessionTimeout;cleanupInterval;constructor(e=10,n=1440*60*1e3){this.maxSessions=e,this.sessionTimeout=n,this.startCleanupInterval(),b.debug("CueSessionManager initialized",{maxSessions:e,sessionTimeout:n})}async getOrCreateSession(e,n={}){if(e){let f=this.sessions.get(e);if(f&&f.isActive())return b.info("Reusing existing live session (HOT RESUME)",{sessionId:e,isHotResume:!0,currentModel:f.getInfo().model,requestedModel:n.model}),this.sessionAccessTime.set(e,new Date),n.model&&n.model!==f.getInfo().model&&(b.info("Model change detected in existing session",{sessionId:e,oldModel:f.getInfo().model,newModel:n.model}),await f.updateModel(n.model)),{session:f,isNew:!1,sessionId:e}}let i=e||KCe(),a=`cue-${Date.now()}-${Math.random().toString(36).substring(2,7)}`,o=e!=null;b.debug(o?"Resuming Cue session from disk (COLD RESUME)":"Creating new Cue session",{sessionId:i,processId:a,isNew:!o,isResumingFromDisk:o}),this.sessions.size>=this.maxSessions&&await this.cleanupOldestSession();let u={...n,sessionId:i},p=new Xh(i,a,u);return n.onMessage&&(p.on("session-message",f=>{n.onMessage(f)}),p.on("partial",f=>{n.onMessage(f)})),this.sessions.set(i,p),this.sessionAccessTime.set(i,new Date),{session:p,isNew:!o,sessionId:i}}async sendMessage(e,n,i=!1){let a=this.sessions.get(e);if(!a)if(i)a=(await this.getOrCreateSession(e)).session;else throw new Error(`No active session found: ${e}`);return this.sessionAccessTime.set(e,new Date),a.sendMessage(n)}async closeSession(e){let n=this.sessions.get(e);n&&(n.close(),this.sessionAccessTime.delete(e),b.debug("Session closed",{sessionId:e}))}async stopSession(e){let n=this.sessions.get(e);n?(n.abort(),b.info("Session stopped (aborted)",{sessionId:e})):b.warn("Cannot stop: session not found",{sessionId:e})}async resetSession(e){let n=this.sessions.get(e);n?(n.close(),this.sessions.delete(e),this.sessionAccessTime.delete(e),b.info("Session reset: closed and removed from memory",{sessionId:e,info:"Session will be recreated on next message"})):b.warn("Cannot reset: session not found",{sessionId:e})}async clearAndResetSession(e,n){let i=this.sessions.get(e),a=n||i?.getInfo().cwd||process.cwd(),{cueSessionPersistence:o}=await Promise.resolve().then(()=>(Pv(),xae));o.clearSessionMessages(e,a)&&b.info("Session messages cleared from disk",{sessionId:e,cwd:a}),i?(i.close(),this.sessions.delete(e),this.sessionAccessTime.delete(e),b.info("Session cleared and reset: messages deleted, session removed from memory",{sessionId:e,cwd:a,info:"Session will start fresh on next message"})):b.info("Session cleared: messages deleted from disk",{sessionId:e,cwd:a,info:"Session was not in memory"})}async deleteSession(e,n=!0){b.info("Deleting session",{sessionId:e,deleteFromDisk:n});let i=this.sessions.get(e);return i&&(i.close(),this.sessions.delete(e),this.sessionAccessTime.delete(e)),!0}async cleanupOldestSession(){let e=new Date,n=null;for(let[i,a]of this.sessionAccessTime.entries())a<e&&(e=a,n=i);n&&(b.info("Cleaning up oldest session due to limit",{sessionId:n,accessTime:e}),await this.closeSession(n))}startCleanupInterval(){this.cleanupInterval=setInterval(async()=>{let e=new Date,n=[];for(let[i,a]of this.sessionAccessTime.entries())e.getTime()-a.getTime()>this.sessionTimeout&&n.push(i);for(let i of n)b.info("Cleaning up expired session",{sessionId:i}),await this.closeSession(i)},6e4)}getActiveSessions(){return Array.from(this.sessions.values()).map(e=>e.getInfo())}getSession(e){return this.sessions.get(e)}async cleanup(){b.debug("Cleaning up all sessions",{count:this.sessions.size}),this.cleanupInterval&&clearInterval(this.cleanupInterval);for(let[,e]of this.sessions.entries())e.close();this.sessions.clear(),this.sessionAccessTime.clear()}}});var Pae=F(()=>{"use strict"});var zae=F(()=>{"use strict";lP();Lae();Pae()});import{readFileSync as jae}from"fs";import{join as $ae,dirname as VCe}from"path";import{fileURLToPath as JCe}from"url";function cP(){try{let t=$ae(Hae,"../../cli/package.json");return JSON.parse(jae(t,"utf-8")).version}catch{try{let t=$ae(Hae,"../package.json");return JSON.parse(jae(t,"utf-8")).version}catch{return"0.0.1"}}}function Gae(){return`Cue-CLI/${cP()} (${process.platform}; Node.js ${process.version})`}var YCe,Hae,qae=F(()=>{"use strict";YCe=JCe(import.meta.url),Hae=VCe(YCe)});var Kae=F(()=>{"use strict"});var D1,Vae=F(()=>{"use strict";D1={text:t=>({type:"text",text:t}),toolUse:(t,e,n)=>({type:"tool_use",id:t,name:e,input:n}),toolCall:(t,e,n)=>({type:"tool_call",id:t,function:{name:e,arguments:n}}),toolMessage:(t,e,n)=>({type:"tool_message",role:t,content:e,tool_call_id:n}),thinking:(t,e)=>({type:"thinking",thinking:t,signature:e}),code:(t,e="plaintext")=>({type:"code",text:t,language:e}),table:t=>({type:"table",markdownText:t}),toolResult:(t,e,n)=>({type:"tool_result",tool_use_id:t,content:e,is_error:n}),getId:(t,e,n)=>{switch(e.type){case"tool_use":return`${t}_${e.id}_${e.type}_${n}`;case"tool_call":return`${t}_${e.id}_${e.type}_${n}`;case"tool_message":return`${t}_${e.tool_call_id}_${e.type}_${n}`;case"tool_result":return`${t}_${e.tool_use_id}_${e.type}_${n}`;default:return`${t}_${e.type}_${n}`}},parseTextContent:t=>{let e=t.trim();if(!e)return[];let n=[],i=e.split(`
|
|
166
|
+
`).filter(v=>v.trim());if(o.length===0)return{messages:[],lastUuid:null};let u=o.map(v=>Eo.parse(v,i)).filter(v=>v!==null),p=new Map;u.forEach(v=>{v.uuid&&p.set(v.uuid,v)});let f=[...u].reverse().find(v=>v.uuid);if(!f||!f.uuid)return{messages:[],lastUuid:null};let A=[],g=f,E=new Set;for(;g&&g.uuid&&!(E.has(g.uuid)||(E.add(g.uuid),A.unshift(g),!g.parent_uuid));)g=p.get(g.parent_uuid);return{messages:A.filter(v=>v.message&&(v.message.role==="user"||v.message.role==="assistant")||v.tool_use_result).map(v=>this.convertToSessionMessage(v)),lastUuid:f.uuid}}catch(i){return b.debug("Failed to load chained history",{sessionId:e,error:i instanceof Error?i.message:String(i)}),{messages:[],lastUuid:null}}}findSessionFile(e,n){if(n){let a=this.getProjectDirName(n),o=ox(this.projectsPath,a,`${e}.jsonl`);if(uP(o))return o}if(!uP(this.projectsPath))return null;let i=zCe(this.projectsPath).filter(a=>{let o=ox(this.projectsPath,a);return jCe(o).isDirectory()});for(let a of i){let o=ox(this.projectsPath,a,`${e}.jsonl`);if(uP(o))return o}return null}getProjectDirName(e){return(e.startsWith("/")?e:`/${e}`).replace(/\//g,"-")}convertToSessionMessage(e){if(e.tool_use_result&&e.message)return{role:e.message.role,content:e.message.content,contentType:typeof e.message.content=="string"?"text":"content_parts",timestamp:e.timestamp||new Date().toISOString(),uuid:e.uuid,messageId:e.message?.id,isToolResult:!0};if(e.tool_use_result)return{role:"tool",content:e.tool_use_result.stdout||e.tool_use_result.stderr||"",contentType:"text",timestamp:e.timestamp||new Date().toISOString(),uuid:e.uuid,isToolResult:!0};let n=e.message.role,i=e.message.content,a;return typeof i=="string"||Array.isArray(i)?a=i:a=String(i),{role:n,content:a,contentType:typeof a=="string"?"text":"content_parts",timestamp:e.timestamp||new Date().toISOString(),uuid:e.uuid,messageId:e.message?.id}}}});function HCe(t){if(!t)return!1;let e=t.toLowerCase();return e.includes("claude")||e.includes("sonnet")||e.includes("opus")||e.includes("haiku")||e.startsWith("claude-")}async function Uae({sessionId:t,cwd:e,conversationHistory:n,model:i}){let a=new rx;b.info("[Session Resume] Attempting to load history for session",{sessionId:t,cwd:e});try{let{messages:o,lastUuid:u}=await a.loadChainedHistory(t,e);if(o.length===0)return{messageCount:0,lastUuid:null};b.info(`[Session Resume] Successfully loaded ${o.length} messages from session history`,{sessionId:t,cwd:e,firstMessage:typeof o[0]?.content=="string"?o[0].content.substring(0,50):"Complex content",lastMessage:o[o.length-1]&&typeof o[o.length-1].content=="string"?o[o.length-1].content.substring(0,50):"Complex content"});let p=HCe(i);for(let f=0;f<o.length;f++){let A=o[f];if(A.isToolResult){if(p){if(A.role==="user"&&A.content&&Array.isArray(A.content)){let I={role:"user",content:A.content};n.addMessage(I),b.debug("Added Claude tool result as user message",{sessionId:t,model:i});continue}b.debug("Skipping legacy tool result for Claude model",{sessionId:t,model:i});continue}let g;for(let I=f-1;I>=0;I--){let v=o[I];if(v.role==="assistant"&&v.content&&Array.isArray(v.content)){let x=v.content.find(w=>typeof w=="object"&&w!==null&&"type"in w&&w.type==="tool_call");if(x&&"id"in x){g=x.id;break}}}let E={role:"tool",content:A.content,tool_call_id:g||"unknown"};n.addMessage(E)}else if(A.role==="assistant"&&Array.isArray(A.content)){let g=[],E=[];for(let I of A.content)if(typeof I=="object"&&I!==null&&"type"in I&&(I.type==="tool_call"||I.type==="tool_use")){let v=I;v.type==="tool_use"?g.push(v):g.push({id:v.id,type:"function",function:v.function})}else E.push(I);if(g.length>0)if(p){let I={role:"assistant",content:A.content};n.addMessage(I),b.debug("Loaded assistant message with embedded tool calls for Claude",{sessionId:t,model:i,toolCallsCount:g.length})}else{let I={role:"assistant",content:E.length>0?E.length===1&&E[0].type==="text"?E[0].text:E:null,tool_calls:g};n.addMessage(I),b.debug("Loaded assistant message with tool_calls field for OpenAI",{sessionId:t,toolCallsCount:g.length,hasTextContent:E.length>0})}else{let I={role:"assistant",content:A.content};n.addMessage(I)}}else{let g={role:A.role,content:A.content};n.addMessage(g)}}return u&&($r.setLastParentUuid(t,u),b.info("[Session Resume] Session history loaded with parent chain restored",{sessionId:t,lastParentUuid:u,messageCount:o.length})),{messageCount:o.length,lastUuid:u}}catch(o){return b.error("Failed to load session history",{sessionId:t,error:o instanceof Error?o.message:String(o)}),{messageCount:0,lastUuid:null}}}var Mae=F(()=>{"use strict";Mt();Oae();Pv()});import{EventEmitter as GCe}from"events";import{randomUUID as qCe}from"crypto";var Xh,lP=F(()=>{"use strict";Mt();ZS();kS();tf();ex();Ov();vL();XL();nP();Mae();Xh=class extends GCe{sessionId;processId;options;conversationHistory;state;tokenTracker;persistenceService;compactionService;historyLoadPromise;constructor(e,n,i={}){super(),this.sessionId=e,this.processId=n;let a=i.cwd||process.cwd();this.options={...i,cwd:a},this.conversationHistory=new Js(e),this.tokenTracker=new E6(e),this.compactionService=new k6,this.persistenceService=new R6(e,{enabled:!0,cwd:this.options.cwd}),this.state={status:"idle",abortController:void 0,createdAt:new Date,lastActivityAt:new Date,messageCount:0},b.debug("CueSession created",{sessionId:e,processId:n,cwd:this.options.cwd,model:this.options.model,provider:this.options.provider,useStreamingRunner:this.options.useStreamingRunner}),this.persistenceService.setupEventListeners(this),this.historyLoadPromise=this.loadSessionHistory()}async sendMessage(e,n){if(this.state.status==="closed")throw new Error("Session is closed");if(this.state.status==="streaming"||this.state.status==="processing")throw b.warn("Session busy, cannot process message",{sessionId:this.sessionId,status:this.state.status}),new Error("Session is busy processing another message");if(!n?.isCompactSummary&&this.tokenTracker.shouldAutoCompact()){b.info("Auto-compacting before processing user input",{sessionId:this.sessionId,tokensUsed:this.tokenTracker.getTokenStats().totalTokensUsed,threshold:this.tokenTracker.getMaxTokens(),userMessage:e.substring(0,100)}),this.emit("session-event",{type:gn.UPDATE,sessionId:this.sessionId,data:{role:"system",content:"Compacting conversation history (exceeded 100k tokens)...",isSystemMessage:!0}});try{await this.compact(),b.info("Pre-processing compaction completed",{sessionId:this.sessionId,newTokenCount:this.tokenTracker.getTokenStats().totalTokensUsed})}catch(a){b.error("Pre-processing compaction failed, continuing anyway",{sessionId:this.sessionId,error:a instanceof Error?a.message:String(a)}),this.emit("session-event",{type:gn.UPDATE,sessionId:this.sessionId,data:{role:"system",content:"Warning: Compaction failed. Continuing with full history.",isSystemMessage:!0}})}}if(this.state={...this.state,status:"processing",lastActivityAt:new Date,messageCount:this.state.messageCount+1},!n?.isCompactSummary){let a={role:"user",content:e};this.conversationHistory.addMessage(a),this.emit("session-message",a)}let i=qCe();this.emit("session-event",{type:"turn_start",sessionId:this.sessionId,data:{message:e,uuid:i,cwd:this.options.cwd,timestamp:new Date().toISOString(),isCompactSummary:n?.isCompactSummary}});try{this.state.abortController=new AbortController;let a=N6(this.options),o=(p,f)=>{b.debug("CueSession: Received session event",{eventType:p,...f}),this.emit("session-event",{type:p,sessionId:this.sessionId,data:f})},u=this.createStreamIterator(a,o);return this.state={...this.state,status:"streaming"},u}catch(a){throw this.state={...this.state,status:"error",error:a instanceof Error?a:new Error(String(a))},a}finally{}}async*createStreamIterator(e,n){try{let i={maxSteps:100,maxTokens:4e3,model:this.options.model||"claude-3-5-haiku-20241022",tools:Ql(),systemPrompt:"You are a helpful AI assistant with access to various development tools.",stream:!0},a=i.model.toLowerCase(),o=a.includes("claude")||a.includes("sonnet")||a.includes("opus")||a.includes("haiku")||a.startsWith("claude-")||a==="claude-sonnet-4-20250514"||a==="claude-opus-4-20250514",u=o?e.anthropicModel:e.openaiModel;if(!u)throw new Error(`No ${o?"Anthropic":"OpenAI"} model available from provider for model: ${i.model}`);b.debug("CueSession.createStreamIterator - agent",{...i,providerType:e.config?.type||"unknown",isClaudeModel:o,hasAnthropicModel:!!e.anthropicModel,hasOpenAIModel:!!e.openaiModel,baseUrl:e.config?.type==="cue"?e.config.baseUrl:void 0,isProxy:e.config?.type==="cue",actualModelUsed:o?"anthropic":"openai"});let p={modelBase:u,hooks:{canContinue:async E=>{E.usage&&this.tokenTracker.updateTokenUsage(E.usage.inputTokens,E.usage.outputTokens);let I=this.tokenTracker.getTokenStats();return I.totalTokensUsed>this.tokenTracker.getMaxTokens()&&(b.warn("Token usage exceeds threshold during execution",{sessionId:this.sessionId,tokensUsed:I.totalTokensUsed,threshold:this.tokenTracker.getMaxTokens(),step:E.step,hasToolResults:E.lastStepResult?.nextStep==="runAgain"}),this.emit("session-event",{type:gn.UPDATE,sessionId:this.sessionId,data:{role:"system",content:`Note: Token usage at ${Math.round(I.percentageUsed)}% of limit. Compaction will occur after this response.`,isSystemMessage:!0}})),!0},canExecuteTool:async E=>(b.debug("CueSession: Tool execution check",{toolName:E.toolName,sessionId:E.sessionId}),!0)}},f={usage:{requests:0,inputTokens:0,outputTokens:0,cacheWriteTokens:0,cacheReadInputTokens:0},abortSignal:this.state.abortController?.signal,currentStep:0},A=new sp,g=E=>{let I=E.contentType;if(b.debug("buildMessageFromUpdate - full data:",{...E}),I=="text")return{id:E.uuid??"",content:[D1.text(E.content)],role:E.role,isUser:!1,timestamp:new Date};if(I=="content_parts")return{id:E.uuid??"",content:E.content,role:E.role,isUser:!1,timestamp:new Date};b.debug(`buildMessageFromUpdate - skip type: ${I}`)};if(this.options.useStreamingRunner){let I=A.runStreaming(i,p,f,this.conversationHistory,n).stream.getReader();try{for(;;){let{done:v,value:x}=await I.read();if(v)break;let w=x;if(w.eventType==="session_update"){let _=g(w.data);_&&(yield _)}}}finally{I.releaseLock()}}else{let E=A.run(i,p,f,this.conversationHistory,n);for await(let I of E)if(I.eventType==="session_update"){let v=g(I.data);v&&(yield v)}}this.tokenTracker.shouldAutoCompact()&&(b.info("Compacting after response completion",{sessionId:this.sessionId,tokensUsed:this.tokenTracker.getTokenStats().totalTokensUsed,threshold:this.tokenTracker.getMaxTokens()}),this.emit("session-event",{type:gn.UPDATE,sessionId:this.sessionId,data:{role:"system",content:"Note: Conversation will be compacted before next message (exceeded 100k tokens).",isSystemMessage:!0}}))}finally{this.state={...this.state,status:"idle",lastActivityAt:new Date},b.debug("Stream iterator completed, status reset to idle",{sessionId:this.sessionId})}}getInfo(){return{sessionId:this.sessionId,projectId:this.options.projectId,processId:this.processId,cwd:this.options.cwd,model:this.options.model,provider:this.options.provider,createdAt:this.state.createdAt,lastActivityAt:this.state.lastActivityAt,messageCount:this.state.messageCount,isActive:this.state.status!=="closed"}}getTokenStats(){return this.tokenTracker.getTokenStats()}getConversationHistory(){return this.conversationHistory.getAllMessages()}async waitForHistoryLoad(){await this.historyLoadPromise}isActive(){return this.state.status!=="closed"&&this.state.status!=="error"}abort(){this.state.abortController&&!this.state.abortController.signal.aborted&&(this.state.abortController.abort(),this.state={...this.state,status:"idle"},b.info("Session aborted",{sessionId:this.sessionId}))}close(){this.abort(),this.state={...this.state,status:"closed"},this.persistenceService.cleanup(),this.removeAllListeners(),b.debug("Session closed",{sessionId:this.sessionId,messageCount:this.state.messageCount})}async loadSessionHistory(){let{messageCount:e}=await Uae({sessionId:this.sessionId,cwd:this.options.cwd,conversationHistory:this.conversationHistory,model:this.options.model});e>0?this.state.messageCount=e:b.info("[Session Resume] No existing history found for session",{sessionId:this.sessionId,cwd:this.options.cwd})}async compact(){if(this.state.status==="streaming"||this.state.status==="processing")throw new Error("Cannot compact while processing a message");return this.compactionService.compact({sessionId:this.sessionId,conversationHistory:this.conversationHistory,tokenTracker:this.tokenTracker,options:this.options,eventEmitter:this,abortSignal:this.state.abortController?.signal})}async updateModel(e){if(this.state.status==="streaming"||this.state.status==="processing")throw new Error("Cannot change model while processing a message");let n=this.options.model,i=this.isClaudeModel(n),a=this.isClaudeModel(e);this.options.model=e,b.info("Model changed",{sessionId:this.sessionId,oldModel:n,newModel:e,requiresReload:i!==a}),i!==a&&(b.info("Provider change detected, reloading conversation history",{sessionId:this.sessionId,fromProvider:i?"Claude":"OpenAI",toProvider:a?"Claude":"OpenAI"}),this.conversationHistory=new Js(this.sessionId),await this.loadSessionHistory(),this.emit("session-event",{type:gn.UPDATE,sessionId:this.sessionId,data:{role:"system",content:`Model changed from ${n||"default"} to ${e}. History reloaded for compatibility.`,isSystemMessage:!0}}))}isClaudeModel(e){if(!e)return!1;let n=e.toLowerCase();return n.includes("claude")||n.includes("sonnet")||n.includes("opus")||n.includes("haiku")||n.startsWith("claude-")}}});import{randomUUID as KCe}from"crypto";var uf,Lae=F(()=>{"use strict";Mt();lP();uf=class{sessions=new Map;sessionAccessTime=new Map;maxSessions;sessionTimeout;cleanupInterval;constructor(e=10,n=1440*60*1e3){this.maxSessions=e,this.sessionTimeout=n,this.startCleanupInterval(),b.debug("CueSessionManager initialized",{maxSessions:e,sessionTimeout:n})}async getOrCreateSession(e,n={}){if(e){let f=this.sessions.get(e);if(f&&f.isActive())return b.info("Reusing existing live session (HOT RESUME)",{sessionId:e,isHotResume:!0,currentModel:f.getInfo().model,requestedModel:n.model}),this.sessionAccessTime.set(e,new Date),n.model&&n.model!==f.getInfo().model&&(b.info("Model change detected in existing session",{sessionId:e,oldModel:f.getInfo().model,newModel:n.model}),await f.updateModel(n.model)),{session:f,isNew:!1,sessionId:e}}let i=e||KCe(),a=`cue-${Date.now()}-${Math.random().toString(36).substring(2,7)}`,o=e!=null;b.debug(o?"Resuming Cue session from disk (COLD RESUME)":"Creating new Cue session",{sessionId:i,processId:a,isNew:!o,isResumingFromDisk:o}),this.sessions.size>=this.maxSessions&&await this.cleanupOldestSession();let u={...n,sessionId:i},p=new Xh(i,a,u);return n.onMessage&&(p.on("session-message",f=>{n.onMessage(f)}),p.on("partial",f=>{n.onMessage(f)})),this.sessions.set(i,p),this.sessionAccessTime.set(i,new Date),{session:p,isNew:!o,sessionId:i}}async sendMessage(e,n,i=!1){let a=this.sessions.get(e);if(!a)if(i)a=(await this.getOrCreateSession(e)).session;else throw new Error(`No active session found: ${e}`);return this.sessionAccessTime.set(e,new Date),a.sendMessage(n)}async closeSession(e){let n=this.sessions.get(e);n&&(n.close(),this.sessionAccessTime.delete(e),b.debug("Session closed",{sessionId:e}))}async stopSession(e){let n=this.sessions.get(e);n?(n.abort(),b.info("Session stopped (aborted)",{sessionId:e})):b.warn("Cannot stop: session not found",{sessionId:e})}async resetSession(e){let n=this.sessions.get(e);n?(n.close(),this.sessions.delete(e),this.sessionAccessTime.delete(e),b.info("Session reset: closed and removed from memory",{sessionId:e,info:"Session will be recreated on next message"})):b.warn("Cannot reset: session not found",{sessionId:e})}async clearAndResetSession(e,n){let i=this.sessions.get(e),a=n||i?.getInfo().cwd||process.cwd(),{cueSessionPersistence:o}=await Promise.resolve().then(()=>(Pv(),xae));o.clearSessionMessages(e,a)&&b.info("Session messages cleared from disk",{sessionId:e,cwd:a}),i?(i.close(),this.sessions.delete(e),this.sessionAccessTime.delete(e),b.info("Session cleared and reset: messages deleted, session removed from memory",{sessionId:e,cwd:a,info:"Session will start fresh on next message"})):b.info("Session cleared: messages deleted from disk",{sessionId:e,cwd:a,info:"Session was not in memory"})}async deleteSession(e,n=!0){b.info("Deleting session",{sessionId:e,deleteFromDisk:n});let i=this.sessions.get(e);return i&&(i.close(),this.sessions.delete(e),this.sessionAccessTime.delete(e)),!0}async cleanupOldestSession(){let e=new Date,n=null;for(let[i,a]of this.sessionAccessTime.entries())a<e&&(e=a,n=i);n&&(b.info("Cleaning up oldest session due to limit",{sessionId:n,accessTime:e}),await this.closeSession(n))}startCleanupInterval(){this.cleanupInterval=setInterval(async()=>{let e=new Date,n=[];for(let[i,a]of this.sessionAccessTime.entries())e.getTime()-a.getTime()>this.sessionTimeout&&n.push(i);for(let i of n)b.info("Cleaning up expired session",{sessionId:i}),await this.closeSession(i)},6e4)}getActiveSessions(){return Array.from(this.sessions.values()).map(e=>e.getInfo())}getSession(e){return this.sessions.get(e)}async cleanup(){b.debug("Cleaning up all sessions",{count:this.sessions.size}),this.cleanupInterval&&clearInterval(this.cleanupInterval);for(let[,e]of this.sessions.entries())e.close();this.sessions.clear(),this.sessionAccessTime.clear()}}});var Pae=F(()=>{"use strict"});var zae=F(()=>{"use strict";lP();Lae();Pae()});import{readFileSync as jae}from"fs";import{join as $ae,dirname as VCe}from"path";import{fileURLToPath as JCe}from"url";function cP(){try{let t=$ae(Hae,"../../cli/package.json");return JSON.parse(jae(t,"utf-8")).version}catch{try{let t=$ae(Hae,"../package.json");return JSON.parse(jae(t,"utf-8")).version}catch{return"0.0.1"}}}function Gae(){return`Cue-CLI/${cP()} (${process.platform}; Node.js ${process.version})`}var YCe,Hae,qae=F(()=>{"use strict";YCe=JCe(import.meta.url),Hae=VCe(YCe)});var Kae=F(()=>{"use strict"});var D1,Vae=F(()=>{"use strict";D1={text:t=>({type:"text",text:t}),toolUse:(t,e,n)=>({type:"tool_use",id:t,name:e,input:n}),toolCall:(t,e,n)=>({type:"tool_call",id:t,function:{name:e,arguments:n}}),toolMessage:(t,e,n)=>({type:"tool_message",role:t,content:e,tool_call_id:n}),thinking:(t,e)=>({type:"thinking",thinking:t,signature:e}),code:(t,e="plaintext")=>({type:"code",text:t,language:e}),table:t=>({type:"table",markdownText:t}),toolResult:(t,e,n)=>({type:"tool_result",tool_use_id:t,content:e,is_error:n}),getId:(t,e,n)=>{switch(e.type){case"tool_use":return`${t}_${e.id}_${e.type}_${n}`;case"tool_call":return`${t}_${e.id}_${e.type}_${n}`;case"tool_message":return`${t}_${e.tool_call_id}_${e.type}_${n}`;case"tool_result":return`${t}_${e.tool_use_id}_${e.type}_${n}`;default:return`${t}_${e.type}_${n}`}},parseTextContent:t=>{let e=t.trim();if(!e)return[];let n=[],i=e.split(`
|
|
167
167
|
`),a=0;for(;a<i.length;){let o=i[a].trim();if(o.startsWith("```")){let u=o.slice(3).trim()||"plaintext";a++;let p=[];for(;a<i.length&&!i[a].trim().startsWith("```");)p.push(i[a]),a++;n.push(D1.code(p.join(`
|
|
168
168
|
`),u)),a++}else if(o.includes("|")&&o.split("|").length>2){let u=[i[a]];for(a++;a<i.length&&i[a].includes("|");)u.push(i[a]),a++;n.push(D1.table(u.join(`
|
|
169
169
|
`)))}else{let u=[];for(;a<i.length&&!i[a].trim().startsWith("```")&&!(i[a].includes("|")&&i[a].split("|").length>2);)u.push(i[a]),a++;let p=u.join(`
|
|
@@ -609,10 +609,10 @@ Read about how to prevent this error on https://github.com/vadimdemedes/ink/#isr
|
|
|
609
609
|
`)}var xw,yIe,Dj,jce,vIe,$ce,Sw,Pce,zce,CIe,gj,bIe,IIe,Hce=F(()=>{Nce();r0();Lce();xw=new Set(["\x1B","\x9B"]),yIe=39,Dj="\x07",jce="[",vIe="]",$ce="m",Sw=`${vIe}8;;`,Pce=t=>`${xw.values().next().value}${jce}${t}${$ce}`,zce=t=>`${xw.values().next().value}${Sw}${t}${Dj}`,CIe=t=>t.split(" ").map(e=>p0(e)),gj=(t,e,n)=>{let i=[...e],a=!1,o=!1,u=p0(Ws(t.at(-1)));for(let[p,f]of i.entries()){let A=p0(f);if(u+A<=n?t[t.length-1]+=f:(t.push(f),u=0),xw.has(f)&&(a=!0,o=i.slice(p+1,p+1+Sw.length).join("")===Sw),a){o?f===Dj&&(a=!1,o=!1):f===$ce&&(a=!1);continue}u+=A,u===n&&p<i.length-1&&(t.push(""),u=0)}!u&&t.at(-1).length>0&&t.length>1&&(t[t.length-2]+=t.pop())},bIe=t=>{let e=t.split(" "),n=e.length;for(;n>0&&!(p0(e[n-1])>0);)n--;return n===e.length?t:e.slice(0,n).join(" ")+e.slice(n).join("")},IIe=(t,e,n={})=>{if(n.trim!==!1&&t.trim()==="")return"";let i="",a,o,u=CIe(t),p=[""];for(let[E,I]of t.split(" ").entries()){n.trim!==!1&&(p[p.length-1]=p.at(-1).trimStart());let v=p0(p.at(-1));if(E!==0&&(v>=e&&(n.wordWrap===!1||n.trim===!1)&&(p.push(""),v=0),(v>0||n.trim===!1)&&(p[p.length-1]+=" ",v++)),n.hard&&u[E]>e){let x=e-v,w=1+Math.floor((u[E]-x-1)/e);Math.floor((u[E]-1)/e)<w&&p.push(""),gj(p,I,e);continue}if(v+u[E]>e&&v>0&&u[E]>0){if(n.wordWrap===!1&&v<e){gj(p,I,e);continue}p.push("")}if(v+u[E]>e&&n.wordWrap===!1){gj(p,I,e);continue}p[p.length-1]+=I}n.trim!==!1&&(p=p.map(E=>bIe(E)));let f=p.join(`
|
|
610
610
|
`),A=[...f],g=0;for(let[E,I]of A.entries()){if(i+=I,xw.has(I)){let{groups:x}=new RegExp(`(?:\\${jce}(?<code>\\d+)m|\\${Sw}(?<uri>.*)${Dj})`).exec(f.slice(g))||{groups:{}};if(x.code!==void 0){let w=Number.parseFloat(x.code);a=w===yIe?void 0:w}else x.uri!==void 0&&(o=x.uri.length===0?void 0:x.uri)}let v=Mce.codes.get(Number(a));A[E+1]===`
|
|
611
611
|
`?(o&&(i+=zce("")),a&&v&&(i+=Pce(v))):I===`
|
|
612
|
-
`&&(a&&v&&(i+=Pce(a)),o&&(i+=zce(o))),g+=I.length}return i}});var bC,CC,yj,Gce=F(()=>{"use strict";Hce();bC=class t{constructor(e,n=0,i=0){this.measuredText=e;this.selection=i;this.offset=Math.max(0,Math.min(this.measuredText.text.length,n))}offset;static fromText(e,n,i=0,a=0){return new t(new yj(e,n-1),i,a)}render(e,n,i){let{line:a,column:o}=this.getPosition();return this.measuredText.getWrappedText().map((u,p,f)=>{let A=u;if(n&&p===f.length-1){let g=Math.max(0,u.length-6);A=n.repeat(g)+u.slice(g)}return a
|
|
613
|
-
`)}left(){return new t(this.measuredText,this.offset-1)}right(){return new t(this.measuredText,this.offset+1)}up(){let{line:e,column:n}=this.getPosition();if(e
|
|
614
|
-
`?this.modifyText(this.right()):this.modifyText(this.endOfLine())}deleteWordBefore(){return this.isAtStart()?this:this.prevWord().modifyText(this)}deleteWordAfter(){return this.isAtEnd()?this:this.modifyText(this.nextWord())}isOverWordChar(){let e=this.text[this.offset]??"";return/\w/.test(e)}equals(e){return this.offset===e.offset&&this.measuredText
|
|
615
|
-
`);for(let u=0;u<o.length;u++){let p=o[u],f=A=>u
|
|
612
|
+
`&&(a&&v&&(i+=Pce(a)),o&&(i+=zce(o))),g+=I.length}return i}});var bC,CC,yj,Gce=F(()=>{"use strict";Hce();bC=class t{constructor(e,n=0,i=0){this.measuredText=e;this.selection=i;this.offset=Math.max(0,Math.min(this.measuredText.text.length,n))}offset;static fromText(e,n,i=0,a=0){return new t(new yj(e,n-1),i,a)}render(e,n,i){let{line:a,column:o}=this.getPosition();return this.measuredText.getWrappedText().map((u,p,f)=>{let A=u;if(n&&p===f.length-1){let g=Math.max(0,u.length-6);A=n.repeat(g)+u.slice(g)}return a!==p?A.trimEnd():A.slice(0,o)+i(A[o]||e)+A.trimEnd().slice(o+1)}).join(`
|
|
613
|
+
`)}left(){return new t(this.measuredText,this.offset-1)}right(){return new t(this.measuredText,this.offset+1)}up(){let{line:e,column:n}=this.getPosition();if(e===0)return new t(this.measuredText,0,0);let i=this.getOffset({line:e-1,column:n});return new t(this.measuredText,i,0)}down(){let{line:e,column:n}=this.getPosition();if(e>=this.measuredText.lineCount-1)return new t(this.measuredText,this.text.length,0);let i=this.getOffset({line:e+1,column:n});return new t(this.measuredText,i,0)}startOfLine(){let{line:e}=this.getPosition();return new t(this.measuredText,this.getOffset({line:e,column:0}),0)}endOfLine(){let{line:e}=this.getPosition(),n=this.measuredText.getLineLength(e),i=this.getOffset({line:e,column:n});return new t(this.measuredText,i,0)}nextWord(){let e=this;for(;e.isOverWordChar()&&!e.isAtEnd();)e=e.right();for(;!e.isOverWordChar()&&!e.isAtEnd();)e=e.right();return e}prevWord(){let e=this;for(e.left().isOverWordChar()||(e=e.left());!e.isOverWordChar()&&!e.isAtStart();)e=e.left();if(e.isOverWordChar())for(;e.left().isOverWordChar()&&!e.isAtStart();)e=e.left();return e}modifyText(e,n=""){let i=this.offset,a=e.offset,o=this.text.slice(0,i)+n+this.text.slice(a);return t.fromText(o,this.columns,i+n.length)}insert(e){return this.modifyText(this,e)}del(){return this.isAtEnd()?this:this.modifyText(this.right())}backspace(){if(this.isAtStart())return this;let e=this.offset,i=this.left().offset,a=this.text.slice(0,i)+this.text.slice(e);return t.fromText(a,this.columns,i)}deleteToLineStart(){return this.startOfLine().modifyText(this)}deleteToLineEnd(){return this.text[this.offset]===`
|
|
614
|
+
`?this.modifyText(this.right()):this.modifyText(this.endOfLine())}deleteWordBefore(){return this.isAtStart()?this:this.prevWord().modifyText(this)}deleteWordAfter(){return this.isAtEnd()?this:this.modifyText(this.nextWord())}isOverWordChar(){let e=this.text[this.offset]??"";return/\w/.test(e)}equals(e){return this.offset===e.offset&&this.measuredText===e.measuredText}isAtStart(){return this.offset===0}isAtEnd(){return this.offset===this.text.length}get text(){return this.measuredText.text}get columns(){return this.measuredText.columns+1}getPosition(){return this.measuredText.getPositionFromOffset(this.offset)}getOffset(e){return this.measuredText.getOffsetFromPosition(e)}},CC=class{constructor(e,n,i,a=!1){this.text=e;this.startOffset=n;this.isPrecededByNewline=i;this.endsWithNewline=a}equals(e){return this.text===e.text&&this.startOffset===e.startOffset}get length(){return this.text.length+(this.endsWithNewline?1:0)}},yj=class{constructor(e,n){this.text=e;this.columns=n;this.wrappedLines=this.measureWrappedText()}wrappedLines;measureWrappedText(){let e=Ej(this.text,this.columns,{hard:!0,trim:!1}),n=[],i=0,a=-1,o=e.split(`
|
|
615
|
+
`);for(let u=0;u<o.length;u++){let p=o[u],f=A=>u===0||A>0&&this.text[A-1]===`
|
|
616
616
|
`;if(p.length===0)if(a=this.text.indexOf(`
|
|
617
617
|
`,a+1),a!==-1){let A=a,g=!0;n.push(new CC(p,A,f(A),g))}else{let A=this.text.length;n.push(new CC(p,A,f(A),!1))}else{let A=this.text.indexOf(p,i);if(A===-1)throw console.log("Debug: Failed to find wrapped line in original text"),console.log("Debug: Current text:",p),console.log("Debug: Full original text:",this.text),console.log("Debug: Search offset:",i),console.log("Debug: Wrapped text:",e),new Error("Failed to find wrapped line in original text");i=A+p.length;let g=A+p.length,E=g<this.text.length&&this.text[g]===`
|
|
618
618
|
`;E&&(a=g),n.push(new CC(p,A,f(A),E))}}return n}getWrappedText(){return this.wrappedLines.map(e=>e.isPrecededByNewline?e.text:e.text.trimStart())}getLine(e){return this.wrappedLines[Math.max(0,Math.min(e,this.wrappedLines.length-1))]}getOffsetFromPosition(e){let n=this.getLine(e.line),i=n.startOffset+e.column;if(n.text.length===0&&n.endsWithNewline)return n.startOffset;let a=n.startOffset+n.text.length,o=n.endsWithNewline?a+1:a;return Math.min(i,o)}getLineLength(e){let n=this.getLine(e),i=this.getLine(e+1);return i.equals(n)?this.text.length-n.startOffset:i.startOffset-n.startOffset-1}getPositionFromOffset(e){let n=this.wrappedLines;for(let a=0;a<n.length;a++){let o=n[a],u=n[a+1];if(e>=o.startOffset&&(!u||e<u.startOffset)){let p=o.isPrecededByNewline?0:o.text.length-o.text.trimStart().length,f=Math.max(0,Math.min(e-o.startOffset-p,o.text.length));return{line:a,column:f}}}let i=n.length-1;return{line:i,column:this.wrappedLines[i].text.length}}get lineCount(){return this.wrappedLines.length}equals(e){return this.text===e.text&&this.columns===e.columns}}});function qce(t,e){if(e.shift){if(e.meta&&e.leftArrow)return"selectWordLeft";if(e.meta&&e.rightArrow)return"selectWordRight";if(e.ctrl&&t==="a")return"selectToStart";if(e.ctrl&&t==="e")return"selectToEnd";if(e.meta&&t==="b")return"selectToStart";if(e.meta&&t==="f")return"selectToEnd";if(e.leftArrow)return"selectLeft";if(e.rightArrow)return"selectRight"}return e.ctrl&&t==="a"?"moveToStart":e.ctrl&&t==="e"?"moveToEnd":e.meta&&t==="b"?"moveWordLeft":e.meta&&t==="f"?"moveWordRight":e.leftArrow&&!e.meta?"moveLeft":e.rightArrow&&!e.meta?"moveRight":e.backspace||t==="\b"||t==="\x7F"||t==="\b"?"deleteBackward":e.delete||t==="\x1B[3~"||e.ctrl&&t==="d"?"deleteForward":null}var Kce=F(()=>{"use strict"});function Zce({value:t,onChange:e,onSubmit:n,commands:i,onToggleShortcuts:a,onClearShortcuts:o,onCancel:u,isLoading:p=!1,disabled:f=!1}){let[A,g]=(0,$i.useState)([]),[E,I]=(0,$i.useState)(-1),[v,x]=(0,$i.useState)({show:!1}),[w,_]=(0,$i.useState)(t.length),Q=bC.fromText(t,80,w),[R,M]=(0,$i.useState)(null),[z,$]=(0,$i.useState)(null),[re,oe]=(0,$i.useState)(!1),Z=(0,$i.useRef)(!1),[j,J]=(0,$i.useState)(""),H=(0,$i.useRef)(""),te=(0,$i.useRef)(""),xe=(0,$i.useRef)(null),ze=(0,$i.useRef)(Date.now()),[de,ye]=(0,$i.useState)(!1),me=50,Ce=(0,$i.useRef)(0);(0,$i.useEffect)(()=>(process.stdout.write(`${ww}[?2004h`),()=>{process.stdout.write(`${ww}[?2004l`)}),[]);let Xe=(0,$i.useCallback)(je=>{let Yt=je.replace(/\r\n/g,`
|
package/package.json
CHANGED
package/cue-v0.0.41.tar.gz
DELETED
|
Binary file
|