@tbox.cn/tboxcode-dsh-sdk 0.1.0-rc.14 → 0.1.0-rc.16
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/lib/embedded.d.ts +2 -2
- package/lib/embedded.js +1 -1
- package/lib/index.d.ts +17 -0
- package/lib/index.js +56 -2
- package/package.json +4 -4
package/lib/embedded.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { SharedAcpCore, SharedConnection, createSharedAcpCore } from "@tbox.cn/dsh-acp-full";
|
|
1
|
+
import { IMAGE_PAYLOAD_BUDGET, ImageRenderOptions, ImageRenderState, RenderImageBytes, SharedAcpCore, SharedConnection, createSharedAcpCore } from "@tbox.cn/dsh-acp-full";
|
|
2
2
|
import { AskUserQuestionItemLike, SubagentCatalogState, ToolJournal, agentCapabilities, buildElicitationSchema, projectRecord, stopReasonFromTurnEnd } from "@tbox.cn/dsh-acp-bridge-core";
|
|
3
3
|
import { LlmConfigSchema, TboxcodeDshModelTraits } from "@tbox.cn/tboxcode-dsh-llm";
|
|
4
|
-
export { type AskUserQuestionItemLike, LlmConfigSchema, type SharedAcpCore, type SharedConnection, SubagentCatalogState, type TboxcodeDshModelTraits, ToolJournal, agentCapabilities, buildElicitationSchema, createSharedAcpCore, projectRecord, stopReasonFromTurnEnd };
|
|
4
|
+
export { type AskUserQuestionItemLike, IMAGE_PAYLOAD_BUDGET, type ImageRenderOptions, ImageRenderState, LlmConfigSchema, type RenderImageBytes, type SharedAcpCore, type SharedConnection, SubagentCatalogState, type TboxcodeDshModelTraits, ToolJournal, agentCapabilities, buildElicitationSchema, createSharedAcpCore, projectRecord, stopReasonFromTurnEnd };
|
package/lib/embedded.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createSharedAcpCore as
|
|
1
|
+
import{IMAGE_PAYLOAD_BUDGET as e,ImageRenderState as t,createSharedAcpCore as n}from"@tbox.cn/dsh-acp-full";import{SubagentCatalogState as r,ToolJournal as i,agentCapabilities as a,buildElicitationSchema as o,projectRecord as s,stopReasonFromTurnEnd as c}from"@tbox.cn/dsh-acp-bridge-core";import{LlmConfigSchema as l}from"@tbox.cn/tboxcode-dsh-llm";export{e as IMAGE_PAYLOAD_BUDGET,t as ImageRenderState,l as LlmConfigSchema,r as SubagentCatalogState,i as ToolJournal,a as agentCapabilities,o as buildElicitationSchema,n as createSharedAcpCore,s as projectRecord,c as stopReasonFromTurnEnd};
|
package/lib/index.d.ts
CHANGED
|
@@ -529,6 +529,23 @@ declare class RpcSessionDeps implements SessionDeps {
|
|
|
529
529
|
};
|
|
530
530
|
readonly llm: LlmCatalogDeps;
|
|
531
531
|
admitPromptContent(parts: Parameters<NonNullable<SessionDeps['admitPromptContent']>>[0]): Promise<Awaited<ReturnType<NonNullable<SessionDeps['admitPromptContent']>>>>;
|
|
532
|
+
/**
|
|
533
|
+
* 图片 URL 准入(载体二):RPC 抵达 dsh 侧同一服务(抓取 + 归一化 + 出处记录),
|
|
534
|
+
* 回传归一化字节与内容寻址 id;桥把字节放进 session/prompt,dsh 二次准入因
|
|
535
|
+
* 直通谓词而 digest 相同(同一次 prompt 内归一化策略一致)。
|
|
536
|
+
*
|
|
537
|
+
* 错误面:RemoteError 一律归一化为 invalidParams——bridge 的 prompt 捕获只
|
|
538
|
+
* 透传 RequestError,其余会变成 internal(对用户不可诊断)。
|
|
539
|
+
*/
|
|
540
|
+
admitImageUrls(sessionId: string, urls: readonly string[], opts?: {
|
|
541
|
+
readonly signal?: AbortSignal;
|
|
542
|
+
readonly names?: readonly (string | undefined)[];
|
|
543
|
+
}): Promise<Awaited<ReturnType<NonNullable<SessionDeps['admitImageUrls']>>>>;
|
|
544
|
+
/** 历史回显读字节(载体二):失败一律 undefined(降级占位,不中断回放)。 */
|
|
545
|
+
readImage(_sessionId: string, attachment: unknown): Promise<{
|
|
546
|
+
mediaType: string;
|
|
547
|
+
data: string;
|
|
548
|
+
} | undefined>;
|
|
532
549
|
applyModeKnobs(session: SessionLike, _agent: AgentLike, knobs: ModeKnobs): void | Promise<void>;
|
|
533
550
|
defaultSelection(): ConfigModelSelection | undefined;
|
|
534
551
|
executeCommand(agent: AgentLike, line: string, _signal?: AbortSignal): Promise<{
|
package/lib/index.js
CHANGED
|
@@ -1,5 +1,59 @@
|
|
|
1
1
|
import{MODE_TABLE as e,classify as t,isIgnorable as n}from"@tbox.cn/dsh-acp-bridge-core";import{spawn as r}from"node:child_process";import{randomUUID as i}from"node:crypto";import a,{WebSocketServer as o}from"ws";var s=class extends Error{kind;report;constructor(e,t,n){super(t),this.name=`SupervisorDeploymentError`,this.kind=e,this.report=n}};function c(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!=`object`||!t||Array.isArray(t))return null;let n=t;return n.v===1&&(n.event===`standby`||n.event===`ready`&&typeof n.port==`number`&&typeof n.token==`string`)?t:null}async function l(e,t){let n=await fetch(`http://127.0.0.1:${e}/connect?token=${encodeURIComponent(t)}&interactions=answer`,{redirect:`manual`});if(n.status!==302)throw Error(`/connect 凭据交换期待 302,实得 ${n.status}(port ${e})`);let r=n.headers.get(`set-cookie`);if(r===null)throw Error(`/connect 凭据交换缺 Set-Cookie`);let i=r.split(`;`)[0]??``;if(i===``)throw Error(`/connect 凭据交换缺 Set-Cookie`);return i}function u(e){return e.replace(/((?:token|access_token|refresh_token|cookie|authorization)=)[^&\s]+/gi,`$1[REDACTED]`).replace(/((?:authorization|cookie):\s*)[^\n]+/gi,`$1[REDACTED]`)}var d=class{#e;#t;#n;#r;#i=`idle`;#a=[];#o;#s=!1;#c=!1;#l=0;#u=[];#d=[];#f=[];#p=[];#m;#h=0;#g=[];#_=!1;#v;constructor(e={},t,n){this.#e={startMode:`immediate`,readyTimeoutMs:12e4,backoffBaseMs:1e3,backoffMaxMs:5e3,maxRestartAttempts:3,ringBufferLines:1e3,...e},this.#t=t??f(e),this.#n=n??l,this.#r=e.log??(()=>{})}phase(){return this.#i}onPhaseChange(e){return this.#a.push(e),()=>{this.#a=this.#a.filter(t=>t!==e)}}onStderrLine(e){return this.#p.push(e),()=>{this.#p=this.#p.filter(t=>t!==e)}}async start(){if(this.#i!==`idle`)throw Error(`Supervisor.start 仅 idle 态可调(当前 ${this.#i})`);this.#T(),await this.#S()}async connect(){this.#b(),this.#s=!0,this.#i===`standby`&&!this.#c&&this.#e.startMode===`on-first-connection`&&this.#O(),this.#i!==`ready`&&await this.#S();let e=this.#m;if(e!==void 0&&e.generation===this.#h)return e;let t=this.#y;if(t===void 0)throw Error(`ready 凭据缺席(状态机时序违例)`);let n=await this.#n(t.port,t.token),r={baseUrl:`http://127.0.0.1:${t.port}`,cookie:n,port:t.port,generation:this.#h};return this.#m=r,this.#r(`凭据交换完成(generation ${this.#h},port ${t.port})`),r}async reconnect(){this.#b(),this.#i!==`ready`&&await this.#S();let e=this.#y;if(e===void 0)throw Error(`ready 凭据缺席(状态机时序违例)`);let t=await this.#n(e.port,e.token),n={baseUrl:`http://127.0.0.1:${e.port}`,cookie:t,port:e.port,generation:this.#h};return this.#m=n,this.#r(`凭据再交换完成(generation ${this.#h},port ${e.port})`),n}crashReport(){return[`phase=${this.#i} restarts=${this.#l} generation=${this.#h}`,`exitCodes=${JSON.stringify(this.#u)}`,`phaseHistory=${this.#d.join(` → `)}`,`stderr(环形缓冲尾部 ${this.#f.length} 行):`,...this.#f.map(e=>` ${e}`)].join(`
|
|
2
2
|
`)}async dispose(){if(this.#_)return;this.#_=!0,this.#v=void 0;let e=this.#o;e!==void 0&&(e.kill(`SIGTERM`),await new Promise(t=>{let n=setTimeout(()=>{e.kill(`SIGKILL`),t()},3e3);e.onExit(()=>{clearTimeout(n),t()})})),this.#w(Error(`Supervisor 已停机`)),this.#x(`disposed`)}#y;#b(){if(this.#_)throw Error(`Supervisor 已停机`);if(this.#i===`idle`)throw Error(`先调用 start()(connect 挂靠 spawn 生命周期)`);if(this.#v!==void 0)throw this.#v.error;if(this.#i===`failed-permanent`||this.#i===`failed-protocol`)throw new s(this.#i===`failed-permanent`?`permanent`:`protocol`,`Supervisor 终态 ${this.#i}`,this.crashReport())}#x(e){this.#i=e,this.#d.push(`${e}@${Date.now()}`),this.#a.forEach(t=>t(e))}#S(){return this.#i===`ready`?Promise.resolve():new Promise((e,t)=>{this.#g.push({generation:this.#h,resolve:e,reject:t})})}#C(){this.#g.splice(0).forEach(e=>e.resolve())}#w(e){this.#g.splice(0).forEach(t=>t.reject(e))}async#T(){for(;;){if(this.#_)return;if(await this.#D(),this.#v!==void 0){this.#x(this.#v.kind===`protocol`?`failed-protocol`:`failed-permanent`);return}return}}#E(e){if(this.#_)return;if(this.#l+=1,this.#l>this.#e.maxRestartAttempts){this.#v={kind:`permanent`,error:new s(`exhausted`,`崩溃退避序列耗尽(${this.#e.maxRestartAttempts} 次)——最后原因:${e}`,this.crashReport())},this.#x(`failed-permanent`),this.#w(this.#v.error);return}let t=Math.min(this.#e.backoffBaseMs*2**(this.#l-1),this.#e.backoffMaxMs);this.#x(`restarting`),this.#r(`瞬时失败(${e})——${t}ms 后第 ${this.#l} 次重启`),setTimeout(()=>{this.#_||this.#D().then(()=>{this.#v!==void 0&&(this.#x(this.#v.kind===`protocol`?`failed-protocol`:`failed-permanent`),this.#w(this.#v.error))})},t)}async#D(){this.#h+=1,this.#m=void 0,this.#c=!1,this.#y=void 0;let e=this.#h;this.#x(`booting`);let t=this.#e.command??[`tboxcode-dsh`],n=this.#t([...t,`server`]);this.#o=n;let r=!1,i;clearTimeout(i),i=setTimeout(()=>{this.#h!==e||this.#i===`ready`||(this.#r(`就绪确认超时——kill 子进程(瞬时面)`),n.kill(`SIGKILL`))},this.#e.readyTimeoutMs),n.onStdoutLine(t=>{if(this.#h!==e)return;let a=c(t);if(!r){if(a===null||a.event!==`standby`){this.#v={kind:`protocol`,error:new s(`protocol`,`首行校验失败(期待 standby 信封,实得 "${t.slice(0,80)}")`,this.crashReport())},this.#x(`failed-protocol`),this.#w(this.#v.error),n.kill(`SIGKILL`);return}r=!0,this.#x(`standby`),(this.#e.startMode===`immediate`||this.#s)&&this.#O();return}if(a===null){this.#i===`ready`&&this.#r(`stdout 违约(ready 后非静默): ${t.slice(0,120)}`),this.#k(`[stdout] ${t}`);return}a.event!==`standby`&&this.#i!==`ready`&&(this.#y=a,this.#x(`ready`),clearTimeout(i),this.#C())}),n.onStderrLine(t=>{if(this.#h!==e)return;let n=u(t);this.#k(n);for(let e of this.#p)try{e(n)}catch{}}),n.onExit(t=>{if(this.#h===e&&(clearTimeout(i),this.#u.push(t),!this.#_&&this.#v===void 0)){if(t===2){this.#v={kind:`permanent`,error:new s(`permanent`,`server 永久失败(退出码 2——config 非法 / 未设 model / profile 损坏)`,this.crashReport())},this.#x(`failed-permanent`),this.#w(this.#v.error);return}if(t===3){this.#v={kind:`protocol`,error:new s(`protocol`,`server 协议版本偏斜(退出码 3——部署错误最显眼信号)`,this.crashReport())},this.#x(`failed-protocol`),this.#w(this.#v.error);return}this.#E(`退出码 ${t??`signal`}`)}})}#O(){this.#c||this.#o===void 0||(this.#c=!0,this.#x(`starting`),this.#o.writeStdin(`${JSON.stringify({v:1,cmd:`start`})}\n`),this.#r(`start 已释放`))}#k(e){this.#f.push(`${Date.now()} ${e}`),this.#f.length>this.#e.ringBufferLines&&this.#f.splice(0,this.#f.length-this.#e.ringBufferLines)}};function f(e){return t=>{let n=r(t[0],t.slice(1),{stdio:[`pipe`,`pipe`,`pipe`],env:{...process.env,...e.env??{}}}),i=``,a=``,o=[],s=[],c=[],l=(e,t,n)=>{for(e+=t.toString();;){let t=e.indexOf(`
|
|
3
|
-
`);if(t<0)break;let r=e.slice(0,t);e=e.slice(t+1),n.forEach(e=>e(r))}return e};return n.stdout?.on(`data`,e=>{i=l(i,e.toString(),o)}),n.stderr?.on(`data`,e=>{a=l(a,e.toString(),s)}),n.on(`close`,e=>{i!==``&&o.forEach(e=>e(i)),a!==``&&s.forEach(e=>e(a)),c.forEach(t=>t(e))}),{writeStdin:e=>n.stdin?.write(e),onStdoutLine:e=>o.push(e),onStderrLine:e=>s.push(e),onExit:e=>c.push(e),kill:e=>n.kill(e??`SIGTERM`)}}}function p(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function m(e){return!p(e)||typeof e.type!=`string`||e.type===``||typeof e.seq!=`number`||!Number.isInteger(e.seq)||typeof e.time!=`number`||!(`data`in e)?null:e}function h(e){if(!p(e)||e.type!==`event`)return null;let t=m(e.event);return t===null?null:{type:`event`,event:t}}function g(e){if(!p(e))return null;if(e.type===`snapshot`){let t=p(e.header)?e.header:null;if(t===null||typeof e.cursor!=`number`||typeof e.hasMore!=`boolean`)return null;let n=[];if(Array.isArray(e.records))for(let t of e.records){let e=h(t);if(e===null)return null;n.push(e)}else return null;return{type:`snapshot`,header:t,cursor:e.cursor,records:n,hasMore:e.hasMore,projections:e.projections,...p(e.assistantStream)?{assistantStream:e.assistantStream}:{}}}return e.type===`assistant-stream`?p(e.frame)?{type:`assistant-stream`,frame:e.frame}:null:h(e)}function _(e){if(!p(e)||typeof e.hasMore!=`boolean`||!Array.isArray(e.records))return null;let t=[];for(let n of e.records){let e=h(n);if(e===null)return null;t.push(e)}return{records:t,hasMore:e.hasMore}}function v(e){return p(e)&&(e.type===`ready`&&typeof e.clientId==`string`&&p(e.host)||e.type===`emit`&&typeof e.event==`string`&&Array.isArray(e.args)||e.type===`waterfall`&&typeof e.eventId==`string`&&typeof e.agentId==`string`&&typeof e.event==`string`&&p(e.request)||e.type===`cancel`&&typeof e.eventId==`string`)?e:null}var y=class extends Error{code;details;constructor(e){super(e.message),this.name=`CarrierRpcError`,this.code=e.code,this.details=e.details}},b=class extends Error{constructor(e){super(e),this.name=`CarrierTransportError`}},x=class{#e;#t;#n;#r;#i;#a;#o=!1;#s=!1;constructor(e){this.#e=e.baseUrl.replace(/\/$/,``),this.#t=e.cookie,this.#n=e.refreshCredentials}async unary(e,t){this.#p();try{return await this.#c(e,t)}catch(n){if(!(n instanceof b&&n.message.endsWith(`HTTP 401`))||this.#n===void 0)throw n;return await this.#f(),this.#c(e,t)}}async#c(e,t){let n=i(),r;try{r=await fetch(`${this.#e}/api/${e}`,{method:`POST`,headers:{"content-type":`application/json`,cookie:this.#t},body:JSON.stringify({type:`client-request`,rpcId:n,method:e,payload:{args:t}}),signal:AbortSignal.timeout(6e4)})}catch(t){throw t instanceof Error&&t.name===`TimeoutError`?new b(`unary ${e} 超时(上游 60s 无响应)`):t}if(r.status!==200)throw new b(`unary ${e} HTTP ${r.status}`);let a=await r.json();if(a.type!==`server-response`||a.rpcId!==n)throw new b(`unary ${e} envelope 畸形(type/rpcId 失配)`);if(a.result.ok)return a.result.value;throw new y(a.result.error)}openStream(e,t,n){this.#p();let r=i(),o=!1,s={canceled:!1,onFrame:e=>{e.type===`item`?n.onItem(e.value):e.type===`end`?(s.canceled=!0,n.onEnd?.()):e.type===`error`&&(s.canceled=!0,n.onError?.(e.error??{code:`gateway/internal`,message:`stream error 帧缺 error 字段`}))},onDown:e=>{s.canceled||(s.canceled=!0,e&&n.onError?.({code:`carrier/mux-closed`,message:`mux 插座意外关闭`}),n.onClose?.(e))}};return this.#l().then(n=>{if(o||s.canceled){process.stderr.write(`[carrier] open ABORTED (canceled=${String(o)} entry=${String(s.canceled)}) ${e}\n`);return}n.streams.set(r,s),n.socket.readyState===a.OPEN?(n.socket.send(JSON.stringify({type:`open`,streamId:r,endpoint:e,payload:{args:t}})),process.env.CARRIER_WIRE_DEBUG===`1`&&process.stderr.write(`[carrier] open sent ${e} streamId=${r.slice(0,8)}\n`)):process.stderr.write(`[carrier] open SKIPPED (readyState ${n.socket.readyState}) ${e}\n`)}).catch(e=>{o||s.canceled||(s.canceled=!0,n.onError?.({code:`carrier/mux-open`,message:e.message}),n.onClose?.(!0))}),{cancel:()=>{o=!0,s.canceled=!0;let e=this.#r;e!==void 0&&e.streams.delete(r)&&e.socket.readyState===a.OPEN&&e.socket.send(JSON.stringify({type:`cancel`,streamId:r}))}}}async#l(){let e=this.#r;if(e!==void 0&&e.socket.readyState===a.OPEN)return e;if(this.#i!==void 0)return this.#i;let t=this.#u().finally(()=>{this.#i===t&&(this.#i=void 0)});return this.#i=t,t}async#u(){this.#p(),this.#o&&this.#n!==void 0&&await this.#f();let e=new a(`${S(this.#e)}/api/remote.mux`,{headers:{cookie:this.#t}});await new Promise((t,n)=>{let r=setTimeout(()=>n(new b(`mux 插座打开超时`)),15e3);r.unref(),e.once(`open`,()=>{clearTimeout(r),t()}),e.once(`error`,e=>{clearTimeout(r),n(new b(`mux 插座打开失败: ${e.message}`))}),e.once(`unexpected-response`,(e,t)=>{clearTimeout(r),n(new b(`mux 升级被拒 HTTP ${t.statusCode??`?`}`))})});let t={socket:e,streams:new Map};e.on(`message`,e=>{let n;try{n=JSON.parse(String(e))}catch{return}typeof n.streamId==`string`&&t.streams.get(n.streamId)?.onFrame(n)});let n=!1;return e.on(`close`,()=>this.#d(t,n)),e.on(`error`,()=>{n=!0}),this.#r=t,this.#o=!0,t}#d(e,t){if(this.#r===e){this.#r=void 0;for(let n of e.streams.values())n.onDown(t);e.streams.clear()}}#f(){if(this.#a!==void 0)return this.#a;let e=(async()=>{let e=this.#n;if(e===void 0)return;let t=await e();this.#t=t.cookie,this.#e=t.baseUrl.replace(/\/$/,``)})().finally(()=>{this.#a===e&&(this.#a=void 0)});return this.#a=e,e}openEvents(e){let t,n=n=>{switch(n.type){case`ready`:t=n.clientId,e.onReady(n);return;case`emit`:e.onEmit(n);return;case`waterfall`:e.onWaterfall(n);return;case`cancel`:e.onCancel(n);return}},r=this.openStream(`$events`,{},{onItem:t=>{let i=v(t);if(i===null){e.onClose?.(!1),r.cancel();return}n(i)},onClose:t=>e.onClose?.(t)});return{respond:async(e,n)=>{if(t===void 0)throw new b(`waterfall 应答先于 ready 帧(clientId 缺席)`);await this.unary(`$events/result`,{clientId:t,eventId:e,outcome:n})},close:()=>r.cancel()}}dispose(){this.#s=!0,this.#r?.socket.close(),this.#r=void 0}#p(){if(this.#s)throw new b(`carrier 已释放`)}};function S(e){if(e.startsWith(`https://`))return`wss://${e.slice(8)}`;if(e.startsWith(`http://`))return`ws://${e.slice(7)}`;throw new b(`baseUrl 非法(期待 http(s)://,实得 ${e})`)}function C(e,r){let i=m(e);if(i===null)return r!==void 0&&(r.invalid+=1),null;if(t(i.type)===`project`)return typeof i.data!=`object`||i.data===null||Array.isArray(i.data)?(r!==void 0&&(r.opaqueWarn+=1),{kind:`opaque`,event:i,level:`warn`}):(r!==void 0&&(r.consumable+=1),{kind:`consumable`,event:i});let a=n(i)?`debug`:`warn`;return a===`debug`?r!==void 0&&(r.opaqueDebug+=1):r!==void 0&&(r.opaqueWarn+=1),{kind:`opaque`,event:i,level:a}}var w=class{#e;#t;#n={invalid:0,opaqueDebug:0,opaqueWarn:0,consumable:0};#r=new Map;#i=0;constructor(e,t){this.#e=e,this.#t=t?.reopenBaseMs??1e3}open(e,t){let n=this.#r.get(e);if(n!==void 0&&!n.closed)return n.handlers=t,{close:()=>this.close(e)};let r={sessionId:e,handlers:t,handle:void 0,cursor:void 0,baseline:void 0,streamSeenRevision:!1,reopening:!1,backoffMs:this.#t,closed:!1,pending:[]};return this.#r.set(e,r),this.#a(r),{close:()=>this.close(e)}}close(e){let t=this.#r.get(e);t!==void 0&&(t.closed=!0,t.handle?.cancel(),this.#r.delete(e))}stats(){let e=0,t=0;for(let n of this.#r.values())n.closed||(n.reopening||n.cursor===void 0?t++:e++);return{live:e,reopening:t,decoded:{...this.#n},gapsRepaired:this.#i}}#a(e){e.closed||(e.reopening=e.cursor!==void 0,e.handle=this.#e.openStream(`session/follow`,{request:{address:{kind:`session`,sessionId:e.sessionId},assistantStream:!0}},{onItem:t=>this.#s(e,t),onEnd:()=>this.#o(e,`stream end`),onError:t=>this.#o(e,`${t.code}: ${t.message}`),onClose:t=>{t&&this.#o(e,`socket error`)}}))}#o(e,t){if(e.closed)return;e.handle=void 0,e.handlers.onDown(t);let n=e.backoffMs;e.backoffMs=Math.min(e.backoffMs*2,3e4),e.baseline=void 0,e.streamSeenRevision=!1,e.reopening=!0,setTimeout(()=>{e.closed||this.#a(e)},n)}#s(e,t){if(t.type===`snapshot`){this.#c(e,t);return}if(e.cursor!==void 0){if(e.reopening){e.pending.push(t);return}this.#d(e,t)}}#c(e,t){let n=e.cursor;if(n!==void 0&&t.cursor<n){e.handlers.onDown(`cursor 回退:${String(t.cursor)} < ${String(n)}`);return}e.baseline=t.assistantStream,e.streamSeenRevision=!1,e.reopening=!0,e.handlers.onSnapshot(t.header,t.cursor,t.projections,t.assistantStream),this.#l(e,t,n)}async#l(e,t,n){try{let r=[];if(n!==void 0&&t.records.length>0){let i=t.records[0]?.event.seq??t.cursor;i>n+1&&(r.push(...await this.#u(e,n+1,i)),this.#i+=r.length)}for(let e of t.records)r.push(e.event);for(let t of r)this.#f(e,t);let i=e.pending;e.pending=[],e.reopening=!1,e.cursor=t.cursor,e.backoffMs=this.#t;for(let t of i)this.#d(e,t)}catch(t){e.handlers.onDown(`backlog 补齐失败:${String(t)}`)}}async#u(e,t,n){let r=[],i=n;for(;i>t;){let n=_(await this.#e.unary(`session/page`,{request:{address:{kind:`session`,sessionId:e.sessionId},throughSeq:i-1,beforeSeq:t,maxMessages:200}}));if(n===null)throw new b(`session/page 帧畸形(records/hasMore 缺失)`);for(let e of n.records)r.push(e.event);let a=n.records[0]?.event.seq;if(a===void 0||a<=t||(i=a,!n.hasMore))break}return r.sort((e,t)=>e.seq-t.seq),r}#d(e,t){if(t.type===`assistant-stream`){if(!e.streamSeenRevision){e.streamSeenRevision=!0;let n=(e.baseline?.revision??-1)+1;if(e.baseline!==void 0&&t.frame.revision!==n){e.handlers.onDown(`assistant-stream 衔接断裂:revision ${String(t.frame.revision)} ≠ ${String(n)}`);return}}e.handlers.onAssistantStream(t.frame);return}t.type===`event`&&this.#f(e,t.event)}#f(e,t){let n=C(t,this.#n);n!==null&&n.kind===`consumable`&&e.handlers.onEvent(n.event)}async readAll(e){return await new Promise((t,n)=>{let r=new Map,i,a,o=!1,s=this.#e.openStream(`session/follow`,{request:{address:{kind:`session`,sessionId:e}}},{onItem:c=>{o||c.type===`snapshot`&&(o=!0,i=c.header,a=c.projections,s.cancel(),this.#p(e,c,r).then(e=>t({header:i,events:e,projections:a}),e=>n(e)))},onEnd:()=>{o||(o=!0,n(new b(`session/follow 在 snapshot 前关闭`)))},onError:e=>{o||(o=!0,n(new y(e)))}})})}async#p(e,t,n){let r=[];for(let e of t.records)r.push(e.event);let i=t.records.length>0?t.records[0]?.event.seq:void 0;for(;t.hasMore===!0;){let n=_(await this.#e.unary(`session/page`,{request:{address:{kind:`session`,sessionId:e},throughSeq:t.cursor,...i===void 0?{}:{beforeSeq:i},maxMessages:200}}));if(n===null)throw new b(`session/page 帧畸形(records/hasMore 缺失)`);for(let e of n.records)r.push(e.event);if(!n.hasMore||n.records.length===0)break;let a=n.records[0]?.event.seq;if(a===void 0||a===0)break;i=a}let a=new Map;for(let e of r)a.set(e.seq,e);let o=[...a.values()].sort((e,t)=>e.seq-t.seq);for(let e=0;e<o.length;e++){let t=o[e];if(t?.seq!==e)throw new y({code:`gateway/internal`,message:`journal 连续性断裂:位置 ${String(e)} 实得 seq ${String(t?.seq)}`});let r=C(t,this.#n);r?.kind===`consumable`&&n.set(t.seq,r.event)}return[...n.values()]}},T=class{#e=new Map;#t=new Map;#n=new Map;#r=new Map;#i;#a;#o=0;#s=0;constructor(e,t){this.#i=e,this.#a=t}attachConnection(e,t,n){this.#e.set(e,{connId:e,send:t,ctx:n})}detachConnection(e){this.#e.delete(e);for(let[t,n]of this.#t)n.delete(e),n.size===0&&this.#t.delete(t),this.#a?.onSessionUnbind?.(e,t);for(let[t,n]of this.#n)n===e&&this.#n.delete(t)}bind(e,t){let n=this.#t.get(t);n===void 0&&(n=new Set,this.#t.set(t,n));let r=n.has(e);n.add(e),r||this.#a?.onSessionBind?.(e,t)}unbind(e,t){this.#t.get(t)?.delete(e),this.#a?.onSessionUnbind?.(e,t)}boundConnIds(e){return[...this.#t.get(e)??[]]}ctxOf(e){return this.#e.get(e)?.ctx}routeResolved(e,t,n){this.routeExt({method:e,payload:t},n===void 0?void 0:{excludeConnId:n})}beginReplayCount(e){this.#r.set(e,0)}takeReplayCount(e){let t=this.#r.get(e);return this.#r.delete(e),t}setTurnOrigin(e,t){this.#n.set(e,t)}clearTurnOrigin(e){this.#n.delete(e)}route(e){let t=e.sessionId;if(t!==void 0&&this.#a?.onSessionUpdate!==void 0){let n=e.update??e;E(this.#i,`onSessionUpdate`,()=>this.#a?.onSessionUpdate?.(t,n))}let n;if(t===void 0)n=[...this.#e.keys()];else{let r=this.#n.get(t),i=e.update?.sessionUpdate===`user_message_chunk`;n=[...this.#t.get(t)??[]],r!==void 0&&i&&(n=n.filter(e=>e!==r),this.#s++);let a=this.#a?.fanout===void 0?void 0:E(this.#i,`fanout`,()=>this.#a?.fanout?.(e,n));if(a!==void 0&&(n=[...a]),n.length===0){this.#o++;return}}for(let t of n){let n=this.#e.get(t);if(n===void 0)continue;let r=e;if(this.#a?.transformOutbound!==void 0){let t=E(this.#i,`transformOutbound`,()=>this.#a?.transformOutbound?.(e,n.ctx));if(t===null)continue;t!==void 0&&(r=t)}n.send({jsonrpc:`2.0`,method:`session/update`,params:r});let i=this.#r.get(t);i!==void 0&&this.#r.set(t,i+1)}}routeExt(e,t){let n=typeof e.payload.sessionId==`string`?e.payload.sessionId:void 0,r=n===void 0?[...this.#e.keys()]:[...this.#t.get(n)??[]];t?.excludeConnId!==void 0&&(r=r.filter(e=>e!==t.excludeConnId));for(let t of r)this.#e.get(t)?.send({jsonrpc:`2.0`,method:e.method,params:e.payload})}stats(){return{connections:this.#e.size,dropped:this.#o,suppressed:this.#s}}};function E(e,t,n){try{return n()}catch(n){e.warn(`gateway hook ${t} failed (fail-open): ${String(n)}`);return}}function D(e){if(typeof e!=`object`||!e)return e;let t=e;if(t.type!==`image`)return e;let n=t.attachment;if(typeof n!=`object`||!n)return e;let r=n;return typeof r.mediaType!=`string`||typeof r.data!=`string`?e:{type:`image`,mediaType:r.mediaType,data:r.data,...typeof r.name==`string`?{name:r.name}:{}}}const O=1e3,k=3e4;function A(e){let t=e,n=t?.values?.modelSelection?.next??t?.values?.modelSelection?.lastUsed;if(!(n==null||typeof n.provider!=`string`||typeof n.model!=`string`))return{provider:n.provider,model:n.model,...typeof n.reasoningEffort==`string`?{reasoningEffort:n.reasoningEffort}:{}}}function j(e,t){return e===void 0||t===void 0?e===t:e.provider===t.provider&&e.model===t.model&&e.reasoningEffort===t.reasoningEffort}function M(e){if(typeof e!=`object`||!e)return-1;let t=e.asOfSeq;return typeof t==`number`?t:-1}function N(e){return e.pendingSelection??A(e.projections)??e.fallbackSelection}function P(e){return{id:e.id,get header(){let t=e.header;return{...t?.cwd===void 0?{}:{cwd:t.cwd},...t?.origin===void 0?{}:{origin:t.origin},...t?.parentSession===void 0?{}:{parentSession:t.parentSession},...t?.createdAt===void 0?{}:{createdAt:t.createdAt}}},requestHeader(){let t=N(e);if(t!==void 0)return{config:{provider:t.provider,model:t.model,...t.reasoningEffort===void 0?{}:{reasoningEffort:t.reasoningEffort}}}}}}function F(e,t,n){return{id:e.id,session:e.session,model:{current:()=>N(e),select:async n=>{j(e.pendingSelection??A(e.projections),n)||(e.pendingSelection=(await t.unary(`session/selectModel`,{request:{sessionId:e.id,...n}}))?.selected??n,e.pendingAtSeq=M(e.projections))}},cancel:async n=>{await t.unary(`session/cancel`,{request:{sessionId:e.id}})},followup:t=>{n(e,t)}}}var I=class{logger;#e;#t;#n;#r=new Map;#i=new Map;#a=new Set;#o=new Set;#s=new Set;#c=new Set;#l=new Set;#u;#d=O;#f;#p=O;#m;#h={groups:[],failures:[]};#g=0;#_;#v=!1;#y;constructor(e){this.#e=e.carrier,this.#t=e.pool,this.#n=e.logger,this.logger=e.logger,this.#y=this.#E(),this.#O(),this.#A()}async createAgent(e){return await this.#b(e)}async resumeAgent(e){return await this.#b(e)}async#b(e){let t=(await this.#e.unary(`session/create`,{request:{sessionId:e.sessionId,cwd:e.cwd}})).sessionId,n=this.#r.get(t);if(n!==void 0)return await this.#i.get(t)?.catch(()=>{}),n.fallbackSelection=this.#_,await e.configureScope?.(this.#C(n),n.agent),{agent:n.agent,dispose:async()=>this.#S(t)};let r={id:t,header:{version:1,id:t,createdAt:0,cwd:e.cwd,isSeeded:!1},projections:{},promptInflight:!1};r.session=P(r),r.agent=F(r,this.#e,(e,t)=>this.#w(e,t));let i=r;this.#r.set(t,i);try{let n=this.#x(t).then(e=>{e!==void 0&&(i.projections=e)});this.#i.set(t,n),await n,this.#i.delete(t),this.#_===void 0&&(await this.#y,this.#_===void 0&&!this.#v&&(this.#v=!0,await this.#E())),i.fallbackSelection=this.#_,await e.configureScope?.(this.#C(i),i.agent),this.#t.open(t,this.#D(i))}catch(e){throw await this.#S(t).catch(()=>{}),e}return{agent:i.agent,dispose:async()=>this.#S(t)}}async#x(e){try{let t=await this.#e.unary(`session/projections`,{request:{sessionId:e}});if(typeof t!=`object`||!t||Array.isArray(t))return;let n=t,r=n.values;return typeof r!=`object`||!r||Array.isArray(r)?void 0:{asOfSeq:typeof n.asOfSeq==`number`?n.asOfSeq:-1,values:r}}catch(t){this.#n.debug(`projection prime failed (${e}): ${String(t)}`);return}}#S(e){return this.#t.close(e),this.#r.delete(e),this.#i.delete(e),Promise.resolve()}#C(e){return{on:(e,t)=>()=>{},tools:{restrict:e=>void 0}}}async#w(e,t){e.promptInflight=!0;let n=t.content.map(D);await this.#e.unary(`session/prompt`,{request:{requestId:t.id,sessionId:e.id,mode:`steer`,content:n}})}persistence={stat:async(e,t)=>{let n=await this.#e.unary(`tboxcode/sessions.stat`,{request:{sessionId:e}});if(n!==null)return{header:n.header}},list:async e=>(await this.#e.unary(`session/list`,{_request:{}})).items.map(e=>({header:{id:e.sessionId,...e.cwd===void 0?{}:{cwd:e.cwd},...e.origin===void 0?{}:{origin:e.origin},...e.parentSessionId===void 0?{}:{parentSession:e.parentSessionId},createdAt:e.updatedAt}})),openHistoryRead:async(e,t)=>{let n=await this.#t.readAll(e);return{read:async()=>({events:n.events}),close:async()=>{}}}};sessionStore={get:e=>this.#r.get(e)?.session,flush:async e=>{await this.#e.unary(`tboxcode/sessions.flush`,{request:{sessionId:e.id}})}};llm={listProviders:()=>this.#T().groups.map(e=>({id:e.id,name:e.name})),listModels:async e=>(this.#T().groups.find(t=>t.id===e)?.models??[]).map(e=>({id:String(e.id),name:String(e.name),...e.description===void 0?{}:{description:String(e.description)}})),resolveModelInfo:async(e,t)=>{let n=this.#T().groups.find(t=>t.id===e)?.models.find(e=>e.id===t)?.reasoning;return{reasoning:{defaultEffort:n?.defaultEffort,efforts:n?.efforts??[]}}},resolveCallConfig:async e=>e};#T(){return Date.now()-this.#g>3e4&&this.#E(),this.#h}async#E(){try{this.#h=await this.#e.unary(`session/modelCatalog`,{}),this.#g=Date.now();let e=await this.#e.unary(`tboxcode/selection.default`,{});this.#_=typeof e.provider==`string`&&typeof e.model==`string`?{provider:e.provider,model:e.model,...e.reasoningEffort===void 0?{}:{reasoningEffort:e.reasoningEffort}}:void 0}catch(e){this.#n.warn(`catalog warm failed: ${String(e)}`)}}async admitPromptContent(e){return e.map(e=>e.type===`text`?e:{type:`image`,attachment:{mediaType:e.mediaType,data:e.data,...e.name===void 0?{}:{name:e.name}}})}applyModeKnobs(t,n,r){let i=Object.entries(e).find(([,e])=>e.sandbox===r.sandbox&&e.approval===r.approval)?.[0];if(i===void 0)throw Error(`tboxcode: mode knobs 无对位(${String(r.sandbox)}/${String(r.approval)}——MODE_TABLE 外组合)`);return this.#e.unary(`tboxcode/mode`,{request:{agentId:t.id,mode:i}}).then(()=>void 0)}defaultSelection(){return this.#_}async executeCommand(e,t,n){let r=await this.#e.unary(`tboxcode/commands.execute`,{request:{agentId:e.id,line:t}});return r?.commandId===void 0?void 0:{commandId:r.commandId}}async listCommands(e){return await this.#e.unary(`tboxcode/commands.list`,{request:{agentId:e.id}})}async listUserInvocableSkills(e){return await this.#e.unary(`tboxcode/skills.userInvocable`,{request:{agentId:e.id}})}onSessionEvent(e){let t=e;return this.#a.add(t),()=>this.#a.delete(t)}onAssistantStream(e){return this.#o.add(e),()=>this.#o.delete(e)}onInboxClaimed(e){return this.#s.add(e),()=>this.#s.delete(e)}onAgentError(e){return this.#c.add(e),()=>this.#c.delete(e)}sessionToolDenies(){return[]}onCommandSurfaceChanged(e){return this.#l.add(e),()=>this.#l.delete(e)}sessionIds(){return[...this.#r.keys()]}hasInflightPrompt(e){return this.#r.get(e)?.promptInflight===!0}poolLive(){return this.#t.stats().live>0}poolEntries(){return this.#r.size}settlePrompt(e,t){let n=this.#r.get(e);if(!(n===void 0||!n.promptInflight)){n.promptInflight=!1;for(let e of this.#c)e({agent:n.agent,turn:0,error:t})}}#D(e){return{onSnapshot:(t,n,r)=>{e.header=t;let i=M(r);e.pendingSelection!==void 0&&i>(e.pendingAtSeq??-1)&&A(r)!==void 0&&(e.pendingSelection=void 0,e.pendingAtSeq=void 0),e.projections=r},onEvent:t=>{t.type===`turn/end`&&(e.promptInflight=!1);for(let n of this.#a)n(e.session,t)},onAssistantStream:t=>{let n={type:t.type??(t.finish===void 0?t.index===0?`start`:`chunk`:`end`),attemptId:t.attemptId,...t.turn===void 0?{}:{turn:t.turn},...t.step===void 0?{}:{step:t.step},...t.chunk===void 0?{}:{chunk:t.chunk}};for(let t of this.#o)t({agent:e.agent,frame:n})},onDown:t=>this.#n.warn(`follow pool down (${e.id}): ${t}`)}}#O(){this.#u=this.#e.openStream(`tboxcode/agent.watch`,{},{onItem:e=>{this.#n.debug(`agent.watch item: ${JSON.stringify(e).slice(0,160)} states=${[...this.#r.keys()].join(`,`)}`);let t=this.#r.get(e.sessionId);if(t!==void 0){if(e.kind===`inboxClaimed`)for(let n of this.#s)n({agent:t.agent,message:{...e.messageId===void 0?{}:{id:e.messageId}},turn:e.turn??0});else if(e.kind===`error`)for(let n of this.#c)n({agent:t.agent,turn:0,error:e.error??`unknown agent error`})}},onError:e=>{this.#n.warn(`agent.watch stream error: ${JSON.stringify(e).slice(0,200)}`),this.#k()},onClose:e=>{e&&(this.#n.warn(`agent.watch stream closed`),this.#k())}})}#k(){let e=this.#d;this.#d=Math.min(this.#d*2,k),setTimeout(()=>{this.#O(),this.#d=O},e)}#A(){let e=()=>{for(let e of this.#l)e()};this.#f=L(this.#e,e,this.#n),this.#m=this.#e.openStream(`tboxcode/skills.watch`,{},{onItem:()=>e(),onError:()=>this.#j(),onClose:e=>{e&&this.#j()}})}#j(){let e=this.#p;this.#p=Math.min(this.#p*2,k),setTimeout(()=>{this.#A(),this.#p=O},e)}dispose(){this.#u?.cancel(),this.#f?.close(),this.#m?.cancel()}};function L(e,t,n){return e.openEvents({onReady:()=>n.debug(`commands/change $events ready`),onEmit:e=>{e.event===`commands/change`&&t()},onWaterfall:()=>{},onCancel:()=>{},onClose:e=>{e&&n.warn(`commands/change $events closed with error`)}})}var R=class{#e;#t;#n;#r;#i;#a;#o=!1;#s;constructor(e,t){this.#e=e,this.#t=t?.timeoutMs??12e4,this.#n=t?.tickMs??1e3,this.#r=t?.now??Date.now,this.#i=t?.logger??{warn:()=>{},info:()=>{},debug:()=>{}}}start(){this.#s=setInterval(()=>this.tick(),this.#n)}stop(){this.#s!==void 0&&clearInterval(this.#s),this.#s=void 0}tick(){if(!(this.#e.poolEntries()>0&&!this.#e.poolLive())){this.#a=void 0,this.#o=!1;return}if(this.#a===void 0){this.#a=this.#r();return}if(this.#o||this.#r()-this.#a<this.#t)return;this.#o=!0;let e=this.#r()-this.#a;for(let t of this.#e.sessionIds())this.#e.hasInflightPrompt(t)&&(this.#i.warn(`carrier timeout settle (${t}): downMs=${String(e)}`),this.#e.settle(t,Error(`tboxcode carrier-timeout (downMs=${String(e)})`)))}snapshot(){return{down:this.#a!==void 0,downSince:this.#a,settled:this.#o}}};const z=6e4,B=36e5,V=3e4,H=-32001;var U=class{#e=new Map;#t;constructor(e){this.#t=e}get size(){return this.#e.size}pendingOf(e){for(let t of this.#e.values())if(t.sessionId===e)return t}begin(e){let t=e.event===`user-questions/request`?`elicitation`:e.event===`approval/request`?`permission`:void 0;if(t===void 0||this.#e.has(e.eventId))return;let n=this.#t.sessionIdOfAgent(e.agentId);if(n===void 0){this.#l(e.eventId,{kind:`rejected`,error:{code:`gateway/agent-not-found`,message:`agent ${e.agentId} not managed by gateway`}});return}let r={kind:t,sessionId:n,eventId:e.eventId,frame:e,asked:new Map,state:`active`,budgetStartedAt:this.#t.now()};this.#e.set(e.eventId,r),this.#n(r),this.#s(r)}cancel(e){let t=this.#e.get(e.eventId);t===void 0||t.state===`settled`||this.#c(t,{kind:`result`,value:`cancelled`},`turn`)}attach(e,t){for(let n of this.#e.values()){if(n.sessionId!==t||n.state!==`grace`)continue;let r=n.graceTimer;n.graceTimer=void 0,r!==void 0&&this.#t.timers.clear(r),n.state=`active`,this.#t.logger.info(`answerer: grace broken by attach (${n.eventId} conn=${e})`),this.#n(n)}}switchBack(e,t){this.attach(e,t)}disconnect(e){for(let t of this.#e.values())t.asked.delete(e)&&t.state===`active`&&t.asked.size===0&&this.#o(t,`member disconnected`)}dispose(){for(let e of[...this.#e.values()])e.state!==`settled`&&this.#c(e,{kind:`result`,value:`cancelled`},`dispose`);this.#e.clear()}#n(e){let t=this.#t.eligibleConns(e.sessionId).filter(t=>!e.asked.has(t)).filter(t=>e.kind===`permission`||this.#t.capsOf(t));if(t.length===0){this.#o(e,`no eligible connections`);return}for(let n of t){let t={connId:n};e.kind===`permission`&&(t.timer=this.#t.timers.set(()=>{e.state!==`active`||!e.asked.has(n)||(e.asked.delete(n),this.#t.logger.info(`answerer: member timeout (${e.eventId} conn=${n})`),e.asked.size===0&&this.#o(e,`all members timed out`))},V)),e.asked.set(n,t),this.#r(e,n)}}async#r(e,t){let n=e.kind===`elicitation`?this.#t.buildQuestionParams(e.sessionId,e.frame):{callId:e.frame.request.callId};try{let r=await this.#t.dispatch(t,e.kind,n);if(e.state===`settled`||!e.asked.has(t))return;let i=this.#i(e,r);if(i.abstain){this.#a(e,t,`abstained`);return}this.#c(e,i.outcome,t)}catch(n){if(e.state===`settled`||!e.asked.has(t))return;if(n.code===H){this.#a(e,t,`abstained`);return}this.#t.logger.warn(`answerer: dispatch failed (${e.eventId} conn=${t}): ${n instanceof Error?n.message:String(n)}`),this.#a(e,t,`dispatch failed`)}}#i(e,t){if(e.kind===`permission`){let e=t?.outcome;return e?.outcome===`cancelled`?{abstain:!1,outcome:{kind:`result`,value:`cancelled`}}:{abstain:!1,outcome:{kind:`result`,value:e?.optionId===`allow-once`?`allowed-once`:`rejected`}}}let n=t;return n?.action===`accept`?{abstain:!1,outcome:{kind:`result`,value:n.content??{}}}:{abstain:!1,outcome:{kind:`rejected`,error:{code:n?.action===`decline`?`ASK_DECLINED`:`ASK_ABORTED`,message:`ask_user_question ${n?.action===`decline`?`declined`:`cancelled`} by client`}}}}#a(e,t,n){let r=e.asked.get(t);r?.timer!==void 0&&this.#t.timers.clear(r.timer),e.asked.delete(t),this.#t.logger.debug(`answerer: member dropped (${e.eventId} conn=${t} ${n})`),e.state===`active`&&e.asked.size===0&&this.#o(e,`all members out (${n})`)}#o(e,t){e.state===`active`&&(e.state=`grace`,e.graceTimer=this.#t.timers.set(()=>{this.#c(e,e.kind===`elicitation`?{kind:`rejected`,error:{code:`ASK_ABORTED`,message:`ask_user_question grace window expired`}}:{kind:`result`,value:`cancelled`},`grace`)},z),this.#t.logger.info(`answerer: grace entered (${e.eventId} ${t})`))}#s(e){let t=B-(this.#t.now()-e.budgetStartedAt);if(t<=0){this.#c(e,e.kind===`elicitation`?{kind:`rejected`,error:{code:`ASK_ABORTED`,message:`ask_user_question form budget exhausted`}}:{kind:`result`,value:`cancelled`},`budget`);return}this.#t.timers.set(()=>{e.state!==`settled`&&(this.#t.logger.warn(`answerer: form budget exhausted (${e.eventId})`),this.#c(e,e.kind===`elicitation`?{kind:`rejected`,error:{code:`ASK_ABORTED`,message:`ask_user_question form budget exhausted`}}:{kind:`result`,value:`cancelled`},`budget`))},t)}#c(e,t,n){if(e.state!==`settled`){e.state=`settled`,e.settledOutcome=t,e.respondedBy=n,e.graceTimer!==void 0&&(this.#t.timers.clear(e.graceTimer),e.graceTimer=void 0);for(let t of e.asked.values())t.timer!==void 0&&this.#t.timers.clear(t.timer);e.asked.clear(),this.#l(e.eventId,t),this.#t.resolvedNotify(e.kind,{sessionId:e.sessionId,eventId:e.eventId,outcome:t,respondedBy:n},typeof n==`string`&&n!==`grace`&&n!==`turn`&&n!==`dispose`&&n!==`budget`?n:void 0),this.#t.logger.info(`answerer: settled (${e.eventId} by=${n} kind=${t.kind})`)}}async#l(e,t){try{await this.#t.respond(e,t)}catch(t){this.#t.logger.warn(`answerer: respond failed (${e}): ${t instanceof Error?t.message:String(t)}`)}}};function W(e,t){e.gate.active||(e.gate.active=!0,e.gate.timer=setTimeout(()=>{e.gate.active&&(t.warn(`gateway load gate timeout (${e.connId})——释放缓存帧`),G(e,!0))},3e4),e.gate.timer.unref?.())}function G(e,t){if(!e.gate.active)return[];e.gate.active=!1,e.gate.timer!==void 0&&clearTimeout(e.gate.timer),e.gate.timer=void 0;let n=t?e.gate.frames.splice(0):[];return e.gate.frames.length=0,n}function K(e,t){e.socket.readyState===e.socket.OPEN&&e.socket.send(JSON.stringify(t))}function q(e,t,n){let{core:r,hooks:i,authenticate:a,logger:s}=n,c=new T(s,i),l=new o({noServer:!0}),u=new Set;return r.io.notify=async e=>{c.route(e)},r.io.extNotify=async e=>{c.routeExt(e)},e.on(`upgrade`,(e,n,o)=>{new URL(e.url??`/`,`http://localhost`).pathname===t&&(async()=>{if(!(a===void 0||await J(a,e,s))){n.write(`HTTP/1.1 401 Unauthorized\r
|
|
3
|
+
`);if(t<0)break;let r=e.slice(0,t);e=e.slice(t+1),n.forEach(e=>e(r))}return e};return n.stdout?.on(`data`,e=>{i=l(i,e.toString(),o)}),n.stderr?.on(`data`,e=>{a=l(a,e.toString(),s)}),n.on(`close`,e=>{i!==``&&o.forEach(e=>e(i)),a!==``&&s.forEach(e=>e(a)),c.forEach(t=>t(e))}),{writeStdin:e=>n.stdin?.write(e),onStdoutLine:e=>o.push(e),onStderrLine:e=>s.push(e),onExit:e=>c.push(e),kill:e=>n.kill(e??`SIGTERM`)}}}function p(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ee(e){return!p(e)||typeof e.type!=`string`||e.type===``||typeof e.seq!=`number`||!Number.isInteger(e.seq)||typeof e.time!=`number`||!(`data`in e)?null:e}function m(e){if(!p(e)||e.type!==`event`)return null;let t=ee(e.event);return t===null?null:{type:`event`,event:t}}function te(e){if(!p(e))return null;if(e.type===`snapshot`){let t=p(e.header)?e.header:null;if(t===null||typeof e.cursor!=`number`||typeof e.hasMore!=`boolean`)return null;let n=[];if(Array.isArray(e.records))for(let t of e.records){let e=m(t);if(e===null)return null;n.push(e)}else return null;return{type:`snapshot`,header:t,cursor:e.cursor,records:n,hasMore:e.hasMore,projections:e.projections,...p(e.assistantStream)?{assistantStream:e.assistantStream}:{}}}return e.type===`assistant-stream`?p(e.frame)?{type:`assistant-stream`,frame:e.frame}:null:m(e)}function ne(e){if(!p(e)||typeof e.hasMore!=`boolean`||!Array.isArray(e.records))return null;let t=[];for(let n of e.records){let e=m(n);if(e===null)return null;t.push(e)}return{records:t,hasMore:e.hasMore}}function re(e){return p(e)&&(e.type===`ready`&&typeof e.clientId==`string`&&p(e.host)||e.type===`emit`&&typeof e.event==`string`&&Array.isArray(e.args)||e.type===`waterfall`&&typeof e.eventId==`string`&&typeof e.agentId==`string`&&typeof e.event==`string`&&p(e.request)||e.type===`cancel`&&typeof e.eventId==`string`)?e:null}var ie=class extends Error{code;details;constructor(e){super(e.message),this.name=`CarrierRpcError`,this.code=e.code,this.details=e.details}},h=class extends Error{constructor(e){super(e),this.name=`CarrierTransportError`}},ae=class{#e;#t;#n;#r;#i;#a;#o=!1;#s=!1;constructor(e){this.#e=e.baseUrl.replace(/\/$/,``),this.#t=e.cookie,this.#n=e.refreshCredentials}async unary(e,t){this.#p();try{return await this.#c(e,t)}catch(n){if(!(n instanceof h&&n.message.endsWith(`HTTP 401`))||this.#n===void 0)throw n;return await this.#f(),this.#c(e,t)}}async#c(e,t){let n=i(),r;try{r=await fetch(`${this.#e}/api/${e}`,{method:`POST`,headers:{"content-type":`application/json`,cookie:this.#t},body:JSON.stringify({type:`client-request`,rpcId:n,method:e,payload:{args:t}}),signal:AbortSignal.timeout(6e4)})}catch(t){throw t instanceof Error&&t.name===`TimeoutError`?new h(`unary ${e} 超时(上游 60s 无响应)`):t}if(r.status!==200)throw new h(`unary ${e} HTTP ${r.status}`);let a=await r.json();if(a.type!==`server-response`||a.rpcId!==n)throw new h(`unary ${e} envelope 畸形(type/rpcId 失配)`);if(a.result.ok)return a.result.value;throw new ie(a.result.error)}openStream(e,t,n){this.#p();let r=i(),o=!1,s={canceled:!1,onFrame:e=>{e.type===`item`?n.onItem(e.value):e.type===`end`?(s.canceled=!0,n.onEnd?.()):e.type===`error`&&(s.canceled=!0,n.onError?.(e.error??{code:`gateway/internal`,message:`stream error 帧缺 error 字段`}))},onDown:e=>{s.canceled||(s.canceled=!0,e&&n.onError?.({code:`carrier/mux-closed`,message:`mux 插座意外关闭`}),n.onClose?.(e))}};return this.#l().then(n=>{if(o||s.canceled){process.stderr.write(`[carrier] open ABORTED (canceled=${String(o)} entry=${String(s.canceled)}) ${e}\n`);return}n.streams.set(r,s),n.socket.readyState===a.OPEN?(n.socket.send(JSON.stringify({type:`open`,streamId:r,endpoint:e,payload:{args:t}})),process.env.CARRIER_WIRE_DEBUG===`1`&&process.stderr.write(`[carrier] open sent ${e} streamId=${r.slice(0,8)}\n`)):process.stderr.write(`[carrier] open SKIPPED (readyState ${n.socket.readyState}) ${e}\n`)}).catch(e=>{o||s.canceled||(s.canceled=!0,n.onError?.({code:`carrier/mux-open`,message:e.message}),n.onClose?.(!0))}),{cancel:()=>{o=!0,s.canceled=!0;let e=this.#r;e!==void 0&&e.streams.delete(r)&&e.socket.readyState===a.OPEN&&e.socket.send(JSON.stringify({type:`cancel`,streamId:r}))}}}async#l(){let e=this.#r;if(e!==void 0&&e.socket.readyState===a.OPEN)return e;if(this.#i!==void 0)return this.#i;let t=this.#u().finally(()=>{this.#i===t&&(this.#i=void 0)});return this.#i=t,t}async#u(){this.#p(),this.#o&&this.#n!==void 0&&await this.#f();let e=new a(`${oe(this.#e)}/api/remote.mux`,{headers:{cookie:this.#t}});await new Promise((t,n)=>{let r=setTimeout(()=>n(new h(`mux 插座打开超时`)),15e3);r.unref(),e.once(`open`,()=>{clearTimeout(r),t()}),e.once(`error`,e=>{clearTimeout(r),n(new h(`mux 插座打开失败: ${e.message}`))}),e.once(`unexpected-response`,(e,t)=>{clearTimeout(r),n(new h(`mux 升级被拒 HTTP ${t.statusCode??`?`}`))})});let t={socket:e,streams:new Map};e.on(`message`,e=>{let n;try{n=JSON.parse(String(e))}catch{return}typeof n.streamId==`string`&&t.streams.get(n.streamId)?.onFrame(n)});let n=!1;return e.on(`close`,()=>this.#d(t,n)),e.on(`error`,()=>{n=!0}),this.#r=t,this.#o=!0,t}#d(e,t){if(this.#r===e){this.#r=void 0;for(let n of e.streams.values())n.onDown(t);e.streams.clear()}}#f(){if(this.#a!==void 0)return this.#a;let e=(async()=>{let e=this.#n;if(e===void 0)return;let t=await e();this.#t=t.cookie,this.#e=t.baseUrl.replace(/\/$/,``)})().finally(()=>{this.#a===e&&(this.#a=void 0)});return this.#a=e,e}openEvents(e){let t,n=n=>{switch(n.type){case`ready`:t=n.clientId,e.onReady(n);return;case`emit`:e.onEmit(n);return;case`waterfall`:e.onWaterfall(n);return;case`cancel`:e.onCancel(n);return}},r=this.openStream(`$events`,{},{onItem:t=>{let i=re(t);if(i===null){e.onClose?.(!1),r.cancel();return}n(i)},onClose:t=>e.onClose?.(t)});return{respond:async(e,n)=>{if(t===void 0)throw new h(`waterfall 应答先于 ready 帧(clientId 缺席)`);await this.unary(`$events/result`,{clientId:t,eventId:e,outcome:n})},close:()=>r.cancel()}}dispose(){this.#s=!0,this.#r?.socket.close(),this.#r=void 0}#p(){if(this.#s)throw new h(`carrier 已释放`)}};function oe(e){if(e.startsWith(`https://`))return`wss://${e.slice(8)}`;if(e.startsWith(`http://`))return`ws://${e.slice(7)}`;throw new h(`baseUrl 非法(期待 http(s)://,实得 ${e})`)}function se(e,r){let i=ee(e);if(i===null)return r!==void 0&&(r.invalid+=1),null;if(t(i.type)===`project`)return typeof i.data!=`object`||i.data===null||Array.isArray(i.data)?(r!==void 0&&(r.opaqueWarn+=1),{kind:`opaque`,event:i,level:`warn`}):(r!==void 0&&(r.consumable+=1),{kind:`consumable`,event:i});let a=n(i)?`debug`:`warn`;return a===`debug`?r!==void 0&&(r.opaqueDebug+=1):r!==void 0&&(r.opaqueWarn+=1),{kind:`opaque`,event:i,level:a}}var ce=class{#e;#t;#n={invalid:0,opaqueDebug:0,opaqueWarn:0,consumable:0};#r=new Map;#i=0;constructor(e,t){this.#e=e,this.#t=t?.reopenBaseMs??1e3}open(e,t){let n=this.#r.get(e);if(n!==void 0&&!n.closed)return n.handlers=t,{close:()=>this.close(e)};let r={sessionId:e,handlers:t,handle:void 0,cursor:void 0,baseline:void 0,streamSeenRevision:!1,reopening:!1,backoffMs:this.#t,closed:!1,pending:[]};return this.#r.set(e,r),this.#a(r),{close:()=>this.close(e)}}close(e){let t=this.#r.get(e);t!==void 0&&(t.closed=!0,t.handle?.cancel(),this.#r.delete(e))}stats(){let e=0,t=0;for(let n of this.#r.values())n.closed||(n.reopening||n.cursor===void 0?t++:e++);return{live:e,reopening:t,decoded:{...this.#n},gapsRepaired:this.#i}}#a(e){e.closed||(e.reopening=e.cursor!==void 0,e.handle=this.#e.openStream(`session/follow`,{request:{address:{kind:`session`,sessionId:e.sessionId},assistantStream:!0}},{onItem:t=>this.#s(e,t),onEnd:()=>this.#o(e,`stream end`),onError:t=>this.#o(e,`${t.code}: ${t.message}`),onClose:t=>{t&&this.#o(e,`socket error`)}}))}#o(e,t){if(e.closed)return;e.handle=void 0,e.handlers.onDown(t);let n=e.backoffMs;e.backoffMs=Math.min(e.backoffMs*2,3e4),e.baseline=void 0,e.streamSeenRevision=!1,e.reopening=!0,setTimeout(()=>{e.closed||this.#a(e)},n)}#s(e,t){if(t.type===`snapshot`){this.#c(e,t);return}if(e.cursor!==void 0){if(e.reopening){e.pending.push(t);return}this.#d(e,t)}}#c(e,t){let n=e.cursor;if(n!==void 0&&t.cursor<n){e.handlers.onDown(`cursor 回退:${String(t.cursor)} < ${String(n)}`);return}e.baseline=t.assistantStream,e.streamSeenRevision=!1,e.reopening=!0,e.handlers.onSnapshot(t.header,t.cursor,t.projections,t.assistantStream),this.#l(e,t,n)}async#l(e,t,n){try{let r=[];if(n!==void 0&&t.records.length>0){let i=t.records[0]?.event.seq??t.cursor;i>n+1&&(r.push(...await this.#u(e,n+1,i)),this.#i+=r.length)}for(let e of t.records)r.push(e.event);for(let t of r)this.#f(e,t);let i=e.pending;e.pending=[],e.reopening=!1,e.cursor=t.cursor,e.backoffMs=this.#t;for(let t of i)this.#d(e,t)}catch(t){e.handlers.onDown(`backlog 补齐失败:${String(t)}`)}}async#u(e,t,n){let r=[],i=n;for(;i>t;){let n=ne(await this.#e.unary(`session/page`,{request:{address:{kind:`session`,sessionId:e.sessionId},throughSeq:i-1,beforeSeq:t,maxMessages:200}}));if(n===null)throw new h(`session/page 帧畸形(records/hasMore 缺失)`);for(let e of n.records)r.push(e.event);let a=n.records[0]?.event.seq;if(a===void 0||a<=t||(i=a,!n.hasMore))break}return r.sort((e,t)=>e.seq-t.seq),r}#d(e,t){if(t.type===`assistant-stream`){if(!e.streamSeenRevision){e.streamSeenRevision=!0;let n=(e.baseline?.revision??-1)+1;if(e.baseline!==void 0&&t.frame.revision!==n){e.handlers.onDown(`assistant-stream 衔接断裂:revision ${String(t.frame.revision)} ≠ ${String(n)}`);return}}e.handlers.onAssistantStream(t.frame);return}t.type===`event`&&this.#f(e,t.event)}#f(e,t){let n=se(t,this.#n);n!==null&&n.kind===`consumable`&&e.handlers.onEvent(n.event)}async readAll(e){return await new Promise((t,n)=>{let r=new Map,i,a,o=!1,s=this.#e.openStream(`session/follow`,{request:{address:{kind:`session`,sessionId:e}}},{onItem:c=>{o||c.type===`snapshot`&&(o=!0,i=c.header,a=c.projections,s.cancel(),this.#p(e,c,r).then(e=>t({header:i,events:e,projections:a}),e=>n(e)))},onEnd:()=>{o||(o=!0,n(new h(`session/follow 在 snapshot 前关闭`)))},onError:e=>{o||(o=!0,n(new ie(e)))}})})}async#p(e,t,n){let r=[];for(let e of t.records)r.push(e.event);let i=t.records.length>0?t.records[0]?.event.seq:void 0;for(;t.hasMore===!0;){let n=ne(await this.#e.unary(`session/page`,{request:{address:{kind:`session`,sessionId:e},throughSeq:t.cursor,...i===void 0?{}:{beforeSeq:i},maxMessages:200}}));if(n===null)throw new h(`session/page 帧畸形(records/hasMore 缺失)`);for(let e of n.records)r.push(e.event);if(!n.hasMore||n.records.length===0)break;let a=n.records[0]?.event.seq;if(a===void 0||a===0)break;i=a}let a=new Map;for(let e of r)a.set(e.seq,e);let o=[...a.values()].sort((e,t)=>e.seq-t.seq);for(let e=0;e<o.length;e++){let t=o[e];if(t?.seq!==e)throw new ie({code:`gateway/internal`,message:`journal 连续性断裂:位置 ${String(e)} 实得 seq ${String(t?.seq)}`});let r=se(t,this.#n);r?.kind===`consumable`&&n.set(t.seq,r.event)}return[...n.values()]}},le=class{#e=new Map;#t=new Map;#n=new Map;#r=new Map;#i;#a;#o=0;#s=0;constructor(e,t){this.#i=e,this.#a=t}attachConnection(e,t,n){this.#e.set(e,{connId:e,send:t,ctx:n})}detachConnection(e){this.#e.delete(e);for(let[t,n]of this.#t)n.delete(e),n.size===0&&this.#t.delete(t),this.#a?.onSessionUnbind?.(e,t);for(let[t,n]of this.#n)n===e&&this.#n.delete(t)}bind(e,t){let n=this.#t.get(t);n===void 0&&(n=new Set,this.#t.set(t,n));let r=n.has(e);n.add(e),r||this.#a?.onSessionBind?.(e,t)}unbind(e,t){this.#t.get(t)?.delete(e),this.#a?.onSessionUnbind?.(e,t)}boundConnIds(e){return[...this.#t.get(e)??[]]}ctxOf(e){return this.#e.get(e)?.ctx}routeResolved(e,t,n){this.routeExt({method:e,payload:t},n===void 0?void 0:{excludeConnId:n})}beginReplayCount(e){this.#r.set(e,0)}takeReplayCount(e){let t=this.#r.get(e);return this.#r.delete(e),t}setTurnOrigin(e,t){this.#n.set(e,t)}clearTurnOrigin(e){this.#n.delete(e)}route(e){let t=e.sessionId;if(t!==void 0&&this.#a?.onSessionUpdate!==void 0){let n=e.update??e;ue(this.#i,`onSessionUpdate`,()=>this.#a?.onSessionUpdate?.(t,n))}let n;if(t===void 0)n=[...this.#e.keys()];else{let r=this.#n.get(t),i=e.update?.sessionUpdate===`user_message_chunk`;n=[...this.#t.get(t)??[]],r!==void 0&&i&&(n=n.filter(e=>e!==r),this.#s++);let a=this.#a?.fanout===void 0?void 0:ue(this.#i,`fanout`,()=>this.#a?.fanout?.(e,n));if(a!==void 0&&(n=[...a]),n.length===0){this.#o++;return}}for(let t of n){let n=this.#e.get(t);if(n===void 0)continue;let r=e;if(this.#a?.transformOutbound!==void 0){let t=ue(this.#i,`transformOutbound`,()=>this.#a?.transformOutbound?.(e,n.ctx));if(t===null)continue;t!==void 0&&(r=t)}n.send({jsonrpc:`2.0`,method:`session/update`,params:r});let i=this.#r.get(t);i!==void 0&&this.#r.set(t,i+1)}}routeExt(e,t){let n=typeof e.payload.sessionId==`string`?e.payload.sessionId:void 0,r=n===void 0?[...this.#e.keys()]:[...this.#t.get(n)??[]];t?.excludeConnId!==void 0&&(r=r.filter(e=>e!==t.excludeConnId));for(let t of r)this.#e.get(t)?.send({jsonrpc:`2.0`,method:e.method,params:e.payload})}stats(){return{connections:this.#e.size,dropped:this.#o,suppressed:this.#s}}};function ue(e,t,n){try{return n()}catch(n){e.warn(`gateway hook ${t} failed (fail-open): ${String(n)}`);return}}const g={initialize:`initialize`,authenticate:`authenticate`,providers_list:`providers/list`,providers_set:`providers/set`,providers_disable:`providers/disable`,session_new:`session/new`,session_load:`session/load`,session_set_mode:`session/set_mode`,session_set_config_option:`session/set_config_option`,session_prompt:`session/prompt`,session_cancel:`session/cancel`,mcp_message:`mcp/message`,session_list:`session/list`,session_delete:`session/delete`,session_fork:`session/fork`,session_resume:`session/resume`,session_close:`session/close`,logout:`logout`,nes_start:`nes/start`,nes_suggest:`nes/suggest`,nes_accept:`nes/accept`,nes_reject:`nes/reject`,nes_close:`nes/close`,document_did_open:`document/didOpen`,document_did_change:`document/didChange`,document_did_close:`document/didClose`,document_did_save:`document/didSave`,document_did_focus:`document/didFocus`},_={session_request_permission:`session/request_permission`,session_update:`session/update`,fs_write_text_file:`fs/write_text_file`,fs_read_text_file:`fs/read_text_file`,terminal_create:`terminal/create`,terminal_output:`terminal/output`,terminal_release:`terminal/release`,terminal_wait_for_exit:`terminal/wait_for_exit`,terminal_kill:`terminal/kill`,mcp_message:`mcp/message`,elicitation_create:`elicitation/create`,elicitation_complete:`elicitation/complete`},de={cancel_request:`$/cancel_request`};function fe(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function pe(e,t=`|`){return e.map(e=>Ie(e)).join(t)}function me(e,t){return typeof t==`bigint`?t.toString():t}var he=class{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;return e!==void 0&&(this._value=e(),this._getter=void 0),this._value}};function ge(e){return new he(e)}function _e(e){return e==null}function ve(e){let t=e.startsWith(`^`)?1:0,n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function ye(e,t){let n=e/t,r=Math.round(n),i=4*2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r)<i?0:n-r}function be(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function xe(e){let t=Object.getOwnPropertyDescriptor(e,`shape`);return t?.get?t.get.raw:t?.value}function v(e){return xe(e._zod.def)??e._zod.def.shape}function Se(e,t,n){Object.defineProperty(e,t,{get(){let e=n();return be(this,t,e),e},enumerable:!0,configurable:!0})}function Ce(e,t,n){t in e?be(e,t,n):e[t]=n}function we(e,t,n,r){let i=v(t);for(let a of n){let n=Object.getOwnPropertyDescriptor(i,a);n.enumerable&&(n.get?Se(e,a,()=>{let e=t._zod.def.shape[a];return r?r(e,a):e}):Ce(e,a,r?r(n.value,a):n.value))}}function Te(e,t){for(let n of Reflect.ownKeys(t)){let r=Object.getOwnPropertyDescriptor(t,n);r.enumerable&&(r.get?Se(e,n,()=>t[n]):Ce(e,n,r.value))}}function y(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function Ee(e){return JSON.stringify(e)}function De(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}const Oe=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function ke(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Ae=ge(()=>{if(w.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function je(e){if(ke(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return!(ke(n)===!1||Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)===!1)}function Me(e){return je(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const Ne=new Set([`string`,`number`,`symbol`]);function Pe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Fe(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function b(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function Ie(e){return typeof e==`bigint`?e.toString()+`n`:typeof e==`string`?`"${e}"`:`${e}`}function Le(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout===`optional`)}const Re=(()=>({safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]}))(),ze={int64:[BigInt(`-9223372036854775808`),BigInt(`9223372036854775807`)],uint64:[BigInt(0),BigInt(`18446744073709551615`)]};function Be(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);let i={};return we(i,e,Ve(e,t)),Fe(e,y(n,{shape:i,checks:[]}))}function Ve(e,t){let n=v(e),r=[];for(let e of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(n,e)?.enumerable)throw Error(`Unrecognized key: "${String(e)}"`);t[e]&&r.push(e)}return r}function He(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);let i=new Set(Ve(e,t)),a={};return we(a,e,Reflect.ownKeys(v(e)).filter(e=>!i.has(e))),Fe(e,y(n,{shape:a,checks:[]}))}function Ue(e,t){if(!je(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=v(e);for(let e of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return Fe(e,y(e._zod.def,{shape:We(e,t)}))}function We(e,t){let n={};return we(n,e,Reflect.ownKeys(v(e))),Te(n,t),n}function Ge(e,t){if(!je(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return Fe(e,y(e._zod.def,{shape:We(e,t)}))}function Ke(e,t){if(!t?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);let n={};return we(n,e,Reflect.ownKeys(v(e))),we(n,t,Reflect.ownKeys(v(t))),Fe(e,y(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function qe(e,t,n,r=`partial`){let i=t._zod.def.checks;if(i&&i.length>0)throw Error(`.${r}() cannot be used on object schemas containing refinements`);let a=n?new Set(Ve(t,n)):void 0,o={};return we(o,t,Reflect.ownKeys(v(t)),e&&((t,n)=>a&&!a.has(n)?t:new e({type:`optional`,innerType:t}))),Fe(t,y(t._zod.def,{shape:o,checks:[]}))}function Je(e,t,n){let r=n?new Set(Ve(t,n)):void 0,i={};return we(i,t,Reflect.ownKeys(v(t)),(t,n)=>r&&!r.has(n)?t:new e({type:`nonoptional`,innerType:t})),Fe(t,y(t._zod.def,{shape:i}))}function x(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function Ye(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function Xe(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function Ze(e){return typeof e==`string`?e:e?.message}function Qe(e){let t=[];for(let n of e??[]){let e=n._zod.def;if(!/_(length|size)$|_equals$/.test(e.check))break;let r=e.maximum??e.length??e.size;r>=0&&t.push([r,n])}return t}function $e(e,t,n){var r;for(let i=t;i<e.length;i++)(r=e[i]).schema??(r.schema=n)}function et(e,t,n){var r;let i=e.inst?._zod?.traits;i?.has(`$ZodType`)&&(i.has(`$ZodCheck`)?(r=e).schema??(r.schema=e.inst):e.schema=e.inst);let a=e.schema===e.inst?void 0:e.schema?._zod.def?.error,o=e.message?e.message:Ze(e.inst?._zod.def?.error?.(e))??Ze(a?.(e))??Ze(t?.error?.(e))??Ze(n.customError?.(e))??Ze(n.localeError?.(e))??`Invalid input`,s={};for(let t of Object.keys(e))t===`inst`||t===`schema`||t===`continue`||t===`input`||t===`__proto__`||(s[t]=e[t]);return s.path??=[],s.message=o,t?.reportInput&&(s.input=e.input),s}const tt=/[\uD800-\uDBFF]/;function nt(e){let t=e.length;if(!tt.test(e))return t;let n=t;for(let r=0;r<t-1;r++)(e.charCodeAt(r)&64512)==55296&&(e.charCodeAt(r+1)&64512)==56320&&(n--,r++);return n}function rt(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function it(e){let t=typeof e;switch(t){case`number`:return Number.isNaN(e)?`nan`:`number`;case`object`:{if(e===null)return`null`;if(Array.isArray(e))return`array`;let t=e;if(t&&Object.getPrototypeOf(t)!==Object.prototype&&`constructor`in t&&t.constructor)return t.constructor.name}}return t}function at(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}function ot(e,t){for(let n in t){let r=Object.getOwnPropertyDescriptor(t,n);r.get?Object.defineProperty(e,n,{...r,enumerable:!1}):ut(e,n,r.value)}}function st(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function ct(e,t,n){return st(e,t,n,!1)}function lt(e,t){for(let n in e){let r=e[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return st(this,n,r(this))},set(e){st(this,n,e)}})}return t}function ut(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:st(this,t,n.bind(this))},set(e){st(this,t,e)}})}function dt(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}let ft,pt=!1;const mt={configurable:!0,get(){pt=!0}};function S(e,t,n){let r=Object.getPrototypeOf(e._zod);if(t in r&&ft!==e._zod){ft=void 0;return}ft=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,mt);let e=pt;pt=!1;try{let r=n(this);return pt?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:r}),pt||=e,r}catch(n){throw delete this[t],pt||=e,n}},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})}function ht(e,t,n,r){let i=dt(e,t);i&&Object.defineProperty(i,t,{configurable:!0,get(){let e={configurable:!0,writable:!0,enumerable:r,value:void 0};return Object.defineProperty(this,t,e),e.value=n(this),Object.defineProperty(this,t,e),e.value},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:r,value:e})}})}function gt(e){let t=()=>e;return t[`~constantCatch`]=!0,t}var _t;const vt=Object.freeze({status:`aborted`}),yt={value:void 0,enumerable:!1};let bt=`captureStackTrace`in Error?Error:null;function xt(e){let t=bt;if(t){let n=t.stackTraceLimit;if(typeof n==`number`){try{t.stackTraceLimit=0}catch{return bt=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}function C(e,t,n,r){let i={};function a(e){this.def=e,this.constr=d,this.traits=new Set}a.prototype=i;let o=n,s=o&&new WeakSet;function c(n,r){if(n._zod){if(n._zod.traits.has(e))return}else{yt.value=new a(r);try{Object.defineProperty(n,`_zod`,yt)}finally{yt.value=void 0}}if(n._zod.traits.add(e),t(n,r),s){let e=Object.getPrototypeOf(n),t=n._zod.constr.prototype,r=e;for(;r&&r!==t;)r=Object.getPrototypeOf(r);let i=r??e;s.has(i)||(s.add(i),ot(i,o))}let i=d.prototype;for(let e in i)Object.prototype.hasOwnProperty.call(i,e)&&(e in n||(n[e]=i[e].bind(n)))}let l=r?.Parent??Object;class u extends l{}Object.defineProperty(u,`name`,{value:e});function d(e){let t=r?.Parent?xt(u):this;c(t,e);let n=t._zod.deferred;if(n){for(let e of n)e();t._zod.deferred=void 0}let i=globalThis.__zod_globalConfig?.postProcessor;return i&&i(t),t}return Object.defineProperty(d,`init`,{value:c}),Object.defineProperty(d,Symbol.hasInstance,{value:t=>r?.Parent&&t instanceof r.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(d,`name`,{value:e}),d}var St=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},Ct=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(_t=globalThis).__zod_globalConfig??(_t.__zod_globalConfig={});const w=globalThis.__zod_globalConfig;function T(e){return e&&Object.assign(w,e),w}function wt(){let e=this._zod;return e.message??=JSON.stringify(e.def,me,2),e.message}function Tt(e){this._zod.message=e}const Et={get:wt,set:Tt,enumerable:!0,configurable:!0},Dt={value:void 0,enumerable:!1},Ot=new WeakSet([Object.prototype,Error.prototype]),kt=(e,t)=>{e.name=`$ZodError`,Dt.value=t,Object.defineProperty(e,`issues`,Dt),Dt.value=void 0,Object.defineProperty(e,`message`,Et);let n=Object.getPrototypeOf(e);Ot.has(n)||(Ot.add(n),Object.defineProperty(n,`toString`,{configurable:!0,enumerable:!1,get(){let e=()=>this.message;return Object.defineProperty(this,`toString`,{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,`toString`,{value:e,configurable:!0,writable:!0})}}))},At=C(`$ZodError`,kt);C(`$ZodError`,kt,void 0,{Parent:Error});function jt(e,t,n){return Object.prototype.hasOwnProperty.call(e,t)||(t===`__proto__`?Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0}):e[t]=n()),e[t]}function Mt(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?jt(n,i.path[0],()=>[]).push(t(i)):r.push(t(i));return{formErrors:r,fieldErrors:n}}function Nt(e,t=e=>e.message){let n={_errors:[]},r=(e,i=[])=>{for(let a of e.issues)if(a.code===`invalid_union`&&a.errors.length)a.errors.map(e=>r({issues:e},[...i,...a.path]));else if(a.code===`invalid_key`)r({issues:a.issues},[...i,...a.path]);else if(a.code===`invalid_element`)r({issues:a.issues},[...i,...a.path]);else{let e=[...i,...a.path];if(e.length===0)n._errors.push(t(a));else{let r=n,i=0;for(;i<e.length;){let n=e[i],o=i===e.length-1;if(n===`_errors`){o&&r._errors.push(t(a)),i++;continue}Object.prototype.hasOwnProperty.call(r,n)||Object.defineProperty(r,n,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let s=r[n];o&&s._errors.push(t(a)),r=s,i++}}}};return r(e),n}function Pt(e,t){return{callee:t?.callee??e,Err:t?.Err}}const Ft=e=>{let t=(n,r,i,a)=>{let o=i?{...i,async:!1}:{async:!1},s=n._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new St;if(s.issues.length){let n=new(a?.Err??e)(s.issues.map(e=>et(e,o,T())));throw Oe(n,a?.callee??t),n}return s.value};return t},It=e=>{let t=async(n,r,i,a)=>{let o=i?{...i,async:!0}:{async:!0},s=n._zod.run({value:r,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){let n=new(a?.Err??e)(s.issues.map(e=>et(e,o,T())));throw Oe(n,a?.callee??t),n}return s.value};return t},Lt=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new St;return a.issues.length?Rt(e,a.issues,i):{success:!0,data:a.value}};function Rt(e,t,n){let r;return{success:!1,get error(){return r||(r=new e(t.map(e=>et(e,n,T()))),t=void 0,n=void 0),r},set error(e){r=e,t=void 0,n=void 0}}}const zt=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?Rt(e,a.issues,i):{success:!0,data:a.value}},Bt=Symbol.for(`zod.compile.invalid`),Vt=Symbol.for(`zod.compile.fallback`),Ht=((e,t,n)=>{let r=e._zod.bag.validator;if(r!==void 0){if(r(t)!==Bt)return!0;if(r.definite===!0&&n===void 0)return!1}return Ut(e,t,n)});function Ut(e,t,n){let r=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},i=e._zod.bag.fallbackRun,a;if(i?(r[Vt]=!0,a=i({value:t,issues:[]},r)):a=e._zod.run({value:t,issues:[]},r),a instanceof Promise)throw new St;return a.issues.length===0}const Wt=async(e,t,n)=>{let r=n?{...n,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},i=e._zod.run({value:t,issues:[]},r);return i instanceof Promise&&(i=await i),i.issues.length===0},Gt=e=>{let t=Ft(e),n=(e,r,i,a)=>t(e,r,i?{...i,direction:`backward`}:{direction:`backward`},Pt(n,a));return n},Kt=e=>{let t=Ft(e),n=(e,r,i,a)=>t(e,r,i,Pt(n,a));return n},qt=e=>{let t=It(e),n=async(e,r,i,a)=>await t(e,r,i?{...i,direction:`backward`}:{direction:`backward`},Pt(n,a));return n},Jt=e=>{let t=It(e),n=async(e,r,i,a)=>await t(e,r,i,Pt(n,a));return n},Yt=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Lt(e)(t,n,i)},Xt=e=>(t,n,r)=>Lt(e)(t,n,r),Zt=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return zt(e)(t,n,i)},Qt=e=>async(t,n,r)=>zt(e)(t,n,r),$t=/^[cC][0-9a-z]{6,}$/,en=/^[0-9a-z]+$/,tn=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,nn=/^[0-9a-vA-V]{20}$/,rn=/^[A-Za-z0-9]{27}$/,an=/^[a-zA-Z0-9_-]{21}$/;function on(e){return RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}const sn=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,cn=/^([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})$/,ln=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[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|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,un=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function dn(){return RegExp(`^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`,`u`)}const fn=/^(?:(?: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])$/,pn=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,mn=/^((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])$/,hn=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,gn=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,_n=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,vn=/^https?$/,yn=/^\+[1-9]\d{6,14}$/,bn=`(?:(?:\\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])))`;function xn(e){return RegExp(`^${e}$`)}const Sn=xn(bn);function Cn(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?`${t}:[0-5]\\d(?:\\.\\d+)?`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function wn(e){return RegExp(`^${Cn(e)}$`)}function Tn(e){let t=[`Z`];e.offset&&t.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let n=`${Cn({precision:e.precision,seconds:!0})}(?:${t.join(`|`)})`,r=e.local?`${n}|${Cn({precision:e.precision})}`:n;return RegExp(`^${bn}T(?:${r})$`)}const En=/^[\s\S]{0,}$/,Dn=/^-?\d+$/,On=/^-?\d+(?:\.\d+)?$/,kn=/^(?:true|false)$/i,An=/^null$/i,jn=/^[^A-Z]*$/,Mn=/^[^a-z]*$/,E=C(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Nn=e=>{let t=e.value;return!_e(t)&&t.length!==void 0},Pn={number:`number`,bigint:`bigint`,object:`date`},Fn=C(`$ZodCheckLessThan`,(e,t)=>{E.init(e,t);let n=Pn[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:Pn[typeof r.value]??n,code:`too_big`,maximum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),In=C(`$ZodCheckGreaterThan`,(e,t)=>{E.init(e,t);let n=Pn[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:Pn[typeof r.value]??n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ln=C(`$ZodCheckMultipleOf`,(e,t)=>{E.init(e,t),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?t.value!==BigInt(0)&&n.value%t.value===BigInt(0):ye(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Rn=C(`$ZodCheckNumberFormat`,(e,t)=>{E.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=Re[t.format];e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),zn=C(`$ZodCheckMaxLength`,(e,t)=>{var n;E.init(e,t),(n=e._zod.def).when??(n.when=Nn),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>t.maximum?nt(r):i)<=t.maximum)return;let a=rt(r);n.issues.push({origin:a,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Bn=C(`$ZodCheckMinLength`,(e,t)=>{var n;E.init(e,t),(n=e._zod.def).when??(n.when=Nn),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>=t.minimum&&i<t.minimum*2?nt(r):i)>=t.minimum)return;let a=rt(r);n.issues.push({origin:a,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Vn=C(`$ZodCheckLengthEquals`,(e,t)=>{var n;E.init(e,t),(n=e._zod.def).when??(n.when=Nn),e._zod.check=n=>{let r=n.value,i=r.length,a=typeof r==`string`&&i>=t.length&&i<=t.length*2?nt(r):i;if(a===t.length)return;let o=rt(r),s=a>t.length;n.issues.push({origin:o,...s?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Hn=C(`$ZodCheckStringFormat`,(e,t)=>{var n,r;E.init(e,t),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Un=C(`$ZodCheckRegex`,(e,t)=>{Hn.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Wn=C(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=jn,Hn.init(e,t)}),Gn=C(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=Mn,Hn.init(e,t)}),Kn=C(`$ZodCheckIncludes`,(e,t)=>{E.init(e,t);let n=Pe(t.includes);t.pattern=new RegExp(typeof t.position==`number`?`^.{${t.position},}${n}`:n),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),qn=C(`$ZodCheckStartsWith`,(e,t)=>{E.init(e,t);let n=RegExp(`^${Pe(t.prefix)}.*`);t.pattern??=n,e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Jn=C(`$ZodCheckEndsWith`,(e,t)=>{E.init(e,t);let n=RegExp(`.*${Pe(t.suffix)}$`);t.pattern??=n,e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Yn=C(`$ZodCheckOverwrite`,(e,t)=>{E.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var Xn=class{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1;try{e(this)}finally{--this.indent}}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
|
|
4
|
+
`).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.content??[``];return new e(...Object.keys(this.closed),`return function (${this.args.join(`, `)}) {\n${t.join(`
|
|
5
|
+
`)}\n};`)(...Object.values(this.closed))}};const Zn={major:4,minor:6,patch:7},D=C(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Zn;let r=e._zod.def.checks,i=e._zod.traits.has(`$ZodCheck`)?[e,...r??[]]:r?.length?[...r]:[];for(let t of i)for(let n of t._zod.onattach)n(e);if(i.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(t,n,r)=>{if(t.memo)return t;let i=x(t),a;for(let o of n){if(o._zod.def.when){if(Ye(t)||!o._zod.def.when(t))continue}else if(i)continue;let n=t.issues.length,s=o._zod.check(t);if(s instanceof Promise&&r?.async===!1)throw new St;if(a||s instanceof Promise)a=(a??Promise.resolve()).then(async()=>{await s,t.issues.length!==n&&($e(t.issues,n,e),i||=x(t,n))});else{if(t.issues.length===n)continue;$e(t.issues,n,e),i||=x(t,n)}}return a?a.then(()=>t):t},n=(n,r,a)=>{if(x(n))return n.aborted=!0,n;let o=t(r,i,a);if(o instanceof Promise){if(a.async===!1)throw new St;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(r,a)=>{if(a.skipChecks)return e._zod.parse(r,a);if(a.direction===`backward`){let t=e._zod.parse({value:r.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,r,a)):n(t,r,a)}let o=e._zod.parse(r,a);if(o instanceof Promise){if(a.async===!1)throw new St;return o.then(e=>t(e,i,a))}return t(o,i,a)}}},{get"~standard"(){return ct(this,`~standard`,er(this))},set"~standard"(e){st(this,`~standard`,e)}}),Qn=(e,t)=>e.issues.length?{issues:e.issues.map(e=>et(e,t,T()))}:{value:e.value};async function $n(e,t){let n={async:!0};return Qn(await e._zod.run({value:t,issues:[]},n),n)}function er(e){return{validate:t=>{let n={async:!1};try{let r=e._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return Qn(r,n)}catch{}return $n(e,t)},vendor:`zod`,version:1}}const tr=C(`$ZodString`,(e,t)=>{D.init(e,t),e._zod.pattern=t.pattern??En,e._zod.parse=(n,r)=>{if(t.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:e}),n}}),O=C(`$ZodStringFormat`,(e,t)=>{Hn.init(e,t),tr.init(e,t)}),nr=C(`$ZodGUID`,(e,t)=>{t.pattern??=cn,O.init(e,t)}),rr=C(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=ln(e)}else t.pattern??=ln();O.init(e,t)}),ir=C(`$ZodEmail`,(e,t)=>{t.pattern??=un,O.init(e,t)});function ar(e){try{return typeof URL<`u`&&typeof URL.canParse==`function`?URL.canParse(e):(new URL(e),!0)}catch{return!1}}function or(e,t){return!(`normalize`in t)&&!(`hostname`in t)&&!(`protocol`in t)?ar(e)||2:sr(e,t)}function sr(e,t){if(!t.normalize&&t.protocol?.source===vn.source&&!/^https?:\/\//i.test(e))return 1;try{if(typeof URL<`u`){let t=URL;if(typeof t.parse==`function`)return t.parse(e)??2}return new URL(e)}catch{return 2}}const cr=/[\t\n\r]/g;function lr(e){return e.replace(cr,``)}function ur(e,t){return t.lastIndex=0,t.test(e.hostname)}function dr(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(`:`)?e.protocol.slice(0,-1):e.protocol)}const fr=C(`$ZodURL`,(e,t)=>{O.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),i=or(r,t);if(i===1){n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid URL format`,input:n.value,inst:e,continue:!t.abort});return}if(i===2){n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort});return}if(i===!0){n.value=lr(r);return}t.hostname&&!ur(i,t.hostname)&&n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort}),t.protocol&&!dr(i,t.protocol)&&n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort}),n.value=t.normalize?i.href:lr(r);return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),pr=C(`$ZodEmoji`,(e,t)=>{t.pattern??=dn(),O.init(e,t)}),mr=C(`$ZodNanoID`,(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw Error(`Invalid nanoid length: ${t.length}`);t.pattern??=t.length===void 0?an:on(t.length),O.init(e,t)}),hr=C(`$ZodCUID`,(e,t)=>{t.pattern??=$t,O.init(e,t)}),gr=C(`$ZodCUID2`,(e,t)=>{t.pattern??=en,O.init(e,t)}),_r=C(`$ZodULID`,(e,t)=>{t.pattern??=tn,O.init(e,t)}),vr=C(`$ZodXID`,(e,t)=>{t.pattern??=nn,O.init(e,t)}),yr=C(`$ZodKSUID`,(e,t)=>{t.pattern??=rn,O.init(e,t)}),br=C(`$ZodISODateTime`,(e,t)=>{t.pattern??=Tn(t),O.init(e,t)}),xr=C(`$ZodISODate`,(e,t)=>{t.pattern??=Sn,O.init(e,t)}),Sr=C(`$ZodISOTime`,(e,t)=>{t.pattern??=wn(t),O.init(e,t)}),Cr=C(`$ZodISODuration`,(e,t)=>{t.pattern??=sn,O.init(e,t)}),wr=C(`$ZodIPv4`,(e,t)=>{t.pattern??=fn,O.init(e,t)}),Tr=/^[0-9a-fA-F:.]+$/;function Er(e){return Tr.test(e)?ar(`http://[${e}]`):!1}const Dr=C(`$ZodIPv6`,(e,t)=>{t.pattern??=pn,O.init(e,t),e._zod.check=n=>{Er(n.value)||n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}),Or=C(`$ZodCIDRv4`,(e,t)=>{t.pattern??=mn,O.init(e,t)});function kr(e){let t=e.split(`/`);if(t.length!==2)return!1;let[n,r]=t;if(!r)return!1;let i=Number(r);return`${i}`!==r||i<0||i>128?!1:Er(n)}const Ar=C(`$ZodCIDRv6`,(e,t)=>{t.pattern??=hn,O.init(e,t),e._zod.check=n=>{kr(n.value)||n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}});function jr(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const Mr=/^[0-9a-zA-Z+/]*={0,2}$/,Nr=C(`$ZodBase64`,(e,t)=>{t.pattern??=Mr,O.init(e,t),e._zod.check=n=>{jr(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}}),Pr=/^[A-Za-z0-9_-]*$/;function Fr(e){if(!Pr.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return jr(t.padEnd(Math.ceil(t.length/4)*4,`=`))}const Ir=C(`$ZodBase64URL`,(e,t)=>{t.pattern??=Pr,O.init(e,t),e._zod.check=n=>{Fr(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),Lr=C(`$ZodE164`,(e,t)=>{t.pattern??=yn,O.init(e,t)});function Rr(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}const zr=C(`$ZodJWT`,(e,t)=>{O.init(e,t),e._zod.check=n=>{Rr(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),Br=C(`$ZodNumber`,(e,t)=>{D.init(e,t),e._zod.pattern=On,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:String(i):void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),Vr=C(`$ZodNumberFormat`,(e,t)=>{Rn.init(e,t),Br.init(e,t)}),Hr=C(`$ZodBoolean`,(e,t)=>{D.init(e,t),e._zod.pattern=kn,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),Ur=C(`$ZodNull`,(e,t)=>{D.init(e,t),e._zod.pattern=An,e._zod.values=new Set([null]),e._zod.parse=(t,n)=>{let r=t.value;return r===null||t.issues.push({expected:`null`,code:`invalid_type`,input:r,inst:e}),t}}),Wr=C(`$ZodUnknown`,(e,t)=>{D.init(e,t),e._zod.parse=e=>e}),Gr=C(`$ZodNever`,(e,t)=>{D.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function Kr(e,t){let n=Qe(e._zod.def.checks);if(!n.length)return;let r=Math.min(...n.map(e=>e[0])),i=e._zod.parse;e._zod.parse=(n,a)=>{let o=t(n.value);if(o>r&&!a?.skipChecks&&a?.direction!==`backward`){for(let[t,r]of Qe(e._zod.def.checks))if(o>t&&r._zod.def.when(n)){let t=n.issues.length;return r._zod.check(n),n.issues[t].continue=!1,$e(n.issues,t,e),n}}return i(n,a)}}const qr=e=>Array.isArray(e)?e.length:-1;function Jr(e,t,n){e.issues.length&&t.issues.push(...Xe(n,e.issues)),t.value[n]=e.value}const Yr=C(`$ZodArray`,(e,t)=>{D.init(e,t);let n=w.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!Array.isArray(a))return r.issues.push({expected:`array`,code:`invalid_type`,input:a,inst:e}),r;r.value=n?n.alloc(e,r,Array(a.length),i):Array(a.length);let o=[],s=i?.abortEarly;for(let e=0;e<a.length;e++){let n=a[e],c=t.element._zod.run({value:n,issues:[]},i);if(c instanceof Promise)o.push(c.then(t=>Jr(t,r,e)));else if(Jr(c,r,e),s&&c.issues.length!==0&&x(c))break}return o.length?Promise.all(o).then(()=>r):r},Kr(e,qr)});function Xr(e,t,n,r,i,a){let o=n in r,s=a===`optional`;if(!(!o&&s&&i===`optional`)){if(e.issues.length){if(i!==void 0&&s&&!o)return;t.issues.push(...Xe(n,e.issues))}if(!o&&i===void 0){e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]});return}e.value===void 0?(o||i===`defaulted`&&!s)&&(t.value[n]=void 0):t.value[n]=e.value}}const Zr=[];function Qr(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:Zr,i=r.length?[...t,...r]:t;for(let t of i)if(!e.shape?.[t]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${String(t)}": expected a Zod schema`);let a=Le(e.shape);return{...e,allKeys:i,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(a)}}function $r(e,t,n,r,i,a,o){let s=[],c=i.keySet,l=i.catchall._zod,u=l.def.type,d=l.optin,f=l.optout,p=0;for(let i in t){if(o&&n.issues.length!==p){if(x(n,p))break;p=n.issues.length}if(c.has(i))continue;if(i===`__proto__`){u===`never`&&s.push(i);continue}if(u===`never`){s.push(i);continue}let a=l.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>Xr(e,n,i,t,d,f))):Xr(a,n,i,t,d,f)}return s.length&&n.issues.push({code:`unrecognized_keys`,keys:s,input:t,inst:a,continue:!0}),e.length?Promise.all(e).then(()=>n):n}const ei=C(`$ZodObject`,(e,t)=>{D.init(e,t);let n=Object.getOwnPropertyDescriptor(t,`shape`),r=n?.get?n.get.raw:t.shape??{};if(r){let e=()=>{let n={...r};return Object.defineProperty(t,`shape`,{value:n}),e.raw=n,n};e.raw=r,Object.defineProperty(t,`shape`,{get:e})}let i=ge(()=>Qr(t));S(e,`propValues`,e=>{let t=e.def.shape,n={};for(let e in t){let r=t[e]._zod;if(r.values){Object.prototype.hasOwnProperty.call(n,e)||be(n,e,new Set);for(let t of r.values)n[e].add(t);r.optin!==void 0&&n[e].add(void 0)}}return n});let a=ke,o=t.catchall,s,c=w.memoizer;c?.attach(e),e._zod.parse=(t,n)=>{s??=i.value;let r=t.value;if(!a(r))return t.issues.push({expected:`object`,code:`invalid_type`,input:r,inst:e}),t;t.value=c?c.alloc(e,t,{},n):{};let l=[],u=s.shape,d=n?.abortEarly,f=t.issues.length;for(let e of s.allKeys){if(d&&t.issues.length!==f){if(x(t,f))break;f=t.issues.length}if(e===`__proto__`)continue;let i=u[e],a=i._zod.optin,o=i._zod.optout,s=i._zod.run({value:r[e],issues:[]},n);s instanceof Promise?l.push(s.then(n=>Xr(n,t,e,r,a,o))):Xr(s,t,e,r,a,o)}return o?$r(l,r,t,n,i.value,e,d===!0):l.length?Promise.all(l).then(()=>t):t}}),ti=C(`$ZodObjectJIT`,(e,t)=>{ei.init(e,t);let n=e._zod.parse,r=ge(()=>Qr(t)),i=w.memoizer,a=t=>{let n=r.value,a=n.symbolKeys,o=new Xn([`payload`,`ctx`],{shape:t,inst:e,memo:i,syms:a}),s=e=>`shape[${e}]._zod.run({ value: input[${e}], issues: [] }, ctx)`,c=(e,t)=>`
|
|
6
|
+
let ${e}_ab = false;
|
|
7
|
+
for (let i = 0; i < ${e}.issues.length; i++) {
|
|
8
|
+
const iss = ${e}.issues[i];
|
|
9
|
+
iss.path = iss.path ? [${t}, ...iss.path] : [${t}];
|
|
10
|
+
payload.issues.push(iss);
|
|
11
|
+
if (iss.continue !== true) ${e}_ab = true;
|
|
12
|
+
}
|
|
13
|
+
if (${e}_ab && ctx && ctx.abortEarly) {
|
|
14
|
+
payload.value = newResult;
|
|
15
|
+
return payload;
|
|
16
|
+
}`;o.write(`const input = payload.value;`);let l=Object.create(null),u=0;for(let e of n.allKeys)l[e]=`key_${u++}`;o.write(i?`const newResult = memo.alloc(inst, payload, {}, ctx);`:`const newResult = {};`);for(let e of n.allKeys){if(e===`__proto__`)continue;let n=l[e],r=typeof e==`symbol`?`syms[${a.indexOf(e)}]`:Ee(e),i=`${r} in input`,u=t[e],d=u?._zod?.optin,f=d!==void 0,p=u?._zod?.optout===`optional`;if(o.write(`const ${n} = ${s(r)};`),f&&p){let e=d===`optional`?`${n}_present`:`${n}.value !== undefined || ${n}_present`;o.write(`
|
|
17
|
+
const ${n}_present = ${i};
|
|
18
|
+
if (!${n}.issues.length || ${n}_present) {
|
|
19
|
+
if (${n}.issues.length) {${c(n,r)}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
if (${e}) {
|
|
23
|
+
newResult[${r}] = ${n}.value;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
`)}else f?(o.write(`
|
|
28
|
+
if (${n}.issues.length) {${c(n,r)}
|
|
29
|
+
}
|
|
30
|
+
`),d===`defaulted`?o.write(`newResult[${r}] = ${n}.value;`):o.write(`
|
|
31
|
+
if (${n}.value !== undefined || ${i}) {
|
|
32
|
+
newResult[${r}] = ${n}.value;
|
|
33
|
+
}
|
|
34
|
+
`)):o.write(`
|
|
35
|
+
const ${n}_present = ${i};
|
|
36
|
+
if (${n}.issues.length) {${c(n,r)}
|
|
37
|
+
}
|
|
38
|
+
if (!${n}_present && !${n}.issues.length) {
|
|
39
|
+
payload.issues.push({
|
|
40
|
+
code: "invalid_type",
|
|
41
|
+
expected: "nonoptional",
|
|
42
|
+
input: undefined,
|
|
43
|
+
path: [${r}]
|
|
44
|
+
});
|
|
45
|
+
if (ctx && ctx.abortEarly) {
|
|
46
|
+
payload.value = newResult;
|
|
47
|
+
return payload;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
if (${n}_present) {
|
|
52
|
+
newResult[${r}] = ${n}.value;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
`)}return o.write(`payload.value = newResult;`),o.write(`return payload;`),o.compile()},o,s=ke,c=!w.jitless,l=c&&Ae.value,u=t.catchall,d;e._zod.parse=(i,f)=>{d??=r.value;let p=i.value;return s(p)?c&&l&&f?.async===!1&&f.jitless!==!0?(o||=a(t.shape),i=o(i,f),u?$r([],p,i,f,d,e,f?.abortEarly===!0):i):n(i,f):(i.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),i)}});function ni(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!x(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>et(e,r,T())))}),t)}const ri=C(`$ZodUnion`,(e,t)=>{D.init(e,t),S(e,`optin`,e=>e.def.options.some(e=>e._zod.optin===`defaulted`)?`defaulted`:e.def.options.some(e=>e._zod.optin!==void 0)?`optional`:void 0),S(e,`optout`,e=>e.def.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),S(e,`values`,e=>{if(e.def.options.every(e=>e._zod.values))return new Set(e.def.options.flatMap(e=>Array.from(e._zod.values)))}),S(e,`pattern`,e=>{if(e.def.options.every(e=>e._zod.pattern)){let t=e.def.options.map(e=>e._zod.pattern);return RegExp(`^(${t.map(e=>ve(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>ni(t,r,e,i)):ni(o,r,e,i)}}),ii=C(`$ZodIntersection`,(e,t)=>{D.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>oi(e,t,n)):oi(e,i,a)}});function ai(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(je(e)&&je(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};Object.prototype.hasOwnProperty.call(i,`__proto__`)&&delete i.__proto__;for(let n of r){if(n===`__proto__`)continue;let r=ai(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=ai(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function oi(e,t,n){let r=new Map,i,a=new Map,o=(e,t)=>{let n;if(e.code===`unrecognized_keys`&&!e.path?.length)i??=e,n=e.keys;else if(e.code===`invalid_key`&&e.origin===`record`&&e.path?.length===1){let t=String(e.path[0]);a.has(t)||a.set(t,e),n=[t]}else return!1;for(let e of n)r.has(e)||r.set(e,{}),r.get(e)[t]=!0;return!0};for(let n of t.issues)o(n,`l`)||e.issues.push(n);for(let t of n.issues)o(t,`r`)||e.issues.push(t);let s=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(s.length){let t=i?s.filter(e=>i.keys.includes(e)):[];t.length&&e.issues.push({...i,keys:t});for(let n of s)!t.includes(n)&&a.has(n)&&e.issues.push(a.get(n))}let c=ai(t.value,n.value);if(!c.valid){if(x(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}const si=C(`$ZodRecord`,(e,t)=>{D.init(e,t);let n=w.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!je(a))return r.issues.push({expected:`record`,code:`invalid_type`,input:a,inst:e}),r;let o=[],s=t.keyType._zod.values;if(s&&!t.partial){r.value=n?n.alloc(e,r,{},i):{};let c=new Set;for(let n of s)if(typeof n==`string`||typeof n==`number`||typeof n==`symbol`){if(c.add(typeof n==`number`?n.toString():n),n===`__proto__`)continue;let s=t.keyType._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(s.issues.length){r.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>et(e,i,T())),input:n,path:[n],inst:e});continue}let l=s.value;if(l===`__proto__`)continue;let u=t.valueType._zod.run({value:a[n],issues:[]},i);u instanceof Promise?o.push(u.then(e=>{e.issues.length&&r.issues.push(...Xe(n,e.issues)),r.value[l]=e.value})):(u.issues.length&&r.issues.push(...Xe(n,u.issues)),r.value[l]=u.value)}let l;for(let e in a)if(!c.has(e))if(t.mode===`loose`){if(e===`__proto__`)continue;r.value[e]=a[e]}else l??=[],l.push(e);l&&l.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:l,continue:!0})}else{r.value=n?n.alloc(e,r,{},i):{};let c;for(let n of Reflect.ownKeys(a)){if(n===`__proto__`||!Object.prototype.propertyIsEnumerable.call(a,n))continue;let l=t.keyType._zod.run({value:n,issues:[]},i);if(l instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof n==`string`&&On.test(n)&&l.issues.length){let e=t.keyType._zod.run({value:Number(n),issues:[]},i);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(l=e)}if(l.issues.length){t.mode===`loose`?r.value[n]=a[n]:s?(c??=[],c.push(n)):r.issues.push({code:`invalid_key`,origin:`record`,issues:l.issues.map(e=>et(e,i,T())),input:n,path:[n],inst:e});continue}let u=l.value;if(u===`__proto__`)continue;let d=t.valueType._zod.run({value:a[n],issues:[]},i);d instanceof Promise?o.push(d.then(e=>{e.issues.length&&r.issues.push(...Xe(n,e.issues)),r.value[u]=e.value})):(d.issues.length&&r.issues.push(...Xe(n,d.issues)),r.value[u]=d.value)}c&&c.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:c,continue:!0})}return o.length?Promise.all(o).then(()=>r):r}}),ci=C(`$ZodEnum`,(e,t)=>{D.init(e,t);let n=fe(t.entries),r=new Set(n);e._zod.values=r,S(e,`pattern`,e=>{let t=fe(e.def.entries).filter(e=>Ne.has(typeof e));return RegExp(t.length?`^(${t.map(e=>Pe(e.toString())).join(`|`)})$`:`^[^\\s\\S]$`)}),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),li=C(`$ZodLiteral`,(e,t)=>{D.init(e,t);let n=new Set(t.values);e._zod.values=n,S(e,`pattern`,e=>{let t=e.def.values;return RegExp(t.length?`^(${t.map(e=>typeof e==`string`?Pe(e):e?Pe(e.toString()):String(e)).join(`|`)})$`:`^[^\\s\\S]$`)}),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}}),ui=C(`$ZodTransform`,(e,t)=>{D.init(e,t),e._zod.optin=`optional`,w.memoizer.guard(e),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Ct(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n));if(i instanceof Promise)throw new St;return n.value=i,n}});function di(e,t){return e.value=t.issues.length?void 0:t.value,e}const fi=C(`$ZodOptional`,(e,t)=>{D.init(e,t),S(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),e._zod.optout=`optional`,S(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t,void 0]):void 0}),S(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${ve(t.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(e.value===void 0){if(t.innerType._zod.optin!==`defaulted`)return e;let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(t=>di(e,t)):di(e,r)}return t.innerType._zod.run(e,n)}}),pi=C(`$ZodExactOptional`,(e,t)=>{fi.init(e,t),S(e,`values`,e=>e.def.innerType._zod.values),S(e,`pattern`,e=>e.def.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),mi=C(`$ZodNullable`,(e,t)=>{D.init(e,t),S(e,`optin`,e=>e.def.innerType._zod.optin),S(e,`optout`,e=>e.def.innerType._zod.optout),S(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${ve(t.source)}|null)$`):void 0}),S(e,`values`,e=>e.def.innerType._zod.values?new Set([...e.def.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),hi=C(`$ZodDefault`,(e,t)=>{D.init(e,t),e._zod.optin=`defaulted`,S(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>gi(e,t)):gi(r,t)}});function gi(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const _i=C(`$ZodPrefault`,(e,t)=>{D.init(e,t),e._zod.optin=`defaulted`,S(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),vi=C(`$ZodNonOptional`,(e,t)=>{D.init(e,t),S(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>yi(t,e)):yi(i,e)}});function yi(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}function bi(e,t,n,r){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(e=>et(e,r,T()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}const xi=C(`$ZodCatch`,(e,t)=>{D.init(e,t),S(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),S(e,`optout`,e=>e.def.innerType._zod.optout),S(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(r=>bi(e,r,t,n)):bi(e,r,t,n)}}),Si=C(`$ZodPipe`,(e,t)=>{D.init(e,t),S(e,`values`,e=>e.def.in._zod.values),S(e,`optin`,e=>e.def.in._zod.optin),S(e,`optout`,e=>e.def.out._zod.optout),S(e,`propValues`,e=>e.def.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>Ci(e,t.in,n)):Ci(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Ci(e,t.out,n)):Ci(r,t.out,n)}});function Ci(e,t,n){return e.issues.some(e=>e.code!==`unrecognized_keys`)?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const wi=C(`$ZodPreprocess`,(e,t)=>{Si.init(e,t)}),Ti=C(`$ZodReadonly`,(e,t)=>{D.init(e,t),S(e,`propValues`,e=>e.def.innerType._zod.propValues),S(e,`values`,e=>e.def.innerType._zod.values),S(e,`optin`,e=>e.def.innerType?._zod?.optin),S(e,`optout`,e=>e.def.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(Ei):Ei(r)}});function Ei(e){return e.memo||(e.value=Object.freeze(e.value)),e}const Di=C(`$ZodCustom`,(e,t)=>{E.init(e,t),D.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>Oi(t,n,r,e));Oi(i,n,r,e)}});function Oi(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(at(e))}}var ki=class extends Error{constructor(){super(`Cannot parse a reference cycle that closes through a transform`),this.name=`ZodCyclicError`}};const Ai=`~memo`,ji=[];function Mi(e){return typeof e==`object`&&!!e}function Ni(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}const Pi=new WeakMap;function Fi(e,t,n){let r=Pi.get(e);if(r!==void 0)return r?2:0;if(t.has(e))return 2;t.add(e);let i=0,a=e=>{if(i!==2&&e?._zod){let r=Fi(e,t,n);r>i&&(i=r)}},o=(e,r)=>{let i=0;for(let a of Reflect.ownKeys(e)){let o=Object.getOwnPropertyDescriptor(e,a);if(r&&!o.enumerable)continue;let s=o.get?1:o.value?._zod?Fi(o.value,t,n):0;s>i&&(i=s)}return i},s=e=>{e>i&&(i=e)},c=e._zod.def;switch(c.type){case`object`:{let e=xe(c);s(e?o(e,!0):1),a(c.catchall);break}case`array`:a(c.element);break;case`tuple`:for(let e of c.items)a(e);a(c.rest);break;case`record`:case`map`:a(c.keyType),a(c.valueType);break;case`set`:a(c.valueType);break;case`union`:for(let e of c.options)a(e);break;case`intersection`:a(c.left),a(c.right);break;case`optional`:case`nullable`:case`default`:case`prefault`:case`catch`:case`readonly`:case`nonoptional`:case`promise`:case`success`:a(c.innerType);break;case`pipe`:a(c.in),a(c.out);break;case`function`:a(c.input),a(c.output);break;case`lazy`:{let r=c._cachedInner??(n?e._zod.innerType:void 0);s(r?Fi(r,t,!1):1);break}case`template_literal`:case`string`:case`number`:case`int`:case`boolean`:case`bigint`:case`symbol`:case`undefined`:case`null`:case`void`:case`never`:case`any`:case`unknown`:case`date`:case`nan`:case`enum`:case`literal`:case`file`:case`transform`:case`custom`:break;default:for(let e in c){let t=Object.getOwnPropertyDescriptor(c,e);if(!t||t.get)continue;let n=t.value;if(!(!n||typeof n!=`object`)){if(n._zod)a(n);else if(Array.isArray(n))for(let e of n)a(e)}}}return t.delete(e),Ii(e,i)}function Ii(e,t){return t!==1&&Pi.set(e,t===2),t}function Li(e,t){let n=e.buckets.get(t);return n||(n=new WeakMap,e.buckets.set(t,n)),n}let Ri;const zi=[],Bi={alloc(e,t,n){let r=Ri;if(!r)return n;Ri=void 0;let i={value:n,issues:null};return r.set(t.value,i),zi.push(i),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,n=(e,n)=>{if(n.direction!==`backward`&&Hi(n,e.value))throw new ki;return t(e,n)};e._zod.parse=n,e._zod.run===t&&(e._zod.run=n)})},attach(e){var t;let n,r=!1,i,a;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,o=(s,c)=>{if(n===void 0){let i=Fi(e,new Set,!1);if(i===0)return e._zod.parse=t,e._zod.run===o&&(e._zod.run=t),t(s,c);i===2||r?n=!0:r=!0}let l=s.value;if(!Mi(l))return t(s,c);let u=c[Ai];u||(u={buckets:new WeakMap,backEdges:void 0},c[Ai]=u);let d;i===c?d=a:(d=Li(u,e),i=c,a=d);let f=d.get(l);if(f)return s.value=f.value,f.issues?f.issues.length&&s.issues.push(...Ni(f.issues)):(s.memo=!0,u.backEdges??=new WeakSet,u.backEdges.add(f.value)),s;Ri=d;let p=zi.length,ee=t(s,c);Ri=void 0;let m=zi.length>p?zi.pop():void 0;return ee instanceof Promise?ee.then(e=>(m&&(m.issues=e.issues.length?Ni(e.issues):ji),e)):(m&&(m.issues=ee.issues.length?Ni(ee.issues):ji),ee)};e._zod.parse=o,e._zod.run===t&&(e._zod.run=o)})}};function Vi(){return Bi}function Hi(e,t){let n=e[Ai]?.backEdges;return n!==void 0&&Mi(t)&&n.has(t)}const Ui=()=>{let e={string:{unit:`characters`,verb:`to have`},file:{unit:`bytes`,verb:`to have`},array:{unit:`items`,verb:`to have`},set:{unit:`items`,verb:`to have`},map:{unit:`entries`,verb:`to have`}};function t(t){return e[t]??null}let n={regex:`input`,email:`email address`,url:`URL`,emoji:`emoji`,uuid:`UUID`,uuidv4:`UUIDv4`,uuidv6:`UUIDv6`,nanoid:`nanoid`,guid:`GUID`,cuid:`cuid`,cuid2:`cuid2`,ulid:`ULID`,xid:`XID`,ksuid:`KSUID`,datetime:`ISO datetime`,date:`ISO date`,time:`ISO time`,duration:`ISO duration`,ipv4:`IPv4 address`,ipv6:`IPv6 address`,mac:`MAC address`,cidrv4:`IPv4 range`,cidrv6:`IPv6 range`,base64:`base64-encoded string`,base64url:`base64url-encoded string`,json_string:`JSON string`,e164:`E.164 number`,currency_code:`currency code`,credit_card:`credit card number`,iban:`IBAN`,jwt:`JWT`,template_literal:`input`},r={nan:`NaN`};function i(e,t){return e===`number`&&typeof t==`number`&&!Number.isFinite(t)?String(t):r[e]??e}return e=>{switch(e.code){case`invalid_type`:return`Invalid input: expected ${i(e.expected)}, received ${i(it(e.input),e.input)}`;case`invalid_value`:return e.values.length===1?`Invalid input: expected ${Ie(e.values[0])}`:`Invalid option: expected one of ${pe(e.values,`|`)}`;case`too_big`:{let n=e.exact?`exactly `:e.inclusive?`<=`:`<`,r=t(e.origin);return r?`Too big: expected ${e.origin??`value`} to have ${n}${e.maximum.toString()} ${r.unit??`elements`}`:`Too big: expected ${e.origin??`value`} to be ${n}${e.maximum.toString()}`}case`too_small`:{let n=e.exact?`exactly `:e.inclusive?`>=`:`>`,r=t(e.origin);return r?`Too small: expected ${e.origin} to have ${n}${e.minimum.toString()} ${r.unit}`:`Too small: expected ${e.origin} to be ${n}${e.minimum.toString()}`}case`invalid_format`:{let t=e;return t.format===`starts_with`?`Invalid string: must start with "${t.prefix}"`:t.format===`ends_with`?`Invalid string: must end with "${t.suffix}"`:t.format===`includes`?`Invalid string: must include "${t.includes}"`:t.format===`regex`?`Invalid string: must match pattern ${t.pattern}`:`Invalid ${n[t.format]??e.format}`}case`not_multiple_of`:return`Invalid number: must be a multiple of ${e.divisor}`;case`unrecognized_keys`:return`Unrecognized key${e.keys.length>1?`s`:``}: ${pe(e.keys,`, `)}`;case`invalid_key`:return`Invalid key in ${e.origin}`;case`invalid_union`:return e.options&&Array.isArray(e.options)&&e.options.length>0?`Invalid discriminator value. Expected ${e.options.map(e=>`'${e}'`).join(` | `)}`:e.inclusive===!1?`Invalid input: more than one option matched`:`Invalid input`;case`invalid_element`:return`Invalid value in ${e.origin}`;default:return`Invalid input`}}};function Wi(){return{localeError:Ui()}}var Gi,Ki=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function qi(){return new Ki}(Gi=globalThis).__zod_globalRegistry??(Gi.__zod_globalRegistry=qi());const Ji=globalThis.__zod_globalRegistry;function Yi(e){return e.checks&&=[...e.checks],e}function Xi(e,t){return new e(Yi({type:`string`,...b(t)}))}function Zi(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...b(t)})}function Qi(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...b(t)})}function $i(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...b(t)})}function ea(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...b(t)})}function ta(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...b(t)})}function na(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...b(t)})}function ra(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...b(t)})}function ia(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...b(t)})}function aa(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...b(t)})}function oa(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...b(t)})}function sa(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...b(t)})}function ca(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...b(t)})}function la(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...b(t)})}function ua(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...b(t)})}function da(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...b(t)})}function fa(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...b(t)})}function pa(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...b(t)})}function ma(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...b(t)})}function ha(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...b(t)})}function ga(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...b(t)})}function _a(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...b(t)})}function va(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...b(t)})}function ya(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...b(t)})}function ba(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...b(t)})}function xa(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...b(t)})}function Sa(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...b(t)})}function Ca(e,t){return new e(Yi({type:`number`,checks:[],...b(t)}))}function wa(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...b(t)})}function Ta(e,t){return new e({type:`boolean`,...b(t)})}function Ea(e,t){return new e({type:`null`,...b(t)})}function Da(e){return new e({type:`unknown`})}function Oa(e,t){return new e({type:`never`,...b(t)})}function ka(e,t){return new Fn({check:`less_than`,...b(t),value:e,inclusive:!1})}function Aa(e,t){return new Fn({check:`less_than`,...b(t),value:e,inclusive:!0})}function ja(e,t){return new In({check:`greater_than`,...b(t),value:e,inclusive:!1})}function Ma(e,t){return new In({check:`greater_than`,...b(t),value:e,inclusive:!0})}function Na(e,t){return new Ln({check:`multiple_of`,...b(t),value:e})}function Pa(e,t){return new zn({check:`max_length`,...b(t),maximum:e})}function Fa(e,t){return new Bn({check:`min_length`,...b(t),minimum:e})}function Ia(e,t){return new Vn({check:`length_equals`,...b(t),length:e})}function La(e,t){return new Un({check:`string_format`,format:`regex`,...b(t),pattern:e})}function Ra(e){return new Wn({check:`string_format`,format:`lowercase`,...b(e)})}function za(e){return new Gn({check:`string_format`,format:`uppercase`,...b(e)})}function Ba(e,t){return new Kn({check:`string_format`,format:`includes`,...b(t),includes:e})}function Va(e,t){return new qn({check:`string_format`,format:`starts_with`,...b(t),prefix:e})}function Ha(e,t){return new Jn({check:`string_format`,format:`ends_with`,...b(t),suffix:e})}function Ua(e){return new Yn({check:`overwrite`,tx:e})}function Wa(e){return Ua(t=>t.normalize(e))}function Ga(){return Ua(e=>e.trim())}function Ka(){return Ua(e=>e.toLowerCase())}function qa(){return Ua(e=>e.toUpperCase())}function Ja(){return Ua(e=>De(e))}function Ya(e,t,n){return new e({type:`array`,element:t,...b(n)})}function Xa(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...b(n)})}function Za(e,t){let n=Qa(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(at(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,`input`in r||(r.input=t.value),r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(at(r))}},e(t.value,t)),t);return n}function Qa(e,t){let n=new E({check:`custom`,...b(t)});return n._zod.check=e,n}function $a(e,...t){for(let n of t)for(let t of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,t)&&be(e,t,n[t]);return e}function eo(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??Ji,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,intersections:[],deferred:[],external:e?.external??void 0}}function to(e,t,n,r,i){let a=typeof t.unrepresentable==`function`?t.unrepresentable({zodSchema:e,path:r.path,message:i}):t.unrepresentable;if(a===`any`)return!1;if(a===void 0||a===`throw`)throw Error(i);return Object.assign(n,a),!0}function k(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,k(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&$a(o.schema,c),t.io===`input`&&A(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function no(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function ro(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);if(e.external&&e.sharedDefsExtractedFor===e.external)return;let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${no(a)}`}}let i=`#/${r}/`;if(t[1]===n&&!t[1].schema.id)return{ref:`#`};let a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+no(a)}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
|
|
56
|
+
|
|
57
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}r.count>1&&e.reused===`ref`&&a(n)}e.external&&(e.sharedDefsExtractedFor=e.external)}function io(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let e of t){if(!e||typeof e!=`object`)return;io(e);let t=Object.keys(e);if(t.length!==1||t[0]!==`type`)return;let r=e.type;for(let e of Array.isArray(r)?r:[r]){if(typeof e!=`string`)return;n.includes(e)||n.push(e)}}delete e.anyOf,e.type=n.length===1?n[0]:n}const ao=new Set([`type`,`properties`,`required`,`additionalProperties`]),oo=[`oneOf`,`anyOf`];function so(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function co(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!ao.has(e))return null;t.push(n)}let n={},r=new Set;for(let e of t){for(let r in e.properties){if(Object.prototype.hasOwnProperty.call(n,r))continue;let e=[];for(let n of t){let t=n.properties?.[r]??so(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}be(n,r,e.length===1?e[0]:co(e)??{allOf:e})}for(let t of e.required??[])r.add(t)}let i={type:`object`,properties:n};if(r.size&&(i.required=[...r]),t.every(e=>e.additionalProperties===!1))i.additionalProperties=!1;else{let e=[];for(let n of t){let t=so(n);t&&!e.some(e=>JSON.stringify(e)===JSON.stringify(t))&&e.push(t)}e.length===1?i.additionalProperties=e[0]:e.length>1&&(i.additionalProperties={allOf:e})}return i}function lo(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of ao)if(t in e)return;let n=t.filter(e=>oo.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=co(t);else{let e=n[0],i=oo.find(t=>Array.isArray(e[t]));if(Object.keys(e).length!==1)return;let a=t.filter(t=>t!==e),o=e[i].map(e=>co([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,$a(e,r))}function uo(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):$a(i,s),$a(i,a),t._zod.parent===o)for(let e in i)e===`$ref`||e===`allOf`||e in a||delete i[e];if(s.$ref&&n.def)for(let e in i)e===`$ref`||e===`allOf`||e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e===`$ref`||e===`allOf`||e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let t of[...e.seen.entries()].reverse())r(t[0]);if(e.target!==`openapi-3.0`)for(let t of e.seen.entries())io(t[1].def??t[1].schema);for(let t of e.deferred)t();if(e.intersections.length){let t=new Map;for(let n of e.seen.values())for(let e of[n.schema,n.def]){let n=e?.allOf;if(!Array.isArray(n))continue;let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let n of e.intersections)for(let e of t.get(n)??[])lo(e)}}let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}$a(i,n.defId?n.schema:n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,be(o,e.defId,e.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,`~standard`,{value:{...t[`~standard`],jsonSchema:{input:po(t,`input`,e.processors),output:po(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function A(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return A(r.element,n);if(r.type===`set`)return A(r.valueType,n);if(r.type===`lazy`)return A(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type===`default`||r.type===`prefault`||r.type===`catch`)return A(r.innerType,n);if(r.type===`intersection`)return A(r.left,n)||A(r.right,n);if(r.type===`record`||r.type===`map`)return A(r.keyType,n)||A(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:A(r.in,n)||A(r.out,n);if(r.type===`object`){for(let e in r.shape)if(A(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(A(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(A(e,n))return!0;return!!(r.rest&&A(r.rest,n))}return!1}const fo=(e,t={})=>n=>{let r=eo({...n,processors:t});return k(e,r),ro(r,e),uo(r,e)},po=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=eo({...i??{},target:a,io:t,processors:n});return k(e,o),ro(o,e),uo(o,e)},mo=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},ho=(e,t,n)=>{(e[t]===void 0||n<e[t])&&(e[t]=n)},go=(e,t)=>{mo(e,`minimum`,t),ho(e,`maximum`,t)},_o=(e,t)=>{e.multipleOf??=[],e.multipleOf.includes(t)||e.multipleOf.push(t)},vo=(e,t)=>{e.patterns??=new Set,e.patterns.add(t)},yo=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]},bo=(e,t)=>{e.format=t,t.includes(`int`)&&(e.isInt=!0)},xo=(e,t)=>mo(e,`minimum`,t.minimum),So=(e,t)=>ho(e,`maximum`,t.maximum),Co=e=>(t,n)=>{bo(t,n.format);let[r,i]=e[n.format];mo(t,`minimum`,r),ho(t,`maximum`,i)},wo={greater_than:(e,t)=>mo(e,t.inclusive?`minimum`:`exclusiveMinimum`,t.value),less_than:(e,t)=>ho(e,t.inclusive?`maximum`:`exclusiveMaximum`,t.value),multiple_of:(e,t)=>_o(e,t.value),number_format:Co(Re),bigint_format:Co(ze),min_length:xo,max_length:So,length_equals:(e,t)=>go(e,t.length),min_size:xo,max_size:So,size_equals:(e,t)=>go(e,t.size),string_format:(e,t)=>{bo(e,t.format),t.pattern&&vo(e,t.pattern),(t.format===`base64`||t.format===`base64url`)&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>yo(e,t.mime)};function j(e){let t={},n=e._zod.def,r=e._zod.traits.has(`$ZodCheck`)?[e,...n.checks??[]]:n.checks??[];for(let e of r)wo[e._zod.def.check]?.(t,e._zod.def);let i=e._zod.bag;i.minimum!==void 0&&mo(t,`minimum`,i.minimum),i.exclusiveMinimum!==void 0&&mo(t,`exclusiveMinimum`,i.exclusiveMinimum),i.maximum!==void 0&&ho(t,`maximum`,i.maximum),i.exclusiveMaximum!==void 0&&ho(t,`exclusiveMaximum`,i.exclusiveMaximum),i.multipleOf!==void 0&&_o(t,i.multipleOf),i.format!==void 0&&(t.format??=i.format,i.format.includes(`int`)&&(t.isInt=!0)),i.mime&&yo(t,i.mime);for(let e of i.patterns??[])vo(t,e);return t}const To={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Eo=new Map([[Mr,gn],[Pr,_n]]),Do=e=>Eo.get(e)??e,Oo=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=j(e);if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=To[s]??s,i.format===``&&delete i.format,(s===`time`||u)&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c].map(Do);e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},ko=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,multipleOf:s,exclusiveMaximum:c,exclusiveMinimum:l,isInt:u}=j(e);i.type=u?`integer`:`number`;let d=typeof l==`number`&&l>=(a??-1/0),f=typeof c==`number`&&c<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;if(d?p?(i.minimum=l,i.exclusiveMinimum=!0):i.exclusiveMinimum=l:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=c,i.exclusiveMaximum=!0):i.exclusiveMaximum=c:typeof o==`number`&&(i.maximum=o),s){let n=new Set;for(let a of s)Number.isFinite(a)&&a!==0?n.add(Math.abs(a)):to(e,t,i,r,`A multipleOf divisor of ${a} cannot be represented in JSON Schema`);let[a,...o]=n;a!==void 0&&(i.multipleOf=a),o.length&&(i.allOf=[...i.allOf??[],...o.map(e=>({multipleOf:e}))])}},Ao=(e,t,n,r)=>{n.type=`boolean`},jo=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},Mo=(e,t,n,r)=>{n.not={}},No=(e,t,n,r)=>{let i=e._zod.def,a=fe(i.entries);if(a.length===0){n.not={};return}a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},Po=(e,t,n,r)=>{let i=e._zod.def;if(i.values.length===0){n.not={};return}let a=[];for(let o of i.values)if(o===void 0){if(to(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof o==`bigint`){if(to(e,t,n,r,`BigInt literals cannot be represented in JSON Schema`))return;a.push(Number(o))}else a.push(o);if(a.length!==0)if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a},Fo=(e,t,n,r)=>{to(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},Io=(e,t,n,r)=>{to(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},Lo=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=j(e);typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=k(a.element,t,{...r,path:[...r.path,`items`]})};function Ro(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?Ro(t.out):t.type===`catch`?Ro(t.innerType):e._zod.optin}const zo=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&to(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;for(let e in i.type=`object`,i.properties={},o)be(i.properties,e,k(o[e],t,{...r,path:[...r.path,`properties`,e]}));let s=[];for(let e of Object.keys(o)){let n=a.shape[e];(t.io===`input`?Ro(n)===void 0:n._zod.optout===void 0)&&s.push(e)}s.length>0&&(i.required=s),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=k(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Bo=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>k(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},Vo=(e,t,n,r)=>{let i=e._zod.def,a=k(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=k(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];n.allOf=c,t.intersections.push(c)};function Ho(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let r=e.get(t)?.def;if(!r)return t;let i=Ho(e,r,n);return i===r?t:i}for(let r of[`anyOf`,`oneOf`]){let i=t[r];if(!Array.isArray(i))continue;let a=i.map(t=>Ho(e,t,n));a.some((e,t)=>e!==i[t])&&(t={...t,[r]:a})}let r=Array.isArray(t.type)?t.type:[t.type],i=!r.includes(`string`)&&r.some(e=>e===`number`||e===`integer`),a=t.enum??(t.const===void 0?void 0:[t.const]);if(!i&&!a?.some(e=>typeof e==`number`))return t;let{minimum:o,maximum:s,exclusiveMinimum:c,exclusiveMaximum:l,multipleOf:u,format:d,id:f,...p}=t;return p.enum?p.enum=p.enum.map(e=>typeof e==`number`?String(e):e):typeof p.const==`number`&&(p.const=String(p.const)),i?(p.type=`string`,a||(p.pattern=(r.includes(`number`)?On:Dn).source),p):p}const Uo=new WeakMap;function Wo(e){let t=new Map;for(let n of e.seen.values())n.def&&!t.has(n.schema)&&t.set(n.schema,n);let n=new Map;for(let r of Uo.get(e)??[]){let i=e.seen.get(r),a=(i?.def??i?.schema)?.propertyNames;if(!a||a===!0||n.has(a))continue;let o=Ho(t,a,new Set);o!==a&&n.set(a,o)}if(n.size)for(let t of e.seen.values())for(let e of[t.schema,t.def]){let t=e&&n.get(e.propertyNames);t&&(e.propertyNames=t)}}const Go=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=j(o).patterns;if(a.mode===`loose`&&s&&s.size>0){let e=k(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)be(i.patternProperties,Do(t).source,e)}else{if(t.target===`draft-07`||t.target===`draft-2020-12`){i.propertyNames=k(a.keyType,t,{...r,path:[...r.path,`propertyNames`]});let n=Uo.get(t);n||(n=[],Uo.set(t,n),t.deferred.push(()=>Wo(t))),n.push(e)}i.additionalProperties=k(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]})}let c=o._zod.values,l=t.io===`input`&&Ro(a.valueType)!==void 0;if(c&&!a.partial&&!l){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e.map(String))}},Ko=(e,t,n,r)=>{let i=e._zod.def,a=k(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},qo=(e,t,n,r)=>{let i=e._zod.def;k(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Jo=Symbol();function Yo(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(to(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),Jo):JSON.parse(o)}const Xo=(e,t,n,r)=>{let i=e._zod.def;k(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o=Yo(i.defaultValue,e,t,n,r);o!==Jo&&(n.default=o)},Zo=(e,t,n,r)=>{let i=e._zod.def;k(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=Yo(i.defaultValue,e,t,n,r);o!==Jo&&(n._prefault=o)},Qo=(e,t,n,r)=>{let i=e._zod.def;k(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{to(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},$o=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;k(o,t,r);let s=t.seen.get(e);s.ref=o},es=(e,t,n,r)=>{let i=e._zod.def;k(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},ts=(e,t,n,r)=>{let i=e._zod.def;k(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},ns=new WeakSet([Object.prototype,Error.prototype]);function rs(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let e=n(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0})}})}const M=C(`ZodError`,(e,t)=>{At.init(e,t),e.name=`ZodError`;let n=Object.getPrototypeOf(e);ns.has(n)||(ns.add(n),rs(n,`format`,e=>t=>Nt(e,t)),rs(n,`flatten`,e=>t=>Mt(e,t)),rs(n,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,me,2)}),rs(n,`addIssues`,e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,me,2)}),Object.defineProperty(n,`isEmpty`,{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},void 0,{Parent:Error}),is=Ft(M),as=It(M),os=Lt(M),ss=zt(M),cs=Gt(M),ls=Kt(M),us=qt(M),ds=Jt(M),fs=Yt(M),ps=Xt(M),ms=Zt(M),hs=Qt(M);function gs(){w.localeError||T(Wi())}function _s(){w.memoizer||T({memoizer:Vi()})}const N=C(`ZodType`,(e,t)=>(gs(),D.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(y(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Fe(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(kc(e,t))},superRefine(e,t){return this.check(Ac(e,t))},overwrite(e){return this.check(Ua(e))},optional(){return uc(this)},exactOptional(){return fc(this)},nullable(){return mc(this)},nullish(){return uc(mc(this))},nonoptional(e){return bc(this,e)},array(){return B(this)},or(e){return H([this,e])},and(e){return U(this,e)},transform(e){return wc(this,cc(e))},default(e){return gc(this,e)},prefault(e){return vc(this,e)},catch(e){return Sc(this,e)},pipe(e){return wc(this,e)},readonly(){return Dc(this)},describe(e){let t=this.clone();return Ji.add(t,{description:e}),t},meta(...e){if(e.length===0)return Ji.get(this);let t=this.clone();return Ji.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return ct(this,`~standard`,{...er(this),jsonSchema:{input:po(this,`input`),output:po(this,`output`)}})},set"~standard"(e){st(this,`~standard`,e)},parse:function e(t,n){return is(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await as(this,t,n,{callee:e})},safeParse(e,t){return os(this,e,t)},async safeParseAsync(e,t){return ss(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){st(this,`spa`,e)},validate(e,t){return Ht(this,e,t)},validateAsync(e,t){return Wt(this,e,t)},encode:function e(t,n){return cs(this,t,n,{callee:e})},decode:function e(t,n){return ls(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await us(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await ds(this,t,n,{callee:e})},safeEncode(e,t){return fs(this,e,t)},safeDecode(e,t){return ps(this,e,t)},async safeEncodeAsync(e,t){return ms(this,e,t)},async safeDecodeAsync(e,t){return hs(this,e,t)},toJSONSchema(e){return fo(this,{})(e)},get description(){return Ji.get(this)?.description},get _def(){return this._zod.def}}),vs=C(`_ZodString`,(e,t)=>{tr.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Oo(e,t,n,r)},lt({format:e=>j(e).format??null,minLength:e=>j(e).minimum??null,maxLength:e=>j(e).maximum??null},{regex(...e){return this.check(La(...e))},includes(...e){return this.check(Ba(...e))},startsWith(...e){return this.check(Va(...e))},endsWith(...e){return this.check(Ha(...e))},min(...e){return this.check(Fa(...e))},max(...e){return this.check(Pa(...e))},length(...e){return this.check(Ia(...e))},nonempty(...e){return this.check(Fa(1,...e))},lowercase(e){return this.check(Ra(e))},uppercase(e){return this.check(za(e))},trim(){return this.check(Ga())},normalize(...e){return this.check(Wa(...e))},toLowerCase(){return this.check(Ka())},toUpperCase(){return this.check(qa())},slugify(){return this.check(Ja())}})),ys=C(`ZodString`,(e,t)=>{tr.init(e,t),vs.init(e,t)},{email(e){return this.check(Zi(ws,e))},url(e){return this.check(ra(Ds,e))},jwt(e){return this.check(va(Us,e))},emoji(e){return this.check(ia(ks,e))},guid(e){return this.check(Qi(Ts,e))},uuid(e){return this.check($i(Es,e))},uuidv4(e){return this.check(ea(Es,e))},uuidv6(e){return this.check(ta(Es,e))},uuidv7(e){return this.check(na(Es,e))},nanoid(e){return this.check(aa(As,e))},cuid(e){return this.check(oa(js,e))},cuid2(e){return this.check(sa(Ms,e))},ulid(e){return this.check(ca(Ns,e))},base64(e){return this.check(ha(Bs,e))},base64url(e){return this.check(ga(Vs,e))},xid(e){return this.check(la(Ps,e))},ksuid(e){return this.check(ua(Fs,e))},ipv4(e){return this.check(da(Is,e))},ipv6(e){return this.check(fa(Ls,e))},cidrv4(e){return this.check(pa(Rs,e))},cidrv6(e){return this.check(ma(zs,e))},e164(e){return this.check(_a(Hs,e))},datetime(e){return this.check(ya(bs,e))},date(e){return this.check(ba(xs,e))},time(e){return this.check(xa(Ss,e))},duration(e){return this.check(Sa(Cs,e))}});function P(e){return Xi(ys,e)}const F=C(`ZodStringFormat`,(e,t)=>{O.init(e,t),vs.init(e,t)}),bs=C(`ZodISODateTime`,(e,t)=>{br.init(e,t),F.init(e,t)}),xs=C(`ZodISODate`,(e,t)=>{xr.init(e,t),F.init(e,t)}),Ss=C(`ZodISOTime`,(e,t)=>{Sr.init(e,t),F.init(e,t)}),Cs=C(`ZodISODuration`,(e,t)=>{Cr.init(e,t),F.init(e,t)}),ws=C(`ZodEmail`,(e,t)=>{ir.init(e,t),F.init(e,t)}),Ts=C(`ZodGUID`,(e,t)=>{nr.init(e,t),F.init(e,t)}),Es=C(`ZodUUID`,(e,t)=>{rr.init(e,t),F.init(e,t)}),Ds=C(`ZodURL`,(e,t)=>{fr.init(e,t),F.init(e,t)});function Os(e){return ra(Ds,e)}const ks=C(`ZodEmoji`,(e,t)=>{pr.init(e,t),F.init(e,t)}),As=C(`ZodNanoID`,(e,t)=>{mr.init(e,t),F.init(e,t)}),js=C(`ZodCUID`,(e,t)=>{hr.init(e,t),F.init(e,t)}),Ms=C(`ZodCUID2`,(e,t)=>{gr.init(e,t),F.init(e,t)}),Ns=C(`ZodULID`,(e,t)=>{_r.init(e,t),F.init(e,t)}),Ps=C(`ZodXID`,(e,t)=>{vr.init(e,t),F.init(e,t)}),Fs=C(`ZodKSUID`,(e,t)=>{yr.init(e,t),F.init(e,t)}),Is=C(`ZodIPv4`,(e,t)=>{wr.init(e,t),F.init(e,t)}),Ls=C(`ZodIPv6`,(e,t)=>{Dr.init(e,t),F.init(e,t)}),Rs=C(`ZodCIDRv4`,(e,t)=>{Or.init(e,t),F.init(e,t)}),zs=C(`ZodCIDRv6`,(e,t)=>{Ar.init(e,t),F.init(e,t)}),Bs=C(`ZodBase64`,(e,t)=>{Nr.init(e,t),F.init(e,t)}),Vs=C(`ZodBase64URL`,(e,t)=>{Ir.init(e,t),F.init(e,t)}),Hs=C(`ZodE164`,(e,t)=>{Lr.init(e,t),F.init(e,t)}),Us=C(`ZodJWT`,(e,t)=>{zr.init(e,t),F.init(e,t)}),Ws=C(`ZodNumber`,(e,t)=>{Br.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ko(e,t,n,r),e.isFinite=!0},lt({minValue:e=>{let{minimum:t,exclusiveMinimum:n}=j(e);return Math.max(t??-1/0,n??-1/0)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=j(e);return Math.min(t??1/0,n??1/0)},isInt:e=>{let{isInt:t,multipleOf:n}=j(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>j(e).format??null},{gt(e,t){return this.check(ja(e,t))},gte(e,t){return this.check(Ma(e,t))},min(e,t){return this.check(Ma(e,t))},lt(e,t){return this.check(ka(e,t))},lte(e,t){return this.check(Aa(e,t))},max(e,t){return this.check(Aa(e,t))},int(e){return this.check(L(e))},safe(e){return this.check(L(e))},positive(e){return this.check(ja(0,e))},nonnegative(e){return this.check(Ma(0,e))},negative(e){return this.check(ka(0,e))},nonpositive(e){return this.check(Aa(0,e))},multipleOf(e,t){return this.check(Na(e,t))},step(e,t){return this.check(Na(e,t))},finite(){return this}}));function I(e){return Ca(Ws,e)}const Gs=C(`ZodNumberFormat`,(e,t)=>{Vr.init(e,t),Ws.init(e,t)});function L(e){return wa(Gs,e)}const Ks=C(`ZodBoolean`,(e,t)=>{Hr.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ao(e,t,n,r)});function R(e){return Ta(Ks,e)}const qs=C(`ZodNull`,(e,t)=>{Ur.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>jo(e,t,n,r)});function Js(e){return Ea(qs,e)}const Ys=C(`ZodUnknown`,(e,t)=>{Wr.init(e,t),N.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function z(){return Da(Ys)}const Xs=C(`ZodNever`,(e,t)=>{Gr.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Mo(e,t,n,r)});function Zs(e){return Oa(Xs,e)}const Qs=C(`ZodArray`,(e,t)=>{_s(),Yr.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Lo(e,t,n,r),e.element=t.element},{min(e,t){return this.check(Fa(e,t))},nonempty(e){return this.check(Fa(1,e))},max(e,t){return this.check(Pa(e,t))},length(e,t){return this.check(Ia(e,t))},unwrap(){return this.element}});function B(e,t){return Ya(Qs,e,t)}const $s=C(`ZodObject`,(e,t)=>{_s(),ti.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>zo(e,t,n,r),ht(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return ac(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(y(this._zod.def,{catchall:e}))},passthrough(){return this.clone(y(this._zod.def,{catchall:z()}))},loose(){return this.clone(y(this._zod.def,{catchall:z()}))},strict(){return this.clone(y(this._zod.def,{catchall:Zs()}))},strip(){return this.clone(y(this._zod.def,{catchall:void 0}))},extend(e){return Ue(this,e)},safeExtend(e){return Ge(this,e)},merge(e){return Ke(this,e)},pick(e){return Be(this,e)},omit(e){return He(this,e)},partial(...e){return qe(lc,this,e[0])},exactPartial(...e){return qe(dc,this,e[0],`exactPartial`)},required(...e){return Je(yc,this,e[0])}});function V(e,t){return new $s({type:`object`,shape:e??{},...b(t)})}function ec(e,t){return new $s({type:`object`,shape:e,catchall:z(),...b(t)})}const tc=C(`ZodUnion`,(e,t)=>{ri.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Bo(e,t,n,r),e.options=t.options});function H(e,t){return new tc({type:`union`,options:e,...b(t)})}const nc=C(`ZodIntersection`,(e,t)=>{ii.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Vo(e,t,n,r)});function U(e,t){return new nc({type:`intersection`,left:e,right:t})}const rc=C(`ZodRecord`,(e,t)=>{_s(),si.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Go(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function W(e,t,n){return!t||!t._zod?new rc({type:`record`,keyType:P(),valueType:e,...b(t)}):new rc({type:`record`,keyType:e,valueType:t,...b(n)})}const ic=C(`ZodEnum`,(e,t)=>{ci.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>No(e,t,n,r),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new ic({...t,checks:[],...b(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new ic({...t,checks:[],...b(r),entries:i})}});function ac(e,t){return new ic({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...b(t)})}const oc=C(`ZodLiteral`,(e,t)=>{li.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Po(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,`value`,{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function G(e,t){return new oc({type:`literal`,values:Array.isArray(e)?e:[e],...b(t)})}const sc=C(`ZodTransform`,(e,t)=>{_s(),ui.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Io(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Ct(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(at(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,`input`in t||(t.input=n.value),t.inst??=e,n.issues.push(at(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function cc(e){return new sc({type:`transform`,transform:e})}const lc=C(`ZodOptional`,(e,t)=>{fi.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ts(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function uc(e){return new lc({type:`optional`,innerType:e})}const dc=C(`ZodExactOptional`,(e,t)=>{pi.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ts(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function fc(e){return new dc({type:`optional`,innerType:e})}const pc=C(`ZodNullable`,(e,t)=>{mi.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ko(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function mc(e){return new pc({type:`nullable`,innerType:e})}const hc=C(`ZodDefault`,(e,t)=>{hi.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function gc(e,t){return new hc({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():Me(t)}})}const _c=C(`ZodPrefault`,(e,t)=>{_i.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function vc(e,t){return new _c({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():Me(t)}})}const yc=C(`ZodNonOptional`,(e,t)=>{vi.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>qo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function bc(e,t){return new yc({type:`nonoptional`,innerType:e,...b(t)})}const xc=C(`ZodCatch`,(e,t)=>{xi.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Qo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Sc(e,t){return new xc({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:gt(t)})}const Cc=C(`ZodPipe`,(e,t)=>{Si.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$o(e,t,n,r),e.in=t.in,e.out=t.out});function wc(e,t){return new Cc({type:`pipe`,in:e,out:t})}const Tc=C(`ZodPreprocess`,(e,t)=>{Cc.init(e,t),wi.init(e,t)}),Ec=C(`ZodReadonly`,(e,t)=>{Ti.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>es(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Dc(e){return new Ec({type:`readonly`,innerType:e})}const Oc=C(`ZodCustom`,(e,t)=>{Di.init(e,t),N.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Fo(e,t,n,r)});function kc(e,t={}){return Xa(Oc,e,t)}function Ac(e,t){return Za(e,t)}function jc(e,t){return new Tc({type:`pipe`,in:cc(e),out:t})}const Mc=Symbol(`skippedItem`);function K(e,t){return e.catch(t)}function q(e,t){let n=e.catch(t);return z().transform((e,t)=>e===void 0?(t.addIssue({code:`custom`,message:`Required value is missing`}),vt):n.parse(e))}function Nc(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return;let n=e[t];return typeof n==`string`?n:void 0}function Pc(e,t,n){return e.superRefine((e,r)=>{let i=Nc(e,t);i!==void 0&&n.includes(i)&&r.addIssue({code:`custom`,path:[t],message:`${t} ${JSON.stringify(i)} is reserved by a known variant, but the value does not match that variant's schema`})})}function Fc(e,t,n){return z().transform((r,i)=>{let a=e.safeParse(r);if(!a.success){for(let e of a.error.issues)i.addIssue({...e,input:r});return vt}let o=a.data,s=Nc(r,t);if(s!==void 0&&!n.includes(s)){let e=r;for(let[t,n]of Object.entries(e))t!==`__proto__`&&(Object.hasOwn(o,t)||(o[t]=n))}return o})}function Ic(e,t){return jc(e=>{if(typeof e!=`object`||!e||Array.isArray(e))return e;let n=e,r=n[t];if(r==null||typeof r==`string`)return e;let i={...n};return delete i[t],i},e)}function J(e){return B(e.catch(Mc)).transform(e=>e.filter(e=>e!==Mc))}const Lc=H([I(),P()]).nullable(),Y=P(),Rc=V({sessionId:Y,path:P(),content:P(),_meta:K(W(P(),z()).nullish(),()=>void 0)}),zc=V({sessionId:Y,path:P(),line:L().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),limit:L().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Bc=P(),Vc=H([G(`read`),G(`edit`),G(`delete`),G(`move`),G(`search`),G(`execute`),G(`think`),G(`fetch`),G(`switch_mode`),G(`other`)]),Hc=H([G(`pending`),G(`in_progress`),G(`completed`),G(`failed`)]),Uc=V({audience:K(J(H([G(`assistant`),G(`user`)])).nullish(),()=>void 0),lastModified:K(P().nullish(),()=>void 0),priority:K(I().nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Wc=V({annotations:K(Uc.nullish(),()=>void 0),text:P(),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Gc=V({annotations:K(Uc.nullish(),()=>void 0),data:P(),mimeType:P(),uri:K(P().nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Kc=V({annotations:K(Uc.nullish(),()=>void 0),data:P(),mimeType:P(),_meta:K(W(P(),z()).nullish(),()=>void 0)}),qc=V({annotations:K(Uc.nullish(),()=>void 0),description:K(P().nullish(),()=>void 0),mimeType:K(P().nullish(),()=>void 0),name:P(),size:K(I().nullish(),()=>void 0),title:K(P().nullish(),()=>void 0),uri:P(),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Jc=H([V({mimeType:K(P().nullish(),()=>void 0),text:P(),uri:P(),_meta:K(W(P(),z()).nullish(),()=>void 0)}),V({blob:P(),mimeType:K(P().nullish(),()=>void 0),uri:P(),_meta:K(W(P(),z()).nullish(),()=>void 0)})]),Yc=V({annotations:K(Uc.nullish(),()=>void 0),resource:Jc,_meta:K(W(P(),z()).nullish(),()=>void 0)}),Xc=H([Wc.and(V({type:G(`text`)})),Gc.and(V({type:G(`image`)})),Kc.and(V({type:G(`audio`)})),qc.and(V({type:G(`resource_link`)})),Yc.and(V({type:G(`resource`)}))]),Zc=V({content:Xc,_meta:K(W(P(),z()).nullish(),()=>void 0)}),Qc=V({path:P(),oldText:K(P().nullish(),()=>void 0),newText:P(),_meta:K(W(P(),z()).nullish(),()=>void 0)}),$c=P(),el=V({terminalId:$c,_meta:K(W(P(),z()).nullish(),()=>void 0)}),tl=H([Zc.and(V({type:G(`content`)})),Qc.and(V({type:G(`diff`)})),el.and(V({type:G(`terminal`)}))]),nl=V({path:P(),line:K(L().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),rl=V({toolCallId:Bc,kind:K(Vc.nullish(),()=>void 0),status:K(Hc.nullish(),()=>void 0),title:K(P().nullish(),()=>void 0),name:K(P().nullish(),()=>void 0),content:K(J(tl).nullish(),()=>void 0),locations:K(J(nl).nullish(),()=>void 0),rawInput:K(z().optional(),()=>void 0),rawOutput:K(z().optional(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),il=P(),al=H([G(`allow_once`),G(`allow_always`),G(`reject_once`),G(`reject_always`)]),ol=V({sessionId:Y,toolCall:rl,options:B(V({optionId:il,name:P(),kind:al,_meta:K(W(P(),z()).nullish(),()=>void 0)})),_meta:K(W(P(),z()).nullish(),()=>void 0)}),sl=V({name:P(),value:P(),_meta:K(W(P(),z()).nullish(),()=>void 0)}),cl=V({sessionId:Y,command:P(),args:B(P()).optional(),env:B(sl).optional(),cwd:P().nullish(),outputByteLimit:I().nullish(),_meta:K(W(P(),z()).nullish(),()=>void 0)}),ll=V({sessionId:Y,terminalId:$c,_meta:K(W(P(),z()).nullish(),()=>void 0)}),ul=V({sessionId:Y,terminalId:$c,_meta:K(W(P(),z()).nullish(),()=>void 0)}),dl=V({sessionId:Y,terminalId:$c,_meta:K(W(P(),z()).nullish(),()=>void 0)}),fl=V({sessionId:Y,terminalId:$c,_meta:K(W(P(),z()).nullish(),()=>void 0)}),pl=V({sessionId:Y,toolCallId:K(Bc.nullish(),()=>void 0)}),ml=V({requestId:Lc}),hl=G(`object`),gl=H([G(`email`),G(`uri`),G(`date`),G(`date-time`)]),_l=V({const:P(),title:P(),description:K(P().nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),vl=V({title:K(P().nullish(),()=>void 0),description:K(P().nullish(),()=>void 0),minLength:L().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),maxLength:L().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),pattern:P().nullish(),format:gl.nullish(),default:K(P().nullish(),()=>void 0),enum:B(P()).nullish(),oneOf:B(_l).nullish(),_meta:K(W(P(),z()).nullish(),()=>void 0)}),yl=V({title:K(P().nullish(),()=>void 0),description:K(P().nullish(),()=>void 0),minimum:I().nullish(),maximum:I().nullish(),default:K(I().nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),bl=V({title:K(P().nullish(),()=>void 0),description:K(P().nullish(),()=>void 0),minimum:I().nullish(),maximum:I().nullish(),default:K(I().nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),xl=V({title:K(P().nullish(),()=>void 0),description:K(P().nullish(),()=>void 0),default:K(R().nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Sl=V({enum:B(P()),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Cl=V({anyOf:B(_l),_meta:K(W(P(),z()).nullish(),()=>void 0)}),wl=Fc(H([Sl.and(V({type:G(`string`)})),Pc(V({type:P()}),`type`,[`string`]),Cl]),`type`,[`string`]),Tl=V({title:K(P().nullish(),()=>void 0),description:K(P().nullish(),()=>void 0),minItems:I().nullish(),maxItems:I().nullish(),items:wl,default:K(J(P()).nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),El=Fc(H([vl.and(V({type:G(`string`)})),yl.and(V({type:G(`number`)})),bl.and(V({type:G(`integer`)})),xl.and(V({type:G(`boolean`)})),Tl.and(V({type:G(`array`)})),Pc(V({type:P()}),`type`,[`array`,`boolean`,`integer`,`number`,`string`])]),`type`,[`array`,`boolean`,`integer`,`number`,`string`]),Dl=V({type:K(hl.optional().default(`object`),()=>`object`),title:K(P().nullish(),()=>void 0),properties:W(P(),El).optional().default({}),required:B(P()).nullish(),description:K(P().nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Ol=U(H([pl,ml]),V({requestedSchema:Dl})),kl=P(),Al=U(H([pl,ml]),V({elicitationId:kl,url:Os()})),jl=Fc(U(H([Ol.and(V({mode:G(`form`)})),Al.and(V({mode:G(`url`)})),Pc(U(H([pl,ml]),V({mode:P()})),`mode`,[`form`,`url`])]),V({message:P(),_meta:K(W(P(),z()).nullish(),()=>void 0)})),`mode`,[`form`,`url`]),Ml=P(),Nl=P(),Pl=V({serverId:Ml,requestId:Nl,method:P(),params:W(P(),z()).nullish(),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Fl=z();V({id:Lc,method:P(),params:H([Rc,zc,ol,cl,ll,ul,dl,fl,jl,Pl,Fl]).nullish()});const Il=L().gte(0).lte(65535),Ll=V({image:K(R().optional().default(!1),()=>!1),audio:K(R().optional().default(!1),()=>!1),embeddedContext:K(R().optional().default(!1),()=>!1),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Rl=V({http:K(R().optional().default(!1),()=>!1),sse:K(R().optional().default(!1),()=>!1),acp:K(R().optional().default(!1),()=>!1),_meta:K(W(P(),z()).nullish(),()=>void 0)}),zl=V({_meta:K(W(P(),z()).nullish(),()=>void 0)}),Bl=V({_meta:K(W(P(),z()).nullish(),()=>void 0)}),Vl=V({_meta:K(W(P(),z()).nullish(),()=>void 0)}),Hl=V({_meta:K(W(P(),z()).nullish(),()=>void 0)}),Ul=V({_meta:K(W(P(),z()).nullish(),()=>void 0)}),Wl=V({_meta:K(W(P(),z()).nullish(),()=>void 0)}),Gl=V({list:K(zl.nullish(),()=>void 0),delete:K(Bl.nullish(),()=>void 0),additionalDirectories:K(Vl.nullish(),()=>void 0),fork:K(Hl.nullish(),()=>void 0),resume:K(Ul.nullish(),()=>void 0),close:K(Wl.nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Kl=V({logout:K(V({_meta:K(W(P(),z()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),ql=V({_meta:K(W(P(),z()).nullish(),()=>void 0)}),Jl=V({_meta:K(W(P(),z()).nullish(),()=>void 0)}),Yl=V({syncKind:H([G(`full`),G(`incremental`)]),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Xl=V({_meta:K(W(P(),z()).nullish(),()=>void 0)}),Zl=V({_meta:K(W(P(),z()).nullish(),()=>void 0)}),Ql=V({_meta:K(W(P(),z()).nullish(),()=>void 0)}),$l=V({document:K(V({didOpen:K(Jl.nullish(),()=>void 0),didChange:K(Yl.nullish(),()=>void 0),didClose:K(Xl.nullish(),()=>void 0),didSave:K(Zl.nullish(),()=>void 0),didFocus:K(Ql.nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),eu=V({maxCount:K(L().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),tu=V({_meta:K(W(P(),z()).nullish(),()=>void 0)}),nu=V({maxCount:K(L().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),ru=V({maxCount:K(L().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),iu=V({_meta:K(W(P(),z()).nullish(),()=>void 0)}),au=V({_meta:K(W(P(),z()).nullish(),()=>void 0)}),ou=V({recentFiles:K(eu.nullish(),()=>void 0),relatedSnippets:K(tu.nullish(),()=>void 0),editHistory:K(nu.nullish(),()=>void 0),userActions:K(ru.nullish(),()=>void 0),openFiles:K(iu.nullish(),()=>void 0),diagnostics:K(au.nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),su=V({events:K($l.nullish(),()=>void 0),context:K(ou.nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),cu=H([G(`utf-16`),G(`utf-32`),G(`utf-8`)]),lu=V({loadSession:K(R().optional().default(!1),()=>!1),promptCapabilities:K(Ll.optional().default({image:!1,audio:!1,embeddedContext:!1}),()=>({image:!1,audio:!1,embeddedContext:!1})),mcpCapabilities:K(Rl.optional().default({http:!1,sse:!1,acp:!1}),()=>({http:!1,sse:!1,acp:!1})),sessionCapabilities:K(Gl.optional().default({}),()=>({})),auth:K(Kl.optional().default({}),()=>({})),providers:K(ql.nullish(),()=>void 0),nes:K(su.nullish(),()=>void 0),positionEncoding:K(cu.nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),uu=P(),du=V({id:uu,name:P(),description:K(P().nullish(),()=>void 0),args:B(P()).optional(),env:W(P(),P()).optional(),_meta:K(W(P(),z()).nullish(),()=>void 0)}),fu=V({id:uu,name:P(),description:K(P().nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),pu=H([du.and(V({type:G(`terminal`)})),fu]),mu=V({name:P(),title:K(P().nullish(),()=>void 0),version:P(),_meta:K(W(P(),z()).nullish(),()=>void 0)}),hu=V({protocolVersion:Il,agentCapabilities:K(lu.optional().default({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}}),()=>({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}})),authMethods:K(J(pu).optional().default([]),()=>[]),agentInfo:K(mu.nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),gu=V({_meta:K(W(P(),z()).nullish(),()=>void 0)}),_u=P(),vu=H([G(`anthropic`),G(`openai`),G(`azure`),G(`vertex`),G(`bedrock`),P()]),yu=V({apiType:vu,baseUrl:P(),_meta:K(W(P(),z()).nullish(),()=>void 0)}),bu=V({providers:B(V({providerId:_u,supported:q(J(vu),()=>[]),required:R(),current:yu.nullish(),_meta:K(W(P(),z()).nullish(),()=>void 0)})),_meta:K(W(P(),z()).nullish(),()=>void 0)}),xu=V({_meta:K(W(P(),z()).nullish(),()=>void 0)}),Su=V({_meta:K(W(P(),z()).nullish(),()=>void 0)}),Cu=V({_meta:K(W(P(),z()).nullish(),()=>void 0)}),wu=P(),Tu=V({currentModeId:wu,availableModes:q(J(V({id:wu,name:P(),description:K(P().nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)})),()=>[]),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Eu=P(),Du=H([G(`mode`),G(`model`),G(`model_config`),G(`thought_level`),P()]),Ou=P(),ku=V({value:Ou,name:P(),description:K(P().nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Au=V({group:P(),name:P(),options:q(J(ku),()=>[]),_meta:K(W(P(),z()).nullish(),()=>void 0)}),ju=V({currentValue:Ou,options:H([B(ku),B(Au)])}),Mu=V({currentValue:R()}),Nu=U(H([ju.and(V({type:G(`select`)})),Mu.and(V({type:G(`boolean`)}))]),V({id:Eu,name:P(),description:K(P().nullish(),()=>void 0),category:K(Du.nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)})),Pu=V({sessionId:Y,modes:K(Tu.nullish(),()=>void 0),configOptions:K(J(Nu).nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Fu=V({modes:K(Tu.nullish(),()=>void 0),configOptions:K(J(Nu).nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Iu=V({sessions:q(J(V({sessionId:Y,cwd:P(),additionalDirectories:K(J(P()).optional(),()=>[]),title:K(P().nullish(),()=>void 0),updatedAt:K(P().nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)})),()=>[]),nextCursor:K(P().nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Lu=V({_meta:K(W(P(),z()).nullish(),()=>void 0)}),Ru=V({sessionId:Y,modes:K(Tu.nullish(),()=>void 0),configOptions:K(J(Nu).nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),zu=V({modes:K(Tu.nullish(),()=>void 0),configOptions:K(J(Nu).nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Bu=V({_meta:K(W(P(),z()).nullish(),()=>void 0)}),Vu=V({_meta:K(W(P(),z()).nullish(),()=>void 0)}),Hu=V({configOptions:q(J(Nu),()=>[]),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Uu=H([G(`end_turn`),G(`max_tokens`),G(`max_turn_requests`),G(`refusal`),G(`cancelled`)]),Wu=V({totalTokens:I(),inputTokens:I(),outputTokens:I(),thoughtTokens:K(I().nullish(),()=>void 0),cachedReadTokens:K(I().nullish(),()=>void 0),cachedWriteTokens:K(I().nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Gu=V({stopReason:Uu,usage:K(Wu.nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Ku=V({sessionId:Y,_meta:K(W(P(),z()).nullish(),()=>void 0)}),qu=P(),Ju=V({line:L().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),character:L().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Yu=V({start:Ju,end:Ju,_meta:K(W(P(),z()).nullish(),()=>void 0)}),Xu=V({range:Yu,newText:P(),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Zu=V({id:qu,uri:P(),edits:B(Xu),cursorPosition:K(Ju.nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Qu=V({id:qu,uri:P(),position:Ju,_meta:K(W(P(),z()).nullish(),()=>void 0)}),$u=V({id:qu,uri:P(),position:Ju,newName:P(),_meta:K(W(P(),z()).nullish(),()=>void 0)}),ed=V({id:qu,uri:P(),search:P(),replace:P(),isRegex:R().nullish(),_meta:K(W(P(),z()).nullish(),()=>void 0)}),td=V({suggestions:B(H([Zu.and(V({kind:G(`edit`)})),Qu.and(V({kind:G(`jump`)})),$u.and(V({kind:G(`rename`)})),ed.and(V({kind:G(`searchAndReplace`)}))])),_meta:K(W(P(),z()).nullish(),()=>void 0)}),nd=V({_meta:K(W(P(),z()).nullish(),()=>void 0)}),rd=z(),id=V({code:H([G(-32700),G(-32600),G(-32601),G(-32602),G(-32603),G(-32800),G(-32e3),G(-32002),L().min(-2147483648,{error:`Invalid value: Expected int32 to be >= -2147483648`}).max(2147483647,{error:`Invalid value: Expected int32 to be <= 2147483647`})]),message:P(),data:K(z().optional(),()=>void 0)});H([V({id:Lc,result:H([hu,gu,bu,xu,Su,Cu,Pu,Fu,Iu,Lu,Ru,zu,Bu,Vu,Hu,Gu,Ku,td,nd,rd])}),V({id:Lc,error:id})]);const ad=P(),od=V({content:Xc,messageId:K(ad.nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),sd=V({toolCallId:Bc,title:P(),name:K(P().nullish(),()=>void 0),kind:K(Vc.optional(),()=>void 0),status:K(Hc.optional(),()=>void 0),content:K(J(tl).optional(),()=>[]),locations:K(J(nl).optional(),()=>[]),rawInput:K(z().optional(),()=>void 0),rawOutput:K(z().optional(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),cd=H([G(`high`),G(`medium`),G(`low`)]),ld=H([G(`pending`),G(`in_progress`),G(`completed`)]),ud=V({content:P(),priority:cd,status:ld,_meta:K(W(P(),z()).nullish(),()=>void 0)}),dd=V({entries:q(J(ud),()=>[]),_meta:K(W(P(),z()).nullish(),()=>void 0)}),fd=P(),pd=V({planId:fd,entries:q(J(ud),()=>[]),_meta:K(W(P(),z()).nullish(),()=>void 0)}),md=V({planId:fd,uri:P(),_meta:K(W(P(),z()).nullish(),()=>void 0)}),hd=V({planId:fd,content:P(),_meta:K(W(P(),z()).nullish(),()=>void 0)}),gd=V({plan:H([pd.and(V({type:G(`items`)})),md.and(V({type:G(`file`)})),hd.and(V({type:G(`markdown`)}))]),_meta:K(W(P(),z()).nullish(),()=>void 0)}),_d=V({planId:fd,_meta:K(W(P(),z()).nullish(),()=>void 0)}),vd=V({hint:P(),_meta:K(W(P(),z()).nullish(),()=>void 0)}),yd=V({availableCommands:q(J(V({name:P(),description:P(),input:K(vd.nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)})),()=>[]),_meta:K(W(P(),z()).nullish(),()=>void 0)}),bd=V({currentModeId:wu,_meta:K(W(P(),z()).nullish(),()=>void 0)}),xd=V({configOptions:q(J(Nu),()=>[]),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Sd=V({title:K(P().nullish(),()=>void 0),updatedAt:K(P().nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Cd=V({amount:I(),currency:P(),_meta:K(W(P(),z()).nullish(),()=>void 0)}),wd=V({used:I(),size:I(),cost:K(Cd.nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Td=V({severity:H([G(`info`),G(`warning`),G(`error`),P()]),title:P().min(1),description:K(P().nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Ed=P(),Dd=V({compactionId:Ed,status:H([G(`in_progress`),G(`completed`),G(`failed`),G(`cancelled`),P()]),summary:K(J(Xc).nullish(),()=>void 0),error:K(P().nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Od=V({compactionId:Ed,content:Xc,_meta:K(W(P(),z()).nullish(),()=>void 0)}),kd=V({cancel:K(V({_meta:K(W(P(),z()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Ad=V({_meta:K(W(P(),z()).nullish(),()=>void 0)}),jd=V({error:K(id.nullish(),()=>void 0)}),Md=Ic(Fc(U(H([V({stopReason:G(`end_turn`)}),V({stopReason:G(`max_tokens`)}),V({stopReason:G(`max_turn_requests`)}),V({stopReason:G(`refusal`)}),V({stopReason:G(`cancelled`)}),jd.and(V({stopReason:G(`error`)})),Pc(V({stopReason:P()}),`stopReason`,[`cancelled`,`end_turn`,`error`,`max_tokens`,`max_turn_requests`,`refusal`]),V({stopReason:Js().optional()})]),V({usage:K(Wu.nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0),stopReason:K(P().nullish(),()=>void 0)})),`stopReason`,[`cancelled`,`end_turn`,`error`,`max_tokens`,`max_turn_requests`,`refusal`]),`stopReason`),Nd=V({_meta:K(W(P(),z()).nullish(),()=>void 0)}),Pd=V({_meta:K(W(P(),z()).nullish(),()=>void 0)}),Fd=Fc(H([Ad.and(V({state:G(`running`)})),Md.and(V({state:G(`idle`)})),Nd.and(V({state:G(`requires_action`)})),Pd.and(V({state:G(`unknown`)})),Pc(V({state:P()}),`state`,[`idle`,`requires_action`,`running`,`unknown`])]),`state`,[`idle`,`requires_action`,`running`,`unknown`]),Id=V({sessionId:Y,title:K(P().nullish(),()=>void 0),description:K(P().nullish(),()=>void 0),capabilities:K(kd.nullish(),()=>void 0),state:K(Fd.nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Ld=V({messageId:ad,senderSessionId:K(Y.nullish(),()=>void 0),recipientSessionId:K(Y.nullish(),()=>void 0),content:K(J(Xc).nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Rd=V({messageId:ad,senderSessionId:K(Y.nullish(),()=>void 0),recipientSessionId:K(Y.nullish(),()=>void 0),content:Xc,_meta:K(W(P(),z()).nullish(),()=>void 0)}),zd=V({sessionId:Y,update:H([od.and(V({sessionUpdate:G(`user_message_chunk`)})),od.and(V({sessionUpdate:G(`agent_message_chunk`)})),od.and(V({sessionUpdate:G(`agent_thought_chunk`)})),sd.and(V({sessionUpdate:G(`tool_call`)})),rl.and(V({sessionUpdate:G(`tool_call_update`)})),dd.and(V({sessionUpdate:G(`plan`)})),gd.and(V({sessionUpdate:G(`plan_update`)})),_d.and(V({sessionUpdate:G(`plan_removed`)})),yd.and(V({sessionUpdate:G(`available_commands_update`)})),bd.and(V({sessionUpdate:G(`current_mode_update`)})),xd.and(V({sessionUpdate:G(`config_option_update`)})),Sd.and(V({sessionUpdate:G(`session_info_update`)})),wd.and(V({sessionUpdate:G(`usage_update`)})),Td.and(V({sessionUpdate:G(`notice`)})),Dd.and(V({sessionUpdate:G(`compaction_update`)})),Od.and(V({sessionUpdate:G(`compaction_summary_chunk`)})),Id.and(V({sessionUpdate:G(`subagent_update`)})),Ld.and(V({sessionUpdate:G(`session_message`)})),Rd.and(V({sessionUpdate:G(`session_message_chunk`)}))]),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Bd=V({elicitationId:kl,_meta:K(W(P(),z()).nullish(),()=>void 0)}),Vd=z();V({method:P(),params:H([zd,Bd,Vd]).nullish()});const Hd=V({readTextFile:K(R().optional().default(!1),()=>!1),writeTextFile:K(R().optional().default(!1),()=>!1),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Ud=W(P(),z()),Wd=V({boolean:K(V({_meta:K(W(P(),z()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Gd=W(P(),z()),Kd=V({compaction:K(Ud.nullish(),()=>void 0),configOptions:K(Wd.nullish(),()=>void 0),notices:K(Gd.nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),qd=V({_meta:K(W(P(),z()).nullish(),()=>void 0)}),Jd=V({_meta:K(W(P(),z()).nullish(),()=>void 0)}),Yd=V({terminal:K(R().optional().default(!1),()=>!1),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Xd=V({_meta:K(W(P(),z()).nullish(),()=>void 0)}),Zd=V({_meta:K(W(P(),z()).nullish(),()=>void 0)}),Qd=V({form:K(Xd.nullish(),()=>void 0),url:K(Zd.nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),$d=V({_meta:K(W(P(),z()).nullish(),()=>void 0)}),ef=V({_meta:K(W(P(),z()).nullish(),()=>void 0)}),tf=V({_meta:K(W(P(),z()).nullish(),()=>void 0)}),nf=V({jump:K($d.nullish(),()=>void 0),rename:K(ef.nullish(),()=>void 0),searchAndReplace:K(tf.nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),rf=V({protocolVersion:Il,clientCapabilities:K(V({fs:K(Hd.optional().default({readTextFile:!1,writeTextFile:!1}),()=>({readTextFile:!1,writeTextFile:!1})),terminal:K(R().optional().default(!1),()=>!1),session:K(Kd.nullish(),()=>void 0),subagents:K(qd.nullish(),()=>void 0),plan:K(Jd.nullish(),()=>void 0),auth:K(Yd.optional().default({terminal:!1}),()=>({terminal:!1})),elicitation:K(Qd.nullish(),()=>void 0),nes:K(nf.nullish(),()=>void 0),positionEncodings:K(J(cu).optional(),()=>[]),_meta:K(W(P(),z()).nullish(),()=>void 0)}).optional().default({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}}),()=>({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}})),clientInfo:K(mu.nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),af=V({methodId:uu,_meta:K(W(P(),z()).nullish(),()=>void 0)}),of=V({_meta:K(W(P(),z()).nullish(),()=>void 0)}),sf=V({providerId:_u,apiType:vu,baseUrl:P(),headers:W(P(),P()).optional(),_meta:K(W(P(),z()).nullish(),()=>void 0)}),cf=V({providerId:_u,_meta:K(W(P(),z()).nullish(),()=>void 0)}),lf=V({_meta:K(W(P(),z()).nullish(),()=>void 0)}),uf=V({name:P(),value:P(),_meta:K(W(P(),z()).nullish(),()=>void 0)}),df=V({name:P(),url:P(),headers:B(uf),_meta:K(W(P(),z()).nullish(),()=>void 0)}),ff=V({name:P(),url:P(),headers:B(uf),_meta:K(W(P(),z()).nullish(),()=>void 0)}),pf=V({name:P(),serverId:Ml,_meta:K(W(P(),z()).nullish(),()=>void 0)}),mf=V({name:P(),command:P(),args:B(P()),env:B(sl),_meta:K(W(P(),z()).nullish(),()=>void 0)}),hf=H([df.and(V({type:G(`http`)})),ff.and(V({type:G(`sse`)})),pf.and(V({type:G(`acp`)})),mf]),gf=V({cwd:P(),additionalDirectories:B(P()).optional(),mcpServers:B(hf),_meta:K(W(P(),z()).nullish(),()=>void 0)}),_f=V({mcpServers:B(hf),cwd:P(),additionalDirectories:B(P()).optional(),sessionId:Y,_meta:K(W(P(),z()).nullish(),()=>void 0)}),vf=V({cwd:P().nullish(),cursor:P().nullish(),_meta:K(W(P(),z()).nullish(),()=>void 0)}),yf=V({sessionId:Y,_meta:K(W(P(),z()).nullish(),()=>void 0)}),bf=V({sessionId:Y,cwd:P(),additionalDirectories:B(P()).optional(),mcpServers:B(hf).optional(),_meta:K(W(P(),z()).nullish(),()=>void 0)}),xf=V({sessionId:Y,cwd:P(),additionalDirectories:B(P()).optional(),mcpServers:B(hf).optional(),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Sf=V({sessionId:Y,_meta:K(W(P(),z()).nullish(),()=>void 0)}),Cf=V({sessionId:Y,modeId:wu,_meta:K(W(P(),z()).nullish(),()=>void 0)}),wf=U(H([V({value:R(),type:G(`boolean`)}),V({value:Ou})]),V({sessionId:Y,configId:Eu,_meta:K(W(P(),z()).nullish(),()=>void 0)})),Tf=V({sessionId:Y,prompt:B(Xc),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Ef=V({uri:P(),name:P(),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Df=V({name:P(),owner:P(),remoteUrl:P(),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Of=V({workspaceUri:K(P().nullish(),()=>void 0),workspaceFolders:B(Ef).nullish(),repository:K(Df.nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),kf=H([G(`automatic`),G(`diagnostic`),G(`manual`)]),Af=V({uri:P(),languageId:P(),text:P(),_meta:K(W(P(),z()).nullish(),()=>void 0)}),jf=V({startLine:L().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),endLine:L().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),text:P(),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Mf=V({uri:P(),excerpts:B(jf),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Nf=V({uri:P(),diff:P(),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Pf=V({action:P(),uri:P(),position:Ju,timestampMs:I(),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Ff=V({uri:P(),languageId:P(),visibleRange:K(Yu.nullish(),()=>void 0),lastFocusedMs:K(I().nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),If=H([G(`error`),G(`warning`),G(`information`),G(`hint`)]),Lf=V({uri:P(),range:Yu,severity:If,message:P(),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Rf=V({recentFiles:B(Af).nullish(),relatedSnippets:B(Mf).nullish(),editHistory:B(Nf).nullish(),userActions:B(Pf).nullish(),openFiles:B(Ff).nullish(),diagnostics:B(Lf).nullish(),_meta:K(W(P(),z()).nullish(),()=>void 0)}),zf=V({sessionId:Y,uri:P(),version:I(),position:Ju,selection:Yu.nullish(),triggerKind:kf,context:Rf.nullish(),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Bf=V({sessionId:Y,_meta:K(W(P(),z()).nullish(),()=>void 0)});V({id:Lc,method:P(),params:H([rf,af,of,sf,cf,lf,gf,_f,vf,yf,bf,xf,Sf,Cf,wf,Tf,Of,zf,Bf,Fl]).nullish()});const Vf=V({_meta:K(W(P(),z()).nullish(),()=>void 0)}),Hf=V({content:P(),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Uf=V({optionId:il,_meta:K(W(P(),z()).nullish(),()=>void 0)}),Wf=V({outcome:H([V({outcome:G(`cancelled`)}),Uf.and(V({outcome:G(`selected`)}))]),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Gf=V({terminalId:$c,_meta:K(W(P(),z()).nullish(),()=>void 0)}),Kf=V({exitCode:K(L().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),signal:K(P().nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),qf=V({output:P(),truncated:R(),exitStatus:K(Kf.nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Jf=V({_meta:K(W(P(),z()).nullish(),()=>void 0)}),Yf=V({exitCode:K(L().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),signal:K(P().nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),Xf=V({_meta:K(W(P(),z()).nullish(),()=>void 0)}),Zf=H([P(),I(),I(),R(),B(P())]),Qf=V({content:W(P(),Zf).nullish()}),$f=Fc(U(H([Qf.and(V({action:G(`accept`)})),V({action:G(`decline`)}),V({action:G(`cancel`)}),Pc(V({action:P()}),`action`,[`accept`,`cancel`,`decline`])]),V({_meta:K(W(P(),z()).nullish(),()=>void 0)})),`action`,[`accept`,`cancel`,`decline`]),ep=ec({code:L().min(-2147483648,{error:`Invalid value: Expected int32 to be >= -2147483648`}).max(2147483647,{error:`Invalid value: Expected int32 to be <= 2147483647`}),message:P(),data:z().optional()});H([V({id:Lc,result:H([Vf,Hf,Wf,Gf,qf,Jf,Yf,Xf,$f,H([V({result:z(),_meta:K(W(P(),z()).nullish(),()=>void 0)}),V({error:ep,_meta:K(W(P(),z()).nullish(),()=>void 0)})]),rd])}),V({id:Lc,error:id})]);const tp=V({sessionId:Y,_meta:K(W(P(),z()).nullish(),()=>void 0)}),np=V({sessionId:Y,uri:P(),languageId:P(),version:I(),text:P(),_meta:K(W(P(),z()).nullish(),()=>void 0)}),rp=V({range:Yu.nullish(),text:P(),_meta:K(W(P(),z()).nullish(),()=>void 0)}),ip=V({sessionId:Y,uri:P(),version:I(),contentChanges:B(rp),_meta:K(W(P(),z()).nullish(),()=>void 0)}),ap=V({sessionId:Y,uri:P(),_meta:K(W(P(),z()).nullish(),()=>void 0)}),op=V({sessionId:Y,uri:P(),_meta:K(W(P(),z()).nullish(),()=>void 0)}),sp=V({sessionId:Y,uri:P(),version:I(),position:Ju,visibleRange:Yu,_meta:K(W(P(),z()).nullish(),()=>void 0)}),cp=V({sessionId:Y,id:qu,_meta:K(W(P(),z()).nullish(),()=>void 0)}),lp=V({sessionId:Y,id:qu,reason:K(H([G(`rejected`),G(`ignored`),G(`replaced`),G(`cancelled`)]).nullish(),()=>void 0),_meta:K(W(P(),z()).nullish(),()=>void 0)}),up=V({serverId:Ml,requestId:Nl,method:P(),params:W(P(),z()).nullish(),_meta:K(W(P(),z()).nullish(),()=>void 0)});V({method:P(),params:H([tp,np,ip,ap,op,sp,cp,lp,up,Vd]).nullish()}),V({requestId:Lc,_meta:K(W(P(),z()).nullish(),()=>void 0)});const dp=`$/cancel_request`;function fp(e){return gp(e)&&`id`in e&&typeof e.method==`string`&&_p(e.id)}function pp(e){if(!gp(e)||`method`in e||!(`id`in e)||!_p(e.id))return!1;let t=Object.hasOwn(e,`result`),n=Object.hasOwn(e,`error`);return t===n?!1:!n||xp(e.error)}function mp(e){return gp(e)&&!(`id`in e)&&typeof e.method==`string`}function hp(e){return typeof e==`object`&&!!e}function gp(e){return hp(e)&&e.jsonrpc===`2.0`}function _p(e){return e===null||typeof e==`string`||typeof e==`number`&&Number.isFinite(e)}function vp(e){return hp(e)&&!(`method`in e)&&(`id`in e||`result`in e||`error`in e)}function yp(e){let t=!1,n=!1,r=!1,i=!1;for(let a of e)t||=fp(a)||mp(a),n||=pp(a),hp(a)&&(r||=`method`in a,i||=`result`in a||`error`in a);return t?!1:n?!0:i&&!r}function bp(e){if(!(!hp(e)||!_p(e.requestId)))return e.requestId}function xp(e){return hp(e)&&typeof e.code==`number`&&Number.isInteger(e.code)&&typeof e.message==`string`}const Sp={yes(){return{handled:!0}},no(e,t=!1){return{handled:!1,message:e,retry:t}}};function Cp(e){let t=Promise.reject(e);return t.catch(()=>{}),t}function wp(e){if(e instanceof Error||typeof e==`object`&&e&&`message`in e&&typeof e.message==`string`)return e.message}function Tp(e){return typeof e==`object`&&!!e&&`name`in e&&e.name===`ZodError`&&`issues`in e&&Array.isArray(e.issues)&&`format`in e&&typeof e.format==`function`}function Ep(e){if(e instanceof X)return e.toResult();if(Tp(e))return X.invalidParams(e.format()).toResult();let t=wp(e);try{return X.internalError(t?JSON.parse(t):{}).toResult()}catch{return X.internalError({details:t}).toResult()}}function Dp(e){return e instanceof X&&e.code===-32800?e:X.requestCancelled(e)}function Op(e,t){let n=kp(e,t);return n?n.toResult():Ep(e)}function kp(e,t){if(!(!t.aborted||!Ap(e)))return Dp(t.reason)}function Ap(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.name===`AbortError`||t.code===`ABORT_ERR`}var jp=class{id;sendResult;signal;finishRequest;didRespond=!1;constructor(e,t,n=new AbortController().signal,r){this.id=e,this.sendResult=t,this.signal=n,this.finishRequest=r}get responded(){return this.didRespond}respond(e){return this.respondWithResult({result:e??null})}respondWithError(e){let t=e instanceof X?e.toErrorResponse():e;return this.respondWithResult({error:t})}respondWithResult(e){return this.didRespond?Cp(Error(`JSON-RPC request already responded`)):(this.didRespond=!0,this.sendResult(e).finally(()=>{this.finishRequest?.()}))}};const Mp=new WeakMap;var Np=class{disposeHandler;active=!0;constructor(e){this.disposeHandler=e}dispose(){this.active&&(this.active=!1,this.disposeHandler())}[Symbol.dispose](){this.dispose()}runIndefinitely(){return this}},Pp=class{connection;constructor(e){this.connection=e}sendRequest(e,t,n,r){return this.connection.sendRequest(e,t,n,r)}sendNotification(e,t){return this.connection.sendNotification(e,t)}sendBatch(e){return this.connection.sendBatch(e)}sendCancelRequest(e){return this.connection.sendCancelRequest(e)}addDynamicHandler(e){return this.connection.addDynamicHandler(e)}get signal(){return this.connection.signal}get closed(){return this.connection.closed}},Fp=class{pendingResponses=new Map;incomingRequests=new Map;nextRequestId=0;staticHandlers=[];dynamicHandlers=new Set;stream;writeQueue=Promise.resolve();abortController=new AbortController;closedPromise;retryQueue=[];context=new Pp(this);receiveReader;allowBatches=!0;constructor(e,t,n,r){if(typeof e==`function`){let i=e,a=t,o=n;this.initialize(o,[...r?.handlers??[],this.legacyHandler(i,a)],r);return}let i=e,a=t,o=n;this.initialize(i,[...o?.handlers??[],...a],o)}static builder(){return new Ip}runUntil(e){let t=!1,n=Promise.resolve().then(()=>e(this.context)).finally(()=>{t=!0}),r=this.closed.then(()=>{if(t)return new Promise(()=>{});throw this.closedReason()});return Promise.race([n,r]).finally(()=>{t=!0,this.close()})}addDynamicHandler(e){if(this.dynamicHandlers.add(e),this.retryQueue.length>0)for(let e of this.retryQueue.splice(0))this.processIncomingMessage(e).catch(e=>this.close(e));return new Np(()=>{this.dynamicHandlers.delete(e)})}get signal(){return this.abortController.signal}get closed(){return this.closedPromise}getContext(){return this.context}sendRequest(e,t,n,r={}){if(this.abortController.signal.aborted)return Cp(this.closedReason());let i=this.prepareRequest(e,t,n,r);return this.sendWireMessage(i.message).catch(()=>{}),r.cancellationSignal?.aborted&&i.cancel(),i.response}sendBatch(e){if(this.abortController.signal.aborted)return Cp(this.closedReason());if(!this.allowBatches)return Cp(TypeError(`JSON-RPC batches are not supported on this connection`));if(e.length===0)return Cp(TypeError(`JSON-RPC batch must contain at least one entry`));let t=[],n=[],r=[];for(let i of e){if(i.kind===`notification`){t.push({jsonrpc:`2.0`,method:i.method,params:i.params}),r.push(Promise.resolve(void 0));continue}let e=this.prepareRequest(i.method,i.params,i.mapResponse,i.options);t.push(e.message),r.push(e.response),n.push({signal:i.options?.cancellationSignal,cancel:e.cancel})}let i=t,a=this.sendWireMessage(i);for(let e of n)e.signal?.aborted&&e.cancel();let o=Promise.all([a,...r]).then(([,...e])=>e);return o.catch(()=>{}),o}sendCancelRequest(e){return this.sendNotification(dp,{requestId:e})}sendNotification(e,t){return this.abortController.signal.aborted?Cp(this.closedReason()):this.sendWireMessage({jsonrpc:`2.0`,method:e,params:t})}prepareRequest(e,t,n,r={}){let i=this.nextRequestId++,a=()=>{},o=new Promise((e,t)=>{let o={resolve:r=>{try{e(n?n(r):r)}catch(e){t(e)}},reject:t};a=()=>{o.cancellationSent||(o.cancellationSent=!0,o.cleanup?.(),this.sendCancelRequest(i).catch(()=>{}))},r.cancellationSignal?.addEventListener(`abort`,a,{once:!0}),o.cleanup=()=>{r.cancellationSignal?.removeEventListener(`abort`,a)},this.pendingResponses.set(i,o)});return o.catch(()=>{}),{message:{jsonrpc:`2.0`,id:i,method:e,params:t},response:o,cancel:()=>a()}}close(e){if(this.abortController.signal.aborted)return;let t=e??Error(`ACP connection closed`);this.abortController.abort(t);for(let e of this.pendingResponses.values())e.cleanup?.(),e.reject(t);this.pendingResponses.clear();for(let e of this.incomingRequests.values())e.abort(t);this.incomingRequests.clear(),this.receiveReader?.cancel(t).catch(()=>{})}initialize(e,t,n){this.stream=e,this.staticHandlers=t,this.allowBatches=n?.allowBatches??!0,this.closedPromise=new Promise(e=>{this.abortController.signal.addEventListener(`abort`,()=>e())}),this.receive()}legacyHandler(e,t){return{handleMessage:async(n,r)=>{if(n.kind===`request`){let t=await e(n.method,n.params,r);await n.responder.respond(t)}else await t(n.method,n.params,r);return Sp.yes()}}}async receive(){let e;try{let e=this.stream.readable.getReader();this.receiveReader=e;try{for(;!this.abortController.signal.aborted;){let{value:t,done:n}=await e.read();if(this.abortController.signal.aborted||n)break;this.receiveWireMessage(t)}}finally{this.receiveReader===e&&(this.receiveReader=void 0),e.releaseLock()}}catch(t){e=t}finally{this.close(e)}}receiveWireMessage(e){if(Array.isArray(e)){if(!this.allowBatches){this.close(TypeError(`JSON-RPC batches are not supported on this connection`));return}this.receiveBatch(e);return}if(!fp(e)&&!mp(e)&&!vp(e)){this.sendWireMessage(Lp(X.invalidRequest(e))).catch(()=>{});return}this.receiveMessage(e)}receiveBatch(e){if(e.length===0){this.sendWireMessage(Lp(X.invalidRequest(e))).catch(()=>{});return}let t=yp(e),n=t?0:e.reduce((e,t)=>e+(mp(t)?0:1),0),r=e.reduce((e,t)=>e+(mp(t)?1:0),0),i=!1,a=[],o=async()=>{i||n!==0||r!==0||a.length===0||(i=!0,await this.sendWireMessage(a))},s=async e=>{a.push(e),--n,await o()};for(let n of e){if(t){vp(n)&&this.receiveMessage(n);continue}if(!fp(n)&&!mp(n)){s(Lp(X.invalidRequest(n))).catch(()=>{});continue}let i=this.receiveMessage(n,fp(n)?s:void 0,e.length);mp(n)&&i.finally(()=>{--r,o().catch(e=>this.close(e))})}}receiveMessage(e,t,n){return this.abortController.signal.aborted?Promise.resolve():hp(e)?`method`in e?(`id`in e||this.handleProtocolNotification(e),this.processIncomingMessage(this.toIncomingMessage(e,t,n)).catch(e=>this.close(e))):(`id`in e?this.handleResponse(e):console.error(`Invalid message`,{message:e}),Promise.resolve()):(console.error(`Invalid message`,{message:e}),Promise.resolve())}async processIncomingMessage(e){if(this.abortController.signal.aborted)return;let t=e,n=!1;try{for(let e of[...this.staticHandlers,...this.dynamicHandlers.values()]){if(this.abortController.signal.aborted)return;let r=await e.handleMessage(t,this.context)??{handled:!0};if(r.handled)return;t=r.message??t,n||=!!r.retry}n?this.retryQueue.push(t):t.kind===`request`&&await t.responder.respondWithError(X.methodNotFound(t.method))}catch(n){if(this.abortController.signal.aborted)return;if(t.kind===`request`&&!t.responder.responded)await t.responder.respondWithResult(Op(n,t.responder.signal));else{let t=Ep(n);`error`in t&&console.error(`Error handling notification`,e.raw,t.error)}}}toIncomingMessage(e,t,n){if(`id`in e){let r=new AbortController;this.incomingRequests.set(e.id,r);let i=new jp(e.id,n=>{let r={jsonrpc:`2.0`,id:e.id,...n};return t?t(r):this.sendWireMessage(r)},r.signal,()=>{this.incomingRequests.get(e.id)===r&&this.incomingRequests.delete(e.id)});return n!==void 0&&Mp.set(i,n),{kind:`request`,method:e.method,params:e.params,raw:e,signal:r.signal,responder:i}}return{kind:`notification`,method:e.method,params:e.params,raw:e}}handleResponse(e){let t=this.pendingResponses.get(e.id);if(t)if(this.pendingResponses.delete(e.id),t.cleanup?.(),!pp(e))t.reject(X.invalidRequest(e));else if(`result`in e)t.resolve(e.result);else{let{code:n,message:r,data:i}=e.error;t.reject(new X(n,r,i))}else console.error(`Got response to unknown request`,e.id)}handleProtocolNotification(e){if(e.method!==dp)return;let t=bp(e.params);if(t===void 0)return;let n=this.incomingRequests.get(t);!n||n.signal.aborted||n.abort(X.requestCancelled({requestId:t}))}closedReason(){return this.abortController.signal.reason??Error(`ACP connection closed`)}async sendWireMessage(e){return this.abortController.signal.aborted?Cp(this.closedReason()):(this.writeQueue=this.writeQueue.then(async()=>{if(this.abortController.signal.aborted)throw this.closedReason();let t=this.stream.writable.getWriter();try{await t.write(e)}finally{t.releaseLock()}}).catch(e=>{throw this.close(e),e}),this.writeQueue)}},Ip=class{handlers=[];connectionName;name(e){return this.connectionName=e,this}withHandler(e){return this.handlers.push(e),this}onReceiveMessage(e){return this.withHandler({handleMessage:async(t,n)=>await e(t,n)??Sp.no(t),describe:()=>this.connectionName??`onReceiveMessage`})}onReceiveRequest(e,t,n){return this.withHandler({handleMessage:async(r,i)=>r.kind!==`request`||r.method!==e?Sp.no(r):await n(t(r.params),r.responder,i)??Sp.yes(),describe:()=>`${this.connectionName??`request`}:${e}`})}onReceiveNotification(e,t,n){return this.withHandler({handleMessage:async(r,i)=>r.kind!==`notification`||r.method!==e?Sp.no(r):await n(t(r.params),i)??Sp.yes(),describe:()=>`${this.connectionName??`notification`}:${e}`})}connect(e,t){return new Fp(e,this.handlers,t)}connectWith(e,t,n){return this.connect(e,n).runUntil(t)}},X=class e extends Error{code;data;constructor(e,t,n){super(t),this.code=e,this.name=`RequestError`,this.data=n}static parseError(t,n){return new e(-32700,`Parse error${n?`: ${n}`:``}`,t)}static invalidRequest(t,n){return new e(-32600,`Invalid request${n?`: ${n}`:``}`,t)}static methodNotFound(t){return new e(-32601,`"Method not found": ${t}`,{method:t})}static invalidParams(t,n){return new e(-32602,`Invalid params${n?`: ${n}`:``}`,t)}static internalError(t,n){return new e(-32603,`Internal error${n?`: ${n}`:``}`,t)}static requestCancelled(t,n){return new e(-32800,`Request cancelled${n?`: ${n}`:``}`,t)}static authRequired(t,n){return new e(-32e3,`Authentication required${n?`: ${n}`:``}`,t)}static resourceNotFound(t){return new e(-32002,`Resource not found${t?`: ${t}`:``}`,t&&{uri:t})}toResult(){return{error:{code:this.code,message:this.message,data:this.data}}}toErrorResponse(){return{code:this.code,message:this.message,data:this.data}}};function Lp(e){return{jsonrpc:`2.0`,id:null,error:e.toErrorResponse()}}Ol.and(V({mode:G(`form`)})).and(V({message:P()})),Al.and(V({mode:G(`url`)})).and(V({message:P()})),H([pl,ml]).and(V({message:P()})),vl.and(V({type:G(`string`)})),yl.and(V({type:G(`number`)})),bl.and(V({type:G(`integer`)})),xl.and(V({type:G(`boolean`)})),Tl.and(V({type:G(`array`)})),Sl.and(V({type:G(`string`)})),Ad.and(V({state:G(`running`)})),Md.and(V({usage:Wu.nullish()})).and(V({state:G(`idle`)})),Nd.and(V({state:G(`requires_action`)})),Pd.and(V({state:G(`unknown`)})),V({stopReason:G(`end_turn`)}),V({stopReason:G(`max_tokens`)}),V({stopReason:G(`max_turn_requests`)}),V({stopReason:G(`refusal`)}),V({stopReason:G(`cancelled`)}),jd.and(V({error:id.nullish()})).and(V({stopReason:G(`error`)})),V({stopReason:Js().optional()}),Qf.and(V({action:G(`accept`)})),V({action:G(`decline`)}),V({action:G(`cancel`)});function Z(e){return e??{}}g.initialize,g.authenticate,g.logout,g.providers_list,g.providers_set,g.providers_disable,g.session_new,g.session_load,g.session_list,g.session_delete,g.session_fork,g.session_resume,g.session_close,g.session_set_mode,g.session_set_config_option,g.session_prompt,g.session_cancel,g.nes_start,g.nes_suggest,g.nes_accept,g.nes_reject,g.nes_close,g.document_did_open,g.document_did_change,g.document_did_close,g.document_did_save,g.document_did_focus,_.session_request_permission,_.session_update,_.fs_write_text_file,_.fs_read_text_file,_.terminal_create,_.terminal_output,_.terminal_release,_.terminal_wait_for_exit,_.terminal_kill,_.elicitation_create,_.elicitation_complete,de.cancel_request,Symbol.dispose;function Q(e,t,n){return{method:e,params:t,mapResponse:n}}function $(e,t){return{method:e,params:t}}function Rp(e){let t={};for(let n of Object.values(e))t[n.method]=n;return t}const zp={initialize:Q(g.initialize,rf),newSession:Q(g.session_new,gf),loadSession:Q(g.session_load,_f,Z),unstable_forkSession:Q(g.session_fork,bf),listSessions:Q(g.session_list,vf),deleteSession:Q(g.session_delete,yf,Z),resumeSession:Q(g.session_resume,xf),closeSession:Q(g.session_close,Sf,Z),setSessionMode:Q(g.session_set_mode,Cf,Z),setSessionConfigOption:Q(g.session_set_config_option,wf),authenticate:Q(g.authenticate,af,Z),unstable_listProviders:Q(g.providers_list,of),unstable_setProvider:Q(g.providers_set,sf,Z),unstable_disableProvider:Q(g.providers_disable,cf,Z),logout:Q(g.logout,lf,Z),prompt:Q(g.session_prompt,Tf),unstable_startNes:Q(g.nes_start,Of),unstable_suggestNes:Q(g.nes_suggest,zf),unstable_closeNes:Q(g.nes_close,Bf,Z)},Bp={cancel:$(g.session_cancel,tp),unstable_didOpenDocument:$(g.document_did_open,np),unstable_didChangeDocument:$(g.document_did_change,ip),unstable_didCloseDocument:$(g.document_did_close,ap),unstable_didSaveDocument:$(g.document_did_save,op),unstable_didFocusDocument:$(g.document_did_focus,sp),unstable_acceptNes:$(g.nes_accept,cp),unstable_rejectNes:$(g.nes_reject,lp)},Vp={requestPermission:Q(_.session_request_permission,ol),writeTextFile:Q(_.fs_write_text_file,Rc,Z),readTextFile:Q(_.fs_read_text_file,zc),createTerminal:Q(_.terminal_create,cl),terminalOutput:Q(_.terminal_output,ll),releaseTerminal:Q(_.terminal_release,ul,Z),waitForTerminalExit:Q(_.terminal_wait_for_exit,dl),killTerminal:Q(_.terminal_kill,fl,Z),createElicitation:Q(_.elicitation_create,jl)},Hp={sessionUpdate:$(_.session_update,zd),completeElicitation:$(_.elicitation_complete,Bd)};Rp(zp),Rp(Bp),Rp(Vp),Rp(Hp),new Set([g.initialize,g.authenticate,g.providers_list,g.providers_set,g.providers_disable,g.session_new,g.session_load,g.session_set_mode,g.session_set_config_option,g.session_prompt,g.session_list,g.session_delete,g.session_fork,g.session_resume,g.session_close,g.logout,g.nes_start,g.nes_suggest,g.nes_close]),new Set([g.session_cancel,g.nes_accept,g.nes_reject,g.document_did_open,g.document_did_change,g.document_did_close,g.document_did_save,g.document_did_focus]),new Set([_.session_request_permission,_.fs_write_text_file,_.fs_read_text_file,_.terminal_create,_.terminal_output,_.terminal_release,_.terminal_wait_for_exit,_.terminal_kill,_.elicitation_create]),new Set([_.session_update,_.elicitation_complete]),Symbol.asyncDispose;function Up(e){if(typeof e!=`object`||!e)return e;let t=e;if(t.type!==`image`)return e;let n=t.attachment;if(typeof n!=`object`||!n)return e;let r=n;if(typeof r.mediaType!=`string`||typeof r.data!=`string`)return e;let i=typeof t.name==`string`?t.name:typeof r.name==`string`?r.name:void 0;return{type:`image`,mediaType:r.mediaType,data:r.data,...i===void 0?{}:{name:i}}}const Wp=1e3,Gp=3e4;function Kp(e){let t=e,n=t?.values?.modelSelection?.next??t?.values?.modelSelection?.lastUsed;if(!(n==null||typeof n.provider!=`string`||typeof n.model!=`string`))return{provider:n.provider,model:n.model,...typeof n.reasoningEffort==`string`?{reasoningEffort:n.reasoningEffort}:{}}}function qp(e,t){return e===void 0||t===void 0?e===t:e.provider===t.provider&&e.model===t.model&&e.reasoningEffort===t.reasoningEffort}function Jp(e){if(typeof e!=`object`||!e)return-1;let t=e.asOfSeq;return typeof t==`number`?t:-1}function Yp(e){return e.pendingSelection??Kp(e.projections)??e.fallbackSelection}function Xp(e){return{id:e.id,get header(){let t=e.header;return{...t?.cwd===void 0?{}:{cwd:t.cwd},...t?.origin===void 0?{}:{origin:t.origin},...t?.parentSession===void 0?{}:{parentSession:t.parentSession},...t?.createdAt===void 0?{}:{createdAt:t.createdAt}}},requestHeader(){let t=Yp(e);if(t!==void 0)return{config:{provider:t.provider,model:t.model,...t.reasoningEffort===void 0?{}:{reasoningEffort:t.reasoningEffort}}}}}}function Zp(e,t,n){return{id:e.id,session:e.session,model:{current:()=>Yp(e),select:async n=>{qp(e.pendingSelection??Kp(e.projections),n)||(e.pendingSelection=(await t.unary(`session/selectModel`,{request:{sessionId:e.id,...n}}))?.selected??n,e.pendingAtSeq=Jp(e.projections))}},cancel:async n=>{await t.unary(`session/cancel`,{request:{sessionId:e.id}})},followup:t=>{n(e,t)}}}var Qp=class{logger;#e;#t;#n;#r=new Map;#i=new Map;#a=new Set;#o=new Set;#s=new Set;#c=new Set;#l=new Set;#u;#d=Wp;#f;#p=Wp;#m;#h={groups:[],failures:[]};#g=0;#_;#v=!1;#y;constructor(e){this.#e=e.carrier,this.#t=e.pool,this.#n=e.logger,this.logger=e.logger,this.#y=this.#E(),this.#O(),this.#A()}async createAgent(e){return await this.#b(e)}async resumeAgent(e){return await this.#b(e)}async#b(e){let t=(await this.#e.unary(`session/create`,{request:{sessionId:e.sessionId,cwd:e.cwd}})).sessionId,n=this.#r.get(t);if(n!==void 0)return await this.#i.get(t)?.catch(()=>{}),n.fallbackSelection=this.#_,await e.configureScope?.(this.#C(n),n.agent),{agent:n.agent,dispose:async()=>this.#S(t)};let r={id:t,header:{version:1,id:t,createdAt:0,cwd:e.cwd,isSeeded:!1},projections:{},promptInflight:!1};r.session=Xp(r),r.agent=Zp(r,this.#e,(e,t)=>this.#w(e,t));let i=r;this.#r.set(t,i);try{let n=this.#x(t).then(e=>{e!==void 0&&(i.projections=e)});this.#i.set(t,n),await n,this.#i.delete(t),this.#_===void 0&&(await this.#y,this.#_===void 0&&!this.#v&&(this.#v=!0,await this.#E())),i.fallbackSelection=this.#_,await e.configureScope?.(this.#C(i),i.agent),this.#t.open(t,this.#D(i))}catch(e){throw await this.#S(t).catch(()=>{}),e}return{agent:i.agent,dispose:async()=>this.#S(t)}}async#x(e){try{let t=await this.#e.unary(`session/projections`,{request:{sessionId:e}});if(typeof t!=`object`||!t||Array.isArray(t))return;let n=t,r=n.values;return typeof r!=`object`||!r||Array.isArray(r)?void 0:{asOfSeq:typeof n.asOfSeq==`number`?n.asOfSeq:-1,values:r}}catch(t){this.#n.debug(`projection prime failed (${e}): ${String(t)}`);return}}#S(e){return this.#t.close(e),this.#r.delete(e),this.#i.delete(e),Promise.resolve()}#C(e){return{on:(e,t)=>()=>{},tools:{restrict:e=>void 0}}}async#w(e,t){e.promptInflight=!0;let n=t.content.map(Up);await this.#e.unary(`session/prompt`,{request:{requestId:t.id,sessionId:e.id,mode:`steer`,content:n}})}persistence={stat:async(e,t)=>{let n=await this.#e.unary(`tboxcode/sessions.stat`,{request:{sessionId:e}});if(n!==null)return{header:n.header}},list:async e=>(await this.#e.unary(`session/list`,{_request:{}})).items.map(e=>({header:{id:e.sessionId,...e.cwd===void 0?{}:{cwd:e.cwd},...e.origin===void 0?{}:{origin:e.origin},...e.parentSessionId===void 0?{}:{parentSession:e.parentSessionId},createdAt:e.updatedAt}})),openHistoryRead:async(e,t)=>{let n=await this.#t.readAll(e);return{read:async()=>({events:n.events}),close:async()=>{}}}};sessionStore={get:e=>this.#r.get(e)?.session,flush:async e=>{await this.#e.unary(`tboxcode/sessions.flush`,{request:{sessionId:e.id}})}};llm={listProviders:()=>this.#T().groups.map(e=>({id:e.id,name:e.name})),listModels:async e=>(this.#T().groups.find(t=>t.id===e)?.models??[]).map(e=>({id:String(e.id),name:String(e.name),...e.description===void 0?{}:{description:String(e.description)}})),resolveModelInfo:async(e,t)=>{let n=this.#T().groups.find(t=>t.id===e)?.models.find(e=>e.id===t)?.reasoning;return{reasoning:{defaultEffort:n?.defaultEffort,efforts:n?.efforts??[]}}},resolveCallConfig:async e=>e};#T(){return Date.now()-this.#g>3e4&&this.#E(),this.#h}async#E(){try{this.#h=await this.#e.unary(`session/modelCatalog`,{}),this.#g=Date.now();let e=await this.#e.unary(`tboxcode/selection.default`,{});this.#_=typeof e.provider==`string`&&typeof e.model==`string`?{provider:e.provider,model:e.model,...e.reasoningEffort===void 0?{}:{reasoningEffort:e.reasoningEffort}}:void 0}catch(e){this.#n.warn(`catalog warm failed: ${String(e)}`)}}async admitPromptContent(e){return e.map(e=>e.type===`text`?e:{type:`image`,attachment:{mediaType:e.mediaType,data:e.data,...e.name===void 0?{}:{name:e.name}}})}async admitImageUrls(e,t,n){try{return(await this.#e.unary(`tboxcode/images.admit`,{request:{sessionId:e,urls:t,...n?.names===void 0?{}:{names:n.names}}})).images.map(e=>({attachment:{mediaType:e.attachment.mediaType,data:e.attachment.data},attachmentId:e.attachmentId,...e.name===void 0?{}:{name:e.name}}))}catch(e){throw X.invalidParams(void 0,e instanceof Error?e.message:String(e))}}async readImage(e,t){try{return(await this.#e.unary(`tboxcode/images.read`,{request:{attachment:t}})).image??void 0}catch{return}}applyModeKnobs(t,n,r){let i=Object.entries(e).find(([,e])=>e.sandbox===r.sandbox&&e.approval===r.approval)?.[0];if(i===void 0)throw Error(`tboxcode: mode knobs 无对位(${String(r.sandbox)}/${String(r.approval)}——MODE_TABLE 外组合)`);return this.#e.unary(`tboxcode/mode`,{request:{agentId:t.id,mode:i}}).then(()=>void 0)}defaultSelection(){return this.#_}async executeCommand(e,t,n){let r=await this.#e.unary(`tboxcode/commands.execute`,{request:{agentId:e.id,line:t}});return r?.commandId===void 0?void 0:{commandId:r.commandId}}async listCommands(e){return await this.#e.unary(`tboxcode/commands.list`,{request:{agentId:e.id}})}async listUserInvocableSkills(e){return await this.#e.unary(`tboxcode/skills.userInvocable`,{request:{agentId:e.id}})}onSessionEvent(e){let t=e;return this.#a.add(t),()=>this.#a.delete(t)}onAssistantStream(e){return this.#o.add(e),()=>this.#o.delete(e)}onInboxClaimed(e){return this.#s.add(e),()=>this.#s.delete(e)}onAgentError(e){return this.#c.add(e),()=>this.#c.delete(e)}sessionToolDenies(){return[]}onCommandSurfaceChanged(e){return this.#l.add(e),()=>this.#l.delete(e)}sessionIds(){return[...this.#r.keys()]}hasInflightPrompt(e){return this.#r.get(e)?.promptInflight===!0}poolLive(){return this.#t.stats().live>0}poolEntries(){return this.#r.size}settlePrompt(e,t){let n=this.#r.get(e);if(!(n===void 0||!n.promptInflight)){n.promptInflight=!1;for(let e of this.#c)e({agent:n.agent,turn:0,error:t})}}#D(e){return{onSnapshot:(t,n,r)=>{e.header=t;let i=Jp(r);e.pendingSelection!==void 0&&i>(e.pendingAtSeq??-1)&&Kp(r)!==void 0&&(e.pendingSelection=void 0,e.pendingAtSeq=void 0),e.projections=r},onEvent:t=>{t.type===`turn/end`&&(e.promptInflight=!1);for(let n of this.#a)n(e.session,t)},onAssistantStream:t=>{let n={type:t.type??(t.finish===void 0?t.index===0?`start`:`chunk`:`end`),attemptId:t.attemptId,...t.turn===void 0?{}:{turn:t.turn},...t.step===void 0?{}:{step:t.step},...t.chunk===void 0?{}:{chunk:t.chunk}};for(let t of this.#o)t({agent:e.agent,frame:n})},onDown:t=>this.#n.warn(`follow pool down (${e.id}): ${t}`)}}#O(){this.#u=this.#e.openStream(`tboxcode/agent.watch`,{},{onItem:e=>{this.#n.debug(`agent.watch item: ${JSON.stringify(e).slice(0,160)} states=${[...this.#r.keys()].join(`,`)}`);let t=this.#r.get(e.sessionId);if(t!==void 0){if(e.kind===`inboxClaimed`)for(let n of this.#s)n({agent:t.agent,message:{...e.messageId===void 0?{}:{id:e.messageId}},turn:e.turn??0});else if(e.kind===`error`)for(let n of this.#c)n({agent:t.agent,turn:0,error:e.error??`unknown agent error`})}},onError:e=>{this.#n.warn(`agent.watch stream error: ${JSON.stringify(e).slice(0,200)}`),this.#k()},onClose:e=>{e&&(this.#n.warn(`agent.watch stream closed`),this.#k())}})}#k(){let e=this.#d;this.#d=Math.min(this.#d*2,Gp),setTimeout(()=>{this.#O(),this.#d=Wp},e)}#A(){let e=()=>{for(let e of this.#l)e()};this.#f=$p(this.#e,e,this.#n),this.#m=this.#e.openStream(`tboxcode/skills.watch`,{},{onItem:()=>e(),onError:()=>this.#j(),onClose:e=>{e&&this.#j()}})}#j(){let e=this.#p;this.#p=Math.min(this.#p*2,Gp),setTimeout(()=>{this.#A(),this.#p=Wp},e)}dispose(){this.#u?.cancel(),this.#f?.close(),this.#m?.cancel()}};function $p(e,t,n){return e.openEvents({onReady:()=>n.debug(`commands/change $events ready`),onEmit:e=>{e.event===`commands/change`&&t()},onWaterfall:()=>{},onCancel:()=>{},onClose:e=>{e&&n.warn(`commands/change $events closed with error`)}})}var em=class{#e;#t;#n;#r;#i;#a;#o=!1;#s;constructor(e,t){this.#e=e,this.#t=t?.timeoutMs??12e4,this.#n=t?.tickMs??1e3,this.#r=t?.now??Date.now,this.#i=t?.logger??{warn:()=>{},info:()=>{},debug:()=>{}}}start(){this.#s=setInterval(()=>this.tick(),this.#n)}stop(){this.#s!==void 0&&clearInterval(this.#s),this.#s=void 0}tick(){if(!(this.#e.poolEntries()>0&&!this.#e.poolLive())){this.#a=void 0,this.#o=!1;return}if(this.#a===void 0){this.#a=this.#r();return}if(this.#o||this.#r()-this.#a<this.#t)return;this.#o=!0;let e=this.#r()-this.#a;for(let t of this.#e.sessionIds())this.#e.hasInflightPrompt(t)&&(this.#i.warn(`carrier timeout settle (${t}): downMs=${String(e)}`),this.#e.settle(t,Error(`tboxcode carrier-timeout (downMs=${String(e)})`)))}snapshot(){return{down:this.#a!==void 0,downSince:this.#a,settled:this.#o}}};const tm=6e4,nm=36e5,rm=3e4,im=-32001;var am=class{#e=new Map;#t;constructor(e){this.#t=e}get size(){return this.#e.size}pendingOf(e){for(let t of this.#e.values())if(t.sessionId===e)return t}begin(e){let t=e.event===`user-questions/request`?`elicitation`:e.event===`approval/request`?`permission`:void 0;if(t===void 0||this.#e.has(e.eventId))return;let n=this.#t.sessionIdOfAgent(e.agentId);if(n===void 0){this.#l(e.eventId,{kind:`rejected`,error:{code:`gateway/agent-not-found`,message:`agent ${e.agentId} not managed by gateway`}});return}let r={kind:t,sessionId:n,eventId:e.eventId,frame:e,asked:new Map,state:`active`,budgetStartedAt:this.#t.now()};this.#e.set(e.eventId,r),this.#n(r),this.#s(r)}cancel(e){let t=this.#e.get(e.eventId);t===void 0||t.state===`settled`||this.#c(t,{kind:`result`,value:`cancelled`},`turn`)}attach(e,t){for(let n of this.#e.values()){if(n.sessionId!==t||n.state!==`grace`)continue;let r=n.graceTimer;n.graceTimer=void 0,r!==void 0&&this.#t.timers.clear(r),n.state=`active`,this.#t.logger.info(`answerer: grace broken by attach (${n.eventId} conn=${e})`),this.#n(n)}}switchBack(e,t){this.attach(e,t)}disconnect(e){for(let t of this.#e.values())t.asked.delete(e)&&t.state===`active`&&t.asked.size===0&&this.#o(t,`member disconnected`)}dispose(){for(let e of[...this.#e.values()])e.state!==`settled`&&this.#c(e,{kind:`result`,value:`cancelled`},`dispose`);this.#e.clear()}#n(e){let t=this.#t.eligibleConns(e.sessionId).filter(t=>!e.asked.has(t)).filter(t=>e.kind===`permission`||this.#t.capsOf(t));if(t.length===0){this.#o(e,`no eligible connections`);return}for(let n of t){let t={connId:n};e.kind===`permission`&&(t.timer=this.#t.timers.set(()=>{e.state!==`active`||!e.asked.has(n)||(e.asked.delete(n),this.#t.logger.info(`answerer: member timeout (${e.eventId} conn=${n})`),e.asked.size===0&&this.#o(e,`all members timed out`))},rm)),e.asked.set(n,t),this.#r(e,n)}}async#r(e,t){let n=e.kind===`elicitation`?this.#t.buildQuestionParams(e.sessionId,e.frame):{callId:e.frame.request.callId};try{let r=await this.#t.dispatch(t,e.kind,n);if(e.state===`settled`||!e.asked.has(t))return;let i=this.#i(e,r);if(i.abstain){this.#a(e,t,`abstained`);return}this.#c(e,i.outcome,t)}catch(n){if(e.state===`settled`||!e.asked.has(t))return;if(n.code===im){this.#a(e,t,`abstained`);return}this.#t.logger.warn(`answerer: dispatch failed (${e.eventId} conn=${t}): ${n instanceof Error?n.message:String(n)}`),this.#a(e,t,`dispatch failed`)}}#i(e,t){if(e.kind===`permission`){let e=t?.outcome;return e?.outcome===`cancelled`?{abstain:!1,outcome:{kind:`result`,value:`cancelled`}}:{abstain:!1,outcome:{kind:`result`,value:e?.optionId===`allow-once`?`allowed-once`:`rejected`}}}let n=t;return n?.action===`accept`?{abstain:!1,outcome:{kind:`result`,value:n.content??{}}}:{abstain:!1,outcome:{kind:`rejected`,error:{code:n?.action===`decline`?`ASK_DECLINED`:`ASK_ABORTED`,message:`ask_user_question ${n?.action===`decline`?`declined`:`cancelled`} by client`}}}}#a(e,t,n){let r=e.asked.get(t);r?.timer!==void 0&&this.#t.timers.clear(r.timer),e.asked.delete(t),this.#t.logger.debug(`answerer: member dropped (${e.eventId} conn=${t} ${n})`),e.state===`active`&&e.asked.size===0&&this.#o(e,`all members out (${n})`)}#o(e,t){e.state===`active`&&(e.state=`grace`,e.graceTimer=this.#t.timers.set(()=>{this.#c(e,e.kind===`elicitation`?{kind:`rejected`,error:{code:`ASK_ABORTED`,message:`ask_user_question grace window expired`}}:{kind:`result`,value:`cancelled`},`grace`)},tm),this.#t.logger.info(`answerer: grace entered (${e.eventId} ${t})`))}#s(e){let t=nm-(this.#t.now()-e.budgetStartedAt);if(t<=0){this.#c(e,e.kind===`elicitation`?{kind:`rejected`,error:{code:`ASK_ABORTED`,message:`ask_user_question form budget exhausted`}}:{kind:`result`,value:`cancelled`},`budget`);return}this.#t.timers.set(()=>{e.state!==`settled`&&(this.#t.logger.warn(`answerer: form budget exhausted (${e.eventId})`),this.#c(e,e.kind===`elicitation`?{kind:`rejected`,error:{code:`ASK_ABORTED`,message:`ask_user_question form budget exhausted`}}:{kind:`result`,value:`cancelled`},`budget`))},t)}#c(e,t,n){if(e.state!==`settled`){e.state=`settled`,e.settledOutcome=t,e.respondedBy=n,e.graceTimer!==void 0&&(this.#t.timers.clear(e.graceTimer),e.graceTimer=void 0);for(let t of e.asked.values())t.timer!==void 0&&this.#t.timers.clear(t.timer);e.asked.clear(),this.#l(e.eventId,t),this.#t.resolvedNotify(e.kind,{sessionId:e.sessionId,eventId:e.eventId,outcome:t,respondedBy:n},typeof n==`string`&&n!==`grace`&&n!==`turn`&&n!==`dispose`&&n!==`budget`?n:void 0),this.#t.logger.info(`answerer: settled (${e.eventId} by=${n} kind=${t.kind})`)}}async#l(e,t){try{await this.#t.respond(e,t)}catch(t){this.#t.logger.warn(`answerer: respond failed (${e}): ${t instanceof Error?t.message:String(t)}`)}}};function om(e,t){e.gate.active||(e.gate.active=!0,e.gate.timer=setTimeout(()=>{e.gate.active&&(t.warn(`gateway load gate timeout (${e.connId})——释放缓存帧`),sm(e,!0))},3e4),e.gate.timer.unref?.())}function sm(e,t){if(!e.gate.active)return[];e.gate.active=!1,e.gate.timer!==void 0&&clearTimeout(e.gate.timer),e.gate.timer=void 0;let n=t?e.gate.frames.splice(0):[];return e.gate.frames.length=0,n}function cm(e,t){e.socket.readyState===e.socket.OPEN&&e.socket.send(JSON.stringify(t))}function lm(e,t,n){let{core:r,hooks:i,authenticate:a,logger:s}=n,c=new le(s,i),l=new o({noServer:!0}),u=new Set;r.io.notify=async e=>{c.route(e)},r.io.extNotify=async e=>{c.routeExt(e)};let d=(e,n,o)=>{new URL(e.url??`/`,`http://localhost`).pathname===t&&(async()=>{if(!(a===void 0||await um(a,e,s))){n.write(`HTTP/1.1 401 Unauthorized\r
|
|
4
58
|
\r
|
|
5
|
-
`),n.destroy();return}l.handleUpgrade(e,n,o,e=>{
|
|
59
|
+
`),n.destroy();return}l.handleUpgrade(e,n,o,e=>{dm(e,r,i,c,s,u)})})().catch(e=>{s.warn(`gateway upgrade failed: ${String(e)}`),n.destroy()})};return e.on(`upgrade`,d),{close:()=>{e.off(`upgrade`,d);for(let e of u)e.socket.close();l.close()},boundConnIds:e=>c.boundConnIds(e),ctxOf:e=>c.ctxOf(e),routeResolved:(e,t,n)=>c.routeResolved(e,t,n)}}async function um(e,t,n){try{return await e(t)}catch(e){return n.warn(`gateway authenticate failed: ${String(e)}`),!1}}function dm(e,t,n,r,a,o){let s=i(),c={elicitation:!1},l={active:!1,frames:[],timer:void 0},u=t=>{if(l.active){l.frames.push(t);return}e.readyState===e.OPEN&&e.send(JSON.stringify(t))},d={connId:s,get caps(){return c},request:async(e,t)=>{throw Error(`tboxcode: server→client request 面直通由 attach 后覆写(answerer 切片消费)`)},notify:async(e,t)=>{u({jsonrpc:`2.0`,method:e,params:t})}};if(r.attachConnection(s,u,d),n?.onConnection!==void 0)try{n.onConnection(d)}catch(e){a.warn(`gateway hook onConnection failed (fail-open): ${String(e)}`)}let f=new TransformStream,p=f.writable.getWriter(),ee={writable:new WritableStream({write:e=>{fm(e,te,r,u)}}),readable:f.readable},m=t.attachConnection(ee,{beforePrompt:e=>r.setTurnOrigin(e,s),afterPrompt:e=>r.clearTurnOrigin(e)}),te={connId:s,socket:e,conn:m,ctx:d,pending:new Map,get caps(){return c},gate:l};d.request=(e,t)=>m.client.request(e,t),o.add(te),e.on(`message`,e=>{let i=typeof e==`string`?e:Buffer.isBuffer(e)?e.toString(`utf8`):void 0;if(i===void 0)return;let o;try{o=JSON.parse(i)}catch{u({jsonrpc:`2.0`,id:null,error:{code:-32700,message:`Parse error`}});return}pm(o,te,p,t,n,r,a)}),e.on(`close`,()=>{if(o.delete(te),r.detachConnection(s),n?.onConnectionClose!==void 0)try{n.onConnectionClose(s)}catch(e){a.warn(`gateway hook onConnectionClose failed (fail-open): ${String(e)}`)}p.close().catch(()=>{}),a.debug(`gateway connection detached (${s})`)}),e.on(`error`,e=>{a.warn(`gateway socket error (${s}): ${String(e)}`)})}function fm(e,t,n,r){if(e.method===void 0&&e.id!==void 0){let r=t.pending.get(String(e.id));if(r!==void 0){t.pending.delete(String(e.id));let i=r.method===`session/load`,a=e.error===void 0;if(a){let i=e.result?.sessionId??r.params?.sessionId;r.method===`session/close`?i!==void 0&&n.unbind(t.connId,i):i!==void 0&&n.bind(t.connId,i)}else if(r.prebound){let e=r.params?.sessionId;e!==void 0&&n.unbind(t.connId,e)}if(i){let n=sm(t,a);if(cm(t,e),a)for(let e of n)cm(t,e);return}}}r(e)}async function pm(e,t,n,r,i,a,o){let s=e.method;if(s===void 0){await n.write(e);return}if(s===`initialize`){let n=e.params?.clientCapabilities;t.caps.elicitation=n?.elicitation!=null}if(s.startsWith(`_tbox.cn/`)){if(e.id===void 0){let n=i?.notifications?.[s];if(n===void 0)return;try{await n(e.params,t.ctx)}catch(e){o.warn(`gateway notification ${s} failed (fail-open): ${String(e)}`)}return}let n=i?.methods?.[s];if(n===void 0){t.socket.send(JSON.stringify({jsonrpc:`2.0`,id:e.id,error:{code:-32601,message:`Method not found: ${s}`}}));return}try{let r=await n(e.params,t.ctx);t.socket.send(JSON.stringify({jsonrpc:`2.0`,id:e.id,result:r??{}}))}catch(n){t.socket.send(JSON.stringify({jsonrpc:`2.0`,id:e.id,error:{code:-32603,message:n instanceof Error?n.message:String(n)}}))}return}if(i?.transformInbound!==void 0&&e.id!==void 0){let n;try{n=await i.transformInbound(s,e.params,t.ctx)}catch(t){o.warn(`gateway hook transformInbound failed (fail-open): ${String(t)}`),n=e.params}if(n===null){t.socket.send(JSON.stringify({jsonrpc:`2.0`,id:e.id,error:{code:-32602,message:`Invalid params: ${s} rejected by gateway`}}));return}e.params=n}if(s===`session/load`&&e.id!==void 0){let n=e.params?.sessionId,s=e.params?.cwd;if(n!==void 0&&s!==void 0&&r.hasSession(n)){a.bind(t.connId,n),om(t,o);try{let a=await r.joinSession({sessionId:n,cwd:s});cm(t,{jsonrpc:`2.0`,id:e.id,result:{configOptions:a.configOptions}});for(let e of a.updates){let r=e;if(i?.transformOutbound!==void 0){let n;try{n=i.transformOutbound(e,t.ctx)}catch(t){o.warn(`gateway hook transformOutbound failed (fail-open): ${String(t)}`),n=e}if(n===null)continue;r=n}cm(t,{jsonrpc:`2.0`,method:`session/update`,params:{sessionId:n,update:r}})}cm(t,{jsonrpc:`2.0`,method:`_tbox.cn/acp_replay_complete`,params:{sessionId:n,notificationCount:a.updates.length}});for(let e of sm(t,!0))cm(t,e)}catch(r){sm(t,!1),a.unbind(t.connId,n),cm(t,{jsonrpc:`2.0`,id:e.id,error:{code:-32603,message:r instanceof Error?r.message:String(r)}})}return}}if((s===`session/new`||s===`session/load`||s===`session/resume`||s===`session/close`)&&e.id!==void 0){let n=!1;if(s===`session/load`){let r=e.params?.sessionId;r!==void 0&&!a.boundConnIds(r).includes(t.connId)&&(a.bind(t.connId,r),n=!0),om(t,o),a.beginReplayCount(t.connId)}if(t.pending.set(String(e.id),{method:s,params:e.params,prebound:n}),s===`session/close`){let n=e.params?.sessionId;n!==void 0&&a.unbind(t.connId,n)}}if(await n.write(e),s===`session/close`&&e.id===void 0){let n=e.params?.sessionId;n!==void 0&&a.unbind(t.connId,n)}}async function mm(e,t,n,r){try{return await n()}catch(n){return e.warn(`gateway hook ${t} failed (fail-open): ${String(n)}`),r}}const hm=`@tbox.cn/tboxcode-dsh-sdk`;export{im as ABSTAIN_RPC_ERROR,ie as CarrierRpcError,h as CarrierTransportError,ae as DshCarrier,nm as FORM_BUDGET_MS,le as FanoutRouter,ce as FollowPool,tm as GRACE_WINDOW_MS,am as InteractionRegistry,em as InterruptionMonitor,hm as PACKAGE_NAME,rm as PERMISSION_MEMBER_TIMEOUT_MS,Qp as RpcSessionDeps,d as Supervisor,s as SupervisorDeploymentError,lm as attachAcpGateway,se as decodeWireEvent,l as exchangeCredentialsViaConnect,p as isRecord,$p as openCommandsChangeEventStream,re as parseWireEventFrame,te as parseWireFollowFrame,m as parseWireHistoryRecord,ne as parseWirePage,ee as parseWireSessionEvent,mm as runHookOpen};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tbox.cn/tboxcode-dsh-sdk",
|
|
3
|
-
"version": "0.1.0-rc.
|
|
3
|
+
"version": "0.1.0-rc.16",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "AcpGateway 扩展点 + Supervisor + 直连 RPC 面(主入口薄 carrier,运行时零 dsh 包依赖;/embedded 子路径提供 in-process ACP core、bridge 投影与 model schema,并携带 dsh peer 闭包)+ 上链 ACP server 面 + wire 契约与 decodeWireEvent;agtcodingbox 唯一依赖面",
|
|
6
6
|
"main": "lib/index.js",
|
|
@@ -37,9 +37,9 @@
|
|
|
37
37
|
"@deepseek-ai/dsh-user-approval": "0.2.2-rc.1",
|
|
38
38
|
"@deepseek-ai/dsh-user-questions": "0.2.2-rc.1",
|
|
39
39
|
"ws": "^8.19.0",
|
|
40
|
-
"@tbox.cn/dsh-acp-
|
|
41
|
-
"@tbox.cn/dsh-
|
|
42
|
-
"@tbox.cn/
|
|
40
|
+
"@tbox.cn/dsh-acp-bridge-core": "0.1.0-rc.16",
|
|
41
|
+
"@tbox.cn/tboxcode-dsh-llm": "0.1.0-rc.16",
|
|
42
|
+
"@tbox.cn/dsh-acp-full": "0.1.0-rc.16"
|
|
43
43
|
},
|
|
44
44
|
"devDependencies": {
|
|
45
45
|
"@types/ws": "^8.18.1",
|