@shumai-one/shumai-agent 0.5.0 → 0.5.2
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/bin/{chunk-7a2w2k8d.js → chunk-099qsxx7.js} +1 -1
- package/bin/{chunk-fzj95ngv.js → chunk-4622htj3.js} +1 -1
- package/bin/{chunk-b442a8p5.js → chunk-5bjq4xfz.js} +1 -1
- package/bin/{chunk-zh89wgq7.js → chunk-5x7t37y2.js} +1 -1
- package/bin/{chunk-nz7zfjn4.js → chunk-dvtetv7g.js} +1 -1
- package/bin/{chunk-hxyaqwyd.js → chunk-esvgx5tp.js} +1 -1
- package/bin/{chunk-ceqg9pm5.js → chunk-gp3pygq4.js} +1 -1
- package/bin/{chunk-ayx6103y.js → chunk-hh1xn96g.js} +1 -1
- package/bin/{chunk-3det6gch.js → chunk-v3m002t2.js} +110 -6
- package/bin/{chunk-w6pgbwev.js → chunk-y25ytsvy.js} +1 -1
- package/bin/{chunk-hvwmzh47.js → chunk-ytemrert.js} +1 -1
- package/bin/shumai-agent-app.js +436 -431
- package/package.json +7 -7
- package/prisma/migrations/20261008134859_add_transcode_3d/migration.sql +2 -0
- package/prisma/schema.prisma +1 -0
- /package/bin/{chunk-zrtmdqst.js → chunk-03afm27e.js} +0 -0
- /package/bin/{chunk-v4qcfyge.js → chunk-04pp5y8r.js} +0 -0
- /package/bin/{chunk-ard58zy1.js → chunk-17krnt1b.js} +0 -0
- /package/bin/{chunk-fx6ftmwf.js → chunk-1pq0fbct.js} +0 -0
- /package/bin/{chunk-h998jkgd.js → chunk-2x49exs8.js} +0 -0
- /package/bin/{chunk-c0yz14s3.js → chunk-5dabj991.js} +0 -0
- /package/bin/{chunk-5rfnm6jw.js → chunk-5tt4cs38.js} +0 -0
- /package/bin/{chunk-87hrcjap.js → chunk-6trcvf7g.js} +0 -0
- /package/bin/{chunk-xss4r7tv.js → chunk-8wfbcygf.js} +0 -0
- /package/bin/{chunk-9y6z8h31.js → chunk-bcyejrnb.js} +0 -0
- /package/bin/{chunk-6r9jnp50.js → chunk-bt74cq3j.js} +0 -0
- /package/bin/{chunk-2tjyjyqp.js → chunk-e56mawh8.js} +0 -0
- /package/bin/{chunk-sc9vspq0.js → chunk-ey92y4db.js} +0 -0
- /package/bin/{chunk-sskw4nqz.js → chunk-fskwwr61.js} +0 -0
- /package/bin/{chunk-gp6c2ra5.js → chunk-h6kmgdqa.js} +0 -0
- /package/bin/{chunk-k1jyx0md.js → chunk-k2e1ywm1.js} +0 -0
- /package/bin/{chunk-0p0qkjs6.js → chunk-nxvssvtc.js} +0 -0
- /package/bin/{chunk-4aq303de.js → chunk-svhmffyd.js} +0 -0
- /package/bin/{chunk-5j6remge.js → chunk-tjhp86sk.js} +0 -0
- /package/bin/{chunk-y8pw01eg.js → chunk-tvaymt9f.js} +0 -0
- /package/bin/{chunk-7nvrknrh.js → chunk-w5ped8e9.js} +0 -0
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ee,Ne,_e,Ge,ke,De,Le,Me}from"./chunk-
|
|
2
|
+
import{Ee,Ne,_e,Ge,ke,De,Le,Me}from"./chunk-03afm27e.js";import{F,Q}from"./chunk-33n9p9q4.js";import{d,B}from"./chunk-xp2anj2s.js";import{Ce}from"./chunk-2vqhhfx4.js";import{I,w,x}from"./shumai-agent-app.js";var S=0,k=(e,a,n)=>{let i=new I;return(async()=>{let t={role:"assistant",content:[],api:"google-generative-ai",provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{let l=n?.apiKey;if(!l)throw Error(`No API key for provider: ${e.provider}`);let s=R(e,l,n?.headers),g=L(e,a,n),p=await n?.onPayload?.(g,e);if(p!==void 0)g=p;let v=await s.models.generateContentStream(g);i.push({type:"start",partial:t});let o=null,b=t.content,u=()=>b.length-1;for await(let c of v){t.responseId||=c.responseId;let f=c.candidates?.[0];if(f?.content?.parts)for(let r of f.content.parts){if(r.text!==void 0){let h=Ne(r);if(!o||h&&o.type!=="thinking"||!h&&o.type!=="text"){if(o)if(o.type==="text")i.push({type:"text_end",contentIndex:b.length-1,content:o.text,partial:t});else i.push({type:"thinking_end",contentIndex:u(),content:o.thinking,partial:t});if(h)o={type:"thinking",thinking:"",thinkingSignature:void 0},t.content.push(o),i.push({type:"thinking_start",contentIndex:u(),partial:t});else o={type:"text",text:""},t.content.push(o),i.push({type:"text_start",contentIndex:u(),partial:t})}if(o.type==="thinking")o.thinking+=r.text,o.thinkingSignature=_e(o.thinkingSignature,r.thoughtSignature),i.push({type:"thinking_delta",contentIndex:u(),delta:r.text,partial:t});else o.text+=r.text,o.textSignature=_e(o.textSignature,r.thoughtSignature),i.push({type:"text_delta",contentIndex:u(),delta:r.text,partial:t})}if(r.functionCall){if(o){if(o.type==="text")i.push({type:"text_end",contentIndex:u(),content:o.text,partial:t});else i.push({type:"thinking_end",contentIndex:u(),content:o.thinking,partial:t});o=null}let h=r.functionCall.id,m={type:"toolCall",id:!h||t.content.some((M)=>M.type==="toolCall"&&M.id===h)?`${r.functionCall.name}_${Date.now()}_${++S}`:h,name:r.functionCall.name||"",arguments:r.functionCall.args??{},...r.thoughtSignature&&{thoughtSignature:r.thoughtSignature}};t.content.push(m),i.push({type:"toolcall_start",contentIndex:u(),partial:t}),i.push({type:"toolcall_delta",contentIndex:u(),delta:JSON.stringify(m.arguments),partial:t}),i.push({type:"toolcall_end",contentIndex:u(),toolCall:m,partial:t})}}if(f?.finishReason){if(t.stopReason=Me(f.finishReason),t.content.some((r)=>r.type==="toolCall"))t.stopReason="toolUse"}if(c.usageMetadata)t.usage={input:(c.usageMetadata.promptTokenCount||0)-(c.usageMetadata.cachedContentTokenCount||0),output:(c.usageMetadata.candidatesTokenCount||0)+(c.usageMetadata.thoughtsTokenCount||0),cacheRead:c.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,reasoning:c.usageMetadata.thoughtsTokenCount||0,totalTokens:c.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},w(e,t.usage)}if(o)if(o.type==="text")i.push({type:"text_end",contentIndex:u(),content:o.text,partial:t});else i.push({type:"thinking_end",contentIndex:u(),content:o.thinking,partial:t});if(n?.signal?.aborted)throw Error("Request was aborted");if(t.stopReason==="aborted"||t.stopReason==="error")throw Error("An unknown error occurred");i.push({type:"done",reason:t.stopReason,message:t}),i.end()}catch(l){for(let s of t.content)if("index"in s)delete s.index;t.stopReason=n?.signal?.aborted?"aborted":"error",t.errorMessage=Q(F(l)),i.push({type:"error",reason:t.stopReason,error:t}),i.end()}})(),i},q=(e,a,n)=>{let i=n?.apiKey;if(!i)throw Error(`No API key for provider: ${e.provider}`);let t=B(e,a,n,i);if(!n?.reasoning)return k(e,a,{...t,thinking:{enabled:!1}});let l=x(e,n.reasoning),s=l==="off"?"high":l,g=e;if(C(g)||T(g)||y(g))return k(e,a,{...t,thinking:{enabled:!0,level:G(s,g)}});return k(e,a,{...t,thinking:{enabled:!0,budgetTokens:P(g,s,n.thinkingBudgets)}})};function R(e,a,n){let i={};if(e.baseUrl)i.baseUrl=e.baseUrl,i.apiVersion="";let t=Ce({...e.headers,...n});if(t)i.headers=t;return new Ee({apiKey:a,httpOptions:Object.keys(i).length>0?i:void 0})}function L(e,a,n={}){let i=Ge(e,a),t={};if(n.temperature!==void 0)t.temperature=n.temperature;if(n.maxTokens!==void 0)t.maxOutputTokens=n.maxTokens;let l=a.tools?.length?Le(a.tools,n.toolChoice,De(e.id)):void 0,s={...Object.keys(t).length>0&&t,...a.systemPrompt&&{systemInstruction:d(a.systemPrompt)},...a.tools&&a.tools.length>0&&{tools:ke(a.tools)},...l!==void 0&&{toolConfig:{functionCallingConfig:{mode:l}}}};if(n.thinking?.enabled&&e.reasoning){let p={includeThoughts:!0};if(n.thinking.level!==void 0)p.thinkingLevel=n.thinking.level;else if(n.thinking.budgetTokens!==void 0)p.thinkingBudget=n.thinking.budgetTokens;s.thinkingConfig=p}else if(e.reasoning&&n.thinking&&!n.thinking.enabled)s.thinkingConfig=_(e);if(n.signal){if(n.signal.aborted)throw Error("Request aborted");s.abortSignal=n.signal}return{model:e.id,contents:i,config:s}}function y(e){return/gemma-?4/.test(e.id.toLowerCase())}function C(e){return/gemini-3(?:\.\d+)?-pro/.test(e.id.toLowerCase())}function T(e){let a=e.id.toLowerCase();return/gemini-3(?:\.\d+)?-flash/.test(a)||a==="gemini-flash-latest"||a==="gemini-flash-lite-latest"}function _(e){if(C(e))return{thinkingLevel:"LOW"};if(T(e))return{thinkingLevel:"MINIMAL"};if(y(e))return{thinkingLevel:"MINIMAL"};return{thinkingBudget:0}}function G(e,a){if(C(a))switch(e){case"minimal":case"low":return"LOW";case"medium":case"high":return"HIGH"}if(y(a))switch(e){case"minimal":case"low":return"MINIMAL";case"medium":case"high":return"HIGH"}switch(e){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH"}}function P(e,a,n){if(n?.[a]!==void 0)return n[a];if(e.id.includes("2.5-pro"))return{minimal:128,low:2048,medium:8192,high:32768}[a];if(e.id.includes("2.5-flash-lite"))return{minimal:512,low:2048,medium:8192,high:24576}[a];if(e.id.includes("2.5-flash"))return{minimal:128,low:2048,medium:8192,high:24576}[a];return-1}export{k as stream,q as streamSimple};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{y}from"./chunk-f913x9vp.js";import"./chunk-xpg34mme.js";import{Ie}from"./chunk-4q9h14c1.js";import{ce,ue,de}from"./chunk-6r9jnp50.js";import{j}from"./chunk-pwagrnm6.js";import{F,Q}from"./chunk-33n9p9q4.js";import{L,B}from"./chunk-xp2anj2s.js";import{U}from"./chunk-2vqhhfx4.js";import{Se,ze,we,I,x,Je}from"./shumai-agent-app.js";var re=new Set;function ne(e){return re.add(e),()=>{re.delete(e)}}function oe(e){let t=e.filter((o)=>o!==void 0);if(t.length===0)return{cleanup:()=>{}};if(t.length===1)return{signal:t[0],cleanup:()=>{}};let r=new AbortController,n=[],s=(o)=>{if(!r.signal.aborted)r.abort(o.reason)};for(let o of t){if(o.aborted){s(o);break}let i=()=>s(o);o.addEventListener("abort",i,{once:!0}),n.push({signal:o,listener:i})}return{signal:r.signal,cleanup:()=>{for(let{signal:o,listener:i}of n)o.removeEventListener("abort",i)}}}var Ce={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function V(e,t){let r=e.toLowerCase(),n=e.toUpperCase();return t?.[r]||t?.[n]||y(r)||y(n)||""}function Oe(e){if(e instanceof URL)return e;try{return new URL(e)}catch{return}}function Ae(e,t,r){let n=V("no_proxy",r).toLowerCase();if(!n)return!0;if(n==="*")return!1;return n.split(/[,\s]/).every((s)=>{if(!s)return!0;let o=s.match(/^(.+):(\d+)$/),i=o?o[1]:s,l=o?Number.parseInt(o[2],10):0;if(l&&l!==t)return!0;if(!/^[.*]/.test(i))return e!==i;if(i.startsWith("*"))i=i.slice(1);return!e.endsWith(i)})}function Le(e,t){let r=Oe(e);if(!r?.protocol||!r.host)return"";let n=r.protocol.split(":",1)[0],s=r.host.replace(/:\d*$/,""),o=Number.parseInt(r.port,10)||Ce[n]||0;if(!Ae(s,o,t))return"";let i=V(`${n}_proxy`,t)||V("all_proxy",t);if(i&&!i.includes("://"))i=`${n}://${i}`;return i}var We="Unsupported proxy protocol. SOCKS and PAC proxy URLs are not supported; use an HTTP or HTTPS proxy URL.";function se(e,t){let r=Le(e,t);if(!r)return;let n;try{n=new URL(r)}catch(s){throw Error(`Invalid proxy URL ${JSON.stringify(r)}: ${s instanceof Error?s.message:String(s)}`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw Error(`${We} Got ${n.protocol}`);return n}function Ne(){if(typeof process>"u"||!(process.versions?.node||process.versions?.bun))return null;return process.getBuiltinModule?.("node:os")??null}var H=Ne(),Pe="https://chatgpt.com/backend-api",Me="https://api.openai.com/auth",De=0,ie=1000,qe=60000,Be=15000,Ue=3,ye=new Set(["openai","openai-codex","opencode"]),$e=1009,Fe="websocket_connection_limit_reached",He="previous_response_not_found",Ke=new Set(["completed","incomplete","failed","cancelled","queued","in_progress"]);function Ge(e){return/GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(e)}function Xe(e,t){if(e===429&&Ge(t))return!1;if(e===429||e===500||e===502||e===503||e===504)return!0;return/rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(t)}function je(e){let t=e.get("retry-after-ms");if(t!==null){let o=Number(t);if(Number.isFinite(o))return Math.max(0,o)}let r=e.get("retry-after");if(!r)return;let n=Number(r);if(Number.isFinite(n))return Math.max(0,n*1000);let s=Date.parse(r);if(!Number.isNaN(s))return Math.max(0,s-Date.now());return}class ee extends Error{}function Ve(e,t){let r=t?.maxRetryDelayMs??qe;if(r>0&&e>r)throw new ee(`Server requested ${Math.ceil(e/1000)}s retry delay (max: ${Math.ceil(r/1000)}s)`);return e}function ae(e,t){return new Promise((r,n)=>{if(t?.aborted){n(Error("Request was aborted"));return}let s=setTimeout(r,e);t?.addEventListener("abort",()=>{clearTimeout(s),n(Error("Request was aborted"))})})}function le(e){if(e===void 0)return;if(!Number.isFinite(e)||e<0)throw Error(`Invalid timeoutMs: ${String(e)}`);return Math.floor(e)}function Ye(){if(typeof process>"u"||!(process.versions?.node||process.versions?.bun))return null;return process.getBuiltinModule?.("node:zlib")??null}function Ze(e){let t=Ye();if(!t||typeof t.zstdCompressSync!=="function")return null;try{let r=t.zstdCompressSync(e,{params:{[t.constants.ZSTD_c_compressionLevel]:Ue}});return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}catch{return null}}var Qe=(e,t,r)=>{let n=new I;return(async()=>{let s={role:"assistant",content:[],api:"openai-codex-responses",provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{let o=r?.apiKey;if(!o)throw Error(`No API key for provider: ${e.provider}`);let i=Ct(o),l=L(t.tools,e.compat?.supportsOpenAIGrammarTools??!1),a=r?.cacheRetention==="none"?void 0:r?.sessionId,c=j(a),d=et(e,t,r,c,l),u=await r?.onPayload?.(d,e);if(u!==void 0)d=u;let S=c||Je(),f=Ot(e.headers,r?.headers,i,o,c),E=At(e.headers,r?.headers,i,o,S),m=JSON.stringify(d),p=le(r?.timeoutMs),C=le(r?.websocketConnectTimeoutMs),b=r?.transport||"auto",w=!1,h=b!=="sse"&&_e(a);if(h)fe(a);if(b!=="sse"&&!h){let g=!1,k=!1,A=!1;while(!0){g=!1;try{if(await xt(rt(e.baseUrl),d,E,s,n,e,()=>{if(g=!0,!w)w=!0,n.push({type:"start",partial:s})},p,C,a,l,r),r?.signal?.aborted)throw Error("Request was aborted");n.push({type:"done",reason:s.stopReason,message:s}),n.end();return}catch(R){let D=r?.signal?.aborted,q=!g&&st(R),N=it(R);if(!D&&N&&!A){A=!0;continue}if(!D&&q&&!k){k=!0;continue}if(D||ot(R)&&!q)throw R;if(we(s,ze("provider_transport_failure",R,{configuredTransport:b,fallbackTransport:g?void 0:"sse",eventsEmitted:g,phase:g?"after_message_stream_start":"before_message_stream_start",requestBytes:new TextEncoder().encode(m).byteLength})),mt(a,R),g)throw R;fe(a);break}}}let O=Ze(m);if(O)f.set("content-encoding","zstd");let W=O??m,_,M,X=r?.maxRetries??De;for(let g=0;g<=X;g++){if(r?.signal?.aborted)throw Error("Request was aborted");try{let k=p!==void 0&&p>0?AbortSignal.timeout(p):void 0,A=oe([r?.signal,k]);try{_=await fetch(ge(e.baseUrl),{method:"POST",headers:f,body:W,signal:A.signal})}catch(N){if(k?.aborted&&!r?.signal?.aborted)throw Error(`Codex SSE response headers timed out after ${p}ms`);throw N}finally{A.cleanup()}if(await r?.onResponse?.({status:_.status,headers:U(_.headers)},e),_.ok)break;let R=await _.text();if(g<X&&Xe(_.status,R)){let N=je(_.headers),ve=N===void 0?ie*2**g:Ve(N,r);await ae(ve,r?.signal);continue}let D=new Response(R,{status:_.status,statusText:_.statusText}),q=await vt(D);throw Error(q.friendlyMessage||q.message)}catch(k){if(k instanceof Error){if(k.name==="AbortError"||k.message==="Request was aborted")throw Error("Request was aborted")}if(M=k instanceof Error?k:Error(String(k)),g<X&&!(M instanceof ee)&&!M.message.includes("usage limit")){let A=ie*2**g;await ae(A,r?.signal);continue}throw M}}if(!_?.ok)throw M??Error("Failed after retries");if(!_.body)throw Error("No response body");if(!w)w=!0,n.push({type:"start",partial:s});if(await nt(_,s,n,e,l,r),r?.signal?.aborted)throw Error("Request was aborted");n.push({type:"done",reason:s.stopReason,message:s}),n.end()}catch(o){for(let i of s.content)delete i.partialJson,delete i.customInput;s.stopReason=r?.signal?.aborted?"aborted":"error",s.errorMessage=Q(F(o)),n.push({type:"error",reason:s.stopReason,error:s}),n.end()}})(),n},jt=(e,t,r)=>{let n=r?.apiKey;if(!n)throw Error(`No API key for provider: ${e.provider}`);let s=B(e,t,r,n),o=r?.reasoning?x(e,r.reasoning):void 0;return Qe(e,t,{...s,reasoningEffort:o==="off"?void 0:o})};function et(e,t,r,n,s=L(t.tools,e.compat?.supportsOpenAIGrammarTools??!1)){let o=e.compat?.supportsStrictMode??!0,i=e.compat?.supportsOpenAIGrammarTools??!1,l=Ie(t,e.compat?.supportsToolSearch??!1),a=ce(e,t,ye,{includeSystemPrompt:!1,grammarToolInputProperties:s,deferredTools:l.deferred,toolOptions:{strict:null,supportsStrictMode:o,supportsOpenAIGrammarTools:i}}),c={model:e.id,store:!1,stream:!0,instructions:t.systemPrompt||"You are a helpful assistant.",input:a,text:{verbosity:r?.textVerbosity||"low"},include:["reasoning.encrypted_content"],prompt_cache_key:n,tool_choice:r?.toolChoice??"auto",parallel_tool_calls:!0};if(r?.temperature!==void 0)c.temperature=r.temperature;if(r?.serviceTier!==void 0)c.service_tier=r.serviceTier;if(l.immediate.length>0)c.tools=ue(l.immediate,{strict:null,supportsStrictMode:o,supportsOpenAIGrammarTools:i});if(r?.reasoningEffort!==void 0){let d=r.reasoningEffort==="none"?e.thinkingLevelMap?.off??"none":e.thinkingLevelMap?.[r.reasoningEffort]??r.reasoningEffort;if(d!==null)c.reasoning={effort:d,summary:r.reasoningSummary??"auto"}}return c}function tt(e,t){switch(t){case"flex":return 0.5;case"priority":return e.id==="gpt-5.5"?2.5:2;default:return 1}}function be(e,t,r){let n=tt(r,t);if(n===1)return;e.cost.input*=n,e.cost.output*=n,e.cost.cacheRead*=n,e.cost.cacheWrite*=n,e.cost.total=e.cost.input+e.cost.output+e.cost.cacheRead+e.cost.cacheWrite}function he(e,t){if(e==="default"&&(t==="flex"||t==="priority"))return t;return e??t}function ge(e){let r=(e&&e.trim().length>0?e:Pe).replace(/\/+$/,"");if(r.endsWith("/codex/responses"))return r;if(r.endsWith("/codex"))return`${r}/responses`;return`${r}/codex/responses`}function rt(e){let t=new URL(ge(e));if(t.protocol==="https:")t.protocol="wss:";if(t.protocol==="http:")t.protocol="ws:";return t.toString()}async function nt(e,t,r,n,s,o){await de(Ee(ut(e,o?.signal)),t,r,n,{serviceTier:o?.serviceTier,grammarToolInputProperties:s,resolveServiceTier:he,applyServiceTierPricing:(i,l)=>be(i,l,n)})}class P extends Error{code;payload;constructor(e,t){super(e);this.name="CodexApiError",this.code=t?.code,this.payload=t?.payload,this.cause=t?.cause}}class z extends Error{payload;constructor(e,t){super(e);this.name="CodexProtocolError",this.payload=t?.payload,this.cause=t?.cause}}function ot(e){return e instanceof P||e instanceof z}function st(e){return e instanceof P&&e.code===Fe}function it(e){return e instanceof P&&e.code===He}function at(e){let t=e.error&&typeof e.error==="object"?e.error:void 0;return{code:typeof e.code==="string"?e.code:typeof t?.code==="string"?t.code:void 0,message:typeof e.message==="string"?e.message:typeof t?.message==="string"?t.message:void 0}}async function*Ee(e){for await(let t of e){let r=typeof t.type==="string"?t.type:void 0;if(!r)continue;if(r==="error"){let{code:n,message:s}=at(t);throw new P(`Codex error: ${s||n||JSON.stringify(t)}`,{code:n,payload:t})}if(r==="response.failed"){let n=t.response,s=n?.error?.code,o=n?.error?.message;throw new P(o||"Codex response failed",{code:s,payload:t})}if(r==="response.done"||r==="response.completed"||r==="response.incomplete"){let n=t.response,s=n?{...n,status:ct(n.status)}:n;yield{...t,type:"response.completed",response:s};return}yield t}}function ct(e){if(typeof e!=="string")return;return Ke.has(e)?e:void 0}async function*ut(e,t){if(!e.body)return;let r=e.body.getReader(),n=new TextDecoder,s="",o=()=>{r.cancel().catch(()=>{})};t?.addEventListener("abort",o,{once:!0});try{while(!0){if(t?.aborted)throw Error("Request was aborted");let{done:i,value:l}=await r.read();if(t?.aborted)throw Error("Request was aborted");if(i)break;s+=n.decode(l,{stream:!0});let a=s.indexOf(`
|
|
2
|
+
import{y}from"./chunk-f913x9vp.js";import"./chunk-xpg34mme.js";import{Ie}from"./chunk-4q9h14c1.js";import{ce,ue,de}from"./chunk-bt74cq3j.js";import{j}from"./chunk-pwagrnm6.js";import{F,Q}from"./chunk-33n9p9q4.js";import{L,B}from"./chunk-xp2anj2s.js";import{U}from"./chunk-2vqhhfx4.js";import{Se,ze,we,I,x,Je}from"./shumai-agent-app.js";var re=new Set;function ne(e){return re.add(e),()=>{re.delete(e)}}function oe(e){let t=e.filter((o)=>o!==void 0);if(t.length===0)return{cleanup:()=>{}};if(t.length===1)return{signal:t[0],cleanup:()=>{}};let r=new AbortController,n=[],s=(o)=>{if(!r.signal.aborted)r.abort(o.reason)};for(let o of t){if(o.aborted){s(o);break}let i=()=>s(o);o.addEventListener("abort",i,{once:!0}),n.push({signal:o,listener:i})}return{signal:r.signal,cleanup:()=>{for(let{signal:o,listener:i}of n)o.removeEventListener("abort",i)}}}var Ce={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function V(e,t){let r=e.toLowerCase(),n=e.toUpperCase();return t?.[r]||t?.[n]||y(r)||y(n)||""}function Oe(e){if(e instanceof URL)return e;try{return new URL(e)}catch{return}}function Ae(e,t,r){let n=V("no_proxy",r).toLowerCase();if(!n)return!0;if(n==="*")return!1;return n.split(/[,\s]/).every((s)=>{if(!s)return!0;let o=s.match(/^(.+):(\d+)$/),i=o?o[1]:s,l=o?Number.parseInt(o[2],10):0;if(l&&l!==t)return!0;if(!/^[.*]/.test(i))return e!==i;if(i.startsWith("*"))i=i.slice(1);return!e.endsWith(i)})}function Le(e,t){let r=Oe(e);if(!r?.protocol||!r.host)return"";let n=r.protocol.split(":",1)[0],s=r.host.replace(/:\d*$/,""),o=Number.parseInt(r.port,10)||Ce[n]||0;if(!Ae(s,o,t))return"";let i=V(`${n}_proxy`,t)||V("all_proxy",t);if(i&&!i.includes("://"))i=`${n}://${i}`;return i}var We="Unsupported proxy protocol. SOCKS and PAC proxy URLs are not supported; use an HTTP or HTTPS proxy URL.";function se(e,t){let r=Le(e,t);if(!r)return;let n;try{n=new URL(r)}catch(s){throw Error(`Invalid proxy URL ${JSON.stringify(r)}: ${s instanceof Error?s.message:String(s)}`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw Error(`${We} Got ${n.protocol}`);return n}function Ne(){if(typeof process>"u"||!(process.versions?.node||process.versions?.bun))return null;return process.getBuiltinModule?.("node:os")??null}var H=Ne(),Pe="https://chatgpt.com/backend-api",Me="https://api.openai.com/auth",De=0,ie=1000,qe=60000,Be=15000,Ue=3,ye=new Set(["openai","openai-codex","opencode"]),$e=1009,Fe="websocket_connection_limit_reached",He="previous_response_not_found",Ke=new Set(["completed","incomplete","failed","cancelled","queued","in_progress"]);function Ge(e){return/GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(e)}function Xe(e,t){if(e===429&&Ge(t))return!1;if(e===429||e===500||e===502||e===503||e===504)return!0;return/rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(t)}function je(e){let t=e.get("retry-after-ms");if(t!==null){let o=Number(t);if(Number.isFinite(o))return Math.max(0,o)}let r=e.get("retry-after");if(!r)return;let n=Number(r);if(Number.isFinite(n))return Math.max(0,n*1000);let s=Date.parse(r);if(!Number.isNaN(s))return Math.max(0,s-Date.now());return}class ee extends Error{}function Ve(e,t){let r=t?.maxRetryDelayMs??qe;if(r>0&&e>r)throw new ee(`Server requested ${Math.ceil(e/1000)}s retry delay (max: ${Math.ceil(r/1000)}s)`);return e}function ae(e,t){return new Promise((r,n)=>{if(t?.aborted){n(Error("Request was aborted"));return}let s=setTimeout(r,e);t?.addEventListener("abort",()=>{clearTimeout(s),n(Error("Request was aborted"))})})}function le(e){if(e===void 0)return;if(!Number.isFinite(e)||e<0)throw Error(`Invalid timeoutMs: ${String(e)}`);return Math.floor(e)}function Ye(){if(typeof process>"u"||!(process.versions?.node||process.versions?.bun))return null;return process.getBuiltinModule?.("node:zlib")??null}function Ze(e){let t=Ye();if(!t||typeof t.zstdCompressSync!=="function")return null;try{let r=t.zstdCompressSync(e,{params:{[t.constants.ZSTD_c_compressionLevel]:Ue}});return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}catch{return null}}var Qe=(e,t,r)=>{let n=new I;return(async()=>{let s={role:"assistant",content:[],api:"openai-codex-responses",provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{let o=r?.apiKey;if(!o)throw Error(`No API key for provider: ${e.provider}`);let i=Ct(o),l=L(t.tools,e.compat?.supportsOpenAIGrammarTools??!1),a=r?.cacheRetention==="none"?void 0:r?.sessionId,c=j(a),d=et(e,t,r,c,l),u=await r?.onPayload?.(d,e);if(u!==void 0)d=u;let S=c||Je(),f=Ot(e.headers,r?.headers,i,o,c),E=At(e.headers,r?.headers,i,o,S),m=JSON.stringify(d),p=le(r?.timeoutMs),C=le(r?.websocketConnectTimeoutMs),b=r?.transport||"auto",w=!1,h=b!=="sse"&&_e(a);if(h)fe(a);if(b!=="sse"&&!h){let g=!1,k=!1,A=!1;while(!0){g=!1;try{if(await xt(rt(e.baseUrl),d,E,s,n,e,()=>{if(g=!0,!w)w=!0,n.push({type:"start",partial:s})},p,C,a,l,r),r?.signal?.aborted)throw Error("Request was aborted");n.push({type:"done",reason:s.stopReason,message:s}),n.end();return}catch(R){let D=r?.signal?.aborted,q=!g&&st(R),N=it(R);if(!D&&N&&!A){A=!0;continue}if(!D&&q&&!k){k=!0;continue}if(D||ot(R)&&!q)throw R;if(we(s,ze("provider_transport_failure",R,{configuredTransport:b,fallbackTransport:g?void 0:"sse",eventsEmitted:g,phase:g?"after_message_stream_start":"before_message_stream_start",requestBytes:new TextEncoder().encode(m).byteLength})),mt(a,R),g)throw R;fe(a);break}}}let O=Ze(m);if(O)f.set("content-encoding","zstd");let W=O??m,_,M,X=r?.maxRetries??De;for(let g=0;g<=X;g++){if(r?.signal?.aborted)throw Error("Request was aborted");try{let k=p!==void 0&&p>0?AbortSignal.timeout(p):void 0,A=oe([r?.signal,k]);try{_=await fetch(ge(e.baseUrl),{method:"POST",headers:f,body:W,signal:A.signal})}catch(N){if(k?.aborted&&!r?.signal?.aborted)throw Error(`Codex SSE response headers timed out after ${p}ms`);throw N}finally{A.cleanup()}if(await r?.onResponse?.({status:_.status,headers:U(_.headers)},e),_.ok)break;let R=await _.text();if(g<X&&Xe(_.status,R)){let N=je(_.headers),ve=N===void 0?ie*2**g:Ve(N,r);await ae(ve,r?.signal);continue}let D=new Response(R,{status:_.status,statusText:_.statusText}),q=await vt(D);throw Error(q.friendlyMessage||q.message)}catch(k){if(k instanceof Error){if(k.name==="AbortError"||k.message==="Request was aborted")throw Error("Request was aborted")}if(M=k instanceof Error?k:Error(String(k)),g<X&&!(M instanceof ee)&&!M.message.includes("usage limit")){let A=ie*2**g;await ae(A,r?.signal);continue}throw M}}if(!_?.ok)throw M??Error("Failed after retries");if(!_.body)throw Error("No response body");if(!w)w=!0,n.push({type:"start",partial:s});if(await nt(_,s,n,e,l,r),r?.signal?.aborted)throw Error("Request was aborted");n.push({type:"done",reason:s.stopReason,message:s}),n.end()}catch(o){for(let i of s.content)delete i.partialJson,delete i.customInput;s.stopReason=r?.signal?.aborted?"aborted":"error",s.errorMessage=Q(F(o)),n.push({type:"error",reason:s.stopReason,error:s}),n.end()}})(),n},jt=(e,t,r)=>{let n=r?.apiKey;if(!n)throw Error(`No API key for provider: ${e.provider}`);let s=B(e,t,r,n),o=r?.reasoning?x(e,r.reasoning):void 0;return Qe(e,t,{...s,reasoningEffort:o==="off"?void 0:o})};function et(e,t,r,n,s=L(t.tools,e.compat?.supportsOpenAIGrammarTools??!1)){let o=e.compat?.supportsStrictMode??!0,i=e.compat?.supportsOpenAIGrammarTools??!1,l=Ie(t,e.compat?.supportsToolSearch??!1),a=ce(e,t,ye,{includeSystemPrompt:!1,grammarToolInputProperties:s,deferredTools:l.deferred,toolOptions:{strict:null,supportsStrictMode:o,supportsOpenAIGrammarTools:i}}),c={model:e.id,store:!1,stream:!0,instructions:t.systemPrompt||"You are a helpful assistant.",input:a,text:{verbosity:r?.textVerbosity||"low"},include:["reasoning.encrypted_content"],prompt_cache_key:n,tool_choice:r?.toolChoice??"auto",parallel_tool_calls:!0};if(r?.temperature!==void 0)c.temperature=r.temperature;if(r?.serviceTier!==void 0)c.service_tier=r.serviceTier;if(l.immediate.length>0)c.tools=ue(l.immediate,{strict:null,supportsStrictMode:o,supportsOpenAIGrammarTools:i});if(r?.reasoningEffort!==void 0){let d=r.reasoningEffort==="none"?e.thinkingLevelMap?.off??"none":e.thinkingLevelMap?.[r.reasoningEffort]??r.reasoningEffort;if(d!==null)c.reasoning={effort:d,summary:r.reasoningSummary??"auto"}}return c}function tt(e,t){switch(t){case"flex":return 0.5;case"priority":return e.id==="gpt-5.5"?2.5:2;default:return 1}}function be(e,t,r){let n=tt(r,t);if(n===1)return;e.cost.input*=n,e.cost.output*=n,e.cost.cacheRead*=n,e.cost.cacheWrite*=n,e.cost.total=e.cost.input+e.cost.output+e.cost.cacheRead+e.cost.cacheWrite}function he(e,t){if(e==="default"&&(t==="flex"||t==="priority"))return t;return e??t}function ge(e){let r=(e&&e.trim().length>0?e:Pe).replace(/\/+$/,"");if(r.endsWith("/codex/responses"))return r;if(r.endsWith("/codex"))return`${r}/responses`;return`${r}/codex/responses`}function rt(e){let t=new URL(ge(e));if(t.protocol==="https:")t.protocol="wss:";if(t.protocol==="http:")t.protocol="ws:";return t.toString()}async function nt(e,t,r,n,s,o){await de(Ee(ut(e,o?.signal)),t,r,n,{serviceTier:o?.serviceTier,grammarToolInputProperties:s,resolveServiceTier:he,applyServiceTierPricing:(i,l)=>be(i,l,n)})}class P extends Error{code;payload;constructor(e,t){super(e);this.name="CodexApiError",this.code=t?.code,this.payload=t?.payload,this.cause=t?.cause}}class z extends Error{payload;constructor(e,t){super(e);this.name="CodexProtocolError",this.payload=t?.payload,this.cause=t?.cause}}function ot(e){return e instanceof P||e instanceof z}function st(e){return e instanceof P&&e.code===Fe}function it(e){return e instanceof P&&e.code===He}function at(e){let t=e.error&&typeof e.error==="object"?e.error:void 0;return{code:typeof e.code==="string"?e.code:typeof t?.code==="string"?t.code:void 0,message:typeof e.message==="string"?e.message:typeof t?.message==="string"?t.message:void 0}}async function*Ee(e){for await(let t of e){let r=typeof t.type==="string"?t.type:void 0;if(!r)continue;if(r==="error"){let{code:n,message:s}=at(t);throw new P(`Codex error: ${s||n||JSON.stringify(t)}`,{code:n,payload:t})}if(r==="response.failed"){let n=t.response,s=n?.error?.code,o=n?.error?.message;throw new P(o||"Codex response failed",{code:s,payload:t})}if(r==="response.done"||r==="response.completed"||r==="response.incomplete"){let n=t.response,s=n?{...n,status:ct(n.status)}:n;yield{...t,type:"response.completed",response:s};return}yield t}}function ct(e){if(typeof e!=="string")return;return Ke.has(e)?e:void 0}async function*ut(e,t){if(!e.body)return;let r=e.body.getReader(),n=new TextDecoder,s="",o=()=>{r.cancel().catch(()=>{})};t?.addEventListener("abort",o,{once:!0});try{while(!0){if(t?.aborted)throw Error("Request was aborted");let{done:i,value:l}=await r.read();if(t?.aborted)throw Error("Request was aborted");if(i)break;s+=n.decode(l,{stream:!0});let a=s.indexOf(`
|
|
3
3
|
|
|
4
4
|
`);while(a!==-1){let c=s.slice(0,a);s=s.slice(a+2);let d=c.split(`
|
|
5
5
|
`).filter((u)=>u.startsWith("data:")).map((u)=>u.slice(5).trim());if(d.length>0){let u=d.join(`
|