@x-otto/service 0.0.1-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +119 -0
- package/dist/index.d.ts +617 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +44 -0
- package/dist/index.js.map +1 -0
- package/package.json +48 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import{existsSync as e,readFileSync as t,readdirSync as n,realpathSync as r,statSync as i}from"node:fs";import{randomUUID as a,timingSafeEqual as o}from"node:crypto";import{dirname as s,extname as c,isAbsolute as l,join as u,relative as d,resolve as f,sep as p}from"node:path";import{Hono as m}from"hono";import{createAdaptorServer as ee,serve as te}from"@hono/node-server";import{TypedEventEmitter as ne,createLogger as h}from"@x-otto/shared";import{WebSocketServer as re}from"ws";import{createProjectorState as ie,projectSessionEvent as ae,shouldShowPulseSurvey as oe}from"@x-otto/session-contract";import{cors as se}from"hono/cors";import{isCheckpointForkParams as ce,isCheckpointRestoreParams as le,isReplaySeekParams as ue,isReplayStartParams as de}from"@x-otto/devtools";import{exportSessionTrace as fe,otlpExporterFromEnv as pe}from"@x-otto/otel";import{BREAKPOINT_POINTS as me,summarizeTrace as he,traceToSpans as ge}from"@x-otto/agent";import{traceEventsToTimeline as _e}from"@x-otto/trace-view";import{streamSSE as ve}from"hono/streaming";import{globalAgentJobRegistry as ye}from"@x-otto/runtime";import{DEFAULT_WORKSPACE_KEY as be,isValidWorkspaceId as xe}from"@x-otto/workspace";import{defineHook as Se}from"@x-otto/hooks";import{SqlitePersistence as Ce,StorageHost as we,acquireDb as Te,releaseDb as Ee}from"@x-otto/persistence";import{SCHEDULE_LEASE_MIGRATIONS as De}from"@x-otto/schedule";const g=h(`@x-otto/service:websocket-manager`),Oe=new Set([`localhost`,`127.0.0.1`,`::1`,`[::1]`]);var ke=class extends ne{wss;clients=new Map;sessionSubscriptions=new Map;options;maxMessagesPerSecond;maxConnections;clientId=0;onClientDisconnected;get clientCount(){return this.clients.size}constructor(e={}){super(),this.options=e,this.maxMessagesPerSecond=e.maxMessagesPerSecond??100,this.maxConnections=e.maxConnections??256,this.wss=new re({noServer:!0,maxPayload:e.maxPayloadBytes??1048576}),this.wss.on(`connection`,this.onConnection)}handleUpgrade(e,t,n,r){return r===`/ws`?this.isOriginAllowed(e)?this.isTokenValid(e)?this.clients.size>=this.maxConnections?(g.warn({active:this.clients.size},`ws upgrade rejected: max connections reached`),this.rejectUpgrade(t,`503 Service Unavailable`),!0):(this.wss.handleUpgrade(e,t,n,t=>this.wss.emit(`connection`,t,e)),!0):(g.warn(`ws upgrade rejected: invalid auth token`),this.rejectUpgrade(t,`401 Unauthorized`),!0):(g.warn({origin:e.headers.origin},`ws upgrade rejected: origin not allowed`),this.rejectUpgrade(t,`403 Forbidden`),!0):!1}rejectUpgrade(e,t){e.on(`error`,()=>{});try{e.write(`HTTP/1.1 ${t}\r\nConnection: close\r\n\r\n`),e.destroy()}catch{}}isOriginAllowed(e){let t=e.headers.origin;if(!t||this.options.allowedOrigins?.includes(t))return!0;try{return Oe.has(new URL(t).hostname)}catch{return!1}}isTokenValid(e){let{authToken:t}=this.options;if(!t)return!0;try{let n=new URL(e.url??`/`,`http://localhost`).searchParams.get(`token`);if(n===null)return!1;let r=Buffer.from(n),i=Buffer.from(t);return r.length===i.length&&o(r,i)}catch{return!1}}broadcast(e){let t=JSON.stringify(e);for(let[,e]of this.clients)e.readyState===e.OPEN&&e.send(t)}sendToSession(e,t){this.sendToSubscribers(e,t)}sendToSubscribers(e,t){let n=this.sessionSubscriptions.get(e);if(!n||n.size===0)return;let r=JSON.stringify(t);for(let e of n){let t=this.clients.get(e);t&&t.readyState===t.OPEN&&t.send(r)}}subscribeClient(e,t){t&&(this.sessionSubscriptions.has(t)||this.sessionSubscriptions.set(t,new Set),this.sessionSubscriptions.get(t)?.add(e))}unsubscribeClient(e,t){t&&this.sessionSubscriptions.get(t)?.delete(e)}clearSessionSubscriptions(e){this.sessionSubscriptions.delete(e)}sendToClient(e,t){let n=this.clients.get(e);n&&n.readyState===n.OPEN&&n.send(JSON.stringify(t))}close(){for(let[,e]of this.clients)e.close();this.clients.clear(),this.sessionSubscriptions.clear(),this.wss.close()}onConnection=e=>{let t=String(++this.clientId);this.clients.set(t,e),g.debug({clientId:t},`client connected`),this.sendToClient(t,{type:`Runtime.connected`,data:{clientId:t}});let n=[];e.on(`message`,r=>{let i=Date.now(),a=i-1e3;for(;n.length>0&&n[0]<=a;)n.shift();if(n.length>=this.maxMessagesPerSecond){g.warn({clientId:t},`ws client rate limit exceeded, closing`),e.close(1008,`rate limit exceeded`);return}n.push(i);try{let e=JSON.parse(r.toString()),n=this.normalizeClientMessage(e);if(!n){g.warn({clientId:t},`invalid message`);return}if(this.handleSystemClientMessage(t,n))return;this.emit(`message`,t,n)}catch{g.warn({clientId:t},`invalid message`)}}),e.on(`close`,()=>{this.clients.delete(t);for(let[,e]of this.sessionSubscriptions)e.delete(t);this.onClientDisconnected?.(t),g.debug({clientId:t},`client disconnected`)}),e.on(`error`,e=>{g.warn({clientId:t,err:e.message},`client error`)})};handleSystemClientMessage(e,t){switch(t.type){case`Runtime.ping`:return this.handleRuntimePing(e),!0;default:return!1}}handleRuntimePing(e){this.sendToClient(e,{type:`Runtime.pong`,data:{timestamp:Date.now()}})}normalizeClientMessage(e){if(!e||typeof e!=`object`||Array.isArray(e))return null;let t=e;if(typeof t.method==`string`){let e=t.method,n=this.asRecord(t.params);return typeof t.id==`number`&&(n.seq===void 0&&(n.seq=t.id),n.requestId===void 0&&(n.requestId=t.id)),{type:e,data:n}}return null}asRecord(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}};const Ae=h(`@x-otto/service:session-event-wire`);function je(e,t){return ae(e,t).map(e=>({type:`Session.event`,data:Me(e)}))}function Me(e){return e.kind===`error`?(Ae.error({sessionId:e.sessionId,code:e.code,message:e.message},`session error`),{...e,message:e.code===`STREAM_ERROR`?`stream error`:`session error`}):e}var Ne=class{unsubscribeSession;projector=ie();pulseSurveyState={};constructor(e,t,n){this.session=e,this.sender=t,this.app=n}attach(){this.unsubscribeSession=this.session.subscribe(e=>{let t=je(e,this.projector);for(let n of t)this.sender.sendToSession(e.sessionId,n);e.type===`prompt.end`&&this.maybeSendPulseSurvey(e.sessionId),e.type===`tool.call.end`&&this.maybeSendA2uiRendererPayload(e.sessionId,e)})}async maybeSendA2uiRendererPayload(e,t){if(this.app)try{let n={role:`tool_result`,name:t.toolCall.name,toolCallId:t.toolCall.id,content:[{type:`text`,text:t.resultText??``}],details:t.details},r=await this.app.resolveA2uiRendererPayload(n);if(!r||r.length===0)return;this.sender.sendToSession(e,{type:`Session.event`,data:{sessionId:e,kind:`a2ui.payload`,forToolCallId:t.toolCall.id,components:r}})}catch{}}maybeSendPulseSurvey(e){if(!this.app||!this.app.isFeedbackAvailable())return;let t=this.app.getPulseSurveyConfig();oe(this.projector.currentTurn,{enabled:t?.enabled??!0,probability:t?.probability??.05,minTurnGap:t?.min_turn_gap??20,forcedUpgradeActive:!1},this.pulseSurveyState)&&(this.pulseSurveyState.lastShownTurn=this.projector.currentTurn,this.sender.sendToSession(e,{type:`Session.event`,data:{sessionId:e,kind:`pulse-survey.show`}}))}detach(){this.unsubscribeSession?.(),this.unsubscribeSession=void 0}};const Pe=h(`@x-otto/service:trace-bridge`);var Fe=class{iterator;stopped=!1;constructor(e,t,n){this.sessionId=e,this.traceStore=t,this.sender=n}attach(){this.iterator||(this.stopped=!1,this.iterator=this.traceStore.tail(this.sessionId)[Symbol.asyncIterator](),this.pump())}async pump(){let e=this.iterator;if(e)try{for(;!this.stopped;){let{value:t,done:n}=await e.next();if(n||this.stopped||!t)break;this.sender.sendToSubscribers(this.sessionId,{type:`Trace.event`,data:{sessionId:this.sessionId,seq:t.seq,event:t.entry}})}}catch(e){Pe.warn({sessionId:this.sessionId,err:e instanceof Error?e.message:String(e)},`trace tail terminated`)}}detach(){this.stopped=!0,this.iterator?.return?.(),this.iterator=void 0}};function Ie(e){switch(e.type){case`Debugger.paused`:return[{type:`Debugger.paused`,data:{reason:`breakpoint`,pauseId:e.pauseId,point:e.snapshot?.point,snapshot:e.snapshot,timestamp:new Date().toISOString()}}];case`Debugger.resumed`:return[{type:`Debugger.resumed`,data:{pauseId:e.pauseId,command:e.command,timestamp:new Date().toISOString()}}];case`Debugger.commandRejected`:return[{type:`Debugger.commandRejected`,data:{code:e.code,pauseId:e.pauseId,command:e.command,timestamp:new Date().toISOString()}}];default:return[]}}const Le=h(`@x-otto/service:debug-bridge`);var Re=class extends ne{logId=0;attached=!1;unsubs=[];logs=[];pauseSessionMap=new Map;constructor(e,t){super(),this.devtools=e,this.sender=t}attach(){if(this.attached)return;this.attached=!0;let e=this.devtools.controller;this.unsubs.push(e.on(`Debugger.paused`,({pauseId:e,snapshot:t})=>{let n=this.extractSessionId(t);n&&this.pauseSessionMap.set(e,n),this.forwardDebugEvent({type:`Debugger.paused`,pauseId:e,snapshot:t},n)}),e.on(`Debugger.resumed`,({pauseId:e,command:t})=>{let n=this.pauseSessionMap.get(e);this.pauseSessionMap.delete(e),this.forwardDebugEvent({type:`Debugger.resumed`,pauseId:e,command:t},n)}),e.on(`Debugger.commandRejected`,e=>{let t=e.pauseId,n=t?this.pauseSessionMap.get(t):void 0;this.forwardDebugEvent({type:`Debugger.commandRejected`,...e},n)}),e.on(`Log.entryAdded`,e=>{this.handleLogMessage(e)}))}detach(){for(let e of this.unsubs)e();this.unsubs.length=0,this.attached=!1,this.pauseSessionMap.clear()}extractSessionId(e){let t=e?.metadata?.sessionId;return typeof t==`string`&&t?t:void 0}get isConnected(){return this.attached}send(e,t){if(e.type===`setBreakpoint`){let t=e.point;t?this.devtools.debugger.setBreakpoint(t,e.enabled!==!1):Le.warn(`setBreakpoint command missing point, dropped`);return}if(e.type===`setBreakpointsActive`){e.active===!1?this.devtools.debugger.disableAllBreakpoints():this.devtools.debugger.enableAllBreakpoints();return}let n=typeof e.pauseId==`string`?e.pauseId:void 0;this.devtools.controller.resume(e,t,n)}getLogs(){return[...this.logs]}forwardDebugEvent(e,t){let n=Ie(e);for(let e of n)t?this.sender.sendToSession(t,e):this.sender.broadcast(e)}handleLogMessage(e){if(e.level!==void 0||typeof e.msg==`string`){let t=e.time,n=typeof t==`number`?new Date(t).toISOString():typeof t==`string`?t:new Date().toISOString(),r={id:++this.logId,timestamp:n,level:this.normalizeLevel(e.level),module:e.name??`unknown`,message:e.msg??JSON.stringify(e),data:e};this.logs.push(r),this.logs.length>2e3&&this.logs.splice(0,this.logs.length-2e3),this.sender.broadcast({type:`Log.entryAdded`,data:{entry:r}}),this.emit(`Log.entryAdded`,r)}}normalizeLevel(e){if(typeof e==`string`){let t=e.toLowerCase();if([`trace`,`debug`,`info`,`warn`,`error`,`fatal`].includes(t))return t}return typeof e==`number`?e<=10?`trace`:e<=20?`debug`:e<=30?`info`:e<=40?`warn`:e<=50?`error`:`fatal`:`info`}};function ze(){let e=new Map;return{acquire(t,n){let r=e.get(t);return r===void 0||r===n?(e.set(t,n),{kind:`acquired`}):{kind:`denied`,leaseOwner:r}},release(t,n){let r=e.get(t);return r===void 0||r!==n?!1:(e.delete(t),!0)},releaseAllForClient(t){let n=[];for(let[r,i]of e.entries())i===t&&(e.delete(r),n.push(r));return n},ownerOf(t){return e.get(t)},canClientWrite(t,n){let r=e.get(t);return r===void 0||r===n},forceAcquire(t,n){let r=e.get(t);return e.set(t,n),{previousOwner:r,newOwner:n}}}}const _=h(`@x-otto/service:inbound-router`);function v(e,t){let n=e[t];return typeof n==`string`?n:void 0}function Be(e,t){let n=e[t];return typeof n==`boolean`?n:void 0}function y(e,t){let n=e[t];return typeof n==`number`?n:void 0}function Ve(e,t){let n=e[t];return typeof n==`object`&&n&&!Array.isArray(n)?n:void 0}function He(e){let t=Ve(e,`answers`);if(!t)return null;let n=v(t,`answer`);return n===void 0?null:{answer:n,acceptedRecommendation:t.acceptedRecommendation===!0,resolvedBy:t.resolvedBy===`auto_recommendation`?`auto_recommendation`:`human`,selectedOptionLabels:Array.isArray(t.selectedOptionLabels)?t.selectedOptionLabels.filter(e=>typeof e==`string`):void 0,freeformText:v(t,`freeformText`)}}function Ue(e){let t=v(e,`message`);return t?{message:t,sessionId:v(e,`sessionId`)}:null}function We(e){let t=v(e,`approvalId`),n=Be(e,`approved`);return!t||n===void 0?null:{approvalId:t,approved:n,sessionId:v(e,`sessionId`)}}function Ge(e){let t=v(e,`requestId`);if(!t)return null;let n=e.cancelled===!0;return{requestId:t,answers:n?null:He(e),cancelled:n,sessionId:v(e,`sessionId`)}}function Ke(e){let t=v(e,`requestId`),n=v(e,`action`);return!t||!n?null:{requestId:t,action:n,feedback:v(e,`feedback`),sessionId:v(e,`sessionId`)}}function b(e){let t=v(e,`sessionId`);if(!t)return null;let n=y(e,`since`);return n===void 0?{sessionId:t}:{sessionId:t,since:n}}function qe(e){return{seq:y(e,`seq`),pauseId:v(e,`pauseId`),depth:y(e,`depth`)}}function Je(e){let t=v(e,`point`),n=Be(e,`enabled`);return t===void 0||n===void 0?null:{point:t,enabled:n}}function Ye(e){let t=Be(e,`active`);return t===void 0?null:{active:t}}var Xe=class{writeLease=ze();constructor(e,t,n,r){this.ws=e,this.app=t,this.bridge=n,this.readEventsSince=r,this.ws.onClientDisconnected=e=>{let t=this.writeLease.releaseAllForClient(e);t.length>0&&_.debug({clientId:e,released:t},`write-lease released on disconnect`)}}dispatch(e,t){let{type:n,data:r}=t;switch(_.debug({clientId:e,type:n},`message from client`),n){case`Session.subscribe`:{let t=b(r);t&&(this.ws.subscribeClient(e,t.sessionId),t.since!==void 0&&this.replaySince(e,t.sessionId,t.since));break}case`Session.unsubscribe`:{let t=b(r);t&&this.ws.unsubscribeClient(e,t.sessionId);break}case`Session.writeLease.acquire`:{let t=b(r);if(!t||!t.sessionId)break;let n=this.writeLease.acquire(t.sessionId,e);n.kind===`acquired`?this.ws.sendToClient(e,{type:`Runtime.writeLease`,data:{sessionId:t.sessionId,state:`acquired`,leaseOwner:e}}):this.ws.sendToClient(e,{type:`Runtime.writeLease`,data:{sessionId:t.sessionId,state:`denied`,reason:`lease held by another client`,leaseOwner:n.leaseOwner}});break}case`Session.writeLease.release`:{let t=b(r);if(!t||!t.sessionId)break;let n=this.writeLease.release(t.sessionId,e);this.ws.sendToClient(e,{type:`Runtime.writeLease`,data:{sessionId:t.sessionId,state:n?`released`:`not-held`,leaseOwner:n?void 0:this.writeLease.ownerOf(t.sessionId)}});break}case`Session.writeLease.force_acquire`:{let t=b(r);if(!t||!t.sessionId)break;let n=this.writeLease.forceAcquire(t.sessionId,e);_.warn({sessionId:t.sessionId,newOwner:e,previousOwner:n.previousOwner},`write-lease force-acquired`),n.previousOwner&&n.previousOwner!==e&&this.ws.sendToClient(n.previousOwner,{type:`Runtime.writeLease`,data:{sessionId:t.sessionId,state:`released`,reason:`forced_by_other_client`,leaseOwner:n.newOwner}}),this.ws.sendToClient(e,{type:`Runtime.writeLease`,data:{sessionId:t.sessionId,state:`acquired`,leaseOwner:n.newOwner}});break}case`Chat.query`:{let t=Ue(r);if(t){let n=t.sessionId;if(n&&!this.writeLease.canClientWrite(n,e)){let t=this.writeLease.ownerOf(n);_.info({sessionId:n,clientId:e,leaseOwner:t},`Chat.query denied by write-lease`),this.ws.sendToClient(e,{type:`Runtime.error`,data:{sessionId:n,code:`WRITE_LEASE_DENIED`,message:`chat query denied — write-lease held by another client`,leaseOwner:t}});break}this.handleQuery(e,t)}break}case`Chat.approval`:{let e=We(r);e&&this.handleApproval(e);break}case`Chat.askUserResponse`:{let e=Ge(r);e&&this.handleAskUserResponse(e);break}case`Chat.planApprovalResponse`:{let e=Ke(r);e&&this.handlePlanApprovalResponse(e);break}case`Debugger.resume`:case`Debugger.stepOver`:case`Debugger.stepInto`:case`Debugger.disable`:this.handleDebugCommand(n,qe(r),r);break;case`Debugger.setBreakpoint`:{let e=Je(r);e&&this.handleDebugSetBreakpoint(e);break}case`Debugger.setBreakpointsActive`:{let e=Ye(r);e&&this.handleDebugSetBreakpointsActive(e);break}default:_.debug({type:n},`unknown client message type`)}}replaySince(e,t,n){if(!this.readEventsSince)return;let r=this.readEventsSince(t,n);if(!r.ok){_.warn({sessionId:t,after:n,oldest:r.oldestAvailable},`event log gap; client must resync`),this.ws.sendToClient(e,{type:`Runtime.error`,data:{sessionId:t,message:`event history gap — re-fetch the session snapshot`,code:`EVENT_LOG_GAP`}});return}for(let t of r.events){let n=t.message.type===`Session.event`?{...t.message,data:{...t.message.data,seq:t.seq}}:t.message;this.ws.sendToClient(e,n)}}resolveSession(e){return e?this.app.getSession(e):this.app.getActiveSession()}handleQuery(e,{message:t,sessionId:n}){let r=this.resolveSession(n);r&&r.prompt(t).catch(t=>{_.error({sessionId:r.id,err:t},`prompt failed`),this.ws.sendToClient(e,{type:`Runtime.error`,data:{sessionId:r.id,message:`prompt failed`,code:`PROMPT_FAILED`}})})}handleApproval({approvalId:e,approved:t,sessionId:n}){let r=this.resolveSession(n);r&&(r.resolveApproval(e,t),_.debug({sessionId:r.id,approved:t},`approval resolved`))}handleAskUserResponse({requestId:e,answers:t,sessionId:n}){let r=this.resolveSession(n);r&&(r.resolveAskUser(e,t),_.debug({sessionId:r.id,requestId:e},`ask_user resolved`))}handlePlanApprovalResponse({requestId:e,action:t,feedback:n,sessionId:r}){let i=this.resolveSession(r);i&&(i.resolvePlanApproval(e,t,n),_.debug({sessionId:i.id,action:t,requestId:e},`plan approval resolved`))}handleDebugCommand(e,{seq:t,pauseId:n,depth:r},i){if(!this.bridge)return;let a=Ve(i,`payload`);this.bridge.send({type:e,seq:t??Date.now(),...n===void 0?{}:{pauseId:n},...r===void 0?{}:{depth:r}},a)}handleDebugSetBreakpoint({point:e,enabled:t}){this.bridge&&this.bridge.send({type:`setBreakpoint`,seq:Date.now(),point:e,enabled:t})}handleDebugSetBreakpointsActive({active:e}){this.bridge&&this.bridge.send({type:`setBreakpointsActive`,seq:Date.now(),active:e})}};function Ze(e,t){let n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length?o(n,r):!1}function Qe(e){return/^Bearer\s+(.+)$/i.exec(e.req.header(`authorization`)??``)?.[1]??``}function $e(e){let t=new m;return t.get(`/`,t=>{let n=e.app.storage.storageHost;return t.json({status:`ok`,service:`otto-coding`,uptime:process.uptime(),namespaces:n?.host?n.host.listNamespaces():null})}),t}function et(e){let t=new m;return t.get(`/`,t=>t.json(e.getAuthorityDescriptor())),t}function x(e){return e.session.messages().map(e=>{let t=tt(e);return{role:e.role,content:nt(e),timestamp:`timestamp`in e?e.timestamp:void 0,toolCalls:rt(e),...t.length>0?{a2ui:t}:{}}})}function tt(e){return Array.isArray(e.content)?e.content.filter(e=>e&&typeof e==`object`&&e.type===`a2ui`&&Array.isArray(e.components)).map(e=>e.components):[]}function nt(e){return typeof e.content==`string`?e.content:Array.isArray(e.content)?e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``):``}function rt(e){return Array.isArray(e.content)?e.content.filter(e=>e.type===`tool_call`).map(e=>({id:e.id??``,name:e.name??``,parameters:e.arguments??{}})):[]}const it=h(`@x-otto/service:chat`);function at(e){let t=new m;return t.post(`/query`,async t=>{let{message:n,sessionId:r}=await t.req.json().catch(()=>({}));if(!n)return t.json({status:`error`,message:`message is required`},400);let i=r?e.getSession(r):e.getActiveSession();return i?(i.prompt(n).catch(t=>{it.error({sessionId:i.id,err:t},`prompt failed`),e.ws.sendToSession(i.id,{type:`Runtime.error`,data:{sessionId:i.id,message:`prompt failed`,code:`PROMPT_FAILED`}})}),t.json({status:`ok`,message:`prompt accepted`,sessionId:i.id})):t.json({status:`error`,message:`no active session`},404)}),t.get(`/messages`,t=>{let n=e.getActiveSession();return n?t.json(x(n)):t.json([])}),t.post(`/interrupt`,t=>{let n=e.getActiveSession();return n?(n.abort(),t.json({status:`ok`,message:`interrupted`})):t.json({status:`error`,message:`no active session`},404)}),t.delete(`/clear`,async t=>{let n=e.getActiveSession();return n?(await n.clearContext(),t.json({status:`ok`,message:`cleared`})):t.json({status:`error`,message:`no active session`},404)}),t}function ot(e,t){let n=d(e,t);return n===``||!n.startsWith(`..${p}`)&&n!==`..`&&!l(n)}function st(t,n){if(n.startsWith(`~`))return null;let i=f(t),a=f(i,n);if(!ot(i,a))return null;if(e(a))try{let e=r(a);if(!ot(r(i),e))return null}catch{return null}return a}function ct(t){let r=new m;return r.post(`/verify-path`,async e=>{let n=(await e.req.json().catch(()=>({}))).path,r=t.app.workspaceDir;if(!n)return e.json({exists:!1,isDirectory:!1,error:`path is required`},400);if(!r)return e.json({exists:!1,isDirectory:!1,error:`workspace not configured`},403);let a=st(r,n);if(!a)return e.json({exists:!1,isDirectory:!1,error:`path is outside workspace`},403);try{let t=i(a);return e.json({exists:!0,isDirectory:t.isDirectory(),path:a})}catch{return e.json({exists:!1,isDirectory:!1,path:a})}}),r.post(`/browse-directory`,async r=>{let i=await r.req.json().catch(()=>({})),a=t.app.workspaceDir,o=i.showHidden??!1;if(!a)return r.json({currentPath:null,parentPath:null,directories:[],error:`workspace not configured`},403);let c=f(a),l=st(a,i.path||c);if(!l)return r.json({currentPath:null,parentPath:null,directories:[],error:`path is outside workspace`},403);let d=l===c?c:s(l);if(!e(l))return r.json({currentPath:l,parentPath:d,directories:[],error:`path does not exist`});try{let e=n(l,{withFileTypes:!0}).filter(e=>e.isDirectory()).filter(e=>o||!e.name.startsWith(`.`)).map(e=>({name:e.name,path:u(l,e.name)})).sort((e,t)=>e.name.localeCompare(t.name));return r.json({currentPath:l,parentPath:d,directories:e,error:null})}catch{return r.json({currentPath:l,parentPath:d,directories:[],error:`failed to read directory`})}}),r.get(`/files`,e=>{let r=e.req.query(`query`);try{let i=n(t.app.workspaceDir,{withFileTypes:!0}).map(e=>({path:u(t.app.workspaceDir,e.name),name:e.name,isFile:e.isFile()}));if(r){let e=r.toLowerCase();i=i.filter(t=>t.name.toLowerCase().includes(e))}return e.json({files:i})}catch{return e.json({files:[]})}}),r}const S=h(`@x-otto/service:timetravel`);function lt(e){if(e===void 0)return;let t=Number(e);return Number.isInteger(t)?t:void 0}function ut(e){let t=new m,n=()=>e.app.sessionManager;return t.get(`/:id/checkpoints`,async e=>{let t=await n().listCheckpoints(e.req.param(`id`));return e.json({sessionId:e.req.param(`id`),checkpoints:t})}),t.post(`/:id/checkpoints`,async e=>{let t=e.req.param(`id`),r=await e.req.json().catch(()=>({}));try{let i=await n().createCheckpoint(t,{label:r.label,files:r.files});return e.json({checkpoint:i})}catch(n){return S.error({sessionId:t,err:n},`createCheckpoint failed`),e.json({error:C(400)},400)}}),t.post(`/:id/checkpoints/:seq/restore`,async e=>{let t=e.req.param(`id`),r=lt(e.req.param(`seq`)),i=await e.req.json().catch(()=>({})),a={sessionId:t,seq:r,mode:i.mode,truncate:i.truncate};if(!le(a))return e.json({error:`invalid Checkpoint.restore params (need seq:number, mode)`},400);try{return a.truncate?await n().rollbackToCheckpoint(a.sessionId,a.seq,a.mode):await n().restoreCheckpoint(a.sessionId,a.seq,a.mode),e.json({status:`ok`,sessionId:t,seq:a.seq,mode:a.mode,truncated:!!a.truncate})}catch(n){let r=ft(n);return S.error({sessionId:t,err:n},`checkpoint restore failed`),e.json({error:C(r)},r)}}),t.post(`/:id/checkpoints/:seq/fork`,async e=>{let t=e.req.param(`id`),r={sessionId:t,seq:lt(e.req.param(`seq`)),newId:(await e.req.json().catch(()=>({}))).newId};if(!ce(r))return e.json({error:`invalid Checkpoint.fork params (need seq:number)`},400);try{let i=await n().forkFromCheckpoint(r.sessionId,r.seq,r.newId);return e.json({status:`ok`,forkedSessionId:i.id,sourceSessionId:t,fromSeq:r.seq})}catch(n){let r=ft(n);return S.error({sessionId:t,err:n},`checkpoint fork failed`),e.json({error:C(r)},r)}}),t.get(`/:id/traceback`,async e=>{let t=e.req.param(`id`),r={sessionId:t,seq:lt(e.req.query(`to`))};if(!ue(r))return e.json({error:`query param "to" (trace seq) is required and must be an integer`},400);let i=await n().traceback(t,r.seq);return e.json(i)}),t.post(`/:id/replay`,async e=>{let t=e.req.param(`id`),r=await e.req.json().catch(()=>({}));if(!de({sessionId:t,to:r.to}))return e.json({error:`invalid Replay.start params`},400);try{let i=await n().replaySession(t,r.newId);return e.json({status:`ok`,replaySessionId:i.id,sourceSessionId:t})}catch(n){return S.error({sessionId:t,err:n},`replay start failed`),e.json({error:C(400)},400)}}),t.get(`/:id/trace/summary`,async t=>{let n=t.req.param(`id`);try{let r=await he(e.app.storage.traceStore.read(n));return t.json({sessionId:n,...r})}catch(e){return S.error({sessionId:n,err:e},`trace summary failed`),t.json({error:C(400)},400)}}),t.get(`/:id/trace/spans`,async t=>{let n=t.req.param(`id`);try{let r=await ge(e.app.storage.traceStore.read(n));return t.json({sessionId:n,spans:r})}catch(e){return S.error({sessionId:n,err:e},`trace spans failed`),t.json({error:C(400)},400)}}),t.get(`/:id/trace/timeline`,async t=>{let n=t.req.param(`id`);try{let r=await _e(e.app.storage.traceStore.read(n));return t.json(r)}catch(e){return S.error({sessionId:n,err:e},`trace timeline failed`),t.json({error:C(400)},400)}}),t.post(`/:id/otel-export`,async t=>{let n=pe();if(!n)return t.json({error:`OTel export not enabled (set OTEL_EXPORTER_OTLP_ENDPOINT to opt in)`},503);let r=t.req.param(`id`),i=[];for await(let t of e.app.storage.traceStore.read(r))i.push(t.entry);let a=await fe(r,i,n,{includeContent:t.req.query(`includeContent`)===`true`});return t.json({sessionId:r,exported:a},a.ok?200:502)}),t}function dt(e){return e instanceof Error?e.message:String(e)}function ft(e){return/not found|unknown/i.test(dt(e))?404:400}function C(e){return e===404?`not found`:`request failed`}function pt(e){let t=new m;return t.get(`/`,t=>{let n=e.app.listSessions();return t.json(n.map(t=>({id:t.id,createdAt:t.createdAt.toISOString(),updatedAt:t.updatedAt?.toISOString(),messageCount:t.messageCount,workingDirectory:e.app.workspaceDir,title:t.title??t.id,status:t.status})))}),t.post(`/`,async t=>{await t.req.json().catch(()=>({}));let n=await e.app.createSession();return t.json({status:`ok`,message:`session created`,session:{id:n.id,workingDirectory:e.app.workspaceDir,createdAt:new Date().toISOString()}})}),t.get(`/current`,t=>{let n=e.getActiveSession();return n?t.json({id:n.id,workingDirectory:e.app.workspaceDir,messageCount:n.session.messages().length,status:n.status}):t.json({status:`error`,message:`no active session`},404)}),t.get(`/bridge-info`,t=>{let n=e.getActiveSession();return t.json({sessionId:n?.id??null})}),t.get(`/:id/messages`,t=>{let n=e.getSession(t.req.param(`id`));return n?t.json(x(n)):t.json([],404)}),t.get(`/:id/snapshot`,t=>{let n=e.getSessionSnapshot(t.req.param(`id`));return n?t.json(n):t.json({status:`error`,message:`session not found`},404)}),t.post(`/:id/resume`,t=>e.getSession(t.req.param(`id`))?t.json({status:`error`,message:`resume is not implemented`},501):t.json({status:`error`,message:`session not found`},404)),t.get(`/:id/trace`,async t=>{let n=t.req.param(`id`),r=e=>{if(e===void 0)return;let t=Number(e);return Number.isFinite(t)?t:void 0},i={from:r(t.req.query(`from`)),to:r(t.req.query(`to`))};try{let r=[];for await(let t of e.app.storage.traceStore.read(n,i))r.push({seq:t.seq,event:t.entry});return t.json({sessionId:n,events:r})}catch{return t.json({sessionId:n,events:[],error:`failed to read trace`},500)}}),t.get(`/:id/export`,t=>{let n=e.getSession(t.req.param(`id`));return n?t.json({id:n.id,messages:n.session.messages(),exportedAt:new Date().toISOString()}):t.json({status:`error`,message:`session not found`},404)}),t.get(`/:id/model`,t=>{let n=e.getSession(t.req.param(`id`));if(!n)return t.json({},404);let r=n.model;return t.json(r?{id:r.id,provider:r.provider}:{})}),t.put(`/:id/model`,async t=>{let n=e.getSession(t.req.param(`id`));if(!n)return t.json({status:`error`,message:`session not found`},404);let r=(await t.req.json().catch(()=>({}))).modelId;if(!r)return t.json({status:`error`,message:`modelId is required`},400);let i=e.app.getAllModels().find(e=>e.id===r);return i?(n.model=i,t.json({status:`ok`,model:{id:i.id,provider:i.provider}})):t.json({status:`error`,message:`model not found: ${r}`},404)}),t.delete(`/:id/model`,e=>e.json({status:`error`,message:`model overlay is not implemented`},501)),t.route(`/`,ct(e)),t.route(`/`,ut(e)),t}Object.freeze({status:`aborted`});function w(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,`_zod`,{value:{def:r,constr:o,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);let i=o.prototype,a=Object.keys(i);for(let e=0;e<a.length;e++){let t=a[e];t in n||(n[t]=i[t].bind(n))}}let i=n?.Parent??Object;class a extends i{}Object.defineProperty(a,`name`,{value:e});function o(e){var t;let i=n?.Parent?new a:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(let e of i._zod.deferred)e();return i}return Object.defineProperty(o,`init`,{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>n?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,`name`,{value:e}),o}var T=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},mt=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};const ht={};function E(e){return e&&Object.assign(ht,e),ht}function gt(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 _t(e,t){return typeof t==`bigint`?t.toString():t}function vt(e){return{get value(){{let t=e();return Object.defineProperty(this,`value`,{value:t}),t}throw Error(`cached value already set`)}}}function D(e){return e==null}function yt(e){let t=e.startsWith(`^`)?1:0,n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}const bt=Symbol(`evaluating`);function O(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==bt)return r===void 0&&(r=bt,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function k(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function A(...e){let t={};for(let n of e)Object.assign(t,Object.getOwnPropertyDescriptors(n));return Object.defineProperties({},t)}function xt(e){return JSON.stringify(e)}const St=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function j(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Ct=vt(()=>{if(typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function M(e){if(j(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return!(j(n)===!1||Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)===!1)}function wt(e){return M(e)?{...e}:Array.isArray(e)?[...e]:e}const Tt=new Set([`string`,`number`,`symbol`]);function Et(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function N(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function P(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 Dt(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}-Number.MAX_VALUE,Number.MAX_VALUE;function Ot(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`);return N(e,A(e._zod.def,{get shape(){let e={};for(let r in t){if(!(r in n.shape))throw Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return k(this,`shape`,e),e},checks:[]}))}function kt(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`);return N(e,A(e._zod.def,{get shape(){let r={...e._zod.def.shape};for(let e in t){if(!(e in n.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return k(this,`shape`,r),r},checks:[]}))}function At(e,t){if(!M(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=e._zod.def.shape;for(let e in t)if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return N(e,A(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return k(this,`shape`,n),n}}))}function jt(e,t){if(!M(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return N(e,A(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return k(this,`shape`,n),n}}))}function Mt(e,t){return N(e,A(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return k(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:[]}))}function Nt(e,t,n){let r=t._zod.def.checks;if(r&&r.length>0)throw Error(`.partial() cannot be used on object schemas containing refinements`);return N(t,A(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return k(this,`shape`,i),i},checks:[]}))}function Pt(e,t,n){return N(t,A(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return k(this,`shape`,i),i}}))}function F(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 Ft(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function I(e){return typeof e==`string`?e:e?.message}function L(e,t,n){let r={...e,path:e.path??[]};return e.message||(r.message=I(e.inst?._zod.def?.error?.(e))??I(t?.error?.(e))??I(n.customError?.(e))??I(n.localeError?.(e))??`Invalid input`),delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function It(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function R(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}const Lt=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,`_zod`,{value:e._zod,enumerable:!1}),Object.defineProperty(e,`issues`,{value:t,enumerable:!1}),e.message=JSON.stringify(t,_t,2),Object.defineProperty(e,`toString`,{value:()=>e.message,enumerable:!1})},Rt=w(`$ZodError`,Lt),zt=w(`$ZodError`,Lt,{Parent:Error});function Bt(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function Vt(e,t=e=>e.message){let n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`&&i.errors.length)i.errors.map(e=>r({issues:e}));else if(i.code===`invalid_key`)r({issues:i.issues});else if(i.code===`invalid_element`)r({issues:i.issues});else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(e),n}const Ht=e=>(t,n,r,i)=>{let a=r?Object.assign(r,{async:!1}):{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new T;if(o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>L(e,a,E())));throw St(t,i?.callee),t}return o.value},z=e=>async(t,n,r,i)=>{let a=r?Object.assign(r,{async:!0}):{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new(i?.Err??e)(o.issues.map(e=>L(e,a,E())));throw St(t,i?.callee),t}return o.value},B=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 T;return a.issues.length?{success:!1,error:new(e??Rt)(a.issues.map(e=>L(e,i,E())))}:{success:!0,data:a.value}},Ut=B(zt),V=e=>async(t,n,r)=>{let i=r?Object.assign(r,{async:!0}):{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>L(e,i,E())))}:{success:!0,data:a.value}},Wt=V(zt),Gt=e=>(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return Ht(e)(t,n,i)},Kt=e=>(t,n,r)=>Ht(e)(t,n,r),qt=e=>async(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return z(e)(t,n,i)},Jt=e=>async(t,n,r)=>z(e)(t,n,r),Yt=e=>(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return B(e)(t,n,i)},Xt=e=>(t,n,r)=>B(e)(t,n,r),Zt=e=>async(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return V(e)(t,n,i)},Qt=e=>async(t,n,r)=>V(e)(t,n,r),H=w(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),$t=w(`$ZodCheckMaxLength`,(e,t)=>{var n;H.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!D(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let r=n.value;if(r.length<=t.maximum)return;let i=It(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),en=w(`$ZodCheckMinLength`,(e,t)=>{var n;H.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!D(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=It(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),tn=w(`$ZodCheckLengthEquals`,(e,t)=>{var n;H.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!D(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=It(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),nn=w(`$ZodCheckOverwrite`,(e,t)=>{H.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var rn=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
|
|
2
|
+
`).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?.args,n=[...(this?.content??[``]).map(e=>` ${e}`)];return new e(...t,n.join(`
|
|
3
|
+
`))}};const an={major:4,minor:3,patch:6},U=w(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=an;let r=[...e._zod.def.checks??[]];e._zod.traits.has(`$ZodCheck`)&&r.unshift(e);for(let t of r)for(let n of t._zod.onattach)n(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,n)=>{let r=F(e),i;for(let a of t){if(a._zod.def.when){if(!a._zod.def.when(e))continue}else if(r)continue;let t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&n?.async===!1)throw new T;if(i||o instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(r||=F(e,t))});else{if(e.issues.length===t)continue;r||=F(e,t)}}return i?i.then(()=>e):e},n=(n,i,a)=>{if(F(n))return n.aborted=!0,n;let o=t(i,r,a);if(o instanceof Promise){if(a.async===!1)throw new T;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(i,a)=>{if(a.skipChecks)return e._zod.parse(i,a);if(a.direction===`backward`){let t=e._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,i,a)):n(t,i,a)}let o=e._zod.parse(i,a);if(o instanceof Promise){if(a.async===!1)throw new T;return o.then(e=>t(e,r,a))}return t(o,r,a)}}O(e,`~standard`,()=>({validate:t=>{try{let n=Ut(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return Wt(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}))}),on=w(`$ZodUnknown`,(e,t)=>{U.init(e,t),e._zod.parse=e=>e}),sn=w(`$ZodNever`,(e,t)=>{U.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function cn(e,t,n){e.issues.length&&t.issues.push(...Ft(n,e.issues)),t.value[n]=e.value}const ln=w(`$ZodArray`,(e,t)=>{U.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:`array`,code:`invalid_type`,input:i,inst:e}),n;n.value=Array(i.length);let a=[];for(let e=0;e<i.length;e++){let o=i[e],s=t.element._zod.run({value:o,issues:[]},r);s instanceof Promise?a.push(s.then(t=>cn(t,n,e))):cn(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function W(e,t,n,r,i){if(e.issues.length){if(i&&!(n in r))return;t.issues.push(...Ft(n,e.issues))}e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}function un(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${n}": expected a Zod schema`);let n=Dt(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function dn(e,t,n,r,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,u=c.optout===`optional`;for(let i in t){if(s.has(i))continue;if(l===`never`){o.push(i);continue}let a=c.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>W(e,n,i,t,u))):W(a,n,i,t,u)}return o.length&&n.issues.push({code:`unrecognized_keys`,keys:o,input:t,inst:a}),e.length?Promise.all(e).then(()=>n):n}const fn=w(`$ZodObject`,(e,t)=>{if(U.init(e,t),!Object.getOwnPropertyDescriptor(t,`shape`)?.get){let e=t.shape;Object.defineProperty(t,`shape`,{get:()=>{let n={...e};return Object.defineProperty(t,`shape`,{value:n}),n}})}let n=vt(()=>un(t));O(e._zod,`propValues`,()=>{let e=t.shape,n={};for(let t in e){let r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(let e of r.values)n[t].add(e)}}return n});let r=j,i=t.catchall,a;e._zod.parse=(t,o)=>{a??=n.value;let s=t.value;if(!r(s))return t.issues.push({expected:`object`,code:`invalid_type`,input:s,inst:e}),t;t.value={};let c=[],l=a.shape;for(let e of a.keys){let n=l[e],r=n._zod.optout===`optional`,i=n._zod.run({value:s[e],issues:[]},o);i instanceof Promise?c.push(i.then(n=>W(n,t,e,s,r))):W(i,t,e,s,r)}return i?dn(c,s,t,o,n.value,e):c.length?Promise.all(c).then(()=>t):t}}),pn=w(`$ZodObjectJIT`,(e,t)=>{fn.init(e,t);let n=e._zod.parse,r=vt(()=>un(t)),i=e=>{let t=new rn([`shape`,`payload`,`ctx`]),n=r.value,i=e=>{let t=xt(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write(`const input = payload.value;`);let a=Object.create(null),o=0;for(let e of n.keys)a[e]=`key_${o++}`;t.write(`const newResult = {};`);for(let r of n.keys){let n=a[r],o=xt(r),s=e[r]?._zod?.optout===`optional`;t.write(`const ${n} = ${i(r)};`),s?t.write(`
|
|
4
|
+
if (${n}.issues.length) {
|
|
5
|
+
if (${o} in input) {
|
|
6
|
+
payload.issues = payload.issues.concat(${n}.issues.map(iss => ({
|
|
7
|
+
...iss,
|
|
8
|
+
path: iss.path ? [${o}, ...iss.path] : [${o}]
|
|
9
|
+
})));
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
if (${n}.value === undefined) {
|
|
14
|
+
if (${o} in input) {
|
|
15
|
+
newResult[${o}] = undefined;
|
|
16
|
+
}
|
|
17
|
+
} else {
|
|
18
|
+
newResult[${o}] = ${n}.value;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
`):t.write(`
|
|
22
|
+
if (${n}.issues.length) {
|
|
23
|
+
payload.issues = payload.issues.concat(${n}.issues.map(iss => ({
|
|
24
|
+
...iss,
|
|
25
|
+
path: iss.path ? [${o}, ...iss.path] : [${o}]
|
|
26
|
+
})));
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
if (${n}.value === undefined) {
|
|
30
|
+
if (${o} in input) {
|
|
31
|
+
newResult[${o}] = undefined;
|
|
32
|
+
}
|
|
33
|
+
} else {
|
|
34
|
+
newResult[${o}] = ${n}.value;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
`)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},a,o=j,s=!ht.jitless,c=s&&Ct.value,l=t.catchall,u;e._zod.parse=(d,f)=>{u??=r.value;let p=d.value;return o(p)?s&&c&&f?.async===!1&&f.jitless!==!0?(a||=i(t.shape),d=a(d,f),l?dn([],p,d,f,u,e):d):n(d,f):(d.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),d)}});function mn(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=>!F(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=>L(e,r,E())))}),t)}const hn=w(`$ZodUnion`,(e,t)=>{U.init(e,t),O(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),O(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),O(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),O(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>yt(e.source)).join(`|`)})$`)}});let n=t.options.length===1,r=t.options[0]._zod.run;e._zod.parse=(i,a)=>{if(n)return r(i,a);let o=!1,s=[];for(let e of t.options){let t=e._zod.run({value:i.value,issues:[]},a);if(t instanceof Promise)s.push(t),o=!0;else{if(t.issues.length===0)return t;s.push(t)}}return o?Promise.all(s).then(t=>mn(t,i,e,a)):mn(s,i,e,a)}}),gn=w(`$ZodIntersection`,(e,t)=>{U.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])=>vn(e,t,n)):vn(e,i,a)}});function _n(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(M(e)&&M(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=_n(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=_n(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 vn(e,t,n){let r=new Map,i;for(let n of t.issues)if(n.code===`unrecognized_keys`){i??=n;for(let e of n.keys)r.has(e)||r.set(e,{}),r.get(e).l=!0}else e.issues.push(n);for(let t of n.issues)if(t.code===`unrecognized_keys`)for(let e of t.keys)r.has(e)||r.set(e,{}),r.get(e).r=!0;else e.issues.push(t);let a=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(a.length&&i&&e.issues.push({...i,keys:a}),F(e))return e;let o=_n(t.value,n.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}const yn=w(`$ZodEnum`,(e,t)=>{U.init(e,t);let n=gt(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=RegExp(`^(${n.filter(e=>Tt.has(typeof e)).map(e=>typeof e==`string`?Et(e):e.toString()).join(`|`)})$`),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}}),bn=w(`$ZodTransform`,(e,t)=>{U.init(e,t),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new mt(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 T;return n.value=i,n}});function xn(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}const Sn=w(`$ZodOptional`,(e,t)=>{U.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,O(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),O(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${yt(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(t.innerType._zod.optin===`optional`){let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(t=>xn(t,e.value)):xn(r,e.value)}return e.value===void 0?e:t.innerType._zod.run(e,n)}}),Cn=w(`$ZodExactOptional`,(e,t)=>{Sn.init(e,t),O(e._zod,`values`,()=>t.innerType._zod.values),O(e._zod,`pattern`,()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),wn=w(`$ZodNullable`,(e,t)=>{U.init(e,t),O(e._zod,`optin`,()=>t.innerType._zod.optin),O(e._zod,`optout`,()=>t.innerType._zod.optout),O(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${yt(e.source)}|null)$`):void 0}),O(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),Tn=w(`$ZodDefault`,(e,t)=>{U.init(e,t),e._zod.optin=`optional`,O(e._zod,`values`,()=>t.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=>En(e,t)):En(r,t)}});function En(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const Dn=w(`$ZodPrefault`,(e,t)=>{U.init(e,t),e._zod.optin=`optional`,O(e._zod,`values`,()=>t.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))}),On=w(`$ZodNonOptional`,(e,t)=>{U.init(e,t),O(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].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=>kn(t,e)):kn(i,e)}});function kn(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}const An=w(`$ZodCatch`,(e,t)=>{U.init(e,t),O(e._zod,`optin`,()=>t.innerType._zod.optin),O(e._zod,`optout`,()=>t.innerType._zod.optout),O(e._zod,`values`,()=>t.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(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>L(e,n,E()))},input:e.value}),e.issues=[]),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>L(e,n,E()))},input:e.value}),e.issues=[]),e)}}),jn=w(`$ZodPipe`,(e,t)=>{U.init(e,t),O(e._zod,`values`,()=>t.in._zod.values),O(e._zod,`optin`,()=>t.in._zod.optin),O(e._zod,`optout`,()=>t.out._zod.optout),O(e._zod,`propValues`,()=>t.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=>G(e,t.in,n)):G(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>G(e,t.out,n)):G(r,t.out,n)}});function G(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const Mn=w(`$ZodReadonly`,(e,t)=>{U.init(e,t),O(e._zod,`propValues`,()=>t.innerType._zod.propValues),O(e._zod,`values`,()=>t.innerType._zod.values),O(e._zod,`optin`,()=>t.innerType?._zod?.optin),O(e._zod,`optout`,()=>t.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(Nn):Nn(r)}});function Nn(e){return e.value=Object.freeze(e.value),e}const Pn=w(`$ZodCustom`,(e,t)=>{H.init(e,t),U.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=>Fn(t,n,r,e));Fn(i,n,r,e)}});function Fn(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(R(e))}}var In,Ln=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 Rn(){return new Ln}(In=globalThis).__zod_globalRegistry??(In.__zod_globalRegistry=Rn());const K=globalThis.__zod_globalRegistry;function zn(e){return new e({type:`unknown`})}function Bn(e,t){return new e({type:`never`,...P(t)})}function Vn(e,t){return new $t({check:`max_length`,...P(t),maximum:e})}function Hn(e,t){return new en({check:`min_length`,...P(t),minimum:e})}function Un(e,t){return new tn({check:`length_equals`,...P(t),length:e})}function Wn(e){return new nn({check:`overwrite`,tx:e})}function Gn(e,t,n){return new e({type:`array`,element:t,...P(n)})}function Kn(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...P(n)})}function qn(e){let t=Jn(n=>(n.addIssue=e=>{if(typeof e==`string`)n.issues.push(R(e,n.value,t._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,r.input??=n.value,r.inst??=t,r.continue??=!t._zod.def.abort,n.issues.push(R(r))}},e(n.value,n)));return t}function Jn(e,t){let n=new H({check:`custom`,...P(t)});return n._zod.check=e,n}function Yn(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??K,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,external:e?.external??void 0}}function q(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);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,q(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),t.io===`input`&&J(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&o.schema._prefault&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function Xn(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);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}/${a}`}}if(t[1]===n)return{ref:`#`};let i=`#/${r}/`,a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+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>
|
|
38
|
+
|
|
39
|
+
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}if(r.count>1&&e.reused===`ref`){a(n);continue}}}function Zn(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)):Object.assign(i,s),Object.assign(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??[]})};for(let t of[...e.seen.entries()].reverse())r(t[0]);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)}Object.assign(i,n.def??n.schema);let a=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(a[e.defId]=e.def)}e.external||Object.keys(a).length>0&&(e.target===`draft-2020-12`?i.$defs=a:i.definitions=a);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,`~standard`,{value:{...t[`~standard`],jsonSchema:{input:Y(t,`input`,e.processors),output:Y(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function J(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 J(r.element,n);if(r.type===`set`)return J(r.valueType,n);if(r.type===`lazy`)return J(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`)return J(r.innerType,n);if(r.type===`intersection`)return J(r.left,n)||J(r.right,n);if(r.type===`record`||r.type===`map`)return J(r.keyType,n)||J(r.valueType,n);if(r.type===`pipe`)return J(r.in,n)||J(r.out,n);if(r.type===`object`){for(let e in r.shape)if(J(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(J(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(J(e,n))return!0;return!!(r.rest&&J(r.rest,n))}return!1}const Qn=(e,t={})=>n=>{let r=Yn({...n,processors:t});return q(e,r),Xn(r,e),Zn(r,e)},Y=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=Yn({...i??{},target:a,io:t,processors:n});return q(e,o),Xn(o,e),Zn(o,e)},$n=(e,t,n,r)=>{n.not={}},er=(e,t,n,r)=>{let i=e._zod.def,a=gt(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},tr=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},nr=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},rr=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=q(a.element,t,{...r,path:[...r.path,`items`]})},ir=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`,i.properties={};let o=a.shape;for(let e in o)i.properties[e]=q(o[e],t,{...r,path:[...r.path,`properties`,e]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e]._zod;return t.io===`input`?n.optin===void 0:n.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=q(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},ar=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>q(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},or=(e,t,n,r)=>{let i=e._zod.def,a=q(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=q(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1;n.allOf=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]]},sr=(e,t,n,r)=>{let i=e._zod.def,a=q(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`}]},cr=(e,t,n,r)=>{let i=e._zod.def;q(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},lr=(e,t,n,r)=>{let i=e._zod.def;q(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},ur=(e,t,n,r)=>{let i=e._zod.def;q(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,t.io===`input`&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},dr=(e,t,n,r)=>{let i=e._zod.def;q(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}n.default=o},fr=(e,t,n,r)=>{let i=e._zod.def,a=t.io===`input`?i.in._zod.def.type===`transform`?i.out:i.in:i.out;q(a,t,r);let o=t.seen.get(e);o.ref=a},pr=(e,t,n,r)=>{let i=e._zod.def;q(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},mr=(e,t,n,r)=>{let i=e._zod.def;q(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},hr=(e,t)=>{Rt.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>Vt(e,t)},flatten:{value:t=>Bt(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,_t,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,_t,2)}},isEmpty:{get(){return e.issues.length===0}}})};w(`ZodError`,hr);const X=w(`ZodError`,hr,{Parent:Error}),gr=Ht(X),_r=z(X),vr=B(X),yr=V(X),br=Gt(X),xr=Kt(X),Sr=qt(X),Cr=Jt(X),wr=Yt(X),Tr=Xt(X),Er=Zt(X),Dr=Qt(X),Z=w(`ZodType`,(e,t)=>(U.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:Y(e,`input`),output:Y(e,`output`)}}),e.toJSONSchema=Qn(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,`_def`,{value:t}),e.check=(...n)=>e.clone(A(t,{checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0}),e.with=e.check,e.clone=(t,n)=>N(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.parse=(t,n)=>gr(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>vr(e,t,n),e.parseAsync=async(t,n)=>_r(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>yr(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>br(e,t,n),e.decode=(t,n)=>xr(e,t,n),e.encodeAsync=async(t,n)=>Sr(e,t,n),e.decodeAsync=async(t,n)=>Cr(e,t,n),e.safeEncode=(t,n)=>wr(e,t,n),e.safeDecode=(t,n)=>Tr(e,t,n),e.safeEncodeAsync=async(t,n)=>Er(e,t,n),e.safeDecodeAsync=async(t,n)=>Dr(e,t,n),e.refine=(t,n)=>e.check(li(t,n)),e.superRefine=t=>e.check(ui(t)),e.overwrite=t=>e.check(Wn(t)),e.optional=()=>Gr(e),e.exactOptional=()=>qr(e),e.nullable=()=>Yr(e),e.nullish=()=>Gr(Yr(e)),e.nonoptional=t=>ti(e,t),e.array=()=>Nr(e),e.or=t=>Lr([e,t]),e.and=t=>zr(e,t),e.transform=t=>ai(e,Ur(t)),e.default=t=>Zr(e,t),e.prefault=t=>$r(e,t),e.catch=t=>ri(e,t),e.pipe=t=>ai(e,t),e.readonly=()=>si(e),e.describe=t=>{let n=e.clone();return K.add(n,{description:t}),n},Object.defineProperty(e,`description`,{get(){return K.get(e)?.description},configurable:!0}),e.meta=(...t)=>{if(t.length===0)return K.get(e);let n=e.clone();return K.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=t=>t(e),e)),Or=w(`ZodUnknown`,(e,t)=>{on.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function kr(){return zn(Or)}const Ar=w(`ZodNever`,(e,t)=>{sn.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$n(e,t,n,r)});function jr(e){return Bn(Ar,e)}const Mr=w(`ZodArray`,(e,t)=>{ln.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(t,n,r)=>rr(e,t,n,r),e.element=t.element,e.min=(t,n)=>e.check(Hn(t,n)),e.nonempty=t=>e.check(Hn(1,t)),e.max=(t,n)=>e.check(Vn(t,n)),e.length=(t,n)=>e.check(Un(t,n)),e.unwrap=()=>e.element});function Nr(e,t){return Gn(Mr,e,t)}const Pr=w(`ZodObject`,(e,t)=>{pn.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ir(e,t,n,r),O(e,`shape`,()=>t.shape),e.keyof=()=>Vr(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:kr()}),e.loose=()=>e.clone({...e._zod.def,catchall:kr()}),e.strict=()=>e.clone({...e._zod.def,catchall:jr()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>At(e,t),e.safeExtend=t=>jt(e,t),e.merge=t=>Mt(e,t),e.pick=t=>Ot(e,t),e.omit=t=>kt(e,t),e.partial=(...t)=>Nt(Wr,e,t[0]),e.required=(...t)=>Pt(ei,e,t[0])});function Fr(e,t){return new Pr({type:`object`,shape:e??{},...P(t)})}const Ir=w(`ZodUnion`,(e,t)=>{hn.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ar(e,t,n,r),e.options=t.options});function Lr(e,t){return new Ir({type:`union`,options:e,...P(t)})}const Rr=w(`ZodIntersection`,(e,t)=>{gn.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(t,n,r)=>or(e,t,n,r)});function zr(e,t){return new Rr({type:`intersection`,left:e,right:t})}const Br=w(`ZodEnum`,(e,t)=>{yn.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(t,n,r)=>er(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);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 Br({...t,checks:[],...P(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 Br({...t,checks:[],...P(r),entries:i})}});function Vr(e,t){return new Br({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...P(t)})}const Hr=w(`ZodTransform`,(e,t)=>{bn.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(t,n,r)=>nr(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new mt(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(R(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push(R(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function Ur(e){return new Hr({type:`transform`,transform:e})}const Wr=w(`ZodOptional`,(e,t)=>{Sn.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(t,n,r)=>mr(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Gr(e){return new Wr({type:`optional`,innerType:e})}const Kr=w(`ZodExactOptional`,(e,t)=>{Cn.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(t,n,r)=>mr(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function qr(e){return new Kr({type:`optional`,innerType:e})}const Jr=w(`ZodNullable`,(e,t)=>{wn.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(t,n,r)=>sr(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Yr(e){return new Jr({type:`nullable`,innerType:e})}const Xr=w(`ZodDefault`,(e,t)=>{Tn.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(t,n,r)=>lr(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Zr(e,t){return new Xr({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():wt(t)}})}const Qr=w(`ZodPrefault`,(e,t)=>{Dn.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ur(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function $r(e,t){return new Qr({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():wt(t)}})}const ei=w(`ZodNonOptional`,(e,t)=>{On.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(t,n,r)=>cr(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function ti(e,t){return new ei({type:`nonoptional`,innerType:e,...P(t)})}const ni=w(`ZodCatch`,(e,t)=>{An.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(t,n,r)=>dr(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function ri(e,t){return new ni({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}const ii=w(`ZodPipe`,(e,t)=>{jn.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fr(e,t,n,r),e.in=t.in,e.out=t.out});function ai(e,t){return new ii({type:`pipe`,in:e,out:t})}const oi=w(`ZodReadonly`,(e,t)=>{Mn.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(t,n,r)=>pr(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function si(e){return new oi({type:`readonly`,innerType:e})}const ci=w(`ZodCustom`,(e,t)=>{Pn.init(e,t),Z.init(e,t),e._zod.processJSONSchema=(t,n,r)=>tr(e,t,n,r)});function li(e,t={}){return Kn(ci,e,t)}function ui(e){return qn(e)}const di=Vr([`readonly`,`confirm`,`auto`]),fi=Vr([`low`,`medium`,`high`,`xhigh`,`max`]),pi=Fr({mode:di}),mi=Fr({level:fi});function hi(e){let t=new m;return t.get(`/`,t=>{let n=e.getActiveSession();return t.json({workingDirectory:e.app.workspaceDir,model:n?.model?.id,modelProvider:n?.model?.provider})}),t.put(`/`,async t=>{let n=await t.req.json().catch(()=>({}));try{let r=await e.app.updateSettings(n);return t.json({status:`ok`,settings:{model:r.model,thinking_level:r.thinking_level,permission_mode:r.permission_mode}})}catch(e){return t.json({status:`error`,message:`setting update failed: ${e instanceof Error?e.message:String(e)}`},500)}}),t.get(`/providers`,t=>{let n=e.app.listProviders();return t.json(n.map(e=>({id:e,name:e,models:[]})))}),t.get(`/models`,t=>{t.header(`Cache-Control`,`public, max-age=300`);try{let n=e.app.getAllModels();return t.json({models:n.map(e=>({id:e.id,provider:e.provider,name:e.name,reasoning:e.reasoning,input:e.input,contextWindow:e.contextWindow,maxOutputTokens:e.maxOutputTokens,cost:e.cost,...e.thinkingLevels?{thinkingLevels:e.thinkingLevels}:{}}))})}catch{return t.json({error:`failed to list models`},500)}}),t.post(`/verify-model`,async t=>{let n=await t.req.json().catch(()=>({}));if(typeof n.model!=`string`||!n.model)return t.json({valid:!1,error:`model is required`},400);try{return e.app.resolveModel(n.model),t.json({valid:!0})}catch{return t.json({valid:!1,error:`model not found`})}}),t.post(`/mode`,async t=>{let n;try{n=await t.req.json()}catch{return t.json({status:`error`,message:`invalid JSON body`},400)}let r=pi.safeParse(n);if(!r.success)return t.json({status:`error`,message:`invalid mode: ${r.error.issues.map(e=>e.message).join(`; `)}`},400);try{return await e.app.updateSettings({permission_mode:r.data.mode}),t.json({status:`ok`})}catch(e){return t.json({status:`error`,message:`mode switch failed: ${e instanceof Error?e.message:String(e)}`},500)}}),t.post(`/autonomy`,async e=>(await e.req.json().catch(()=>({})),e.json({status:`error`,message:`autonomy is not a configurable setting field; use PUT /api/setting to update permission_mode or thinking_level`},501))),t.post(`/thinking`,async t=>{let n;try{n=await t.req.json()}catch{return t.json({status:`error`,message:`invalid JSON body`},400)}let r=mi.safeParse(n);if(!r.success)return t.json({status:`error`,message:`invalid thinking level: ${r.error.issues.map(e=>e.message).join(`; `)}`},400);try{return await e.app.updateSettings({thinking_level:r.data.level}),t.json({status:`ok`})}catch(e){return t.json({status:`error`,message:`thinking switch failed: ${e instanceof Error?e.message:String(e)}`},500)}}),t}function gi(e,t){let n=new m;return n.get(`/status`,e=>e.json({enabled:t!==null})),n.use(`/*`,async(e,n)=>{if(!t)return e.json({error:`debugger not enabled`},503);await n()}),n.get(`/breakpoints`,e=>{let n=t?.debugger.listBreakpoints();return e.json({breakpoints:n})}),n}const _i=me.map(e=>e.point);function vi(e){let t=new m,n=()=>e.app.devtools;return t.use(`/*`,async(e,t)=>{if(!n())return e.json({error:`debugger not available (start with --inspect)`},503);await t()}),t.get(`/breakpoints`,e=>{let t=n().debugger,r=me.map(({point:e})=>{let n=t.getBreakpoint(e);return{point:e,enabled:n?.enabled??!1,set:n!==void 0}});return e.json({breakpoints:r})}),t.put(`/breakpoints/:point`,async e=>{let t=e.req.param(`point`);if(!_i.includes(t))return e.json({error:`unknown breakpoint point: ${t}`},400);let r=(await e.req.json().catch(()=>({enabled:!0}))).enabled??!0,i=n().debugger.setBreakpoint(t,r);return e.json({breakpoint:i})}),t.post(`/breakpoints/enable-all`,e=>(n().debugger.enableAllBreakpoints(),e.json({status:`ok`}))),t.post(`/breakpoints/disable-all`,e=>(n().debugger.disableAllBreakpoints(),e.json({status:`ok`}))),t.get(`/state`,e=>{let t=n().debugger.listBreakpoints(),r=t.filter(e=>e.enabled).length,i=n().controller.pending();return e.json({enabled:!0,connected:!0,breakpoints:{total:t.length,enabled:r},paused:i.length>0,pendingPauses:i.map(e=>({pauseId:e.pauseId,point:e.snapshot.point,turn:e.snapshot.turn}))})}),t.post(`/resume`,async t=>{let n=e.bridge;if(!n)return t.json({error:`debug bridge not available`},503);if(!n.isConnected)return t.json({error:`debug bridge not connected to worker — command cannot be delivered`},503);let r=await t.req.json().catch(()=>({})),i=r.command??`continue`;return[`continue`,`next`,`step`,`over`,`stop`].includes(i)?(n.send({type:i,seq:Date.now(),depth:0},r.payload),t.json({status:`ok`,command:i})):t.json({error:`invalid command: ${i}`},400)}),t.post(`/inject`,async t=>{let n=e.bridge;if(!n)return t.json({error:`debug bridge not available`},503);if(!n.isConnected)return t.json({error:`debug bridge not connected to worker — command cannot be delivered`},503);let r=await t.req.json().catch(()=>null);return!r||r.injectMessages===void 0&&r.systemPrompt===void 0&&r.llmParams===void 0?t.json({error:`at least one of injectMessages, systemPrompt, or llmParams is required`},400):(n.send({type:`continue`,seq:Date.now()},{systemPrompt:r.systemPrompt,injectMessages:r.injectMessages?.map(e=>({role:e.role,content:e.content})),llmParams:r.llmParams}),t.json({status:`ok`}))}),t}const yi={trace:0,debug:1,info:2,warn:3,error:4,fatal:5};function bi(e){let t=new m;return t.get(`/history`,t=>{if(!e.bridge)return t.json({entries:[],total:0});let n=Number(t.req.query(`limit`)??100),r=Number.isFinite(n)&&n>0?Math.min(n,2e3):100,i=t.req.query(`level`),a=t.req.query(`module`),o=e.bridge.getLogs();if(i&&yi[i]!==void 0){let e=yi[i];o=o.filter(t=>(yi[t.level]??0)>=e)}a&&(o=o.filter(e=>e.module.includes(a)));let s=o.length;return o=o.slice(-r),t.json({entries:o,total:s})}),t.get(`/stream`,t=>e.bridge?ve(t,async t=>{let n=e.bridge?.on(`Log.entryAdded`,e=>{t.writeSSE({event:`log`,data:JSON.stringify(e)})});await new Promise(e=>{t.onAbort(()=>{n?.(),e()})})}):t.text(`debugger not enabled`,503)),t}function xi(e){let t=new m;return t.get(`/extensions`,t=>t.json({extensions:e.app.extensions.list()})),t.post(`/extensions/toggle`,async t=>{let n=await t.req.json().catch(()=>({}));if(!n.category||!n.id||typeof n.enabled!=`boolean`)return t.json({error:`category, id, enabled required`},400);try{return await e.app.extensions.setEnabled(n.category,n.id,n.enabled),t.json({ok:!0})}catch(e){return t.json({error:e instanceof Error?e.message:String(e)},400)}}),t.get(`/commands`,t=>{let n=e.app.listFileCommands();return t.json({commands:n.map(e=>({name:e.name,description:e.description,argumentHint:e.argumentHint,source:e.source,scope:e.scope,pluginId:e.pluginId}))})}),t.get(`/sigil`,async t=>{let n=t.req.query(`q`)??``,r=t.req.query(`sigil`),i=r===`#`||r===`@`?r:void 0,a=Number(t.req.query(`max`)??`50`),o=Number.isFinite(a)&&a>0?a:50,s=await e.app.pluginInput.searchAsync(n,i,o);return t.json({entries:s})}),t.post(`/sigil/expand`,async t=>{let n=await t.req.json().catch(()=>({}));if(typeof n.text!=`string`)return t.json({error:`text required`},400);let r=await e.app.expandSigilChips(n.text,{uiHost:!1,skipPrefixes:new Set([`model`])});return t.json({text:r})}),t.get(`/plugin-status-items`,t=>{let n=e.app.getPluginStatusItems();return t.json({items:n})}),t.get(`/plugin-menu-items`,t=>{let n=e.app.getGlobalMenuItems();return t.json({items:n})}),t.get(`/shortcuts`,t=>t.json({shortcuts:e.app.getShortcuts()})),t.post(`/shortcuts`,async t=>{let n=await t.req.json().catch(()=>({}));if(typeof n.name!=`string`||typeof n.text!=`string`)return t.json({error:`name and text are required`},400);try{return await e.app.saveShortcut(n.name,n.text,n.previousName),t.json({shortcuts:e.app.getShortcuts()})}catch(e){return t.json({error:e instanceof Error?e.message:String(e)},400)}}),t.delete(`/shortcuts/:name`,async t=>(await e.app.deleteShortcut(t.req.param(`name`)),t.json({shortcuts:e.app.getShortcuts()}))),t.get(`/plugin-renderers`,t=>{let n=e.app.getPluginRenderers();return t.json({renderers:n})}),t.get(`/plugin-status-widgets`,t=>{let n=e.app.getPluginStatusWidgets();return t.json({widgets:n})}),t.get(`/plugin-file-viewers`,t=>{let n=e.app.getPluginFileViewers();return t.json({viewers:n})}),t}function Si(e){let t=new m;function n(e){return{id:e.id,sessionId:e.sessionId,title:e.title,origin:e.origin,status:e.status,startedAt:e.startedAt,hasDiff:e.diff!=null}}return t.get(`/`,e=>{let t=[...ye.list()].sort((e,t)=>t.startedAt-e.startedAt);return e.json({jobs:t.map(n)})}),t.get(`/:id/diff`,e=>{let t=e.req.param(`id`),n=ye.get(t);return n?n.diff==null?e.json({error:`diff not ready (job may still be running)`},409):e.json({id:n.id,diff:n.diff}):e.json({error:`job not found`},404)}),t.get(`/:id`,e=>{let t=e.req.param(`id`),r=ye.get(t);return r?e.json({job:n(r)}):e.json({error:`job not found`},404)}),t}function Ci(e){let t=new m;return t.get(`/status`,t=>e.app.isFeedbackAvailable()?t.json({available:!0}):t.json({available:!1},503)),t.post(`/pulse-survey`,async t=>{if(!e.app.isFeedbackAvailable())return t.json({error:`feedback plugin not available`},503);let n=await t.req.json().catch(()=>({}));return!n.rating||![`good`,`neutral`,`bad`].includes(n.rating)?t.json({error:`rating must be one of good|neutral|bad`},400):n.sdkVersion?(e.app.recordPulseSurvey({ts:Date.now(),rating:n.rating,comment:n.comment,sdkVersion:n.sdkVersion,modelId:n.modelId}),t.json({ok:!0})):t.json({error:`sdkVersion is required`},400)}),t.post(`/issue`,async t=>{if(!e.app.isFeedbackAvailable())return t.json({error:`feedback plugin not available`},503);let n=await t.req.json().catch(()=>({}));if(!n.title)return t.json({error:`title is required`},400);if(!n.repo)return t.json({error:`repo is required`},400);let r=e.app.buildFeedbackIssueUrl({title:n.title,reproduce:n.reproduce,expected:n.expected,actual:n.actual,envInfo:n.envInfo??``,repo:n.repo});return r?t.json({url:r}):t.json({error:`feedback plugin does not support buildIssueUrl`},503)}),t}function Q(e){let t=()=>e.app.storage.storageHost??null;return{middleware:async(e,n)=>{let r=t();if(!r)return e.json({error:`storage_host_not_configured`},404);if(!r.token||!Ze(Qe(e),r.token))return e.json({error:`forbidden`},403);await n()},binding:t}}function wi(){return async(e,t)=>{let n=e.req.param(`wsKey`);if(!n)return e.json({error:`missing_workspace_key`},400);if(n!==be&&(!n.startsWith(`ws_`)||!xe(n.slice(3))))return e.json({error:`invalid_workspace_key`},400);await t()}}function Ti(e){let t=e.req.query(`ws`);return t?t===be?t:!t.startsWith(`ws_`)||!xe(t.slice(3))?null:t:null}var Ei=class{listeners=new Map;on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>{this.listeners.get(e)?.delete(t)}}emit(e){let t=this.listeners.get(e.namespace);if(t)for(let n of t)try{n(e)}catch{}}reset(){this.listeners.clear()}get listenerCount(){let e=0;for(let t of this.listeners.values())e+=t.size;return e}};const Di=new Ei,$=h(`@x-otto/service:storage`);function Oi(e){let t=new m,{middleware:n,binding:r}=Q(e);t.use(`/:namespace/:wsKey/*`,wi()),t.use(`*`,n);let i=e=>{let t=r(),n=e.req.param(`namespace`),i=e.req.param(`wsKey`);return!t||!n||!i||!t.host.has(n)?null:{namespace:n,wsKey:i,host:t.host}};return t.get(`/:namespace/:wsKey`,async e=>{let t=i(e);if(!t)return e.json({error:`unknown_namespace`},404);let{namespace:n,wsKey:r,host:a}=t;try{let t=e.req.header(`X-Agent-Id`),i=e.req.query(`scope`),o=e.req.query(`page`);if(o===void 0){let o=await a.list(n,r,t,i);return e.json({ids:o})}let s=Number.parseInt(o,10),c=Number.parseInt(e.req.query(`pageSize`)??``,10),l=await a.listPaginated(n,r,{page:Number.isFinite(s)&&s>=0?s:0,pageSize:Number.isFinite(c)&&c>0?c:20,sortBy:e.req.query(`sortBy`)??`updatedAt`,order:e.req.query(`order`)===`asc`?`asc`:`desc`});return e.json(l)}catch(t){return $.error({namespace:n,wsKey:r,error:t},`storage list failed`),e.json({error:`storage_error`},500)}}),t.get(`/:namespace/:wsKey/:id`,async e=>{let t=i(e);if(!t)return e.json({error:`unknown_namespace`},404);let{namespace:n,wsKey:r,host:a}=t;try{let t=await a.load(n,r,e.req.param(`id`));return t===null?e.json({error:`not_found`},404):e.json(t)}catch(t){return $.error({namespace:n,wsKey:r,error:t},`storage load failed`),e.json({error:`storage_error`},500)}}),t.put(`/:namespace/:wsKey/:id`,async e=>{let t=i(e);if(!t)return e.json({error:`unknown_namespace`},404);let{namespace:n,wsKey:r,host:a}=t,o=await e.req.json().catch(()=>void 0);if(o===void 0)return e.json({error:`invalid_body`},400);try{let t=e.req.header(`X-Agent-Id`);return await a.save(n,r,e.req.param(`id`),o,t),e.json({ok:!0})}catch(t){return $.error({namespace:n,wsKey:r,error:t},`storage save failed`),e.json({error:`storage_error`},500)}}),t.delete(`/:namespace/:wsKey/:id`,async e=>{let t=i(e);if(!t)return e.json({error:`unknown_namespace`},404);let{namespace:n,wsKey:r,host:a}=t;try{return await a.delete(n,r,e.req.param(`id`))?e.json({ok:!0}):e.json({error:`not_found`},404)}catch(t){return $.error({namespace:n,wsKey:r,error:t},`storage delete failed`),e.json({error:`storage_error`},500)}}),t.post(`/:namespace/:wsKey/:id/entries`,async e=>{let t=i(e);if(!t)return e.json({error:`unknown_namespace`},404);let{namespace:n,wsKey:r,host:a}=t,o=e.req.param(`id`),s=await e.req.json().catch(()=>void 0);if(s===void 0)return e.json({error:`invalid_body`},400);try{let t=await a.appendEntry(n,r,o,s);return Di.emit({namespace:n,wsKey:r,docId:o,entry:t.entry,ts:Date.now()}),e.json({seq:t.seq,ts:Date.now()})}catch(t){return $.error({namespace:n,docId:o,error:t},`entry append failed`),e.json({error:`storage_error`},500)}}),t}const ki=[`/api/health`,`/api/storage`];function Ai(e,t={}){let n=new m;if(t.corsOrigin&&n.use(`/api/*`,se({origin:t.corsOrigin,allowMethods:[`GET`,`POST`,`PUT`,`DELETE`,`OPTIONS`],allowHeaders:[`Content-Type`,`Authorization`]})),t.authToken){let e=t.authToken,r=async(t,n)=>{if(!Ze(Qe(t),e))return t.json({error:`forbidden`},403);await n()};n.use(`/api/*`,(e,t)=>{let n=e.req.path;return ki.some(e=>n===e||n.startsWith(`${e}/`))?t():r(e,t)})}return n.route(`/api/health`,$e(e)),n.route(`/api/authority`,et(e)),n.route(`/api/chat`,at(e)),n.route(`/api/sessions`,pt(e)),n.route(`/api/storage`,Oi(e)),n.route(`/api/setting`,hi(e)),n.route(`/api/devtools`,gi(e,t.devtools||null)),n.route(`/api/debugger`,vi(e)),n.route(`/api/logs`,bi(e)),n.route(`/api/catalog`,xi(e)),n.route(`/api/jobs`,Si(e)),n.route(`/api/plugin-feedback`,Ci(e)),t.staticDir&&n.get(`*`,t=>e.static(t)),n.notFound(e=>e.text(`not found`,404)),n}var ji=class{buffers=new Map;cursors=new Map;constructor(e=512){this.capacity=e}append(e,t){let n=(this.cursors.get(e)??0)+1;this.cursors.set(e,n);let r=this.buffers.get(e)??[];return r.push({seq:n,message:t}),r.length>this.capacity&&r.splice(0,r.length-this.capacity),this.buffers.set(e,r),n}cursorOf(e){return this.cursors.get(e)??0}readFrom(e,t){let n=this.cursorOf(e);if(t>n)return{ok:!1,reason:`gap`,oldestAvailable:n};if(t===n)return{ok:!0,events:[]};let r=this.buffers.get(e)??[],i=r[0]?.seq??n+1;return t+1<i?{ok:!1,reason:`gap`,oldestAvailable:i}:{ok:!0,events:r.filter(e=>e.seq>t)}}clear(e){this.buffers.delete(e),this.cursors.delete(e)}};const Mi=h(`@x-otto/service`),Ni={".html":`text/html`,".js":`application/javascript`,".css":`text/css`,".json":`application/json`,".png":`image/png`,".svg":`image/svg+xml`,".ico":`image/x-icon`,".woff2":`font/woff2`,".woff":`font/woff`};var Pi=class{httpApp;server;host;port;staticDir;apiToken;wsAuthToken;authority;eventLog=new ji;bridges=new Map;traceBridges=new Map;router;started=!1;bridge=null;ws;get httpServer(){return this.server}constructor(e,t){this.app=e,this.host=t.host??`127.0.0.1`,this.port=t.port,this.staticDir=t.staticDir,this.apiToken=t.apiToken,this.wsAuthToken=t.wsAuthToken,this.authority=Object.freeze({instanceId:t.authorityId??a(),workspaceDir:e.workspaceDir,protocolVersion:1,capabilities:Object.freeze([`session.snapshot`,`session.subscribe`])}),this.ws=new ke({allowedOrigins:t.cors?[t.cors]:void 0,authToken:t.wsAuthToken}),e.devtools&&(this.bridge=new Re(e.devtools,this.ws)),this.router=new Xe(this.ws,this.app,this.bridge,(e,t)=>this.eventLog.readFrom(e,t)),this.httpApp=Ai(this,{corsOrigin:t.cors,devtools:e.devtools??void 0,staticDir:t.staticDir,debug:this.bridge,authToken:t.apiToken}),this.server=ee({fetch:this.httpApp.fetch})}registerHooks(e){let t=({sessionId:e})=>{let t=this.getSession(e);t&&this.attachSession(t)};e.registerHook(Se({name:`service_session_attach`,timing:`session.created`,priority:5,handle:t})),e.registerHook(Se({name:`service_session_restore_attach`,timing:`session.restored`,priority:5,handle:t})),e.registerHook(Se({name:`service_session_detach`,timing:`session.deleted`,priority:5,handle:({sessionId:e})=>{this.detachSession(e)}}))}unregisterHooks(e){e.unregisterHook(`service_session_attach`),e.unregisterHook(`service_session_restore_attach`),e.unregisterHook(`service_session_detach`)}getSession(e){return this.app.getSession(e)}getActiveSession(){return this.app.getActiveSession()}getAuthorityDescriptor(){return this.authority}getSessionSnapshot(e){let t=this.getSession(e);if(t)return{authority:this.authority,session:{id:t.id,status:t.status,messageCount:t.session.messages().length,messages:x(t)},cursor:this.eventLog.cursorOf(e),snapshotAt:new Date().toISOString()}}readSessionEventsSince(e,t){return this.eventLog.readFrom(e,t)}onUpgrade=(e,t,n)=>{let r=new URL(e.url??`/`,`http://${this.host}:${this.port}`);this.ws.handleUpgrade(e,t,n,r.pathname)||t.destroy()};onWsMessage=(e,t)=>{this.router.dispatch(e,t)};async start(){if(!this.started){if(!(this.host===`127.0.0.1`||this.host===`::1`||this.host===`localhost`)&&(!this.apiToken||!this.wsAuthToken))throw Error(`Refusing to bind non-loopback host "${this.host}" without both apiToken and wsAuthToken: the HTTP API and the WS control channel each expose full tool execution and are authenticated independently. Set options.apiToken AND options.wsAuthToken, or bind to 127.0.0.1.`);return this.server.on(`upgrade`,this.onUpgrade),this.ws.on(`message`,this.onWsMessage),this.registerHooks(this.app),new Promise((e,t)=>{let n=e=>{this.server.off(`error`,n),this.server.off(`upgrade`,this.onUpgrade),this.ws.off(`message`,this.onWsMessage),this.unregisterHooks(this.app),t(e)};this.server.on(`error`,n),this.server.listen(this.port,this.host,()=>{this.server.off(`error`,n),this.started=!0,this.bridge?.attach(),Mi.info({host:this.host,port:this.port},`service started`),e()})})}}async stop(){if(this.started){this.bridge?.detach();for(let[,e]of this.bridges)e.detach();this.bridges.clear();for(let[,e]of this.traceBridges)e.detach();return this.traceBridges.clear(),this.server.off(`upgrade`,this.onUpgrade),this.ws.off(`message`,this.onWsMessage),this.unregisterHooks(this.app),this.ws.close(),new Promise(e=>{this.server.close(()=>{this.started=!1,Mi.info(`service stopped`),e()})})}}attachSession(e){if(this.bridges.has(e.id))return;let t=new Ne(e,{broadcast:e=>this.ws.broadcast(e),sendToSession:(e,t)=>{let n=this.eventLog.append(e,t),r=t.type===`Session.event`?{...t,data:{...t.data,seq:n}}:t;this.ws.sendToSession(e,r)},sendToSubscribers:(e,t)=>this.ws.sendToSubscribers(e,t)},this.app);t.attach(),this.bridges.set(e.id,t);let n=new Fe(e.id,this.app.storage.traceStore,this.ws);n.attach(),this.traceBridges.set(e.id,n)}detachSession(e){let t=this.bridges.get(e);t&&(t.detach(),this.bridges.delete(e));let n=this.traceBridges.get(e);n&&(n.detach(),this.traceBridges.delete(e)),this.ws.clearSessionSubscriptions(e),this.eventLog.clear(e)}static(n){if(!this.staticDir)return n.text(`not found`,404);let r=n.req.path;(r===`/`||!r.includes(`.`))&&(r=`/index.html`);let i=u(this.staticDir,r);if(i!==this.staticDir&&!i.startsWith(this.staticDir+p))return n.text(`forbidden`,403);if(!e(i)){let r=u(this.staticDir,`index.html`);if(e(r)){let e=t(r);return new Response(e,{headers:{"Content-Type":`text/html`}})}return n.text(`not found`,404)}let a=Ni[c(i)]||`application/octet-stream`,o=t(i);return new Response(o,{headers:{"Content-Type":a}})}};function Fi(e,t){return new Pi(e,t)}function Ii(){return async(e,t)=>{let n=e.req.header(`X-Request-Id`)??a();e.set(`requestId`,n),e.header(`X-Request-Id`,n),await t()}}const Li=h(`@x-otto/service:access`);function Ri(){return async(e,t)=>{let n=Date.now();await t();let r=Date.now()-n;Li.info({requestId:e.get(`requestId`)??``,method:e.req.method,path:e.req.path,status:e.res.status,latency:r},`${e.req.method} ${e.req.path} → ${e.res.status} ${r}ms`)}}function zi(e){let t=e.defaultRps,n=e.burst??t,r=new Map,i=setInterval(()=>{let e=Date.now()-5*6e4;for(let[t,n]of r)n.lastRefill<e&&r.delete(t)},6e4);i.unref&&i.unref();function a(e){return`${e.req.param(`namespace`)??e.req.path.split(`/`)[2]??`root`}:${e.req.header(`X-Forwarded-For`)?.split(`,`)[0]?.trim()??e.req.header(`X-Real-IP`)??`127.0.0.1`}`}return async(e,i)=>{let o=a(e),s=Date.now(),c=r.get(o);c||(c={tokens:n,lastRefill:s},r.set(o,c));let l=(s-c.lastRefill)/1e3;return c.tokens=Math.min(n,c.tokens+l*t),c.lastRefill=s,c.tokens>=1?(c.tokens--,i()):e.json({error:`rate_limit_exceeded`},429)}}const Bi=h(`@x-otto/service:events`);function Vi(e){let t=new m,{middleware:n,binding:r}=Q(e);return t.use(`*`,n),t.get(`/`,async e=>{let t=r();if(!t)return e.json({error:`storage_host_not_configured`},404);let n=e.req.query(`topics`);if(!n)return e.json({error:`missing_topics`},400);let i=n.split(`,`).map(e=>e.trim()).filter(Boolean);if(i.length===0)return e.json({error:`missing_topics`},400);for(let n of i)if(!t.host.has(n))return e.json({error:`unknown_namespace: ${n}`},404);let a=Hi(t,i,Ti(e)||void 0,Number.parseInt(e.req.query(`since`)??`0`,10)||0,200,new AbortController,{includeTopic:!0});return new Response(a,{headers:{"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`,"X-Accel-Buffering":`no`}})}),t.get(`/:namespace`,async e=>{let t=r(),n=e.req.param(`namespace`);if(!t||!n||!t.host.has(n))return e.json({error:`unknown_namespace`},404);let i=Ti(e)||void 0,a=Number.parseInt(e.req.query(`since`)??`0`,10)||0,o=new AbortController,s=Hi(t,[n],i,a,200,o,{includeTopic:!1});return new Response(s,{headers:{"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`,"X-Accel-Buffering":`no`}})}),t}function Hi(e,t,n,r,i,a,o){let s=a.signal;return new ReadableStream({async start(c){let l=[];for(let e of t)l.push(Di.on(e,e=>{try{if(n!==void 0&&e.wsKey!==n)return;let t={docId:e.docId,entry:e.entry,ts:e.ts};o.includeTopic&&(t.topic=e.namespace),c.enqueue(`event: append\ndata: ${JSON.stringify(t)}\n\n`)}catch{}}));let u=setInterval(()=>{try{c.enqueue(`: ping
|
|
40
|
+
|
|
41
|
+
`)}catch{a.abort()}},3e4);u.unref?.(),s.addEventListener(`abort`,()=>{clearInterval(u),l.forEach(e=>e())},{once:!0});let d=t.map(async t=>{try{for await(let a of e.host.streamEvents(t,n,r,i,s)){if(s.aborted)break;try{let e=a.op===`delete`?`delete`:`update`,n={id:a.doc_id,updatedAt:a.ts};o.includeTopic&&(n.topic=t),c.enqueue(`event: ${e}\ndata: ${JSON.stringify(n)}\n\n`)}catch{break}}}catch(e){s.aborted||Bi.error({topic:t,error:e},`sse poller error`)}});await Promise.allSettled(d)},cancel(){a.abort()}})}const Ui=h(`@x-otto/service:sync`);function Wi(e){let t=new m,{middleware:n,binding:r}=Q(e);return t.use(`/:namespace/:wsKey/*`,wi()),t.use(`*`,n),t.post(`/:namespace/:wsKey/push`,async e=>{let t=r(),n=e.req.param(`namespace`),i=e.req.param(`wsKey`);if(!t||!n||!i||!t.host.has(n))return e.json({error:`unknown_namespace`},404);let a=await e.req.json().catch(()=>void 0);if(!a||!Array.isArray(a.ops))return e.json({error:`invalid_body`},400);let{ops:o}=a,s=e.req.header(`X-Agent-Id`),c=0,l=0,u=[];for(let e of o)try{switch(e.type){case`save`:if(typeof e.id!=`string`||e.data===void 0){l++;continue}await t.host.save(n,i,e.id,e.data,s),c++;break;case`delete`:if(typeof e.id!=`string`){l++;continue}await t.host.delete(n,i,e.id),c++;break;default:l++}}catch(t){l++,u.push(e.id),Ui.warn({namespace:n,wsKey:i,opType:e.type,id:e.id,error:t},`sync push op failed`)}return e.json({accepted:c,rejected:l,conflicts:u})}),t.get(`/:namespace/:wsKey/pull`,async e=>{let t=r(),n=e.req.param(`namespace`),i=e.req.param(`wsKey`);if(!t||!n||!i||!t.host.has(n))return e.json({error:`unknown_namespace`},404);let a=Number.parseInt(e.req.query(`since`)??`0`,10)||0,o=e.req.query(`ids`),s=o?o.split(`,`).map(e=>e.trim()).filter(Boolean):void 0;try{let{documents:r,cursor:o}=await t.host.getChangesSince(n,i,a,s),c={};for(let[e,t]of r)c[e]=t;return e.json({documents:c,cursor:o})}catch(t){return Ui.error({namespace:n,error:t},`sync pull failed`),e.json({error:`storage_error`},500)}}),t}const Gi=h(`@x-otto/service:schedule-lease`);function Ki(e,t){let n=new m,{middleware:r,binding:i}=t;n.use(`/:wsKey/*`,wi()),n.use(`*`,r);let a=e.prepare(`INSERT INTO schedule_lease (ws_key, token, renewed_at) VALUES (?, ?, ?)
|
|
42
|
+
ON CONFLICT(ws_key) DO UPDATE SET token = excluded.token, renewed_at = excluded.renewed_at
|
|
43
|
+
WHERE excluded.renewed_at - schedule_lease.renewed_at > ?`),o=e.prepare(`UPDATE schedule_lease SET renewed_at = ? WHERE ws_key = ? AND token = ?`),s=e.prepare(`DELETE FROM schedule_lease WHERE ws_key = ? AND token = ?`),c=async e=>{let t=await e.req.json().catch(()=>void 0);return!t||typeof t.token!=`string`||t.token.length===0?null:{token:t.token}};return n.post(`/:wsKey/lease/acquire`,async e=>{if(!i())return e.json({error:`storage_host_not_configured`},404);let t=e.req.param(`wsKey`),n=await c(e);if(!n)return e.json({error:`invalid_body`},400);try{let r=Date.now(),i=a.run(t,n.token,r,18e4);return e.json({acquired:i.changes>0})}catch(n){return Gi.error({wsKey:t,error:n},`schedule lease acquire failed`),e.json({error:`lease_error`},500)}}),n.post(`/:wsKey/lease/renew`,async e=>{if(!i())return e.json({error:`storage_host_not_configured`},404);let t=e.req.param(`wsKey`),n=await c(e);if(!n)return e.json({error:`invalid_body`},400);try{let r=Date.now(),i=o.run(r,t,n.token);return e.json({renewed:i.changes>0})}catch(n){return Gi.error({wsKey:t,error:n},`schedule lease renew failed`),e.json({error:`lease_error`},500)}}),n.post(`/:wsKey/lease/release`,async e=>{if(!i())return e.json({error:`storage_host_not_configured`},404);let t=e.req.param(`wsKey`),n=await c(e);if(!n)return e.json({error:`invalid_body`},400);try{return s.run(t,n.token),e.json({released:!0})}catch(n){return Gi.error({wsKey:t,error:n},`schedule lease release failed`),e.json({error:`lease_error`},500)}}),n}const qi=3001,Ji=[`sessions`,`schedules`];async function Yi(e){let t=e.port??3001,n=e.host??`127.0.0.1`,r=e.namespaces??Ji,i=`${e.dir}/storage.db`,a=new we({namespaces:r,backend:e=>new Ce({dbPath:i,namespace:e,wal:!0})}),o=Te(`${e.dir}/schedule-lease.db`,!0,De),s={app:{storage:{storageHost:{host:a,token:e.token}}}},c=Q(s),l=new m;e.corsOrigin&&l.use(`/api/*`,se({origin:e.corsOrigin,allowMethods:[`GET`,`POST`,`PUT`,`DELETE`,`OPTIONS`],allowHeaders:[`Content-Type`,`Authorization`]})),l.use(`*`,Ii()),l.use(`*`,Ri()),l.use(`*`,zi({defaultRps:e.rateLimitRps??100})),l.get(`/health`,e=>e.json({status:`ok`,service:`otto-persistenced`,uptime:process.uptime(),namespaces:r})),l.route(`/api/storage`,Oi(s)),l.route(`/api/events`,Vi(s)),l.route(`/api/sync`,Wi(s)),l.route(`/api/schedules`,Ki(o,c)),l.notFound(e=>e.text(`not found`,404));let u=te({fetch:l.fetch,port:t,hostname:n});return u.once(`close`,()=>Ee(o)),new Promise((e,r)=>{u.once(`listening`,()=>{let r=u.address();e({app:l,server:u,host:a,url:`http://${n}:${typeof r==`object`&&r?r.port:t}`})}),u.once(`error`,r)})}export{Pi as CodingService,Re as DebugBridge,Ne as EventBridge,Ei as EventBus,Xe as InboundRouter,qi as PERSISTENCED_DEFAULT_PORT,ji as SessionEventLog,ke as WebSocketManager,Fi as createCodingService,ie as createProjectorState,je as encodeSessionEvent,Di as eventBus,Yi as startPersistenced};
|
|
44
|
+
//# sourceMappingURL=index.js.map
|