@task-handoff/node-agent 0.0.41-alpha.14 → 0.0.41-alpha.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1 +1 @@
1
- "use strict";var e=require("commander"),t=require("node:fs"),n=require("node:path"),i=require("node:http"),s=require("node:os"),o=require("node:url"),r=require("fastify"),a=require("@fastify/websocket"),c=require("zod"),d=require("node:crypto"),l=require("node:child_process"),u=require("@noble/hashes/sha256"),p=require("node-pty"),m=require("write-file-atomic"),h=require("ws"),g=require("node:net"),f=require("node:stream"),y=require("node:fs/promises"),I=require("node:stream/promises"),_=require("tar"),E=require("node:async_hooks"),A=require("drizzle-orm"),T=require("drizzle-orm/sqlite-core"),w=require("node:util"),b=require("node:sqlite"),N=require("drizzle-orm/node-sqlite"),S=require("semver"),v=require("cron-parser"),O=require("node:readline/promises"),R=require("node:process"),z="undefined"!=typeof document?document.currentScript:null;function x(e,n){try{const i=JSON.parse(t.readFileSync(e,"utf8"));if(n&&i.name!==n)return;return"string"==typeof i.version&&i.version.trim()?i.version.trim():void 0}catch{return}}function C(e){if(e)try{return n.dirname(t.realpathSync(e))}catch{return}}function k(e,t=process.env,i=e){const s=t.TASK_HANDOFF_VERSION?.trim();if(s)return s;const o=i.split("/").at(-1),r=process.argv[1]?n.resolve(process.argv[1]):void 0,a=r?n.dirname(r):void 0,c=[C(r),a,process.cwd()].filter(e=>Boolean(e));for(const t of new Set(c)){let i=t;for(;;){const t=x(n.join(i,"package.json"),e);if(t)return t;const s=n.dirname(i);if(s===i)break;i=s}}let d;for(const e of new Set(c)){let t=e;for(;;){if(o){const e=x(n.join(t,"packages",o,"package.json"),i);if(e)return e}d||=x(n.join(t,"package.json"));const e=n.dirname(t);if(e===t)break;t=e}}return d||"unknown"}const D={perMessageDeflate:{threshold:256,serverNoContextTakeover:!0,clientNoContextTakeover:!0,concurrencyLimit:4,zlibDeflateOptions:{level:1}}};function L(e){return e.readyState===(e.OPEN??1)}function P(e){const t=Buffer.isBuffer(e)?e.toString("utf8"):"string"==typeof e?e:"";if(Buffer.byteLength(t,"utf8")<=123)return t;let n="";for(const e of t){const t=`${n}${e}`;if(Buffer.byteLength(t,"utf8")>123)break;n=t}return n}function M(e){if("number"==typeof e&&Number.isInteger(e))return e>=3e3&&e<=4999||e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e?e:void 0}function j(e,t,n){e.close(M(t),P(n)||void 0)}function U(e,t,n,i){if(L(e))for(const e of t.splice(0))if(i(e),!n(e))return}function F(e,t,n={}){const i=n.pendingFrameLimit??256,s=n.maxFrameBytes??8388608,o=n.maxTotalBytes??1073741824,r=n.maxBufferedBytes??16777216;let a=!1,c=L(t);const d=[],l=[];let u,p=0,m=0,h=0;const g=e=>Buffer.isBuffer(e)||e instanceof ArrayBuffer||ArrayBuffer.isView(e)?e.byteLength:Buffer.byteLength("string"==typeof e?e:String(e),"utf8"),f=(i,r)=>{const a=g(r);return h+=a,n.onFrame?.(i,a),!(a>s||h>o)||(j(e,1009,"WebSocket bridge traffic limit exceeded."),j(t,1009,"WebSocket bridge traffic limit exceeded."),!1)},y=()=>{u&&(clearTimeout(u),u=void 0)},I=(n,i)=>{const s=i.bytes;if((n.bufferedAmount??0)+s>r)return j(e,1013,"WebSocket bridge consumer is too slow."),j(t,1013,"WebSocket bridge consumer is too slow."),!1;try{return function(e,t){e.send(t.data,{binary:t.isBinary,compress:!1})}(n,i),!0}catch{return j(e,1011,"WebSocket bridge send failed."),j(t,1011,"WebSocket bridge send failed."),!1}},_=(n,s,o)=>{if(s.length>=i)return j(e,1011,"WebSocket bridge pending frame limit exceeded."),void j(t,1011,"WebSocket bridge pending frame limit exceeded.");const a="upstream"===n?p:m;if((("upstream"===n?t:e).bufferedAmount??0)+a+o.bytes>r)return j(e,1013,"WebSocket bridge consumer is too slow."),void j(t,1013,"WebSocket bridge consumer is too slow.");s.push(o),"upstream"===n?p+=o.bytes:m+=o.bytes};return n.upstreamOpenTimeoutMs&&!c&&(u=setTimeout(()=>{c||a||(j(e,1011,"Upstream websocket did not open."),j(t))},n.upstreamOpenTimeoutMs)),e.on("open",()=>U(e,l,t=>I(e,t),e=>{m-=e.bytes})),t.on("open",()=>{y(),c=!0,n.onUpstreamOpen?.(),U(t,d,e=>I(t,e),e=>{p-=e.bytes})}),e.on("message",(e,n=!1)=>{if(!f("client-to-upstream",e))return;const i={data:e,isBinary:Boolean(n),bytes:g(e)};L(t)?I(t,i):_("upstream",d,i)}),t.on("message",(t,n=!1)=>{if(!f("upstream-to-client",t))return;const i={data:t,isBinary:Boolean(n),bytes:g(t)};L(e)?I(e,i):_("client",l,i)}),t.on("close",(t,i)=>{y(),n.onUpstreamClose?.(t,i),(c||a||!n.onUpstreamCloseBeforeOpen?.())&&j(e,t,i)}),t.on("error",t=>{n.onUpstreamError?.(t),(c||a||!n.onUpstreamErrorBeforeOpen?.(t))&&j(e)}),e.on("close",(e,i)=>{y(),a=!0,n.onClientClose?.(e,i),j(t,e,i)}),e.on("error",e=>{y(),a=!0,n.onClientError?.(e),j(t,1011,"WebSocket bridge client failed.")}),{close:(n,i)=>{y(),j(t,n,i),j(e,n,i)}}}var $,H,q=function(){if(H)return $;H=1;const e=t,{spawnSync:n}=l;return $={processStartIdentity:function(t,i=process.platform){if(Number.isInteger(t)&&!(t<=0)){if("linux"===i)try{const n=e.readFileSync(`/proc/${t}/stat`,"utf8"),i=n.lastIndexOf(")");if(i<0)return;const s=n.slice(i+2).trim().split(/\s+/)[19];return s?`linux:${s}`:void 0}catch{return}if(["darwin","freebsd","openbsd","aix","sunos"].includes(i)){const e=n("ps",["-o","lstart=","-p",String(t)],{encoding:"utf8",timeout:1e3}),s=0===e.status?e.stdout.trim().replace(/\s+/g," "):"";return s?`${i}:${s}`:void 0}if("win32"===i){const e=n("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${t} -ErrorAction Stop).StartTime.ToUniversalTime().Ticks`],{encoding:"utf8",timeout:2e3}),i=0===e.status?e.stdout.trim():"";return/^\d+$/.test(i)?`win32:${i}`:void 0}}}}}();class B extends Error{code;lockPath;owner;constructor(e,t,n={}){const i=t?.pid?` pid ${t.pid}`:"";super(`${n.label||"Process"} is already running${i}. Lock: ${e}`),this.name="ProcessSingletonError",this.code=n.code||"PROCESS_ALREADY_RUNNING",this.lockPath=e,this.owner=t}}function V(e){return n.join(e,"owner.json")}function G(e){return n.join(e,"initializing.json")}function K(e){return n.join(e,"recovering.json")}function W(e){return Number.isInteger(e)&&Number(e)>0}function Y(e){try{const n=JSON.parse(t.readFileSync(V(e),"utf8"));if(W(n.pid)&&"string"==typeof n.startTime){const e=n;return{pid:e.pid,hostname:"string"==typeof e.hostname&&e.hostname?e.hostname:s.hostname(),component:e.component||"server-update",command:"string"==typeof e.command?e.command:"",acquiredAt:"string"==typeof e.createdAt&&Number.isFinite(Date.parse(e.createdAt))?e.createdAt:new Date(0).toISOString(),token:"string"==typeof e.token&&e.token?e.token:`legacy:${e.pid}:${e.startTime}`,startIdentity:e.startTime.startsWith("linux:")?e.startTime:`linux:${e.startTime}`}}if(!(W(n.pid)&&"string"==typeof n.hostname&&n.hostname&&"string"==typeof n.command&&"string"==typeof n.acquiredAt&&Number.isFinite(Date.parse(n.acquiredAt))&&"string"==typeof n.token&&n.token))return;return n}catch{return}}const X=Y;function J(e){if(!W(e))return!1;try{return process.kill(Number(e),0),!0}catch(e){return"EPERM"===e.code}}function Q(e){if(!e||!J(e.pid))return!1;if(!e.startIdentity)return!0;const t=q.processStartIdentity(e.pid);return void 0===t||t===e.startIdentity}function Z(e,i){const s=n.join(e,`.owner-${i.token}.tmp`);t.writeFileSync(s,`${JSON.stringify(i,null,2)}\n`,{encoding:"utf8",mode:384,flag:"wx"});const o=te(e);if(o?.token!==i.token)throw ie(s),new Error(`Process lock initialization was superseded: ${e}`);t.renameSync(s,V(e)),ie(G(e))}function ee(e,i,s){const o=X(e);if(o?.token!==i.token)return!1;const r={...i};for(const[e,t]of Object.entries(s))void 0===t?delete r[e]:Object.assign(r,{[e]:t});const a=n.join(e,`.owner-update-${i.token}-${d.randomUUID()}.tmp`);try{if(t.writeFileSync(a,`${JSON.stringify(r,null,2)}\n`,{encoding:"utf8",mode:384,flag:"wx"}),X(e)?.token!==i.token)return!1;t.renameSync(a,V(e));for(const e of Object.keys(i))delete i[e];return Object.assign(i,r),!0}catch(e){if("ENOENT"===e.code)return!1;throw e}finally{ie(a)}}function te(e){try{return JSON.parse(t.readFileSync(G(e),"utf8"))}catch{return}}function ne(e){const t=te(e);return W(t?.pid)&&Q({pid:t.pid,startIdentity:t.startIdentity})}function ie(e){try{t.unlinkSync(e)}catch(e){if("ENOENT"!==e.code)throw e}}function se(){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,20)}function oe(e){try{const n=te(e),i=Date.parse(n?.startedAt||"");return Number.isFinite(i)?Math.max(0,Date.now()-i):Math.max(0,Date.now()-t.statSync(e).mtimeMs)}catch{return 0}}function re(e,i){try{return t.writeFileSync(K(e),`${JSON.stringify({token:i,pid:process.pid,startedAt:(new Date).toISOString()})}\n`,{encoding:"utf8",mode:384,flag:"wx"}),!0}catch(s){if("EEXIST"===s.code)return!!function(e){const i=K(e),s=ae(i),o=Date.parse(s?.startedAt||"");if(J(s?.pid)||Number.isFinite(o)&&Date.now()-o<2e3)return!1;const r=n.join(e,`.recovering-${d.randomUUID()}.stale`);try{t.renameSync(i,r)}catch(e){if(["ENOENT","EEXIST"].includes(e.code||""))return!1;throw e}const a=ae(r);if(a?.token===s?.token)return ie(r),!0;try{t.linkSync(r,i)}catch(e){if("EEXIST"!==e.code)throw e}finally{ie(r)}return!1}(e)&&re(e,i);if("ENOENT"===s.code)return!1;throw s}}function ae(e){try{return JSON.parse(t.readFileSync(e,"utf8"))}catch{return}}function ce(e,t){return ae(K(e))?.token===t}function de(){return(new Date).toISOString()}const le=6048e5;function ue(e,t=Date.now()){return`${t}-${e}`}const pe=/(\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z)$/;function me(e){const t=e.split("-",1)[0];if(/^\d+$/.test(t))return Number(t);const n=pe.exec(e)?.[1];if("string"!=typeof n)return;const i=Date.parse(n.replace(/T(\d{2})-(\d{2})-(\d{2})-(\d{3})Z$/,"T$1:$2:$3.$4Z"));return Number.isFinite(i)?i:void 0}function he(e,t){const i=n.resolve(e),s=n.resolve(i,t);if(n.dirname(s)!==i||n.basename(s)!==t)throw new Error(`Retention entry is not a direct child of its managed root: ${t}`);return s}function ge(e){if(t.existsSync(e)){const n=t.lstatSync(e);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`Managed persistence path must be a real directory: ${e}`)}t.mkdirSync(e,{recursive:!0,mode:448}),t.chmodSync(e,448)}const fe=c.z.enum(["openai-responses","openai-chat-completions","anthropic-messages"]),ye="2026-08-27",Ie="2026-10-02",_e=c.z.object({upstreamName:c.z.string().trim().min(1).max(240).optional(),name:c.z.string().trim().min(1).max(240),order:c.z.number().int().min(0).max(1e6)}).strip(),Ee={id:c.z.string().trim().min(1).max(120),protocols:c.z.array(fe).min(1).max(3),modelNames:c.z.array(_e).min(1).max(256)},Ae=c.z.object({protocolVersion:c.z.literal(ye),instanceId:c.z.string().trim().min(1).max(120),entities:c.z.array(c.z.object({...Ee,endpoint:c.z.string().trim().min(1).max(2048),key:c.z.string().trim().min(1).max(4096)}).strip()).max(64),updatedAt:c.z.string().datetime()}).strip(),Te=c.z.object({protocolVersion:c.z.literal(Ie),instanceId:c.z.string().trim().min(1).max(120),entities:c.z.array(c.z.object({...Ee,routes:c.z.array(c.z.object({protocol:fe,baseUrl:c.z.string().trim().min(1).max(2048)}).strip()).min(1).max(3)}).strip().superRefine((e,t)=>{const n=new Set;for(const[i,s]of e.routes.entries())n.has(s.protocol)&&t.addIssue({code:"custom",path:["routes",i,"protocol"],message:`Duplicate relay route for ${s.protocol}.`}),n.add(s.protocol)})).max(64),updatedAt:c.z.string().datetime()}).strip(),we=c.z.discriminatedUnion("protocolVersion",[Ae,Te]);function be(e){return e.upstreamName?.trim()||e.name.trim()}function Ne(e,t){const n=e.find(e=>be(e)===t);if(n)return n;const i=e.filter(e=>e.name===t);return 1===i.length?i[0]:void 0}const Se=c.z.object({id:c.z.string().trim().min(1).max(120),protocols:c.z.array(fe).min(1).max(3),modelNames:c.z.array(_e).min(1).max(256)}).strip();function ve(e,t){if(!e||"object"!=typeof e||Array.isArray(e))return e;const n=e,i=n.protocolVersion===Ie;return{protocolVersion:n.protocolVersion,instanceId:n.instanceId,entities:Array.isArray(n.entities)?n.entities.map((e,t)=>{if(!e||"object"!=typeof e||Array.isArray(e))return e;const n=e,s={id:n.id,protocols:n.protocols,modelNames:Array.isArray(n.modelNames)?n.modelNames.map((e,t)=>{if(!e||"object"!=typeof e||Array.isArray(e))return e;const n=e;for(const e of Object.keys(n));return{..."string"==typeof n.upstreamName?{upstreamName:n.upstreamName}:{},name:n.name,order:n.order}}):n.modelNames};if(i)return{...s,routes:Array.isArray(n.routes)?n.routes.map((e,t)=>{if(!e||"object"!=typeof e||Array.isArray(e))return e;const n=e;for(const e of Object.keys(n));return{protocol:n.protocol,baseUrl:n.baseUrl}}):n.routes};for(const e of Object.keys(n));return{...s,endpoint:n.endpoint,key:n.key}}):n.entities,updatedAt:n.updatedAt}}c.z.object({protocolVersion:c.z.union([c.z.literal(ye),c.z.literal(Ie)]),instanceId:c.z.string().trim().min(1).max(120),updatedAt:c.z.string().datetime(),entities:c.z.array(Se).max(64)}).strip();const Oe=c.z.string().trim().min(1).max(160),Re=Oe.optional(),ze=c.z.string().trim().min(1).max(120),xe=20971520,Ce=512e3,ke=Ce,De=xe,Le=41943040,Pe="ai.sessions",Me="ai-session.snapshot",je="ai-session.patch",Ue="ai-session.removed",Fe="ai-session.message-delta",$e="ai-session.timeline-item",He="ai-session.timeline-item-delta",qe=c.z.string().trim().min(1).max(80),Be=c.z.enum(["app-session","ai-session"]),Ve=c.z.enum(["image","file"]),Ge={scopeType:c.z.enum(["session","create-request"]),scopeId:c.z.string().trim().min(1).max(160),kind:Ve,name:c.z.string().trim().min(1).max(240),mime:c.z.string().trim().min(1).max(120)};c.z.object({...Ge,size:c.z.coerce.number().int().positive().max(xe)}).strict();const Ke=c.z.string().regex(/^cia_[a-f0-9]{24}$/);c.z.object({attachmentId:Ke,...Ge,size:c.z.number().int().positive().max(xe)}).strict(),c.z.object({offset:c.z.coerce.number().int().nonnegative()}).strict(),c.z.object({attachmentId:Ke,offset:c.z.number().int().nonnegative()}),c.z.object({id:Ke,kind:Ve,name:c.z.string().trim().min(1).max(240),mime:c.z.string().trim().min(1).max(120),size:c.z.number().int().positive().max(xe),expiresAt:c.z.string().datetime()});const We=c.z.object({id:c.z.string().trim().min(1).max(120),kind:Ve,name:c.z.string().trim().min(1).max(240),mime:c.z.string().trim().min(1).max(120),size:c.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER)}),Ye=c.z.enum(["available","expired","missing"]),Xe=We.extend({contentState:Ye.default("available")}).strict(),Je=c.z.object({id:c.z.string().trim().min(1).max(240),text:c.z.string(),attachments:c.z.array(Xe).max(6).default([])}).strict(),Qe=c.z.enum(["running","waiting","idle","failed"]),Ze=c.z.enum(["thinking","tool","editing","approval","responding","unknown"]),et=c.z.object({id:c.z.string().trim().min(1).max(240).optional(),kind:c.z.string().trim().min(1).max(80).optional(),name:c.z.string().trim().min(1).max(120),inputPreview:c.z.string().trim().max(500).optional(),startedAt:c.z.string().datetime().optional()}).strict(),tt=c.z.enum(["running","completed","failed","waiting"]),nt=c.z.object({id:c.z.string().trim().min(1).max(240),turnId:c.z.string().trim().min(1).max(240)}).strict(),it=nt.extend({type:c.z.literal("user-message"),text:c.z.string(),attachments:c.z.array(Xe).max(6).optional()}).strict(),st=nt.extend({type:c.z.literal("ai-message"),text:c.z.string()}).strict(),ot=nt.extend({type:c.z.literal("activity"),activityKind:c.z.string().trim().min(1).max(120),title:c.z.string().trim().min(1).max(240),status:tt.optional(),summary:c.z.string().max(4e3).optional(),input:c.z.string().max(1e5).optional(),output:c.z.string().max(1e6).optional(),paths:c.z.array(c.z.string().trim().min(1).max(4096)).max(500).optional(),exitCode:c.z.number().int().optional(),durationMs:c.z.number().int().nonnegative().optional()}).strict(),rt=c.z.discriminatedUnion("type",[it,st,ot]);c.z.object({sessionId:c.z.string().trim().min(1).max(120),providerSessionId:c.z.string().trim().min(1).max(240),items:c.z.array(rt),generatedAt:c.z.string().datetime()}).strict();const at=c.z.object({sessionId:c.z.string().trim().min(1).max(120),turnId:c.z.string().trim().min(1).max(240),items:c.z.array(rt),generatedAt:c.z.string().datetime()}).strict(),ct=c.z.enum(["pending-init","running","interrupted","completed","errored","shutdown","not-found"]),dt=c.z.enum(["started","interacted","interrupted"]),lt=c.z.object({threadId:c.z.string().trim().min(1).max(240),path:c.z.string().trim().max(4096).optional(),status:ct,activity:dt.optional(),message:c.z.string().trim().max(1e3).optional(),updatedAt:c.z.string().datetime()}).strict();function ut(e){return"completed"!==e.status}const pt=c.z.array(lt).max(50).transform(e=>e.filter(ut)),mt=c.z.object({toolCalls:c.z.number().int().min(0).default(0),edits:c.z.number().int().min(0).default(0),approvals:c.z.number().int().min(0).default(0)}).strict().default({toolCalls:0,edits:0,approvals:0}),ht=c.z.object({send:c.z.boolean().optional(),interrupt:c.z.boolean().optional(),approval:c.z.boolean().optional(),fork:c.z.boolean().optional(),rename:c.z.boolean().optional(),openApp:c.z.boolean().optional(),close:c.z.boolean().optional()}),gt=c.z.string().trim().min(1).max(240),ft=c.z.discriminatedUnion("kind",[c.z.object({kind:c.z.literal("fork"),parentProviderSessionId:gt,throughTurnId:c.z.string().trim().min(1).max(240).optional()}).strict(),c.z.object({kind:c.z.literal("subagent"),parentProviderSessionId:gt}).strict()]),yt=c.z.preprocess(function(e){if(!e||"object"!=typeof e||Array.isArray(e))return;const t=e;if("fork"===t.kind){const e=ft.safeParse({kind:"fork",parentProviderSessionId:t.parentProviderSessionId,..."string"==typeof t.throughTurnId?{throughTurnId:t.throughTurnId}:{}});return e.success?e.data:void 0}if("subagent"===t.kind){const e=ft.safeParse({kind:"subagent",parentProviderSessionId:t.parentProviderSessionId});return e.success?e.data:void 0}},ft.optional()),It=c.z.union([We.extend({source:c.z.object({type:c.z.literal("inline"),encoding:c.z.literal("base64"),data:c.z.string().min(1).max(31457280)}).strict()}).strict().superRefine((e,t)=>{const n="image"===e.kind?xe:Ce;(e.size<=0||("file"===e.kind?e.size>=n:e.size>n))&&t.addIssue({code:c.z.ZodIssueCode.custom,path:["size"],message:`Inline ${e.kind} must be between 1 byte and ${n} bytes.`})}),We.extend({source:c.z.object({type:c.z.literal("runtime-path"),path:c.z.string().trim().min(1).max(4096)}).strict()}).strict()]),_t=We.extend({sourceType:c.z.enum(["inline","runtime-path"])}).strict(),Et=c.z.union([c.z.object({id:c.z.string().trim().min(1).max(120),kind:Ve.optional(),source:c.z.object({type:c.z.literal("upload-ref")}).strict().default({type:"upload-ref"})}).strict(),c.z.object({id:c.z.string().trim().min(1).max(120),kind:Ve,name:c.z.string().trim().min(1).max(240),mime:c.z.string().trim().min(1).max(120),size:c.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),source:c.z.object({type:c.z.literal("runtime-path"),path:c.z.string().trim().min(1).max(4096)}).strict()}).strict()]),At=c.z.enum(["auto","queue","steer","immediate"]),Tt=c.z.enum(["ask","auto-review","full-access"]),wt=c.z.enum(["review","rename","goal","compact"]);c.z.object({command:wt,argument:c.z.string().trim().max(4e3).optional()}).strict().superRefine((e,t)=>{"rename"!==e.command||e.argument||t.addIssue({code:"custom",path:["argument"],message:"Rename requires a thread name."}),"review"!==e.command&&"compact"!==e.command||!e.argument||t.addIssue({code:"custom",path:["argument"],message:`${e.command} does not accept an argument.`})}),c.z.object({command:wt,value:c.z.string().max(4e3).optional(),turnId:c.z.string().trim().min(1).max(240).optional()}).strict(),c.z.object({title:c.z.string().trim().max(120),expectedTitle:c.z.string().trim().max(240).optional(),clientRequestId:Oe}).strict(),c.z.object({disposition:c.z.enum(["renamed","already-named"]),aiSessionId:c.z.string().trim().min(1).max(120),appSessionId:c.z.string().trim().min(1).max(120).optional(),title:c.z.string().trim().max(120)}).strict(),c.z.enum(["skill","app","plugin"]);const bt=c.z.object({name:c.z.string().trim().min(1).max(240),path:c.z.string().trim().min(1).max(4096)}),Nt=c.z.discriminatedUnion("kind",[bt.extend({kind:c.z.literal("skill"),path:c.z.string().trim().min(1).max(4096).refine(e=>e.startsWith("/"),"Skill paths must be absolute.")}).strict(),bt.extend({kind:c.z.literal("app"),path:c.z.string().trim().min(7).max(4096).regex(/^app:\/\/[^\s/]+$/,"App paths must use app://<id>.")}).strict(),bt.extend({kind:c.z.literal("plugin"),path:c.z.string().trim().min(10).max(4096).regex(/^plugin:\/\/[^\s/]+$/,"Plugin paths must use plugin://<id>.")}).strict()]),St=c.z.array(Nt).max(20).default([]),vt=c.z.enum(["plugin","skill","file","directory","app"]),Ot=c.z.object({kind:vt,name:c.z.string().trim().min(1).max(240),description:c.z.string().trim().max(1e3).optional(),path:c.z.string().trim().min(1).max(4096),icon:c.z.string().trim().max(4096).optional()}).strict().superRefine((e,t)=>{"skill"!==e.kind||e.path.startsWith("/")||t.addIssue({code:"custom",path:["path"],message:"Skill paths must be absolute."}),"app"!==e.kind||/^app:\/\/[^\s/]+$/.test(e.path)||t.addIssue({code:"custom",path:["path"],message:"App paths must use app://<id>."}),"plugin"!==e.kind||/^plugin:\/\/[^\s/]+$/.test(e.path)||t.addIssue({code:"custom",path:["path"],message:"Plugin paths must use plugin://<id>."}),"file"!==e.kind&&"directory"!==e.kind||!e.path.startsWith("/")&&!e.path.split(/[\\/]+/).includes("..")||t.addIssue({code:"custom",path:["path"],message:"File and directory paths must be relative to the session cwd."})}),Rt=c.z.object({category:c.z.enum(["skills","plugins","apps","files"]),code:c.z.string().trim().min(1).max(160),message:c.z.string().trim().min(1).max(2e3)}).strict();c.z.object({sessionId:c.z.string().trim().min(1).max(120),providerSessionId:c.z.string().trim().min(1).max(240),cwd:c.z.string().trim().min(1).max(4096),candidates:c.z.array(Ot).max(1e3).default([]),diagnostics:c.z.array(Rt).max(20).default([])}).strict(),c.z.object({query:c.z.string().trim().max(240).default("")}).strict(),c.z.object({sessionId:c.z.string().trim().min(1).max(120),cwd:c.z.string().trim().min(1).max(4096),query:c.z.string().trim().max(240),requestId:c.z.string().trim().min(1).max(160),candidates:c.z.array(Ot.refine(e=>"file"===e.kind||"directory"===e.kind,"File search only returns files and directories.")).max(200).default([]),complete:c.z.boolean().default(!1)}).strict();const zt=c.z.object({message:c.z.string().trim().min(1).max(2e4),mode:At.optional(),permissionMode:Tt.optional(),clientRequestId:Re}),xt=zt.extend({attachments:c.z.array(It).max(6).default([]),references:St}).strict().superRefine((e,t)=>{e.attachments.reduce((e,t)=>e+("inline"===t.source.type?t.size:0),0)>Le&&t.addIssue({code:c.z.ZodIssueCode.custom,path:["attachments"],message:"Inline attachments must be 41943040 bytes or less in total."})}),Ct=zt.extend({attachments:c.z.array(Et).max(6).default([]),references:St}).strict(),kt=c.z.object({type:c.z.literal("runtime-path"),path:c.z.string().trim().min(1).max(4096).refine(e=>e.startsWith("/")||/^[A-Za-z]:[\\/]/.test(e),"Runtime paths must be absolute in the target controlled instance.")}).strict(),Dt=c.z.object({modelEntityId:c.z.string().trim().min(1).max(120),modelName:c.z.string().trim().min(1).max(240),modelUpstreamName:c.z.string().trim().min(1).max(240).optional()}).strict(),Lt=c.z.enum(["none","minimal","low","medium","high","xhigh","max","ultra"]),Pt=c.z.discriminatedUnion("type",[c.z.object({type:c.z.literal("current-folder"),branch:c.z.string().trim().min(1).max(1024)}).strict(),c.z.object({type:c.z.literal("existing-worktree"),repositoryContextId:c.z.string().trim().min(1).max(160),worktreeId:c.z.string().trim().min(1).max(160)}).strict(),c.z.object({type:c.z.literal("new-worktree"),branchName:c.z.string().trim().min(1).max(255),startRef:c.z.string().trim().min(1).max(2048),expectedSnapshotId:c.z.string().trim().min(1).max(160)}).strict()]),Mt=c.z.object({mode:c.z.enum(["current-folder","worktree"]),branch:c.z.string().trim().min(1).max(1024)}).strict();xt.safeExtend({agent:qe,cwd:kt,cwdFolderId:c.z.string().trim().min(1).max(120).optional(),gitSelection:Mt.optional(),workspaceSelection:Pt.optional(),clientRequestId:Oe,modelSelection:Dt.optional(),reasoningEffort:Lt.optional(),storyId:ze.optional()}).strict(),Ct.extend({agent:qe,cwdFolderId:c.z.string().trim().min(1).max(120).optional(),gitSelection:Mt.optional(),workspaceSelection:Pt.optional(),clientRequestId:Oe,modelSelection:Dt.optional(),reasoningEffort:Lt.optional(),storyId:ze.optional()}).strict(),c.z.object({clientRequestId:Oe,modelSelection:Dt}).strict(),c.z.object({sessionId:c.z.string().trim().min(1).max(120),accepted:c.z.literal(!0)}).strict(),c.z.object({clientRequestId:Oe,reasoningEffort:Lt}).strict(),c.z.object({cwdFolderId:c.z.string().trim().min(1).max(120).optional(),branch:c.z.string().trim().min(1).max(1024)}).strict(),c.z.object({sessionId:c.z.string().trim().min(1).max(120),accepted:c.z.literal(!0)}).strict(),c.z.object({storyId:ze.nullable()}).strict(),c.z.object({sessionId:c.z.string().trim().min(1).max(120),storyId:ze.optional()}).strict(),c.z.object({sessionId:c.z.string().trim().min(1).max(120),unread:c.z.boolean()}).strict(),c.z.object({path:c.z.string().trim().min(1).max(4096),lineCount:c.z.number().int().nonnegative(),tail:c.z.string()}).strict(),c.z.object({disposition:c.z.enum(["created","already-created"]),aiSessionId:c.z.string().trim().min(1).max(120),providerSessionId:c.z.string().trim().min(1).max(240),creationSource:c.z.literal("ai-session")}).strict();const jt=c.z.object({mode:c.z.enum(["current","managed-worktree"]).default("current")}).strict().default({mode:"current"});c.z.object({clientRequestId:Oe,throughTurnId:c.z.string().trim().min(1).max(240).optional(),workspace:jt.optional().default({mode:"current"})}).strict(),c.z.object({disposition:c.z.enum(["created","already-created"]),aiSessionId:c.z.string().trim().min(1).max(120),providerSessionId:c.z.string().trim().min(1).max(240),creationSource:c.z.literal("ai-session")}).strict(),c.z.object({clientRequestId:Oe}).strict(),c.z.object({disposition:c.z.enum(["opened","already-open"]),aiSessionId:c.z.string().trim().min(1).max(120),providerSessionId:c.z.string().trim().min(1).max(240),appSessionId:c.z.string().trim().min(1).max(120),creationSource:Be}).strict(),c.z.object({clientRequestId:Oe}).strict(),c.z.object({disposition:c.z.enum(["closed","already-closed"]),aiSessionId:c.z.string().trim().min(1).max(120),providerSessionId:c.z.string().trim().min(1).max(240),creationSource:Be}).strict(),c.z.object({disposition:c.z.enum(["cleared","already-cleared"]),aiSessionId:c.z.string().trim().min(1).max(120),clearedSessionIds:c.z.array(c.z.string().trim().min(1).max(120))}).strict(),c.z.object({code:c.z.enum(["invalid-request","not-found","unsupported","provider-unavailable","materialization-failed","open-app-failed","close-failed","conflict"]),message:c.z.string().trim().min(1).max(4e3),retryable:c.z.boolean().default(!1),aiSessionId:c.z.string().trim().min(1).max(120).optional(),providerSessionId:c.z.string().trim().min(1).max(240).optional()}).strict(),c.z.object({decision:c.z.enum(["allow","deny","skip"])}).strict(),c.z.object({expectedRevision:c.z.number().int().min(0),queueIds:c.z.array(c.z.string().trim().min(1).max(120)).max(100)}).strict(),c.z.object({paused:c.z.boolean()}).strict(),c.z.object({expectedRevision:c.z.number().int().min(0),message:c.z.string().trim().min(1).max(2e4),attachments:c.z.array(c.z.union([c.z.object({id:c.z.string().trim().min(1).max(120),source:c.z.object({type:c.z.literal("retained")}).strict()}).strict(),Et])).max(6).optional()}).strict(),c.z.object({code:c.z.string().trim().min(1).max(160),message:c.z.string(),instanceId:c.z.string().trim().min(1).max(160).optional(),nodeId:c.z.string().trim().min(1).max(160).optional(),route:c.z.string().trim().min(1).max(4096).optional()}).strict();const Ut=c.z.object({id:c.z.string().trim().min(1).max(120),messageId:c.z.string().trim().min(1).max(240).optional(),message:c.z.string().trim().min(1).max(2e4),attachments:c.z.array(_t).max(6).default([]),references:St,permissionMode:Tt.optional(),status:c.z.enum(["queued","sending","failed"]).default("queued"),createdAt:c.z.string().datetime(),updatedAt:c.z.string().datetime(),error:c.z.string().trim().max(4e3).optional()}).strict(),Ft=c.z.object({revision:c.z.number().int().min(0).default(0),pendingCount:c.z.number().int().min(0).default(0),paused:c.z.boolean().optional(),items:c.z.array(Ut).max(100).default([])}).strict().default({revision:0,pendingCount:0,items:[]}),$t=c.z.enum(["control","realtime","adapter-snapshot","transcript-tail","transcript-scan","process-scan","app-session"]),Ht=c.z.object({id:c.z.string().trim().min(1).max(240),status:c.z.enum(["running","completed"]),startedAt:c.z.string().datetime().optional(),completedAt:c.z.string().datetime().optional()}).strict(),qt=c.z.object({id:c.z.string().trim().min(1).max(240),providerTurnId:c.z.string().trim().max(240).optional(),source:$t.optional(),userPrompt:c.z.string().trim().optional(),userMessages:c.z.array(Je).max(100).optional(),status:c.z.enum(["queued","running","waiting","completed","failed"]).default("running"),phase:Ze.optional(),summary:c.z.string().trim().max(1e3).optional(),lastMessage:c.z.string().trim().optional(),lastMessageItemId:c.z.string().trim().max(240).optional(),contextCompactions:c.z.array(Ht).max(20).optional(),revision:c.z.number().int().min(0).default(0),sourcePriority:c.z.number().int().min(0).max(100).optional(),snapshotVersion:c.z.number().int().min(0).optional(),observedAt:c.z.string().datetime().optional(),startedAt:c.z.string().datetime().optional(),updatedAt:c.z.string().datetime().optional(),completedAt:c.z.string().datetime().optional()}).strict(),Bt=qt.pick({id:!0,providerTurnId:!0,userPrompt:!0,userMessages:!0,status:!0,phase:!0,summary:!0,lastMessage:!0,contextCompactions:!0,startedAt:!0,updatedAt:!0,completedAt:!0}).strict(),Vt=c.z.object({id:c.z.string().trim().min(1).max(120),agent:qe,creationSource:Be.default("app-session"),appSessionId:c.z.string().trim().max(120).optional(),appId:c.z.string().trim().max(120).optional(),providerSessionId:c.z.string().trim().max(240).optional(),lineage:yt,providerMeta:c.z.record(c.z.string(),c.z.unknown()).optional(),modelSelection:Dt.optional(),reasoningEffort:Lt.optional(),storyId:ze.optional(),appBindingKeys:c.z.array(c.z.string().trim().min(1).max(240)).max(20).optional(),actions:ht.optional(),activeTurnId:c.z.string().trim().max(240).optional(),title:c.z.string().trim().max(240).optional(),cwd:c.z.string().trim().max(4096).optional(),cwdFolderId:c.z.string().trim().min(1).max(120).optional(),userPrompt:c.z.string().trim().optional(),turns:c.z.array(qt).max(50).optional(),status:Qe.default("running"),phase:Ze.default("unknown"),summary:c.z.string().trim().max(1e3).optional(),lastMessage:c.z.string().trim().optional(),lastMessageItemId:c.z.string().trim().max(240).optional(),currentTool:et.optional(),toolCallsSinceLastMessage:c.z.number().int().min(0).default(0),subAgents:pt.default([]),transcriptPath:c.z.string().trim().max(4096).optional(),transcriptSize:c.z.number().int().min(0).optional(),startedAt:c.z.string().datetime(),updatedAt:c.z.string().datetime(),completedAt:c.z.string().datetime().optional(),error:c.z.string().trim().max(4e3).optional(),counters:mt,queue:Ft,unread:c.z.boolean().default(!1)}).strict(),Gt=Vt.pick({id:!0,appBindingKeys:!0,cwd:!0,error:!0,providerMeta:!0,modelSelection:!0,reasoningEffort:!0,queue:!0,subAgents:!0}).strict(),Kt=qt.pick({id:!0,providerTurnId:!0,status:!0,phase:!0,revision:!0,startedAt:!0,updatedAt:!0,completedAt:!0}).extend({bodyRevision:c.z.string().trim().min(1).max(64)}).strict(),Wt=c.z.object({sessionId:c.z.string().trim().min(1).max(120),revision:c.z.string().trim().min(1).max(64),turns:c.z.array(Kt).max(50)}).strict(),Yt=c.z.object({sessionId:c.z.string().trim().min(1).max(120),revision:c.z.string().trim().min(1).max(64),turn:qt}).strict(),Xt=c.z.string().trim().min(1).max(64),Jt=c.z.object({kind:c.z.literal("not-modified"),revision:Xt}).strict();c.z.discriminatedUnion("kind",[Jt,c.z.object({kind:c.z.literal("updated"),revision:Xt,detail:Gt}).strict()]),c.z.discriminatedUnion("kind",[Jt,c.z.object({kind:c.z.literal("updated"),revision:Xt,index:Wt}).strict()]),c.z.discriminatedUnion("kind",[Jt,c.z.object({kind:c.z.literal("updated"),revision:Xt,body:Yt}).strict()]);const Qt=c.z.object({session:Vt,provider:c.z.string().trim().min(1).max(80),action:c.z.enum(["send","queue","steer","interrupt","approval"]),decision:c.z.enum(["allow","deny","skip"]).optional(),turnId:c.z.string().trim().min(1).max(240).optional(),providerTurnId:c.z.string().trim().min(1).max(240).optional(),queueId:c.z.string().trim().min(1).max(120).optional()}).strict(),Zt=Qt.omit({session:!0}).extend({sessionId:c.z.string().trim().min(1).max(120),messageId:c.z.string().trim().min(1).max(240).optional()}).strict();c.z.object({sessionId:c.z.string().trim().min(1).max(120),queueRevision:c.z.number().int().min(0),action:c.z.enum(["retry","remove","edit","reorder","pause"]),queueId:c.z.string().trim().min(1).max(120).optional()}).strict(),c.z.union([Zt,Qt.transform(function(e){const t=e.session.turns?.at(-1),n=(e.queueId?e.session.queue?.items.find(t=>t.id===e.queueId)?.messageId:void 0)||("send"===e.action||"queue"===e.action||"steer"===e.action?t?.userMessages?.at(-1)?.id:void 0);return Zt.parse({sessionId:e.session.id,provider:e.provider,action:e.action,...e.decision?{decision:e.decision}:{},...e.turnId||e.session.activeTurnId||t?.id?{turnId:e.turnId||e.session.activeTurnId||t?.id}:{},...e.providerTurnId||t?.providerTurnId?{providerTurnId:e.providerTurnId||t?.providerTurnId}:{},...e.queueId?{queueId:e.queueId}:{},...n?{messageId:n}:{}})})]);const en=500,tn=365,nn=c.z.object({id:c.z.string().trim().min(1).max(120),agent:qe,creationSource:Be,providerSessionId:c.z.string().trim().min(1).max(240),lineage:yt,modelSelection:Dt.optional(),reasoningEffort:Lt.optional(),storyId:ze.optional(),title:c.z.string().trim().max(240).optional(),userPrompt:c.z.string().trim().optional(),lastMessage:c.z.string().trim().optional(),cwd:c.z.string().trim().min(1).max(4096),cwdFolderId:c.z.string().trim().min(1).max(120).optional(),lastActiveAt:c.z.string().datetime(),archivedAt:c.z.string().datetime()}).strict();c.z.object({schemaVersion:c.z.literal(1).default(1),items:c.z.array(nn).max(1e4).default([])}).strict(),c.z.object({items:c.z.array(nn).max(1e4).default([])}).strict(),c.z.object({item:nn,turns:c.z.array(Bt).max(50).default([])}).strict(),c.z.object({modelSelection:Dt.optional(),reasoningEffort:Lt.optional()}).strict(),c.z.object({disposition:c.z.enum(["resumed","already-open"]),aiSessionId:c.z.string().trim().min(1).max(120),providerSessionId:c.z.string().trim().min(1).max(240),appSessionId:c.z.string().trim().min(1).max(120).optional(),creationSource:Be}).strict();const sn=qt.omit({userMessages:!0}),on=Vt.pick({id:!0,agent:!0,creationSource:!0,appSessionId:!0,appId:!0,providerSessionId:!0,lineage:!0,providerMeta:!0,modelSelection:!0,reasoningEffort:!0,storyId:!0,appBindingKeys:!0,actions:!0,activeTurnId:!0,title:!0,cwd:!0,cwdFolderId:!0,userPrompt:!0,turns:!0,status:!0,phase:!0,summary:!0,lastMessage:!0,lastMessageItemId:!0,currentTool:!0,toolCallsSinceLastMessage:!0,subAgents:!0,queue:!0,startedAt:!0,updatedAt:!0,error:!0,unread:!0}).extend({turns:c.z.array(sn).max(50).optional(),detailRevision:c.z.string().trim().min(1).max(64).optional(),turnsRevision:c.z.string().trim().min(1).max(64).optional(),latestTurnRef:c.z.object({id:qt.shape.id,bodyRevision:c.z.string().trim().min(1).max(64)}).strict().optional(),turnCount:c.z.number().int().min(0).optional(),subAgentCount:c.z.number().int().min(0).optional(),lastUserMessageAt:c.z.string().datetime().optional()}).strict(),rn=c.z.object({runningCount:c.z.number().int().min(0).default(0),waitingCount:c.z.number().int().min(0).default(0),staleCount:c.z.number().int().min(0).default(0),sessions:c.z.array(on).default([]),updatedAt:c.z.string().datetime()}).strict(),an=c.z.object({streamId:c.z.string().trim().min(1).max(240),revision:c.z.number().int().min(0),lastEventAt:c.z.string().datetime(),snapshot:rn}).strict();rn.pick({runningCount:!0,waitingCount:!0,staleCount:!0,updatedAt:!0}).extend({idleCount:c.z.number().int().min(0).default(0),problemCount:c.z.number().int().min(0).default(0),revision:c.z.number().int().min(0).optional()});const cn=c.z.enum(["provider-event","app-session-created","app-session-updated","app-session-deleted","discovery-scan","control-action","heartbeat-sync","startup"]),dn=c.z.object({streamId:c.z.string().trim().min(1).max(240),instanceId:c.z.string().trim().min(1).max(160),nodeId:c.z.string().trim().min(1).max(160).optional(),revision:c.z.number().int().min(0),previousRevision:c.z.number().int().min(0).optional(),traceId:c.z.string().trim().min(1).max(160),generatedAt:c.z.string().datetime(),reason:cn}).strict(),ln=c.z.object({meta:dn,snapshot:rn}).strict(),un=c.z.object({meta:dn,upserted:c.z.array(on).default([]),removed:c.z.array(c.z.string().trim().min(1).max(120)).default([])}).strict(),pn=c.z.object({meta:dn,sessionIds:c.z.array(c.z.string().trim().min(1).max(120)).default([]),expiresAt:c.z.string().datetime()}).strict(),mn=c.z.object({instanceId:c.z.string().trim().min(1).max(160),nodeId:c.z.string().trim().min(1).max(160).optional(),sessionId:c.z.string().trim().min(1).max(120),providerSessionId:c.z.string().trim().min(1).max(240).optional(),turnId:c.z.string().trim().min(1).max(240),itemId:c.z.string().trim().min(1).max(240),delta:c.z.string().min(1),generatedAt:c.z.string().datetime()}).strict(),hn=mn.omit({instanceId:!0,nodeId:!0,providerSessionId:!0}).strict();c.z.object({instanceId:c.z.string().trim().min(1).max(160),nodeId:c.z.string().trim().min(1).max(160).optional(),sessionId:c.z.string().trim().min(1).max(120),providerSessionId:c.z.string().trim().min(1).max(240),item:rt,generatedAt:c.z.string().datetime()}).strict();const gn=c.z.object({instanceId:c.z.string().trim().min(1).max(160),nodeId:c.z.string().trim().min(1).max(160).optional(),sessionId:c.z.string().trim().min(1).max(120),providerSessionId:c.z.string().trim().min(1).max(240).optional(),turnId:c.z.string().trim().min(1).max(240),itemId:c.z.string().trim().min(1).max(240),field:c.z.literal("output"),delta:c.z.string().min(1),generatedAt:c.z.string().datetime()}).strict(),fn=gn.omit({instanceId:!0,nodeId:!0,providerSessionId:!0}).strict();function yn(e){return fn.parse({sessionId:e.sessionId,turnId:e.turnId,itemId:e.itemId,field:e.field,delta:e.delta,generatedAt:e.generatedAt})}function In(e,t){if(t?.subagents||"subagent"!==e.lineage?.kind)return e;const{lineage:n,...i}=e;return i}function _n(e,t){return t?.subagents?e:{...e,sessions:e.sessions.map(e=>In(e,t))}}c.z.object({streamId:c.z.string().trim().min(1).max(240),instanceId:c.z.string().trim().min(1).max(160),sinceRevision:c.z.number().int().min(0),latestRevision:c.z.number().int().min(0),earliestRetainedRevision:c.z.number().int().min(0),syncRequired:c.z.boolean().default(!1),events:c.z.array(c.z.discriminatedUnion("type",[c.z.object({type:c.z.literal(Me),payload:ln}).strict(),c.z.object({type:c.z.literal(je),payload:un}).strict(),c.z.object({type:c.z.literal(Ue),payload:pn}).strict()])).default([])}).strict();const En=c.z.object({source:$t,sourcePriority:c.z.number().int().min(0).max(100).optional(),observedAt:c.z.string().datetime().optional(),snapshotVersion:c.z.number().int().min(0).optional()}).strict(),An=En.extend({type:c.z.literal("snapshot"),agent:c.z.string().trim().min(1).max(80),creationSource:Be.optional(),appSessionId:c.z.string().trim().max(120).optional(),appId:c.z.string().trim().max(120).optional(),providerSessionId:c.z.string().trim().max(240).optional(),lineage:ft.optional(),providerMeta:c.z.record(c.z.string(),c.z.unknown()).optional(),modelSelection:Dt.optional(),reasoningEffort:Lt.optional(),storyId:ze.optional(),appBindingKeys:c.z.array(c.z.string().trim().min(1).max(240)).max(20).optional(),actions:ht.optional(),title:c.z.string().trim().max(240).optional(),cwd:c.z.string().trim().max(4096).optional(),cwdFolderId:c.z.string().trim().min(1).max(120).optional(),activeTurnId:c.z.string().trim().max(240).optional(),userPrompt:c.z.string().trim().optional(),turns:c.z.array(qt).max(50).optional(),status:Qe.optional(),phase:Ze.optional(),summary:c.z.string().trim().max(1e3).optional(),lastMessage:c.z.string().trim().optional(),lastMessageItemId:c.z.string().trim().max(240).optional(),error:c.z.string().trim().max(4e3).optional(),currentTool:et.optional(),toolCallsSinceLastMessage:c.z.number().int().min(0).optional(),subAgents:pt.optional(),transcriptPath:c.z.string().trim().max(4096).optional(),transcriptSize:c.z.number().int().min(0).optional(),replaceActivity:c.z.boolean().optional()}).strict(),Tn=En.extend({type:c.z.literal("event"),sessionId:c.z.string().trim().min(1).max(120),kind:c.z.enum(["lifecycle","send-ack","turn-started","user-message","assistant-message","approval-requested","turn-completed","session-error","tool-activity","sub-agent-activity","context-compaction","model-selection","reasoning-effort"]),modelSelection:Dt.optional(),reasoningEffort:Lt.optional(),activeTurnId:c.z.string().trim().max(240).optional(),providerTurnId:c.z.string().trim().max(240).optional(),userPrompt:c.z.string().trim().optional(),userMessage:Je.optional(),text:c.z.string().optional(),itemId:c.z.string().trim().max(240).optional(),status:Qe.optional(),phase:Ze.optional(),summary:c.z.string().trim().max(1e3).optional(),error:c.z.string().trim().max(4e3).optional(),currentTool:et.nullable().optional(),toolCallsSinceLastMessage:c.z.number().int().min(0).optional(),subAgents:pt.optional(),contextCompaction:Ht.optional(),counters:c.z.object({toolCalls:c.z.number().int().min(0).optional(),edits:c.z.number().int().min(0).optional(),approvals:c.z.number().int().min(0).optional()}).strict().optional()}).strict().superRefine((e,t)=>{if("model-selection"===e.kind?e.modelSelection||t.addIssue({code:"custom",path:["modelSelection"],message:"model-selection events require modelSelection"}):void 0!==e.modelSelection&&t.addIssue({code:"custom",path:["modelSelection"],message:"modelSelection is only valid for model-selection events"}),"reasoning-effort"===e.kind?e.reasoningEffort||t.addIssue({code:"custom",path:["reasoningEffort"],message:"reasoning-effort events require reasoningEffort"}):void 0!==e.reasoningEffort&&t.addIssue({code:"custom",path:["reasoningEffort"],message:"reasoningEffort is only valid for reasoning-effort events"}),"session-error"!==e.kind||e.error||t.addIssue({code:"custom",path:["error"],message:"session-error events require error"}),"context-compaction"===e.kind?e.contextCompaction||t.addIssue({code:"custom",path:["contextCompaction"],message:"context-compaction events require contextCompaction"}):void 0!==e.contextCompaction&&t.addIssue({code:"custom",path:["contextCompaction"],message:"contextCompaction is only valid for context-compaction events"}),"send-ack"!==e.kind&&"user-message"!==e.kind&&void 0!==e.userMessage&&t.addIssue({code:"custom",path:["userMessage"],message:"userMessage is only valid for send-ack and user-message events"}),"sub-agent-activity"===e.kind?e.subAgents||t.addIssue({code:"custom",path:["subAgents"],message:"sub-agent-activity events require subAgents"}):void 0!==e.subAgents&&t.addIssue({code:"custom",path:["subAgents"],message:"subAgents is only valid for sub-agent-activity events"}),"tool-activity"!==e.kind)return void 0!==e.currentTool&&t.addIssue({code:"custom",path:["currentTool"],message:"currentTool is only valid for tool-activity events"}),void(void 0!==e.toolCallsSinceLastMessage&&t.addIssue({code:"custom",path:["toolCallsSinceLastMessage"],message:"toolCallsSinceLastMessage is only valid for tool-activity events"}));"currentTool"in e||t.addIssue({code:"custom",path:["currentTool"],message:"tool-activity events require currentTool"}),void 0===e.toolCallsSinceLastMessage&&t.addIssue({code:"custom",path:["toolCallsSinceLastMessage"],message:"tool-activity events require toolCallsSinceLastMessage"})});c.z.discriminatedUnion("type",[An,Tn]);const wn=c.z.union([c.z.object({type:c.z.literal("schedule"),scheduleKind:c.z.literal("interval").default("interval"),intervalMs:c.z.number().int().min(1e3)}).strict(),c.z.object({type:c.z.literal("schedule"),scheduleKind:c.z.literal("daily"),timeOfDay:c.z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/),timezone:c.z.string().trim().min(1).max(120)}).strict(),c.z.object({type:c.z.literal("schedule"),scheduleKind:c.z.literal("weekly"),weekdays:c.z.array(c.z.number().int().min(0).max(6)).min(1).max(7),timeOfDay:c.z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/),timezone:c.z.string().trim().min(1).max(120)}).strict()]),bn=c.z.union([wn,c.z.object({type:c.z.literal("file-change"),roots:c.z.array(c.z.string().trim().min(1).max(4096)).min(1).max(50),globs:c.z.array(c.z.string().trim().min(1).max(500)).min(1).max(100),ignore:c.z.array(c.z.string().trim().min(1).max(500)).max(100).optional(),debounceMs:c.z.number().int().min(100).max(6e4).default(1500)}).strict(),c.z.object({type:c.z.literal("ai-session"),agent:c.z.string().trim().min(1).max(80).optional(),statuses:c.z.array(c.z.enum(["running","waiting","idle","failed"])).max(20).optional(),phases:c.z.array(c.z.enum(["thinking","tool","editing","approval","responding","unknown"])).max(20).optional()}).strict()]),Nn=c.z.object({promptTemplate:c.z.string().trim().min(1).max(2e4)}).strict(),Sn=c.z.object({cooldownMs:c.z.number().int().min(0).max(864e5).optional(),maxConcurrentRuns:c.z.number().int().min(1).max(20).default(1),whenBusy:c.z.enum(["skip","queue"]).default("skip")}).strict(),vn=c.z.object({configHash:c.z.string().trim().min(8).max(80),name:c.z.string().trim().min(1).max(160),description:c.z.string().trim().max(1e3).optional(),source:bn,action:Nn,policy:Sn.default({maxConcurrentRuns:1,whenBusy:"skip"}),createdAt:c.z.string().datetime(),updatedAt:c.z.string().datetime()}).strict(),On=c.z.object({type:c.z.literal("ai-session"),aiSessionId:c.z.string().trim().min(1).max(160)}).strict(),Rn=c.z.object({configHash:c.z.string().trim().min(8).max(80),deploymentId:c.z.string().trim().min(1).max(240).optional(),instanceId:c.z.string().trim().min(1).max(160),origin:c.z.enum(["control-plane","controlled-instance"]).default("controlled-instance"),enabled:c.z.boolean().default(!0),target:On,localName:c.z.string().trim().min(1).max(160).optional(),createdAt:c.z.string().datetime(),updatedAt:c.z.string().datetime()}).strict(),zn=c.z.object({configHash:c.z.string().trim().min(8).max(80),deploymentId:c.z.string().trim().min(1).max(240).optional(),instanceId:c.z.string().trim().min(1).max(160),status:c.z.enum(["idle","running","disabled","error"]).default("idle"),lastTriggeredAt:c.z.string().datetime().optional(),lastCompletedAt:c.z.string().datetime().optional(),lastSkippedAt:c.z.string().datetime().optional(),lastError:c.z.string().trim().max(4e3).optional(),runCount:c.z.number().int().min(0).default(0),skippedCount:c.z.number().int().min(0).default(0)}).strict(),xn=c.z.object({id:c.z.string().trim().min(1).max(160),configHash:c.z.string().trim().min(8).max(80),deploymentId:c.z.string().trim().min(1).max(240).optional(),instanceId:c.z.string().trim().min(1).max(160),eventType:c.z.enum(["manual","schedule","file-change","ai-session"]),status:c.z.enum(["started","completed","failed","skipped"]),target:On,promptPreview:c.z.string().trim().max(500),eventSummary:c.z.string().trim().max(1e3).optional(),error:c.z.string().trim().max(4e3).optional(),startedAt:c.z.string().datetime(),completedAt:c.z.string().datetime().optional()}).strict();c.z.object({schemaVersion:c.z.literal(1).default(1),configs:c.z.array(vn).default([]),deployments:c.z.array(Rn).default([]),runtime:c.z.array(zn).default([]),recentRuns:c.z.array(xn).default([])}).strict();const Cn=c.z.object({config:vn,deployment:Rn,runtime:zn.optional()}).strict();c.z.object({instanceId:c.z.string().trim().min(1).max(160),sessionId:c.z.string().trim().min(1).max(160),mutation:Cn.optional()}).strip(),c.z.object({instanceId:c.z.string().trim().min(1).max(160),sessionId:c.z.string().trim().min(1).max(160),configHash:vn.shape.configHash}).strip();const kn=c.z.object({instanceId:c.z.string().trim().min(1).max(160),instanceName:c.z.string().trim().min(1).max(160),deployment:Rn,runtime:zn.optional()}).strip(),Dn=xn.extend({instanceName:c.z.string().trim().min(1).max(160).optional()}).strip(),Ln=c.z.object({configHash:c.z.string().trim().min(8).max(80),config:vn,deploymentCount:c.z.number().int().min(0),enabledCount:c.z.number().int().min(0),runningCount:c.z.number().int().min(0),errorCount:c.z.number().int().min(0),ownedByControlPlane:c.z.boolean(),controlPlaneDeploymentCount:c.z.number().int().min(0),deployments:c.z.array(kn),recentRuns:c.z.array(Dn)}).strip();c.z.object({updatedAt:c.z.string().datetime(),triggers:c.z.array(Ln)}).strip(),c.z.object({name:vn.shape.name,description:vn.shape.description,source:bn,action:Nn,policy:Sn.partial().optional()}).strict(),c.z.object({scope:c.z.enum(["node","instance"]),nodeId:c.z.string().trim().min(1).max(160).optional(),instanceId:c.z.string().trim().min(1).max(160).optional(),code:c.z.string().trim().min(1).max(160),message:c.z.string().trim().min(1).max(4e3)}).strip();const Pn=c.z.string().regex(/^\d{4}-\d{2}-\d{2}$/,"Proxy protocol version must use YYYY-MM-DD format."),Mn=c.z.string().trim().min(1).max(160).regex(/^[a-zA-Z0-9][a-zA-Z0-9_.:-]*$/),jn=c.z.string().datetime(),Un=c.z.string().trim().min(32).max(4096),Fn=c.z.string().trim().max(2048).transform((e,t)=>{try{return function(e){const t=new URL(e.trim());if("https:"!==t.protocol||t.username||t.password||"/"!==t.pathname||t.search||t.hash)throw new Error("Proxy origin must be an HTTPS origin without credentials, path, query, or fragment.");return t.origin}(e)}catch(e){return t.addIssue({code:"custom",message:e instanceof Error?e.message:String(e)}),c.z.NEVER}});c.z.string().trim().min(1).max(4096).transform((e,t)=>{try{return function(e){const t=e.trim();if(!t.startsWith("/")||t.startsWith("//")||t.includes("\\")||/%25/i.test(t))throw new Error("Proxy route must be a single-encoded node-agent relative route.");const n=t.split("?",1)[0];let i,s;try{i=n.split("/").map(e=>decodeURIComponent(e))}catch{throw new Error("Proxy route contains invalid percent encoding.")}if(i.some(e=>".."===e||"."===e))throw new Error("Proxy route cannot traverse outside the node-agent API.");try{s=new URL(t,"https://node-agent.invalid")}catch{throw new Error("Proxy route is invalid.")}if("https://node-agent.invalid"!==s.origin||s.username||s.password)throw new Error("Proxy route cannot select an absolute upstream URL.");return`${s.pathname}${s.search}`}(e)}catch(e){return t.addIssue({code:"custom",message:e instanceof Error?e.message:String(e)}),c.z.NEVER}});const $n=c.z.enum(Object.values({ProtocolUnsupported:"CONTROL_PLANE_PROXY_PROTOCOL_UNSUPPORTED",InviteInvalid:"CONTROL_PLANE_PROXY_INVITE_INVALID",InviteExpired:"CONTROL_PLANE_PROXY_INVITE_EXPIRED",InviteConsumed:"CONTROL_PLANE_PROXY_INVITE_CONSUMED",InviteRevoked:"CONTROL_PLANE_PROXY_INVITE_REVOKED",TargetUnavailable:"CONTROL_PLANE_PROXY_TARGET_UNAVAILABLE",TargetMismatch:"CONTROL_PLANE_PROXY_TARGET_MISMATCH",BindingUnknown:"CONTROL_PLANE_PROXY_BINDING_UNKNOWN",BindingRevoked:"CONTROL_PLANE_PROXY_BINDING_REVOKED",BindingIdentityConflict:"CONTROL_PLANE_PROXY_BINDING_IDENTITY_CONFLICT",AuthenticationFailed:"CONTROL_PLANE_PROXY_AUTHENTICATION_FAILED",RouteInvalid:"CONTROL_PLANE_PROXY_ROUTE_INVALID",HeaderInvalid:"CONTROL_PLANE_PROXY_HEADER_INVALID",ResourceLimit:"CONTROL_PLANE_PROXY_RESOURCE_LIMIT",SnapshotRequired:"CONTROL_PLANE_PROXY_SNAPSHOT_REQUIRED",Unavailable:"CONTROL_PLANE_PROXY_UNAVAILABLE",TransportFailed:"CONTROL_PLANE_PROXY_TRANSPORT_FAILED"})),Hn=c.z.object({code:$n,message:c.z.string().trim().min(1).max(2048),retryable:c.z.boolean(),details:c.z.record(c.z.string(),c.z.unknown()).optional()}).strict(),qn=c.z.enum(["active","revoked"]),Bn=c.z.object({id:Mn,targetNodeId:Mn,status:qn,createdBy:Mn,expiresAt:jn,revokedAt:jn.optional(),createdAt:jn,updatedAt:jn}).strict();c.z.object({targetNodeId:Mn,expiresInSeconds:c.z.number().int().min(60).max(3600).default(600)}).strict(),c.z.object({invite:Bn,token:c.z.string().trim().min(24).max(512),proxyOrigin:Fn,protocolVersion:Pn}).strict();const Vn=c.z.enum(["active","revoked"]),Gn=c.z.object({id:Mn,claimId:Mn,sourceControlPlaneId:Mn,targetNodeId:Mn,bindingKeyId:Mn,status:Vn,revision:c.z.number().int().positive(),lastError:Hn.optional(),revokedAt:jn.optional(),createdAt:jn,updatedAt:jn}).strict();c.z.object({protocolVersion:Pn,inviteToken:c.z.string().trim().min(24).max(512).optional(),claimId:Mn,sourceControlPlaneId:Mn,targetNodeId:Mn.optional(),bindingKeyId:Mn,credential:Un}).strict(),c.z.object({sourceControlPlaneId:Mn,bindingKeyId:Mn,credential:Un}).strict();const Kn=c.z.object({id:Mn,name:c.z.string().trim().min(1).max(160),status:c.z.enum(["unknown","online","offline","degraded"]),health:c.z.enum(["unknown","ok","degraded","failed"]),lastSeenAt:jn.optional(),capabilities:c.z.record(c.z.string(),c.z.unknown()).default({})}).strict(),Wn=c.z.object({protocolVersion:Pn,binding:Gn,streamId:Mn,revision:c.z.number().int().nonnegative(),observedAt:jn,target:Kn}).strict(),Yn=c.z.object({type:c.z.literal("control-plane-proxy.event"),protocolVersion:Pn,streamId:Mn,bindingId:Mn,sourceControlPlaneId:Mn,targetNodeId:Mn,revision:c.z.number().int().positive(),source:c.z.object({id:c.z.string().trim().min(1).max(512),seq:c.z.number().int().nonnegative()}).strict(),target:Kn,event:c.z.object({type:c.z.string().trim().min(1).max(240),topic:c.z.string().trim().min(1).max(240),createdAt:jn}).strict()}).strict(),Xn=c.z.object({type:c.z.literal("control-plane-proxy.events.ready"),protocolVersion:Pn,streamId:Mn,bindingId:Mn,sourceControlPlaneId:Mn,targetNodeId:Mn,latestRevision:c.z.number().int().nonnegative(),earliestRetainedRevision:c.z.number().int().nonnegative()}).strict(),Jn=c.z.object({type:c.z.literal("control-plane-proxy.snapshot-required"),protocolVersion:Pn,streamId:Mn,bindingId:Mn,sourceControlPlaneId:Mn,targetNodeId:Mn,sinceRevision:c.z.number().int().nonnegative(),latestRevision:c.z.number().int().nonnegative(),earliestRetainedRevision:c.z.number().int().nonnegative(),error:Hn}).strict();c.z.discriminatedUnion("type",[Yn,Xn,Jn]),c.z.object({protocolVersion:Pn,binding:Gn,target:Wn.shape.target}).strict(),c.z.object({id:Mn,claimId:Mn,proxyOrigin:Fn,requestedName:c.z.string().trim().min(1).max(160).optional(),sourceControlPlaneId:Mn,targetNodeId:Mn.optional(),bindingKeyId:Mn,credential:Un,status:c.z.enum(["pending","compensation-required"]),createdAt:jn,updatedAt:jn,expiresAt:jn}).strict().omit({credential:!0}),c.z.object({id:Mn,nodeId:Mn,proxyOrigin:Fn,proxyBindingId:Mn,targetNodeId:Mn,sourceControlPlaneId:Mn,bindingKeyId:Mn,credential:Un,createdAt:jn,updatedAt:jn}).strict();const Qn=c.z.string().trim().min(1).max(120).regex(/^[a-zA-Z0-9][a-zA-Z0-9_.:-]*$/),Zn=c.z.string().datetime(),ei=c.z.number().int().nonnegative(),ti=c.z.enum(["https-token","ssh-key"]),ni=c.z.enum(["operation-only","instance-retained"]),ii=c.z.enum(["enabled","disabled"]),si=c.z.enum(["pending","synced","deferred","revoking","revoked"]),oi=c.z.object({scheme:c.z.enum(["https","ssh"]),host:c.z.string().trim().min(1).max(253),port:c.z.number().int().min(1).max(65535).optional(),pathPrefix:c.z.string().min(1).max(2048).default("/")}).strict();function ri(e){throw new Error(`Invalid Git credential scope: ${e}`)}function ai(e){const t=e.trim().replace(/^\[|\]$/g,"");(!t||t.includes("*")||/[/?#@\s]/.test(t))&&ri("host is invalid");try{const e=new URL(t.includes(":")?`http://[${t}]/`:`http://${t}/`).hostname.replace(/^\[|\]$/g,"").toLowerCase();return(!e||e.length>253||e.includes("*"))&&ri("host is invalid"),e}catch{ri("host is invalid")}}function ci(e){try{return decodeURIComponent(e)}catch{ri("path contains invalid percent encoding")}}function di(e){const t=e?.trim()||"/";(t.includes("?")||t.includes("#")||t.includes("\\")||t.includes("\0"))&&ri("path contains an unsupported delimiter");const n=(t.startsWith("/")?t:`/${t}`).split("/").filter(Boolean);for(const e of n){const t=ci(e);("."===t||".."===t||t.includes("/")||t.includes("\\")||t.includes("\0"))&&ri("path contains an unsafe segment")}return 0===n.length?"/":`/${n.join("/")}/`}function li(e){const t=oi.parse(e),n="https"===t.scheme?443:22;return oi.parse({scheme:t.scheme,host:ai(t.host),...void 0===t.port||t.port===n?{}:{port:t.port},pathPrefix:di(t.pathPrefix)})}function ui(e){return di(e.replace(/\.git\/?$/,""))}const pi=c.z.object({id:Qn,name:c.z.string().trim().min(1).max(160),kind:ti,scope:oi,secretSet:c.z.literal(!0),status:ii,revision:ei,createdAt:Zn,updatedAt:Zn}).strict(),mi=c.z.object({kind:c.z.literal("https-token"),username:c.z.string().trim().min(1).max(240),token:c.z.string().min(1).max(8192)}).strict(),hi=c.z.object({kind:c.z.literal("ssh-key"),privateKey:c.z.string().min(1).max(131072),passphrase:c.z.string().max(8192).optional(),pinnedKnownHosts:c.z.string().min(1).max(131072)}).strict(),gi=c.z.discriminatedUnion("kind",[mi,hi]);c.z.object({name:c.z.string().trim().min(1).max(160),scope:oi,secret:gi}).strict().superRefine((e,t)=>{"https"===e.scope.scheme!=("https-token"===e.secret.kind)&&t.addIssue({code:"custom",path:["scope","scheme"],message:"Credential kind must match the remote scheme."});try{li(e.scope)}catch(e){t.addIssue({code:"custom",path:["scope"],message:e instanceof Error?e.message:"Invalid Git scope."})}}),c.z.object({name:c.z.string().trim().min(1).max(160).optional(),scope:oi.optional(),secret:gi.optional(),status:ii.optional()}).strict().refine(e=>Object.keys(e).length>0,"At least one credential field must be updated."),c.z.object({items:c.z.array(pi).max(1e4)}).strict(),c.z.object({host:c.z.string().trim().min(1).max(253),port:c.z.number().int().min(1).max(65535).optional()}).strict();const fi=c.z.object({keyType:c.z.string().trim().min(1).max(64),fingerprint:c.z.string().trim().min(1).max(256),publicKey:c.z.string().trim().min(1).max(8192),knownHosts:c.z.string().min(1).max(8192)}).strict();c.z.object({host:c.z.string().trim().min(1).max(253),port:c.z.number().int().min(1).max(65535),fetchedAt:Zn,knownHosts:c.z.string().min(1).max(65536),entries:c.z.array(fi).min(1).max(32)}).strict();const yi=c.z.object({instanceId:Qn,credentialId:Qn,credentialRevision:ei,assignmentRevision:ei,status:si,authorizedAt:Zn,updatedAt:Zn}).strict(),Ii=c.z.object({credential:pi,secret:gi}).strict().superRefine((e,t)=>{e.credential.kind!==e.secret.kind&&t.addIssue({code:"custom",path:["secret","kind"],message:"Credential payload kind mismatch."})}),_i=c.z.object({instanceId:Qn,generation:ei,credentialIds:c.z.array(Qn).max(256).transform(e=>[...new Set(e)].sort()),updatedAt:Zn}).strict(),Ei=c.z.object({remoteUrl:c.z.string().trim().min(1).max(4096)}).strict(),Ai=c.z.discriminatedUnion("status",[c.z.object({status:c.z.literal("ok"),username:c.z.string().min(1).max(240),password:c.z.string().min(1).max(8192)}).strict(),c.z.object({status:c.z.enum(["none","ambiguous","unsupported","missing-host-key","rejected"])}).strict()]),Ti=c.z.object({remoteUrl:c.z.string().trim().min(1).max(4096)}).strict(),wi=c.z.discriminatedUnion("status",[c.z.object({status:c.z.literal("ok"),invocationId:Qn,publicIdentity:c.z.string().min(1).max(131072),pinnedKnownHosts:c.z.string().min(1).max(131072)}).strict(),c.z.object({status:c.z.enum(["none","ambiguous","unsupported","missing-host-key","rejected"])}).strict()]),bi=c.z.object({invocationId:Qn,frame:c.z.string().min(1).max(1048576)}).strict(),Ni=c.z.object({frame:c.z.string().min(1).max(1048576)}).strict(),Si=c.z.object({operationId:Qn,retention:ni,payload:Ii}).strict(),vi=c.z.object({operationId:Qn,instanceId:Qn,remoteUrl:c.z.string().trim().min(1).max(4096),ref:c.z.discriminatedUnion("type",[c.z.object({type:c.z.enum(["branch","tag"]),name:c.z.string().trim().min(1).max(240)}).strict(),c.z.object({type:c.z.literal("commit"),commit:c.z.string().trim().regex(/^[0-9a-fA-F]{4,64}$/,"commit must be a hexadecimal Git object id")}).strict()]),clone:c.z.object({depth:c.z.number().int().positive().max(1e5).optional(),submodules:c.z.boolean().default(!1),lfs:c.z.boolean().default(!1),subdirectory:c.z.string().trim().max(240).refine(e=>!e.startsWith("/")&&!e.split("/").some(e=>".."===e),"subdirectory must be a relative path within the repository").transform(e=>e.split("/").filter(e=>e&&"."!==e).join("/")).default("")}).strict(),credentials:c.z.array(Si).max(256).default([])}).strict();function Oi(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:void 0}function Ri(e,t){if(e)return Object.fromEntries(t.filter(t=>Object.prototype.hasOwnProperty.call(e,t)).map(t=>[t,e[t]]))}function zi(e,t){let n;try{n=function(e){const t=e.trim();if(t&&!t.includes("\0")||ri("remote is empty or invalid"),/^https?:\/\//i.test(t)||/^ssh:\/\//i.test(t)){let e;di(t.replace(/^[a-z][a-z0-9+.-]*:\/\/[^/]+/i,"").split(/[?#]/,1)[0]||"/");try{e=new URL(t)}catch{ri("remote URL is invalid")}"https:"!==e.protocol&&"ssh:"!==e.protocol&&ri("remote scheme is unsupported"),(e.password||"https:"===e.protocol&&e.username)&&ri("HTTPS userinfo is forbidden"),(e.search||e.hash)&&ri("query and fragment are forbidden");const n="https:"===e.protocol?"https":"ssh",i=e.port?Number(e.port):void 0;return{...li({scheme:n,host:e.hostname,port:i,pathPrefix:ui(e.pathname)}),original:t}}/^[a-z][a-z0-9+.-]*:\/\//i.test(t)&&ri("remote scheme is unsupported");const n=/^(?:([^@/:\s]+)@)?([^/:\s]+):(.+)$/.exec(t);n||ri("remote must use HTTPS, ssh://, or scp-like SSH syntax");const[,,i,s]=n;return(s.includes("?")||s.includes("#"))&&ri("query and fragment are forbidden"),{...li({scheme:"ssh",host:i,pathPrefix:ui(s)}),original:t}}(e)}catch(e){return{status:"unsupported",reason:e instanceof Error?e.message:"Unsupported Git remote."}}const i=t.filter(e=>"enabled"===e.status).filter(e=>"https"===n.scheme==("https-token"===e.kind)).filter(e=>function(e,t){const n=li(e);return n.scheme===t.scheme&&n.host===t.host&&n.port===t.port&&("/"===n.pathPrefix||t.pathPrefix.startsWith(n.pathPrefix))}(e.scope,n)).map(e=>({candidate:e,specificity:li(e.scope).pathPrefix.length}));if(0===i.length)return{status:"none",remote:n};const s=Math.max(...i.map(e=>e.specificity)),o=i.filter(e=>e.specificity===s).map(e=>e.candidate);if(o.length>1)return{status:"ambiguous",remote:n,credentialIds:o.map(e=>e.id).sort()};const r=o[0];return"ssh-key"===r.kind&&!0!==r.pinnedKnownHosts?{status:"missing-host-key",remote:n,credentialId:r.id}:{status:"unique",remote:n,credential:r}}const xi=c.z.enum(["openai-responses","openai-chat-completions","anthropic-messages"]);c.z.object({}).strict();const Ci=c.z.enum(["docker","local","wsl"]),ki=c.z.object({docker:c.z.boolean().default(!1),kubernetes:c.z.boolean().default(!1),local:c.z.boolean().default(!1),wsl:c.z.boolean().default(!1)}).strip(),Di=c.z.object({registry:c.z.boolean().default(!1),runtimeBroker:c.z.boolean().default(!1),workspaceProvisioning:ki.default({docker:!1,kubernetes:!1,local:!1,wsl:!1})}).strip(),Li=c.z.object({multiEntityAssignment:c.z.boolean().default(!1),privateModelCatalog:c.z.boolean().default(!1),stableModelIdentity:c.z.boolean().default(!1),requestMappings:c.z.boolean().default(!1),modelRelay:c.z.object({protocols:c.z.array(xi).max(3).default([]),streaming:c.z.boolean().default(!1),unknownModelPolicy:c.z.boolean().default(!1)}).strip().default(()=>({protocols:[],streaming:!1,unknownModelPolicy:!1}))}).strip(),Pi=c.z.object({policy:c.z.boolean().default(!1),actions:c.z.boolean().default(!1),automations:c.z.boolean().default(!1),aiSessionRead:c.z.boolean().default(!1),decisions:c.z.boolean().default(!1)}).strip(),Mi=c.z.object({enabled:c.z.boolean().default(!1),agentTools:c.z.boolean().default(!1),agentToolCapabilities:Pi.optional(),sessionRetention:c.z.boolean().default(!1),maxFileBytes:c.z.number().int().positive().default(33554432),maxBatchPaths:c.z.number().int().min(1).max(100).default(20)}).strip(),ji=c.z.object({runtime:c.z.enum(["docker","local"]),workspaceMaterializer:c.z.enum(["overlay-copy-on-write","worktree"]),processSandbox:c.z.enum(["instance","container","local-runtime"]),providerId:c.z.string().trim().min(1).max(120)}).strip(),Ui=c.z.object({definitions:c.z.boolean().default(!1),runs:c.z.boolean().default(!1),orchestration:c.z.object({storyEntryAuthorization:c.z.boolean().default(!1),orchestrations:c.z.boolean().default(!1),runMembers:c.z.boolean().default(!1),manualRuns:c.z.boolean().default(!1)}).strip().default({storyEntryAuthorization:!1,orchestrations:!1,runMembers:!1,manualRuns:!1}),sharedSpace:c.z.object({enabled:c.z.boolean().default(!1),runtimes:c.z.array(Ci).default([])}).strip().default({enabled:!1,runtimes:[]}),combinations:c.z.array(ji).default([])}).strip(),Fi=c.z.object({enabled:c.z.boolean().default(!1),runtimes:c.z.array(c.z.string().trim().min(1).max(64)).default([])}).strip().default({enabled:!1,runtimes:[]});Ui.omit({combinations:!0,sharedSpace:!0}).extend({combinations:c.z.array(c.z.unknown()).default([]),sharedSpace:Fi}).strip();const $i=c.z.object({modelEndpointProbe:c.z.boolean().optional(),aiSessionHistoryLimit:c.z.boolean().optional(),aiSessionAttachmentRetention:c.z.boolean().optional(),aiSessionFileAttachmentLimit:c.z.boolean().optional(),folderPlaces:c.z.boolean().optional(),localFolderNameUpdate:c.z.boolean().optional(),managedGitCredentials:Di.optional(),managedModels:Li.optional(),stories:Mi.optional(),codexManagedSettings:c.z.boolean().optional(),agentExecution:Ui.optional()}).strip(),Hi=new TextEncoder;function qi(e){return u.sha256("string"==typeof e?Hi.encode(e):e)}function Bi(e){const t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),t}function Vi(e){const t=atob(e),n=Uint8Array.from(t,e=>e.charCodeAt(0)),i=globalThis.Buffer;return i?i.from(n):n}const Gi=c.z.string().trim().min(1).max(120),Ki=c.z.object({selectModelAtCreate:c.z.boolean().default(!1),selectProviderAtCreate:c.z.boolean().default(!1),selectModelAtResume:c.z.boolean().default(!1),selectProviderAtResume:c.z.boolean().default(!1),switchModelWithinProvider:c.z.boolean().default(!1),switchProviderDuringSession:c.z.boolean().default(!1),stableIdentity:c.z.boolean().default(!1)}).strip().default({selectModelAtCreate:!1,selectProviderAtCreate:!1,selectModelAtResume:!1,selectProviderAtResume:!1,switchModelWithinProvider:!1,switchProviderDuringSession:!1,stableIdentity:!1}),Wi=c.z.object({selectAtCreate:c.z.boolean().default(!1),updateDuringSession:c.z.boolean().default(!1)}).strip().default({selectAtCreate:!1,updateDuringSession:!1}),Yi=c.z.object({subagents:c.z.boolean().default(!1)}).strip().default({subagents:!1}),Xi=c.z.object({agent:Gi,actions:c.z.object({create:c.z.boolean().default(!1),send:c.z.boolean().default(!1),queue:c.z.boolean().default(!1),steer:c.z.boolean().default(!1),interrupt:c.z.boolean().default(!1),archive:c.z.boolean().default(!1),delete:c.z.boolean().default(!1),fork:c.z.boolean().default(!1),rename:c.z.boolean().default(!1),approvalDecisions:c.z.array(c.z.enum(["allow","deny","skip"])).max(3).default([])}).passthrough(),permissionModes:c.z.array(c.z.enum(["ask","auto-review","full-access"])).max(3).default([]),timeline:c.z.object({sessionRead:c.z.boolean().default(!1),turnRead:c.z.boolean().default(!1),liveItems:c.z.boolean().default(!1)}).passthrough(),modelSelection:Ki.optional(),reasoningEffort:Wi.optional(),hierarchy:Yi.optional()}).passthrough(),Ji=c.z.array(Xi).max(100).default([]),Qi="2026-10-02",Zi=new Set(["2026-08-01","2026-08-16","2026-08-17","2026-08-20","2026-09-24","2026-09-29",Qi]),es=c.z.string().regex(/^\d{4}-\d{2}-\d{2}$/,"Protocol version must use YYYY-MM-DD format."),ts=c.z.string().trim().min(1).max(120),ns=c.z.enum(["low","medium","high"]),is=c.z.enum(["none","friendly","pragmatic"]),ss=c.z.object({modelEntityId:c.z.string().trim().min(1).max(120),modelName:c.z.string().trim().min(1).max(240),modelUpstreamName:c.z.string().trim().min(1).max(240).optional()}).strict(),os=c.z.object({modelVerbosity:ns.optional(),personality:is.optional(),multiAgent:c.z.object({enabled:c.z.boolean().default(!0),maxConcurrentThreads:c.z.number().int().min(1).max(64).optional(),defaultModel:ss.optional(),defaultReasoningEffort:Lt.optional()}).strict().default({enabled:!0})}).strict();function rs(){return{features:{appRuntime:!1,tty:!1,gui:!1,browser:!1,browserTunnel:!1,screenshots:!1,logs:!1,aiSessionWorkspaceSelection:!1,aiSessionWorkspaceCheckout:!1,aiSessionPersistenceSettings:!1,privateModelCatalog:!1,codexManagedSettings:!1,nodeAgentConnectionUpdate:!1,gitCliCredentialBroker:!1,gitCredentialProxy:!1,repositoryPathSearch:!1,repositoryWorktreeMoveToMain:!1,modelRelay:{protocols:[],streaming:!1},managedModelEnvironment:{openCodeConfig:!1},aiSessionSendIdempotency:!1,aiSessionQueuePause:!1,aiSessionTimeline:{sessionReadAgents:[],turnReadAgents:[],liveItemAgents:[]},aiSessionConversationAttachments:{metadataAgents:[],contentAgents:[],uploadAgents:[],retentionSettings:!1,fileSizeLimitSettings:!1},aiSessionProviders:[]}}}const as=c.z.object({sessionReadAgents:c.z.array(ts).max(100).default([]),turnReadAgents:c.z.array(ts).max(100).default([]),liveItemAgents:c.z.array(ts).max(100).default([])}).passthrough(),cs=c.z.object({metadataAgents:c.z.array(ts).max(100).default([]),contentAgents:c.z.array(ts).max(100).default([]),uploadAgents:c.z.array(ts).max(100).default([]),retentionSettings:c.z.boolean().default(!1),fileSizeLimitSettings:c.z.boolean().default(!1)}).passthrough(),ds=c.z.object({protocols:c.z.array(xi).max(3).default([]),streaming:c.z.boolean().default(!1)}).strip(),ls=c.z.object({openCodeConfig:c.z.boolean().default(!1)}).strip(),us=c.z.object({appRuntime:c.z.boolean().default(!1),tty:c.z.boolean().default(!1),gui:c.z.boolean().default(!1),browser:c.z.boolean().default(!1),browserTunnel:c.z.boolean().optional(),screenshots:c.z.boolean().default(!1),logs:c.z.boolean().default(!1),aiSessionWorkspaceSelection:c.z.boolean().default(!1),aiSessionWorkspaceCheckout:c.z.boolean().optional(),aiSessionPersistenceSettings:c.z.boolean().default(!1),privateModelCatalog:c.z.boolean().optional(),codexManagedSettings:c.z.boolean().optional(),nodeAgentConnectionUpdate:c.z.boolean().optional(),gitCliCredentialBroker:c.z.boolean().optional(),gitCredentialProxy:c.z.boolean().optional(),repositoryPathSearch:c.z.boolean().optional(),repositoryWorktreeMoveToMain:c.z.boolean().optional(),aiSessionSendIdempotency:c.z.boolean().optional(),aiSessionQueuePause:c.z.boolean().optional(),aiSessionTimeline:as.default(function(){return{sessionReadAgents:[],turnReadAgents:[],liveItemAgents:[]}}),aiSessionConversationAttachments:cs.optional(),aiSessionProviders:Ji.optional(),modelRelay:ds.optional(),managedModelEnvironment:ls.optional()}).passthrough(),ps=c.z.object({features:us.default(function(){return{appRuntime:!1,tty:!1,gui:!1,browser:!1,browserTunnel:!1,screenshots:!1,logs:!1,aiSessionWorkspaceSelection:!1,aiSessionWorkspaceCheckout:!1,aiSessionPersistenceSettings:!1,privateModelCatalog:!1,codexManagedSettings:!1,nodeAgentConnectionUpdate:!1,gitCliCredentialBroker:!1,gitCredentialProxy:!1,repositoryPathSearch:!1,repositoryWorktreeMoveToMain:!1,modelRelay:{protocols:[],streaming:!1},managedModelEnvironment:{openCodeConfig:!1},aiSessionSendIdempotency:!1,aiSessionQueuePause:!1,aiSessionTimeline:{sessionReadAgents:[],turnReadAgents:[],liveItemAgents:[]},aiSessionConversationAttachments:{metadataAgents:[],contentAgents:[],uploadAgents:[],retentionSettings:!1,fileSizeLimitSettings:!1},aiSessionProviders:[]}})}).passthrough(),ms=c.z.object({nodeAgentUrl:c.z.string().trim().url().max(2048).refine(e=>{const t=new URL(e);return/^https?:$/.test(t.protocol)&&!t.username&&!t.password&&"/"===t.pathname&&!t.search&&!t.hash},"Node agent URL must be an HTTP(S) origin.")}).strict();function hs(e){const t={features:{appRuntime:!1,tty:!1,gui:!1,browser:!1,browserTunnel:!1,screenshots:!1,logs:!1,aiSessionWorkspaceSelection:!1,aiSessionWorkspaceCheckout:!1,aiSessionPersistenceSettings:!1,privateModelCatalog:!1,codexManagedSettings:!1,nodeAgentConnectionUpdate:!1,gitCliCredentialBroker:!1,gitCredentialProxy:!1,repositoryPathSearch:!1,repositoryWorktreeMoveToMain:!1,modelRelay:{protocols:[],streaming:!1},managedModelEnvironment:{openCodeConfig:!1},aiSessionSendIdempotency:!1,aiSessionQueuePause:!1,aiSessionTimeline:{sessionReadAgents:[],turnReadAgents:[],liveItemAgents:[]},aiSessionConversationAttachments:{metadataAgents:[],contentAgents:[],uploadAgents:[],retentionSettings:!1,fileSizeLimitSettings:!1},aiSessionProviders:[]}};if(!e||"object"!=typeof e||Array.isArray(e))return t;const n=e,i=n.features;if(!i||"object"!=typeof i||Array.isArray(i))return t;const s=i,o={appRuntime:!1,tty:!1,gui:!1,browser:!1,browserTunnel:!1,screenshots:!1,logs:!1,aiSessionWorkspaceSelection:!1,aiSessionWorkspaceCheckout:!1,aiSessionPersistenceSettings:!1,privateModelCatalog:!1,codexManagedSettings:!1,nodeAgentConnectionUpdate:!1,gitCliCredentialBroker:!1,gitCredentialProxy:!1,repositoryPathSearch:!1,repositoryWorktreeMoveToMain:!1,modelRelay:{protocols:[],streaming:!1},managedModelEnvironment:{openCodeConfig:!1},aiSessionSendIdempotency:!1,aiSessionQueuePause:!1,aiSessionTimeline:{sessionReadAgents:[],turnReadAgents:[],liveItemAgents:[]},aiSessionConversationAttachments:{metadataAgents:[],contentAgents:[],uploadAgents:[],retentionSettings:!1,fileSizeLimitSettings:!1},aiSessionProviders:[]};for(const e of["appRuntime","tty","gui","browser","browserTunnel","screenshots","logs","aiSessionWorkspaceSelection","aiSessionWorkspaceCheckout","aiSessionPersistenceSettings","privateModelCatalog","codexManagedSettings","nodeAgentConnectionUpdate","gitCliCredentialBroker","gitCredentialProxy","repositoryPathSearch","repositoryWorktreeMoveToMain","aiSessionSendIdempotency","aiSessionQueuePause"]){const t=c.z.boolean().safeParse(s[e]);t.success&&(o[e]=t.data)}const r=as.safeParse(s.aiSessionTimeline);r.success&&(o.aiSessionTimeline=r.data);const a=cs.safeParse(s.aiSessionConversationAttachments);a.success&&(o.aiSessionConversationAttachments=a.data);const d=Ji.safeParse(s.aiSessionProviders);d.success&&(o.aiSessionProviders=d.data);const l=ds.safeParse(s.modelRelay);l.success&&(o.modelRelay=l.data);const u=ls.safeParse(s.managedModelEnvironment);return u.success&&(o.managedModelEnvironment=u.data),ps.parse({...n,features:{...s,...o}})}function gs(e){return hs(e).features.modelRelay}function fs(e){return gs(e).protocols.length>0}function ys(e,t){return gs(e).protocols.includes(t)}function Is(e,t){return function(e){return hs(e).features.aiSessionProviders}(e).find(e=>e.agent===t)}function _s(e,t,n){if(void 0===n.modelUpstreamName)return n;if(Is(e,t)?.modelSelection?.stableIdentity)return n;const{modelUpstreamName:i,...s}=n;return s}const Es=c.z.string().trim().min(1).max(120).regex(/^[a-zA-Z0-9][a-zA-Z0-9_.:-]*$/),As=c.z.string().datetime(),Ts=c.z.record(c.z.string(),c.z.string()).default({}),ws=c.z.record(c.z.string(),c.z.string()).default({}),bs=c.z.object({encoding:c.z.enum(["utf8","base64"]),data:c.z.string()}).strict().superRefine((e,t)=>{if("base64"!==e.encoding)return;let n=!1;try{n=function(e){const t=[];for(let n=0;n<e.length;n+=24576)t.push(btoa(String.fromCharCode(...e.subarray(n,n+24576))));return t.join("")}(Vi(e.data))===e.data}catch{n=!1}n||t.addIssue({code:"custom",path:["data"],message:"Node tunnel binary body must use canonical base64 encoding."})}),Ns=/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$/,Ss=/^sha256:([a-fA-F0-9]{64})$/,vs=/^(?:localhost|[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?)(?::[1-9][0-9]{0,4})?$/,Os=/^[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*$/;function Rs(e){const t=e.trim();if(!t||t.length>512||t.includes("://")||/\s/.test(t))throw new Error("Docker image reference must not contain a URL scheme or whitespace.");const n=t.indexOf("@");if(-1!==n&&n!==t.lastIndexOf("@"))throw new Error("Docker image reference contains more than one digest separator.");const i=-1===n?void 0:t.slice(n+1),s=-1===n?t:t.slice(0,n),o=i?Ss.exec(i):void 0;if(i&&!o)throw new Error("Docker image digest must use sha256 followed by 64 hexadecimal characters.");const r=s.lastIndexOf("/"),a=s.lastIndexOf(":"),c=a>r,d=c?s.slice(a+1):void 0,l=c?s.slice(0,a):s;if(d&&!Ns.test(d))throw new Error("Docker image tag is invalid.");if(!d&&!o)throw new Error("Docker image reference must include an explicit tag or sha256 digest.");const u=l.split("/");if(!u.length||u.some(e=>!e))throw new Error("Docker image repository path is invalid.");const p=u.length>1&&(u[0].includes(".")||u[0].includes(":")||"localhost"===u[0]),m=p?u.slice(1):u;if(p&&!vs.test(u[0].toLowerCase()))throw new Error("Docker image registry host or port is invalid.");if(!m.length||m.some(e=>!Os.test(e)))throw new Error("Docker image repository names must be lowercase and use valid separators.");const h=u.map((e,t)=>p&&0===t?e.toLowerCase():e).join("/"),g=o?`sha256:${o[1].toLowerCase()}`:void 0;return`${h}${d?`:${d}`:""}${g?`@${g}`:""}`}function zs(e){const t=Rs(e),n=t.indexOf("@"),i=-1===n?void 0:t.slice(n+1),s=-1===n?t:t.slice(0,n),o=s.lastIndexOf("/"),r=s.lastIndexOf(":"),a=r>o;return{reference:t,repository:a?s.slice(0,r):s,tag:a?s.slice(r+1):void 0,digest:i}}const xs=c.z.string().trim().min(1).max(512).transform((e,t)=>{try{return Rs(e)}catch(e){return t.addIssue({code:"custom",message:e instanceof Error?e.message:String(e)}),c.z.NEVER}}),Cs=c.z.string().trim().transform((e,t)=>{const n=Ss.exec(e);return n?`sha256:${n[1].toLowerCase()}`:(t.addIssue({code:"custom",message:"Docker image digest must use sha256 followed by 64 hexadecimal characters."}),c.z.NEVER)}),ks=c.z.object({modelEntityIds:c.z.array(Es).max(64).transform(e=>[...new Set(e)]).optional(),codexModelHash:Es.nullable().optional(),claudeModelHash:Es.nullable().optional(),opencodeModelHash:Es.nullable().optional()}).strict().default({}),Ds=c.z.object({imageId:Es,tag:c.z.string().trim().min(1).max(128).regex(Ns).optional()}).strict(),Ls=c.z.discriminatedUnion("type",[c.z.object({type:c.z.literal("image"),imageSelection:Ds}).strict(),c.z.object({type:c.z.literal("template"),environmentTemplateId:Es}).strict()]),Ps=c.z.enum(["creating","ready","failed","deleting"]),Ms=c.z.enum(["linux","darwin","win32","freebsd","openbsd","aix","sunos","unknown"]),js=c.z.enum(["x64","arm64","arm","ia32","ppc64","s390x","riscv64","unknown"]),Us=c.z.object({code:c.z.string().trim().min(1).max(120),message:c.z.string().trim().min(1).max(2048),phase:c.z.enum(["validate","commit","inspect","security-check","persist","delete","recovery"]).optional()}).strict(),Fs=c.z.object({templateId:Es,nodeId:Es,imageId:Cs,name:c.z.string().trim().min(1).max(160),platform:Ms,architecture:js}).strict(),$s=c.z.enum(["data","agent-home","workspace"]),Hs=c.z.object({deleteVolumes:c.z.boolean()}).strict(),qs=c.z.object({role:$s,name:c.z.string().trim().min(1).max(255),mountPath:c.z.string().trim().startsWith("/").max(4096),status:c.z.enum(["deleted","retained","missing","failed"]),error:c.z.object({code:c.z.string().trim().min(1).max(120),message:c.z.string().trim().min(1).max(2048)}).strict().optional()}).strict(),Bs=c.z.object({instanceId:Es,containerDeleted:c.z.boolean(),completed:c.z.boolean(),deletedVolumes:c.z.array(qs),retainedVolumes:c.z.array(qs),volumeResults:c.z.array(qs)}).strict(),Vs={img_default:"market_taskhandoff_browser",img_codex:"market_taskhandoff_codex",img_ai:"market_taskhandoff_ai"};function Gs(e,t){if(e&&"object"==typeof e&&!Array.isArray(e)){const t=e;return{imageId:"string"==typeof t.imageId&&Vs[t.imageId]||t.imageId,..."string"==typeof t.tag?{tag:t.tag}:{}}}if("string"==typeof t)return{imageId:Vs[t]||t}}function Ks(e){if(!e||"object"!=typeof e||Array.isArray(e))return e;const t=e,{defaultImageId:n,origin:i,localizedNames:s,...o}=t;return{...o,defaultImageSelection:Gs(t.defaultImageSelection,n)}}const Ws=c.z.object({id:Es,name:c.z.string().trim().min(1).max(120),kind:c.z.enum(["tty","gui","web"]),source:c.z.enum(["builtin","custom"]),availability:c.z.enum(["available","missing-dependency"]),capabilities:c.z.object({automation:c.z.enum(["cdp"]).optional(),supportsCwdSelection:c.z.boolean().default(!1),supportsProfiles:c.z.boolean().default(!1)}).strict().default({supportsCwdSelection:!1,supportsProfiles:!1}),diagnosticCode:c.z.enum(["APP_EXECUTABLE_NOT_FOUND"]).optional()}).strict(),Ys=c.z.object({code:c.z.enum(["APP_CATALOG_INVALID"]),message:c.z.string().trim().min(1).max(500)}).strict(),Xs=c.z.object({items:c.z.array(Ws).max(256),observedAt:As,issues:c.z.array(Ys).max(32).default([])}).strict(),Js=c.z.object({id:Es,name:c.z.string().trim().min(1).max(160),sourceInstanceId:Es,nodeId:Es,imageId:Cs.optional(),internalTag:c.z.string().trim().min(1).max(512).optional(),platform:Ms.optional(),architecture:js.optional(),sizeBytes:c.z.number().int().nonnegative().optional(),status:Ps,error:Us.optional(),createdAt:As,updatedAt:As}).strict().superRefine((e,t)=>{if("ready"===e.status)for(const n of["imageId","internalTag","platform","architecture","sizeBytes"])void 0===e[n]&&t.addIssue({code:"custom",path:[n],message:`Ready environment template requires ${n}.`});"failed"!==e.status||e.error||t.addIssue({code:"custom",path:["error"],message:"Failed environment template requires an error diagnostic."})}),Qs=c.z.enum(["apt","dnf","brew","npm"]),Zs=c.z.enum(["user","passwordless-sudo","root"]),eo=c.z.object({platform:Ms,arch:js,installers:c.z.array(Qs).max(8),privilege:Zs,installerAccess:c.z.object({npmGlobalWritable:c.z.boolean().optional()}).strict().optional()}).strict(),to=c.z.enum(["installed","not-installed","broken","unsupported"]),no=c.z.enum(["recipe","bundled","external","none"]),io=c.z.object({code:c.z.enum(["BUNDLED","EXTERNALLY_MANAGED","ALREADY_INSTALLED","NOT_INSTALLED","UNSUPPORTED_PLATFORM","INSTALLER_UNAVAILABLE","INSTALLER_NOT_WRITABLE","INSUFFICIENT_PRIVILEGE","OPERATION_IN_PROGRESS"]),message:c.z.string().trim().min(1).max(500)}).strict(),so=c.z.enum(["update-available","up-to-date","unknown","unsupported"]),oo=c.z.object({status:so,installedVersion:c.z.string().trim().max(120).optional(),latestVersion:c.z.string().trim().max(120).optional(),checkedAt:As,reason:c.z.string().trim().max(500).optional()}).strict(),ro=oo.extend({appId:Es}).strict(),ao=c.z.object({id:Es,name:c.z.string().trim().min(1).max(120),kind:c.z.enum(["tty","gui","web"]),description:c.z.string().trim().max(500).optional(),state:to,managementSource:no,version:c.z.string().trim().max(120).optional(),canInstall:c.z.boolean(),canUninstall:c.z.boolean(),canUpdate:c.z.boolean().optional(),installReason:io.optional(),uninstallReason:io.optional(),updateReason:io.optional(),updateCheck:oo.optional(),activeJobId:Es.optional()}).strict(),co=c.z.enum(["install","uninstall","update"]),lo=c.z.enum(["queued","running","succeeded","failed","cancelled","interrupted"]),uo=c.z.object({current:c.z.number().finite().nonnegative().optional(),total:c.z.number().finite().positive().optional(),unit:c.z.string().trim().min(1).max(40).optional()}).strict().refine(e=>void 0===e.total||void 0===e.current||e.current<=e.total,{message:"Progress current must not exceed total.",path:["current"]}),po=c.z.object({executable:c.z.string().trim().min(1).max(4096),args:c.z.array(c.z.string().max(4096)).max(128)}).strict(),mo=c.z.object({code:c.z.string().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),message:c.z.string().trim().min(1).max(4096),retryable:c.z.boolean(),sessionIds:c.z.array(Es).max(64).optional()}).strict(),ho=c.z.object({id:Es,requestId:Es.optional(),appId:Es,operation:co,state:lo,phase:c.z.string().trim().min(1).max(120).optional(),progress:uo.optional(),command:po.optional(),logTail:c.z.string().max(32768).optional(),logTruncated:c.z.boolean().optional(),error:mo.optional(),requestedAt:As,startedAt:As.optional(),finishedAt:As.optional(),updatedAt:As}).strict(),go=c.z.object({streamId:Es,sequence:c.z.number().int().nonnegative(),capabilities:eo,apps:c.z.array(ao).max(256),activeJobs:c.z.array(ho).max(256),recentJobs:c.z.array(ho).max(256),observedAt:As}).strict();c.z.object({requestId:Es.optional()}).strict(),c.z.object({job:ho}).strict(),c.z.object({check:ro}).strict(),c.z.object({type:c.z.literal("app-management"),streamId:Es,sequence:c.z.number().int().nonnegative(),observedAt:As,job:ho.optional(),snapshot:go.optional()}).strict().refine(e=>void 0!==e.job||void 0!==e.snapshot,{message:"An app management event requires a job or snapshot."});const fo=c.z.object({component:c.z.enum(["control-plane","node-agent","controlled-instance"]),packageName:c.z.string().trim().max(160).optional(),packageVersion:c.z.string().trim().max(80).optional(),protocolVersion:es.optional(),buildId:c.z.string().trim().max(160).optional(),builtAt:c.z.string().trim().max(120).optional(),gitCommit:c.z.string().trim().max(120).optional(),imageRef:c.z.string().trim().max(512).optional(),imageDigest:c.z.string().trim().max(240).optional()}).strict();c.z.object({data:c.z.object({ok:c.z.literal(!0),role:c.z.literal("control-plane"),protocolVersion:es,build:fo.extend({component:c.z.literal("control-plane"),packageVersion:c.z.string().trim().min(1).max(80)}).loose(),serverTime:As}).loose()}).loose();const yo=c.z.enum(["stable","beta","alpha"]),Io=c.z.object({packageName:c.z.literal("@task-handoff/controlled-instance"),version:c.z.string().trim().min(1).max(80),platform:c.z.string().trim().min(1).max(40),arch:c.z.string().trim().min(1).max(40),formatVersion:c.z.number().int().positive(),launcherAbi:c.z.number().int().positive(),entrypoint:c.z.string().trim().min(1).max(512),sha256:c.z.string().regex(/^[a-f0-9]{64}$/)}).strict(),_o=c.z.object({code:c.z.enum(["INSTANCE_RUNTIME_VERSION_MISMATCH","INSTANCE_RUNTIME_ARTIFACT_UNAVAILABLE","INSTANCE_RUNTIME_ARTIFACT_INVALID","INSTANCE_RUNTIME_INSTALL_FAILED","INSTANCE_RUNTIME_RESTART_FAILED","INSTANCE_RUNTIME_VERIFICATION_FAILED","INSTANCE_BASE_RUNTIME_INCOMPATIBLE","NODE_UPDATE_PREFLIGHT_FAILED","NODE_UPDATE_FAILED","LEGACY_INSTANCE_UPDATE_RETIRED"]),message:c.z.string().trim().min(1).max(4096),expectedVersion:c.z.string().trim().min(1).max(80).optional(),actualVersion:c.z.string().trim().min(1).max(80).optional(),retryable:c.z.boolean().default(!1)}).strict(),Eo=c.z.object({desiredVersion:c.z.string().trim().min(1).max(80),actualVersion:c.z.string().trim().min(1).max(80).optional(),phase:c.z.enum(["pending","draining","installing","restarting","verifying","matched","failed"]),attempt:c.z.number().int().nonnegative().default(0),lastAttemptAt:As.optional(),matchedAt:As.optional(),error:_o.optional()}).strict(),Ao=c.z.object({runningInstanceCount:c.z.number().int().nonnegative(),stoppedInstanceCount:c.z.number().int().nonnegative(),activeInstanceCount:c.z.number().int().nonnegative(),restartInstanceCount:c.z.number().int().nonnegative(),runningInstanceIds:c.z.array(Es).max(1024).default([]),stoppedInstanceIds:c.z.array(Es).max(1024).default([]),activeInstanceIds:c.z.array(Es).max(1024).default([])}).strict(),To=c.z.object({phase:c.z.enum(["queued","updating-node","restarting-node","converging-instances","succeeded","degraded","failed"]),desiredVersion:c.z.string().trim().min(1).max(80),nodeVersion:c.z.string().trim().min(1).max(80).optional(),expectedInstanceIds:c.z.array(Es).max(1024).default([]),expectedInstanceCount:c.z.number().int().nonnegative(),matchedInstanceCount:c.z.number().int().nonnegative(),pendingInstanceCount:c.z.number().int().nonnegative(),failedInstanceCount:c.z.number().int().nonnegative(),deferredInstanceCount:c.z.number().int().nonnegative().default(0)}).strict(),wo=c.z.object({channel:yo.default("stable")}).strict(),bo=c.z.object({source:c.z.literal("npm"),channel:yo,currentVersion:c.z.string().trim().max(240).optional(),availableVersion:c.z.string().trim().min(1).max(240),artifactRef:c.z.string().trim().min(1).max(512).optional(),runtimeArtifacts:c.z.array(Io).default([]),impact:Ao,updateAvailable:c.z.boolean(),supported:c.z.boolean().default(!0),reason:c.z.string().trim().max(2048).optional(),checkedAt:As,preflightToken:c.z.string().trim().min(16).max(240).optional()}).strict(),No=c.z.object({id:Es,nodeId:Es,source:c.z.literal("npm"),channel:yo,fromVersion:c.z.string().trim().max(240).optional(),toVersion:c.z.string().trim().min(1).max(240),artifactRef:c.z.string().trim().min(1).max(512).optional(),runtimeArtifacts:c.z.array(Io).default([]),impact:Ao,rollout:To,status:c.z.enum(["queued","updating-node","restarting-node","converging-instances","succeeded","degraded","failed"]),error:_o.optional(),startedAt:As.optional(),completedAt:As.optional(),createdAt:As,updatedAt:As}).strict(),So=c.z.object({channel:yo,targetVersion:c.z.string().trim().min(1).max(240),preflightToken:c.z.string().trim().min(16).max(240)}).strict(),vo=c.z.object({type:c.z.enum(["branch","tag"]),name:c.z.string().trim().min(1).max(240)}).strict(),Oo=c.z.object({type:c.z.literal("commit"),commit:c.z.string().trim().regex(/^[0-9a-fA-F]{4,64}$/,"commit must be a hexadecimal Git object id")}).strict(),Ro=c.z.discriminatedUnion("type",[vo,Oo]),zo=c.z.object({type:c.z.enum(["none","ssh-key","https-token"]).default("none"),secretId:c.z.string().trim().min(1).max(120).optional()}).strict(),xo=c.z.object({depth:c.z.number().int().positive().max(1e5).optional(),submodules:c.z.boolean().default(!1),lfs:c.z.boolean().default(!1),subdirectory:c.z.string().trim().max(240).refine(e=>!e.startsWith("/")&&!e.split("/").some(e=>".."===e),"subdirectory must be a relative path within the repository").transform(e=>e.split("/").filter(e=>e&&"."!==e).join("/")).default("")}).strict();c.z.object({id:Es,name:c.z.string().trim().min(1).max(160),url:c.z.string().trim().min(1).max(2048),provider:c.z.string().trim().max(80).optional(),ref:Ro.default({type:"branch",name:"main"}),auth:zo.default({type:"none"}),clone:xo.default({submodules:!1,lfs:!1,subdirectory:""}),defaultImageSelection:Ds.optional(),labels:Ts,createdAt:As,updatedAt:As}).strict();const Co=c.z.enum(["user","builtin"]),ko=c.z.record(c.z.string().trim().min(2).max(35),c.z.string().trim().min(1).max(160)),Do=c.z.object({id:Es,nodeId:Es,name:c.z.string().trim().min(1).max(160),path:c.z.string().trim().min(1).max(4096),origin:Co.default("user"),localizedNames:ko.optional(),defaultImageSelection:Ds.optional(),labels:Ts,createdAt:As,updatedAt:As}).strict(),Lo=c.z.discriminatedUnion("type",[c.z.object({type:c.z.literal("git-repository"),repositoryId:Es.optional(),url:c.z.string().trim().min(1).max(2048),provider:c.z.string().trim().max(80).optional(),ref:Ro.default({type:"branch",name:"main"}),auth:zo.default({type:"none"}),clone:xo.default({submodules:!1,lfs:!1,subdirectory:""})}).strict(),c.z.object({type:c.z.literal("git-template"),url:c.z.string().trim().min(1).max(2048),templateId:c.z.string().trim().min(1).max(120).optional(),ref:Ro.default({type:"branch",name:"main"}),auth:zo.default({type:"none"}),clone:xo.default({submodules:!1,lfs:!1,subdirectory:""})}).strict(),c.z.object({type:c.z.literal("local-folder"),localFolderId:Es.optional(),path:c.z.string().trim().min(1).max(4096),ownerNodeId:Es.optional()}).strict()]),Po=c.z.object({mode:c.z.enum(["local-bind","git-clone","empty-volume","persistent-volume"]),path:c.z.string().trim().min(1).max(4096).default("/workspace"),volumeName:c.z.string().trim().max(240).optional(),readOnly:c.z.boolean().default(!1)}).strict(),Mo=c.z.enum(["codex","claude","opencode"]),jo=c.z.object({name:c.z.string().trim().min(1).max(240),upstreamName:c.z.string().trim().min(1).max(240).optional(),order:c.z.number().int().min(0).max(1e6).default(0)}).strict(),Uo=c.z.array(jo).max(256).default([]).superRefine((e,t)=>{const n=new Set;for(const[i,s]of e.entries())n.has(s.name)&&t.addIssue({code:"custom",path:[i,"name"],message:`Duplicate model name ${s.name}.`}),n.add(s.name)}),Fo=c.z.object({name:c.z.string().trim().min(1).max(240),upstreamName:c.z.string().trim().min(1).max(240),order:c.z.number().int().min(0).max(1e6).default(0)}).strict(),$o=c.z.array(Fo).max(64).superRefine((e,t)=>{const n=new Set;for(const[i,s]of e.entries())n.has(s.name)&&t.addIssue({code:"custom",path:[i,"name"],message:`Duplicate request mapping ${s.name}.`}),n.add(s.name)}),Ho=$o.default([]),qo=c.z.object({id:Es,name:c.z.string().trim().min(1).max(160),source:Lo,defaultImageSelection:Ds.optional(),defaultNodeId:Es.optional(),workspacePolicy:Po,labels:Ts,createdAt:As,updatedAt:As}).strict(),Bo=c.z.object({id:Es,name:c.z.string().trim().min(1).max(160),endpoint:c.z.string().trim().min(1).max(2048),key:c.z.string().trim().min(1).max(4096),model:c.z.string().trim().min(1).max(240),modelNames:Uo,mappings:Ho,protocols:c.z.array(xi).max(3).default([]),app:Mo,enabled:c.z.boolean().default(!0),order:c.z.number().int().min(0).max(1e6).default(0),labels:Ts,createdAt:As,updatedAt:As}).strict(),Vo=Bo,Go=Bo.omit({key:!0}).extend({keyPreview:c.z.string().trim().min(1).max(160),keySet:c.z.boolean(),revision:c.z.string().trim().min(1).max(160).optional()}).strict(),Ko=Go.extend({referenceCount:c.z.number().int().min(0)}).strict(),Wo=c.z.object({instanceId:Es,modelEntityIds:c.z.array(Es).max(64).transform(e=>[...new Set(e)]).optional(),codexModelHash:Es.optional(),claudeModelHash:Es.optional(),opencodeModelHash:Es.optional(),updatedAt:As}).strict().transform(e=>({...e,modelEntityIds:void 0!==e.modelEntityIds?e.modelEntityIds:[...new Set([e.codexModelHash,e.claudeModelHash,e.opencodeModelHash].filter(e=>Boolean(e)))]})),Yo=c.z.discriminatedUnion("type",[c.z.object({type:c.z.literal("control-plane"),name:Bo.shape.name,enabled:Bo.shape.enabled,order:Bo.shape.order,revision:c.z.string().trim().min(1).max(160).optional()}).strict(),c.z.object({type:c.z.literal("node"),nodeId:Es,name:Bo.shape.name,enabled:Bo.shape.enabled,order:Bo.shape.order,referenceCount:c.z.number().int().min(0),revision:c.z.string().trim().min(1).max(160).optional()}).strict()]),Xo=c.z.object({id:Es,model:Go,locations:c.z.array(Yo).min(1),referenceCount:c.z.number().int().min(0).default(0)}).strict(),Jo=c.z.object({nodeId:Es,code:c.z.string().trim().min(1).max(120),message:c.z.string().trim().min(1).max(2e3)}).strict();c.z.object({models:c.z.array(Xo),nodeDiagnostics:c.z.array(Jo).default([]),updatedAt:As}).strict();const Qo=Bo.omit({id:!0,createdAt:!0,updatedAt:!0}).extend({mappings:$o.optional()}).strict(),Zo=Qo.partial().strict(),er=Bo,tr=c.z.enum(["synced","pending","unsupported","error"]),nr=c.z.object({nodeId:Es,state:tr,code:c.z.string().trim().min(1).max(120).optional(),message:c.z.string().trim().min(1).max(2e3).optional()}).strict();c.z.object({model:Go,locations:c.z.array(nr).default([])}).strict();const ir=c.z.object({targetModelId:Es}).strict();c.z.object({merged:c.z.literal(!0),reassignedInstances:c.z.array(Es).default([])}).strict();const sr=c.z.object({nodeId:Es,merged:c.z.boolean(),reassignedInstances:c.z.array(Es).default([]),code:c.z.string().trim().min(1).max(120).optional(),message:c.z.string().trim().min(1).max(2e3).optional()}).strict();c.z.object({modelId:Es,targetModelId:Es,merged:c.z.boolean(),locations:c.z.array(sr).default([])}).strict();const or=c.z.object({modelSelection:ks,modelEntityIds:c.z.array(Es).max(64).transform(e=>[...new Set(e)]).optional(),codexModelHash:Es.optional(),claudeModelHash:Es.optional(),opencodeModelHash:Es.optional()}).strict().transform(e=>({...e,modelEntityIds:e.modelEntityIds||e.modelSelection.modelEntityIds||[...new Set([e.codexModelHash,e.claudeModelHash,e.opencodeModelHash].filter(e=>Boolean(e)))]}));function rr(e,t,n){if(!Array.isArray(e))return e;const i=new Set;return e.flatMap((e,s)=>{if(!e||"object"!=typeof e||Array.isArray(e))return[e];const o=e;for(const e of Object.keys(o))"name"!==e&&"upstreamName"!==e&&"order"!==e&&n?.({field:`${t}[${s}].${e}`});const r="string"==typeof o.name?o.name.trim():void 0,a="string"==typeof o.upstreamName?o.upstreamName.trim():void 0;if(r){if(i.has(r))return n?.({field:`${t}[${s}].name`}),[];i.add(r)}return[{...r?{name:r}:{name:o.name},...a?{upstreamName:a}:{},order:o.order}]})}function ar(e,t,n={}){const i=(e?.length?e:t?.trim()?[{name:t.trim(),order:100}]:[]).map(e=>({name:e.name.trim(),upstreamName:e.upstreamName?.trim()||e.name.trim(),order:e.order})).sort((e,t)=>e.order-t.order||e.name.localeCompare(t.name));return!1===n.renumber?i:i.map((e,t)=>({...e,order:100*(t+1)}))}function cr(e){return e.map(e=>({name:e.name,...e.upstreamName&&e.upstreamName!==e.name?{upstreamName:e.upstreamName}:{},order:e.order}))}function dr(e,t={}){const n=(e??[]).map(e=>({name:e.name.trim(),upstreamName:e.upstreamName.trim(),order:e.order})).sort((e,t)=>e.order-t.order||e.name.localeCompare(t.name));return!1===t.renumber?n:n.map((e,t)=>({...e,order:100*(t+1)}))}function lr(e){const t=Mo.parse(e.app),n=ar(e.modelNames,e.model),i=dr(e.mappings),s=e.protocols?.length?e.protocols:function(e){return"claude"===e?["anthropic-messages"]:"opencode"===e?["openai-chat-completions"]:["openai-responses"]}(t),o={algorithm:"model-content-revision-v1",app:t,endpoint:Bo.shape.endpoint.parse(e.endpoint),key:Bo.shape.key.parse(e.key),model:Bo.shape.model.parse(e.model),modelNames:n.map(e=>({name:e.name,upstreamName:e.upstreamName,order:e.order})),protocols:[...new Set(s)].sort(),...i.length?{mappings:i.map(e=>({name:e.name,upstreamName:e.upstreamName,order:e.order}))}:{}};return`mdlr_${r=JSON.stringify(o),Array.from(qi(r),e=>e.toString(16).padStart(2,"0")).join("")}`;var r}const ur=Date.UTC(2026,0,1),pr="0123456789abcdefghjkmnpqrstvwxyz",mr=new RegExp(`^mdl_[${pr}]{13}$`);function hr(e,t){const n=[];let i=e;for(;i>0n;)n.unshift(pr[Number(i%32n)]),i/=32n;return`${"0".repeat(Math.max(0,t-n.length))}${n.join("")}`}let gr;function fr(e,t=Date.now()){const n=BigInt(Math.max(0,t-ur))&(1n<<41n)-1n,i=function(e){for(gr?.timestamp!==e&&(gr={timestamp:e,random:new Set});;){const e=Bi(3),t=BigInt(e[0]<<16|e[1]<<8|e[2])>>1n;if(!gr.random.has(t))return gr.random.add(t),t}}(n);return`${e}_${hr(n<<23n|i,13)}`}function yr(e=Date.now()){return fr("mdl",e)}function Ir(e){return mr.test(e)}function _r(e){const t=qi(`task-handoff:model-entity-migration:v1:${e}`);let n=0n;for(const e of t.subarray(0,8))n=n<<8n|BigInt(e);return`mdl_${hr(n,13)}`}const Er=c.z.enum(["market","custom"]),Ar=c.z.enum(["active","deprecated","yanked"]),Tr=c.z.discriminatedUnion("kind",[c.z.object({kind:c.z.literal("builtin"),key:c.z.string().trim().min(1).max(120)}).strict(),c.z.object({kind:c.z.literal("remote"),url:c.z.string().trim().url().max(2048),mediaType:c.z.enum(["image/png","image/jpeg","image/webp"]).optional(),digest:Cs.optional()}).strict()]),wr=c.z.array(c.z.string().trim().min(1).max(80)).default([]),br=c.z.array(c.z.string().trim().min(1).max(120)).default([]),Nr=c.z.record(c.z.string().trim().min(2).max(35),c.z.string().trim().min(1).max(4096)),Sr=c.z.object({os:c.z.string().trim().min(1).max(40),architecture:c.z.string().trim().min(1).max(40),digest:Cs.optional(),downloadSizeBytes:c.z.number().int().positive().optional(),unpackedSizeBytes:c.z.number().int().positive().optional()}).strict(),vr=c.z.object({name:c.z.string().trim().min(1).max(128).regex(Ns),version:c.z.string().trim().min(1).max(160).optional(),reference:xs,manifestDigest:Cs.optional(),publishedAt:As.optional(),platforms:c.z.array(Sr).default([]),status:Ar.default("active")}).strict(),Or=c.z.object({id:Es,publisher:c.z.string().trim().min(1).max(160),slug:c.z.string().trim().min(1).max(160),name:c.z.string().trim().min(1).max(160),description:c.z.string().trim().min(1).max(4096),localizedDescriptions:Nr.optional(),cover:Tr.optional(),repository:c.z.string().trim().min(1).max(512),defaultTag:c.z.string().trim().min(1).max(128).regex(Ns),tags:c.z.array(vr).min(1),capabilities:wr,optionalApps:br,defaultEnv:ws,labels:Ts,status:Ar.default("active")}).strict().superRefine((e,t)=>{e.tags.some(t=>t.name===e.defaultTag)||t.addIssue({code:"custom",path:["defaultTag"],message:"Market defaultTag must identify one of the image tags."})});c.z.object({protocolVersion:es,catalogId:Es,revision:c.z.string().trim().min(1).max(240),source:c.z.enum(["embedded","remote","cache"]),generatedAt:As,expiresAt:As.optional(),items:c.z.array(Or)}).strict(),c.z.object({source:c.z.enum(["embedded","remote","cache"]),state:c.z.enum(["ready","refreshing","stale","failed"]),revision:c.z.string().trim().min(1).max(240),updatedAt:As,error:c.z.string().trim().max(4096).optional()}).strict();const Rr=c.z.object({id:Es,origin:c.z.literal("custom"),name:c.z.string().trim().min(1).max(160),description:c.z.string().trim().max(4096).optional(),localizedDescriptions:Nr.optional(),cover:Tr.optional(),reference:xs,repository:c.z.string().trim().min(1).max(512),tag:c.z.string().trim().min(1).max(128).regex(Ns).optional(),pullPolicy:c.z.literal("if-not-present").default("if-not-present"),capabilities:wr,optionalApps:br,defaultEnv:ws,labels:Ts,createdAt:As,updatedAt:As}).strict(),zr=c.z.object({name:c.z.string().trim().min(1).max(128).regex(Ns),version:c.z.string().trim().min(1).max(160).optional(),reference:xs,manifestDigest:Cs.optional(),status:Ar}).strict(),xr=c.z.object({id:Es,origin:Er,name:c.z.string().trim().min(1).max(160),description:c.z.string().trim().max(4096).optional(),localizedDescriptions:Nr.optional(),cover:Tr,repository:c.z.string().trim().min(1).max(512),tag:c.z.string().trim().min(1).max(128).regex(Ns).optional(),availableTags:c.z.array(zr),reference:xs,digest:Cs.optional(),downloadSizeBytes:c.z.number().int().positive().optional(),unpackedSizeBytes:c.z.number().int().positive().optional(),capabilities:wr,optionalApps:br,defaultEnv:ws,labels:Ts,readOnly:c.z.boolean(),lifecycleStatus:Ar.optional(),market:c.z.object({catalogId:Es,catalogRevision:c.z.string().trim().min(1).max(240),publisher:c.z.string().trim().min(1).max(160),version:c.z.string().trim().min(1).max(160).optional()}).strict().optional()}).strict(),Cr=c.z.object({id:Es,origin:Er,name:c.z.string().trim().min(1).max(160),description:c.z.string().trim().max(4096).optional(),localizedDescriptions:Nr.optional(),cover:Tr.optional(),repository:c.z.string().trim().min(1).max(512),tag:c.z.string().trim().min(1).max(128).regex(Ns).optional(),requestedReference:xs,resolvedDigest:Cs.optional(),resolvedReference:xs.optional(),downloadSizeBytes:c.z.number().int().positive().optional(),pullPolicy:c.z.literal("if-not-present").default("if-not-present"),capabilities:wr,optionalApps:br,defaultEnv:ws,labels:Ts,market:c.z.object({catalogId:Es,catalogRevision:c.z.string().trim().min(1).max(240),publisher:c.z.string().trim().min(1).max(160),version:c.z.string().trim().min(1).max(160).optional()}).strict().optional(),createdAt:As,updatedAt:As}).strict(),kr=c.z.object({phase:c.z.enum(["checking-image","pulling-image","resolving-image","ready","failed"]),requestedReference:xs,generation:c.z.number().int().nonnegative().default(0),error:c.z.string().trim().max(4096).optional(),startedAt:As,updatedAt:As}).strict(),Dr="image.pull.terminal.output",Lr="image.pull.terminal.finished",Pr=c.z.object({instanceId:Es,generation:c.z.number().int().nonnegative(),requestedReference:xs,sequence:c.z.number().int().nonnegative(),observedAt:As}).strict(),Mr=Pr.extend({data:c.z.string().min(1).max(65536),replay:c.z.boolean().optional()}).strict(),jr=Pr.extend({outcome:c.z.enum(["succeeded","failed"])}).strict();Pr.extend({status:c.z.enum(["connecting","pulling","extracting","complete","failed"]),layers:c.z.object({total:c.z.number().int().nonnegative(),completed:c.z.number().int().nonnegative(),downloaded:c.z.number().int().nonnegative(),downloading:c.z.number().int().nonnegative(),extracting:c.z.number().int().nonnegative()}).strict(),bytes:c.z.object({current:c.z.number().finite().nonnegative(),total:c.z.number().finite().positive()}).strict().optional(),percent:c.z.number().finite().min(0).max(100).optional(),message:c.z.string().trim().min(1).max(500),terminalTail:c.z.string().max(262144).optional(),terminalTruncated:c.z.boolean().optional()}).strict();const Ur=c.z.enum(["pending","cloning","checking-out","submodules","lfs","finalizing","ready","failed"]),Fr=c.z.object({phase:Ur,remoteUrl:c.z.string().trim().min(1).max(2048),generation:c.z.number().int().nonnegative().default(0),error:c.z.string().trim().max(4096).optional(),startedAt:As,updatedAt:As}).strict(),$r="git.provisioning.terminal.output",Hr="git.provisioning.terminal.finished",qr=c.z.object({instanceId:Es,generation:c.z.number().int().nonnegative(),remoteUrl:c.z.string().trim().min(1).max(2048),sequence:c.z.number().int().nonnegative(),observedAt:As}).strict(),Br=qr.extend({data:c.z.string().min(1).max(65536),replay:c.z.boolean().optional()}).strict(),Vr=qr.extend({outcome:c.z.enum(["succeeded","failed"])}).strict();qr.extend({status:c.z.enum(["connecting","cloning","checking-out","submodules","lfs","finalizing","complete","failed"]),objects:c.z.object({received:c.z.number().int().nonnegative(),total:c.z.number().int().nonnegative()}).strict().optional(),bytes:c.z.object({current:c.z.number().finite().nonnegative(),total:c.z.number().finite().positive()}).strict().optional(),percent:c.z.number().finite().min(0).max(100).optional(),message:c.z.string().trim().min(1).max(500),terminalTail:c.z.string().max(262144).optional(),terminalTruncated:c.z.boolean().optional()}).strict();const Gr=c.z.discriminatedUnion("kind",[c.z.object({kind:c.z.literal("direct")}).strict(),c.z.object({kind:c.z.literal("control-plane-proxy"),proxyId:Es,proxyBindingId:Es,targetNodeId:Es}).strict()]),Kr=c.z.object({pingRttMs:c.z.number().nonnegative().optional(),pingRttP95Ms:c.z.number().nonnegative().optional(),consecutiveReconnects:c.z.number().int().nonnegative(),nextRetryAt:As.optional()}).strict();c.z.object({nodeId:Es,inviteId:Es.optional()}).strict(),c.z.discriminatedUnion("status",[c.z.object({id:Es,status:c.z.literal("pending")}).strict(),c.z.object({id:Es,status:c.z.literal("completed"),nodeId:Es}).strict()]);const Wr=c.z.object({reachability:c.z.enum(["unknown","reachable","unreachable"]),bindingStatus:c.z.enum(["unknown","active","revoked"]),bindingRevision:c.z.number().int().positive().optional(),streamId:c.z.string().trim().min(1).max(160).optional(),revision:c.z.number().int().nonnegative().optional(),observedAt:As.optional(),target:Kn.optional(),lastError:Hn.optional(),updatedAt:As}).strict(),Yr=c.z.object({id:Es,name:c.z.string().trim().min(1).max(160),connectionMode:c.z.enum(["local-ipc","local-loopback","direct-http","reverse-wss","control-plane-proxy"]).default("direct-http"),connectionPath:Gr.default({kind:"direct"}),connectionEnabled:c.z.boolean().default(!0),auth:c.z.object({mode:c.z.enum(["local-static-key","paired-hmac","proxy-binding"]).default("local-static-key"),keyId:Es.optional(),secret:c.z.string().trim().max(4096).optional(),pairedAt:As.optional(),pairing:c.z.object({status:c.z.enum(["pending","paired","expired"]).default("pending"),joinToken:c.z.string().trim().max(4096).optional(),expiresAt:As.optional()}).strict().optional()}).strict().default({mode:"local-static-key"}),endpoint:c.z.string().trim().max(2048).optional(),controlEndpoint:c.z.string().trim().max(2048).optional(),containerEndpoint:c.z.string().trim().max(2048).optional(),publicWebBase:c.z.string().trim().max(2048).optional(),status:c.z.enum(["unknown","online","offline","degraded"]).default("unknown"),health:c.z.enum(["unknown","ok","degraded","failed"]).default("unknown"),capabilities:c.z.record(c.z.string(),c.z.unknown()).default({}),proxyState:Wr.optional(),appInventory:Xs.optional(),labels:Ts,lastSeenAt:As.optional(),createdAt:As,updatedAt:As}).strict().superRefine((e,t)=>{"control-plane-proxy"===e.connectionPath.kind&&"control-plane-proxy"!==e.connectionMode&&t.addIssue({code:"custom",path:["connectionPath"],message:"Control-plane proxy paths require control-plane-proxy connection mode."}),"control-plane-proxy"===e.connectionMode&&"control-plane-proxy"!==e.connectionPath.kind&&t.addIssue({code:"custom",path:["connectionPath"],message:"Control-plane proxy nodes require a control-plane-proxy connection path."})});c.z.object({nodeId:Es,status:c.z.enum(["unknown","online","offline","degraded"]),health:c.z.enum(["unknown","ok","degraded","failed"]),lastSeenAt:As.nullable(),connectionPhase:c.z.enum(["connecting","handshaking","healthy","reconnecting","suspect","offline"]).nullable(),connectionDiagnostics:Kr.nullable(),proxyState:Wr.nullable()}).strict();const Xr=["docker","kubernetes","local","wsl"],Jr=c.z.enum(Xr),Qr=c.z.object({id:Es,nodeId:Es,name:c.z.string().trim().min(1).max(160),type:Jr,status:c.z.enum(["unknown","online","offline","degraded"]).default("unknown"),accessStrategy:c.z.enum(["node-proxy","direct-port","kubernetes-ingress","kubernetes-port-forward"]).default("node-proxy"),capabilities:c.z.record(c.z.string(),c.z.unknown()).default({}),labels:Ts,createdAt:As,updatedAt:As}).strict();c.z.array(c.z.unknown()).transform(e=>e.filter(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return!0;const t=e.type;return!("string"==typeof t&&!function(e){return"string"==typeof e&&Xr.includes(e)}(t))})).pipe(c.z.array(Qr));const Zr="bundled-runtime-artifact",ea=c.z.enum(["none","process","distro","container","vm"]),ta=c.z.object({requiresImage:c.z.boolean().default(!1),artifactKind:c.z.enum(["none",Zr]).default(Zr),isolation:ea.default("distro"),supportsControlledInstanceApi:c.z.boolean().default(!0),supportsContainerLifecycle:c.z.boolean().default(!1),supportsAppSessions:c.z.boolean().default(!0),supportsHostSessions:c.z.boolean().default(!1),workspaceProvisioning:c.z.object({git:c.z.boolean().default(!1),localFolder:c.z.boolean().default(!1)}).strip().default({git:!1,localFolder:!1}),baseProfiles:c.z.array(c.z.string().trim().min(1).max(120)).max(8).default([])}).strip();function na(e={}){return ta.parse(e)}const ia=c.z.object({instanceId:Es,runtimeKind:c.z.literal("docker"),state:c.z.enum(["pending","available","stopped","unavailable"]),sampledAt:As,cpu:c.z.object({usagePercent:c.z.number().nonnegative()}).strict().optional(),memory:c.z.object({usageBytes:c.z.number().nonnegative(),limitBytes:c.z.number().nonnegative().optional(),usagePercent:c.z.number().nonnegative().optional()}).strict().optional(),network:c.z.object({rxBytes:c.z.number().nonnegative(),txBytes:c.z.number().nonnegative()}).strict().optional(),blockIo:c.z.object({readBytes:c.z.number().nonnegative(),writeBytes:c.z.number().nonnegative()}).strict().optional(),pids:c.z.number().int().nonnegative().optional(),error:c.z.string().trim().max(2048).optional()}).strict(),sa=c.z.object({status:c.z.enum(["healthy","congested","recovering"]),activeOutputs:c.z.number().int().nonnegative(),bufferedBytes:c.z.number().int().nonnegative(),peakBufferedBytes:c.z.number().int().nonnegative(),coalescedEvents:c.z.number().int().nonnegative(),oversizedEvents:c.z.number().int().nonnegative().optional(),peakEventBytes:c.z.number().int().nonnegative().optional(),congestedSince:As.optional(),lastCongestedAt:As.optional()}).strip();c.z.object({ok:c.z.boolean().optional(),role:c.z.string().optional(),nodeId:Es.optional(),hostname:c.z.string().trim().min(1).max(255).optional(),platform:Ms.optional(),arch:js.optional(),protocolVersion:es.optional(),capabilities:$i.optional(),build:fo.strip().optional(),process:c.z.object({pid:c.z.number().int().positive(),startIdentity:c.z.string().trim().min(1).optional()}).strip().optional(),listener:c.z.object({host:c.z.string().trim().min(1),port:c.z.number().int().min(1).max(65535)}).strip().optional(),instanceProxy:c.z.object({requests:c.z.number().int().nonnegative(),active:c.z.number().int().nonnegative(),completed:c.z.number().int().nonnegative(),aborted:c.z.number().int().nonnegative(),limitRejected:c.z.number().int().nonnegative(),responseBytes:c.z.number().nonnegative(),totalDurationMs:c.z.number().nonnegative(),maxResponseBytes:c.z.number().int().nonnegative()}).partial().strip().optional(),eventTransport:sa.optional(),serverTime:As.optional()}).strip();const oa=c.z.object({bindScope:c.z.enum(["loopback","all-ipv4"]),port:c.z.number().int().min(1).max(65535)}).strict(),ra=oa.extend({host:c.z.enum(["127.0.0.1","0.0.0.0"]),status:c.z.enum(["listening","error"]),source:c.z.enum(["bootstrap","persisted"]),error:c.z.string().trim().max(2048).optional()}).strict(),aa=oa,ca=c.z.enum(["passthrough","reject"]),da=c.z.object({enabled:c.z.boolean(),unknownModelPolicy:ca.optional()}).strict();c.z.object({enabled:c.z.boolean(),unknownModelPolicy:ca.optional(),source:c.z.enum(["default","persisted"])}).strip();const la=da;c.z.object({nodeId:Es,joinToken:c.z.string().trim().min(1),expiresAt:As}).passthrough(),c.z.object({nodeId:Es,keyId:Es,secret:c.z.string().regex(/^[A-Za-z0-9_-]{32,128}$/),pairedAt:As}).strict();const ua=c.z.object({id:Es,keyId:Es,name:c.z.string().trim().min(1).max(160).optional(),pairedAt:As,updatedAt:As,current:c.z.boolean()}).passthrough();c.z.object({keyId:Es,revoked:c.z.literal(!0),revokedAt:As}).strict(),c.z.object({id:Es,pairingKeyId:Es,url:c.z.string().trim().min(1).max(2048),name:c.z.string().trim().min(1).max(160).optional(),enabled:c.z.boolean(),createdAt:As,updatedAt:As,status:c.z.enum(["disabled","connecting","connected","reconnecting","failed"]),pingRttMs:c.z.number().nonnegative().optional(),pingRttP95Ms:c.z.number().nonnegative().optional(),consecutiveReconnects:c.z.number().int().nonnegative().optional(),nextRetryAt:As.optional(),lastConnectedAt:As.optional(),lastDisconnectedAt:As.optional(),error:c.z.string().optional()}).passthrough(),c.z.object({pairing:ua,connection:c.z.object({id:Es,pairingKeyId:Es,url:c.z.string().trim().min(1).max(2048),name:c.z.string().trim().min(1).max(160).optional(),enabled:c.z.boolean(),createdAt:As,updatedAt:As}).passthrough(),tunnel:c.z.object({status:c.z.enum(["disabled","saved","connecting","connected","failed"]),error:c.z.string().trim().max(2048).optional()}).passthrough()}).passthrough(),c.z.object({deleted:c.z.boolean().optional()}).passthrough();const pa=c.z.object({repository:c.z.string().trim().optional(),tag:c.z.string().trim().optional(),id:c.z.string().trim(),createdSince:c.z.string().trim().optional(),size:c.z.string().trim().optional(),sizeBytes:c.z.number().int().nonnegative().optional(),reference:c.z.string().trim().min(1),repoDigests:c.z.array(c.z.string().trim().min(1).max(512)).default([])}).passthrough();c.z.object({image:xr,status:c.z.enum(["available","pull-required","unknown"]),localImage:pa.optional(),localSizeBytes:c.z.number().int().nonnegative().optional(),downloadSizeBytes:c.z.number().int().positive().optional(),unpackedSizeBytes:c.z.number().int().positive().optional(),error:c.z.string().trim().max(2048).optional()}).strict();const ma=c.z.lazy(()=>c.z.object({name:c.z.string().trim().min(1),path:c.z.string().trim().min(1).max(4096),children:c.z.array(ma)}).passthrough());c.z.object({kind:c.z.enum(["home","root"]),name:c.z.string().trim().min(1),path:c.z.string().trim().min(1).max(4096)}).passthrough(),c.z.object({status:c.z.number().int().min(100).max(599).optional(),headers:c.z.record(c.z.string(),c.z.string()).optional(),bodyBase64:c.z.string().optional()}).passthrough();const ha=c.z.object({strategy:c.z.enum(["node-proxy","direct-port","kubernetes-ingress","kubernetes-port-forward"]).default("node-proxy"),web:c.z.string().trim().max(2048).optional(),api:c.z.string().trim().max(2048).optional(),vnc:c.z.string().trim().max(2048).optional(),tty:c.z.string().trim().max(2048).optional(),logs:c.z.string().trim().max(2048).optional(),status:c.z.enum(["unknown","reachable","endpoint-unreachable"]).default("unknown")}).strict(),ga=c.z.object({...ha.shape}).strict(),fa=c.z.object({strategy:c.z.enum(["control-plane-proxy","direct-port","node-proxy","kubernetes-ingress","kubernetes-port-forward"]).default("control-plane-proxy"),web:c.z.string().trim().max(2048).optional(),api:c.z.string().trim().max(2048).optional(),ws:c.z.string().trim().max(2048).optional(),status:c.z.enum(["unknown","reachable","endpoint-unreachable"]).default("unknown")}).strict().default({strategy:"control-plane-proxy",status:"unknown"}),ya=c.z.object({mode:c.z.enum(["local-bind","git-clone","empty-volume","persistent-volume"]).optional(),status:c.z.enum(["unknown","pending","ready","failed"]).default("unknown"),path:c.z.string().trim().max(4096).optional(),resolvedCommit:c.z.string().trim().max(120).optional(),error:c.z.string().trim().max(2048).optional(),gitProvisioning:Fr.optional()}).passthrough(),Ia=c.z.object({id:Es,name:c.z.string().trim().min(1).max(160),projectId:Es.optional(),source:Lo,sourceSnapshot:c.z.record(c.z.string(),c.z.unknown()).default({}),modelSelection:ks,nodeId:Es,runtimeId:Es,imageSelection:Ds.optional(),environmentSource:Ls.optional(),environmentTemplateOrigin:Fs.optional(),imageSnapshot:Cr.optional(),imageProvisioning:kr.optional(),stateRevision:c.z.number().int().min(0).default(0),processIncarnationId:c.z.string().trim().min(1).max(120).optional(),status:c.z.enum(["created","provisioning","starting","registering","registered","running","stopping","stopped","deleting","failed","unhealthy"]).default("created"),health:c.z.enum(["unknown","ok","degraded","failed"]).default("unknown"),connectionStatus:c.z.enum(["unknown","online","offline","endpoint-unreachable"]).default("unknown"),agentStatus:c.z.enum(["unknown","online","offline"]).default("unknown"),targetStatus:c.z.enum(["unknown","reachable","endpoint-unreachable"]).default("unknown"),uiAccessStatus:c.z.enum(["unknown","reachable","endpoint-unreachable"]).default("unknown"),controlMode:c.z.enum(["standalone","controlled"]).default("controlled"),protocolVersion:es.optional(),instanceVersion:c.z.string().trim().max(80).optional(),build:fo.optional(),runtimeVersion:Eo.optional(),ready:c.z.boolean().default(!1),capabilities:ps.default(rs),appInventory:Xs.optional(),config:c.z.object({autoImportAgentConfigs:c.z.boolean().default(!0),codexConfigEnabled:c.z.boolean().default(!0),codexHomeMode:c.z.enum(["default","taskhandoff"]).default("taskhandoff"),defaultCodexPermissionMode:Tt.default("ask"),codexSettings:os.optional(),aiSessionHistoryLimit:c.z.number().int().min(1).max(en).default(50),aiSessionAttachmentRetentionDays:c.z.number().int().min(0).max(tn).default(30),aiSessionMaxFileAttachmentBytes:c.z.number().int().positive().max(De).default(ke)}).strict().default({autoImportAgentConfigs:!0,codexConfigEnabled:!0,codexHomeMode:"taskhandoff",defaultCodexPermissionMode:"ask",aiSessionHistoryLimit:50,aiSessionAttachmentRetentionDays:30,aiSessionMaxFileAttachmentBytes:ke}),workspace:ya.default({status:"unknown"}),target:ha.default({strategy:"direct-port",status:"unknown"}),access:fa,apps:c.z.object({runningCount:c.z.number().int().min(0).default(0),problemCount:c.z.number().int().min(0).default(0),updatedAt:As.optional(),revision:c.z.number().int().min(0).optional()}).strict().default({runningCount:0,problemCount:0}),aiSessions:rn.default(()=>({runningCount:0,waitingCount:0,staleCount:0,sessions:[],updatedAt:(new Date).toISOString()})),triggers:c.z.object({enabledCount:c.z.number().int().min(0).default(0),runningCount:c.z.number().int().min(0).default(0),errorCount:c.z.number().int().min(0).default(0),configs:c.z.array(c.z.object({configHash:c.z.string().trim().min(1),config:vn,deployments:c.z.array(Rn).default([]),runtime:c.z.array(zn).default([])}).strict()).default([]),recentRuns:c.z.array(xn).default([])}).strict().optional(),runtime:c.z.object({kind:c.z.string().trim().max(80).optional(),containerName:c.z.string().trim().max(240).optional(),containerId:c.z.string().trim().max(240).optional(),workspacePath:c.z.string().trim().max(4096).optional(),pid:c.z.number().int().positive().optional(),port:c.z.number().int().positive().max(65535).optional(),labels:c.z.record(c.z.string(),c.z.string()).default({})}).strict().default({labels:{}}),registrationToken:c.z.string().trim().min(1).max(240).optional(),lastHeartbeatAt:As.optional(),createdAt:As,updatedAt:As}).strict(),_a=c.z.object({autoImportAgentConfigs:c.z.boolean().optional(),codexConfigEnabled:c.z.boolean().optional(),codexHomeMode:c.z.enum(["default","taskhandoff"]).optional(),defaultCodexPermissionMode:Tt.optional(),codexSettings:os.optional(),aiSessionHistoryLimit:c.z.number().int().min(1).max(en).optional(),aiSessionAttachmentRetentionDays:c.z.number().int().min(0).max(tn).optional(),aiSessionMaxFileAttachmentBytes:c.z.number().int().positive().max(De).optional()}).strict();c.z.object({name:Ia.shape.name.optional(),config:_a.optional(),modelSelection:Ia.shape.modelSelection.unwrap().optional()}).strict(),c.z.object({id:Ia.shape.id.optional(),name:Ia.shape.name.optional(),projectId:Ia.shape.projectId,source:Lo.optional(),sourceSnapshot:c.z.record(c.z.string(),c.z.unknown()).optional(),nodeId:Ia.shape.nodeId.optional(),runtimeId:Ia.shape.runtimeId.optional(),environmentSource:Ls.optional(),imageSelection:Ia.shape.imageSelection,config:_a.optional(),modelSelection:Ia.shape.modelSelection.optional(),gitCredentialRetention:ni.optional(),start:c.z.boolean().default(!1)}).strict().superRefine((e,t)=>{e.environmentSource&&e.imageSelection&&t.addIssue({code:"custom",path:["environmentSource"],message:"environmentSource and imageSelection are mutually exclusive."}),e.gitCredentialRetention&&"local-folder"===e.source?.type&&t.addIssue({code:"custom",path:["gitCredentialRetention"],message:"Git credential retention requires a Git source."})});const Ea=c.z.object({status:c.z.enum(["not-requested","started","failed"]),error:c.z.object({code:c.z.string().trim().min(1).max(120),message:c.z.string().trim().min(1).max(2048)}).strict().optional()}).strict();c.z.object({...Ia.omit({registrationToken:!0}).shape,startOutcome:Ea}).strict();const Aa=c.z.union([Ia.transform(e=>({instance:e,gitWorkspaceProvisioningOperationId:void 0})),c.z.object({instance:Ia,gitWorkspaceProvisioningOperationId:Es.optional()}).strict()]);c.z.preprocess(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return e;const t=e;return t.instance&&"object"==typeof t.instance&&!Array.isArray(t.instance)?{instance:Na(t.instance),..."string"==typeof t.gitWorkspaceProvisioningOperationId?{gitWorkspaceProvisioningOperationId:t.gitWorkspaceProvisioningOperationId}:{}}:Na(t)},Aa);const Ta="instance.lifecycle.snapshot",wa=c.z.object({instanceId:Ia.shape.id,revision:c.z.number().int().min(0),updatedAt:As,status:Ia.shape.status.unwrap(),health:Ia.shape.health.unwrap(),connectionStatus:Ia.shape.connectionStatus.unwrap(),accessStatus:c.z.enum(["reachable","endpoint-unreachable"]),imageProvisioning:kr.optional(),workspace:ya,runtime:Ia.shape.runtime.unwrap(),runtimeVersion:Eo.optional(),ready:c.z.boolean(),lastHeartbeatAt:As.optional()}).strict();function ba(e,t){return Ia.safeParse(Na(e,t))}function Na(e,t){if(!e||"object"!=typeof e||Array.isArray(e))return e;const n=e,i=new Set(Object.keys(Ia.shape)),s={};for(const[e,o]of Object.entries(n))i.has(e)?s[e]=o:t?.({instanceId:"string"==typeof n.id?n.id:void 0,field:e});if(n.capabilities&&"object"==typeof n.capabilities&&!Array.isArray(n.capabilities)){const e={...n.capabilities};Object.prototype.hasOwnProperty.call(e,"apps")&&(t?.({instanceId:"string"==typeof n.id?n.id:void 0,field:"capabilities.apps"}),delete e.apps),s.capabilities=hs(e)}else s.capabilities=hs(void 0);s.appInventory=function(e,t,n){if(!e||"object"!=typeof e||Array.isArray(e))return;const i=e;Object.keys(i).some(e=>!["observedAt","items","issues"].includes(e))&&t?.({instanceId:n,field:"appInventory"});const s={observedAt:i.observedAt,items:Array.isArray(i.items)?i.items.map(e=>{e&&"object"==typeof e&&!Array.isArray(e)&&Object.keys(e).some(e=>!["id","name","kind","source","availability","capabilities","diagnosticCode"].includes(e))&&t?.({instanceId:n,field:"appInventory.items"});const i=Oa(e,["id","name","kind","source","availability","diagnosticCode"]);return!i||"object"!=typeof i||Array.isArray(i)?i:{...i,capabilities:Oa(e.capabilities,["automation","supportsCwdSelection","supportsProfiles"])}}):i.items,issues:Array.isArray(i.issues)?i.issues.map(e=>Oa(e,["code","message"])):i.issues},o=Xs.safeParse(s);return o.success?o.data:void 0}(n.appInventory,t,"string"==typeof n.id?n.id:void 0),s.source=function(e,t,n){if(!e||"object"!=typeof e||Array.isArray(e))return e;const i=e,s=i.type,o=Lo.options.find(e=>e.shape.type.value===s);if(!o)return e;const r="local-folder"===s?["type","localFolderId","path","ownerNodeId"]:"git-template"===s?["type","url","templateId","ref","auth","clone"]:["type","repositoryId","url","provider","ref","auth","clone"],a=Oa(i,r);if("local-folder"!==s){const e=function(e,t,n){const i=e&&"object"==typeof e&&!Array.isArray(e)?e:void 0,s=Ro.safeParse(Oa(i,["type","name","commit"]));if(s.success)return s.data;const o="string"==typeof i?.commit?i.commit.trim():"",r="string"==typeof i?.name?i.name.trim():"",a=o?Ro.safeParse({type:"commit",commit:o}):r?Ro.safeParse({type:"tag"===i?.type?"tag":"branch",name:r}):Ro.safeParse({type:"branch",name:"main"});return a.success?(t?.({instanceId:n,field:"source.ref"}),a.data):void 0}(i.ref,t,n),s=Sa(zo,Oa(i.auth,["type","secretId"]),"source.auth",t,n),o=Sa(xo,Oa(i.clone,["depth","submodules","lfs","subdirectory"]),"source.clone",t,n);e?a.ref=e:delete a.ref,s?a.auth=s:delete a.auth,o?a.clone=o:delete a.clone}const c=Sa(o,a,"source",t,n);return c?(Object.keys(i).some(e=>!r.includes(e))&&t?.({instanceId:n,field:"source"}),c):a}(n.source,t,"string"==typeof n.id?n.id:void 0),s.sourceSnapshot=n.sourceSnapshot&&"object"==typeof n.sourceSnapshot&&!Array.isArray(n.sourceSnapshot)?n.sourceSnapshot:{},s.build=Sa(fo,n.build,"build",t,"string"==typeof n.id?n.id:void 0),s.aiSessions=function(e,t,n){if(!e||"object"!=typeof e||Array.isArray(e))return;const i=e,s=Array.isArray(i.sessions)?i.sessions.flatMap((e,i)=>{const s=Sa(on,e,`aiSessions.sessions.${i}`,t,n);return s?[s]:[]}):[],o={runningCount:"number"==typeof i.runningCount&&Number.isInteger(i.runningCount)&&i.runningCount>=0?i.runningCount:0,waitingCount:"number"==typeof i.waitingCount&&Number.isInteger(i.waitingCount)&&i.waitingCount>=0?i.waitingCount:0,staleCount:"number"==typeof i.staleCount&&Number.isInteger(i.staleCount)&&i.staleCount>=0?i.staleCount:0,sessions:s,updatedAt:As.safeParse(i.updatedAt).success?i.updatedAt:(new Date).toISOString()};return Object.keys(i).some(e=>!["runningCount","waitingCount","staleCount","sessions","updatedAt"].includes(e))&&t?.({instanceId:n,field:"aiSessions"}),rn.parse(o)}(n.aiSessions,t,"string"==typeof n.id?n.id:void 0),s.triggers=function(e,t,n){if(!e||"object"!=typeof e||Array.isArray(e))return;const i=e;Object.keys(i).some(e=>!["enabledCount","runningCount","errorCount","configs","recentRuns"].includes(e))&&t?.({instanceId:n,field:"triggers"});const s=(e,i,s)=>Array.isArray(e)?e.flatMap((e,o)=>{const r=Sa(i,e,`${s}.${o}`,t,n);return r?[r]:[]}):[],o=Array.isArray(i.configs)?i.configs.flatMap((e,i)=>{if(!e||"object"!=typeof e||Array.isArray(e))return[];const o=e;Object.keys(o).some(e=>!["configHash","config","deployments","runtime"].includes(e))&&t?.({instanceId:n,field:`triggers.configs.${i}`});const r=function(e,t,n,i){if(!e||"object"!=typeof e||Array.isArray(e))return;const s=e,o=Oa(s,["configHash","name","description","createdAt","updatedAt"]);if(s.source&&"object"==typeof s.source&&!Array.isArray(s.source)){const e=s.source,t="schedule"===e.type?"interval"===e.scheduleKind?["type","scheduleKind","intervalMs"]:"daily"===e.scheduleKind?["type","scheduleKind","timeOfDay","timezone"]:["type","scheduleKind","weekdays","timeOfDay","timezone"]:"file-change"===e.type?["type","roots","globs","ignore","debounceMs"]:["type","agent","statuses","phases"];o.source=Oa(e,t)}return o.action=Oa(s.action,["promptTemplate"]),o.policy=Oa(s.policy,["cooldownMs","maxConcurrentRuns","whenBusy"]),Sa(vn,o,t,n,i)}(o.config,`triggers.configs.${i}.config`,t,n);return"string"==typeof o.configHash&&r?[{configHash:o.configHash,config:r,deployments:s(o.deployments,Rn,`triggers.configs.${i}.deployments`),runtime:s(o.runtime,zn,`triggers.configs.${i}.runtime`)}]:[]}):[];return{enabledCount:"number"==typeof i.enabledCount&&Number.isInteger(i.enabledCount)&&i.enabledCount>=0?i.enabledCount:0,runningCount:"number"==typeof i.runningCount&&Number.isInteger(i.runningCount)&&i.runningCount>=0?i.runningCount:0,errorCount:"number"==typeof i.errorCount&&Number.isInteger(i.errorCount)&&i.errorCount>=0?i.errorCount:0,configs:o,recentRuns:s(i.recentRuns,xn,"triggers.recentRuns")}}(n.triggers,t,"string"==typeof n.id?n.id:void 0),s.apps=Sa(Ia.shape.apps.unwrap(),Oa(n.apps,["runningCount","problemCount","updatedAt","revision"]),"apps",t,"string"==typeof n.id?n.id:void 0)||{runningCount:0,problemCount:0},s.config=Sa(Ia.shape.config.unwrap(),Oa(n.config,["autoImportAgentConfigs","codexConfigEnabled","codexHomeMode","defaultCodexPermissionMode","codexSettings","aiSessionHistoryLimit","aiSessionAttachmentRetentionDays","aiSessionMaxFileAttachmentBytes"]),"config",t,"string"==typeof n.id?n.id:void 0)||{autoImportAgentConfigs:!0,codexConfigEnabled:!0,codexHomeMode:"taskhandoff",defaultCodexPermissionMode:"ask",aiSessionHistoryLimit:50,aiSessionAttachmentRetentionDays:30,aiSessionMaxFileAttachmentBytes:ke},s.modelSelection=Sa(ks.unwrap(),Oa(n.modelSelection,["modelEntityIds","codexModelHash","claudeModelHash","opencodeModelHash"]),"modelSelection",t,"string"==typeof n.id?n.id:void 0)||{},s.imageSnapshot=function(e,t,n,i){if(!e||"object"!=typeof e||Array.isArray(e))return e;const s=e,o=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return e;const t=e,n=new Set(["id","origin","name","description","localizedDescriptions","cover","reference","repository","tag","image","registry","pullPolicy","capabilities","optionalApps","defaultEnv","labels","createdAt","updatedAt"]);for(const e of Object.keys(t))n.has(e);"string"==typeof t.id&&t.id;const i="string"==typeof t.image?t.image:void 0;Object.prototype.hasOwnProperty.call(t,"registry");let s,o="string"==typeof t.reference?t.reference:i;if(o)try{o=Rs(o)}catch{if(!o.includes("@")&&o.lastIndexOf(":")<=o.lastIndexOf("/"))try{o=Rs(`${o}:latest`)}catch{}}try{s=o?zs(o):void 0}catch{}return{id:t.id,origin:"custom",name:t.name,description:t.description,localizedDescriptions:t.localizedDescriptions,cover:Oa(t.cover,["kind","key","url","mediaType","digest"]),reference:s?.reference??o,repository:s?.repository??t.repository,tag:s?.tag??t.tag,pullPolicy:t.pullPolicy??"if-not-present",capabilities:t.capabilities,optionalApps:t.optionalApps,defaultEnv:t.defaultEnv,labels:t.labels,createdAt:t.createdAt,updatedAt:t.updatedAt}}(s),{reference:r,...a}=o,c=s.requestedReference??r;let d;try{d="string"==typeof c?zs(c):void 0}catch{}const l={img_default:"market_taskhandoff_browser",img_codex:"market_taskhandoff_codex",img_ai:"market_taskhandoff_ai"},u="string"==typeof s.id?s.id:"string"==typeof t?t:void 0,p="market"===s.origin||u&&l[u]?"market":"custom";return void 0===s.image&&void 0===s.reference||n?.({instanceId:i,field:"imageSnapshot.reference"}),{...a,id:u&&l[u]?l[u]:u,origin:p,repository:d?.repository??s.repository,tag:d?.tag??s.tag,requestedReference:d?.reference??c,resolvedDigest:s.resolvedDigest,resolvedReference:s.resolvedReference,downloadSizeBytes:s.downloadSizeBytes,market:"market"===p?Oa(s.market,["catalogId","catalogRevision","publisher","version"])??{catalogId:"task_handoff_embedded",catalogRevision:"legacy",publisher:"task-handoff"}:void 0}}(n.imageSnapshot,n.imageId,t,"string"==typeof n.id?n.id:void 0);const o="string"==typeof n.imageId?{img_default:"market_taskhandoff_browser",img_codex:"market_taskhandoff_codex",img_ai:"market_taskhandoff_ai"}[n.imageId]||n.imageId:void 0,r=Oa(n.imageSelection,["imageId","tag"]);s.imageSelection=r||(o?{imageId:o,tag:s.imageSnapshot?.tag}:void 0),s.imageProvisioning=Sa(kr,Oa(n.imageProvisioning,["phase","requestedReference","generation","error","startedAt","updatedAt"]),"imageProvisioning",t,"string"==typeof n.id?n.id:void 0),s.runtimeVersion=function(e,t,n){if(!e||"object"!=typeof e||Array.isArray(e))return;const i=e,s=e=>{if("string"!=typeof e)return;const t=e.trim();return t&&t.length<=80?t:void 0},o=s(i.desiredVersion);if(!o)return void t?.({instanceId:n,field:"runtimeVersion.desiredVersion"});const r=new Set(Eo.shape.phase.options),a="string"==typeof i.phase?i.phase:"pending",c=r.has(a)?a:{idle:"pending",queued:"pending",checking:"pending",downloading:"installing",updating:"installing",completed:"matched",succeeded:"matched",ready:"matched",error:"failed"}[a]||"pending";let d;if(c!==a&&t?.({instanceId:n,field:"runtimeVersion.phase"}),i.error&&"object"==typeof i.error&&!Array.isArray(i.error)){const e=i.error,o="string"==typeof e.message?e.message.trim().slice(0,4096):"";if(o){const i=new Set(_o.shape.code.options),r="string"==typeof e.code&&i.has(e.code)?e.code:"INSTANCE_RUNTIME_INSTALL_FAILED";r!==e.code&&t?.({instanceId:n,field:"runtimeVersion.error.code"});const a=s(e.expectedVersion),c=s(e.actualVersion);d={code:r,message:o,...a?{expectedVersion:a}:{},...c?{actualVersion:c}:{},retryable:!0===e.retryable}}else t?.({instanceId:n,field:"runtimeVersion.error"})}"string"==typeof i.error&&i.error.trim()&&(d={code:"INSTANCE_RUNTIME_INSTALL_FAILED",message:i.error.trim().slice(0,4096),expectedVersion:o,...s(i.actualVersion)?{actualVersion:s(i.actualVersion)}:{},retryable:!1});const l=s(i.actualVersion),u=As.safeParse(i.lastAttemptAt),p=As.safeParse(i.matchedAt);return void 0===i.lastAttemptAt||u.success||t?.({instanceId:n,field:"runtimeVersion.lastAttemptAt"}),void 0===i.matchedAt||p.success||t?.({instanceId:n,field:"runtimeVersion.matchedAt"}),{desiredVersion:o,...l?{actualVersion:l}:{},phase:c,attempt:"number"==typeof i.attempt&&Number.isInteger(i.attempt)&&i.attempt>=0?i.attempt:0,...u.success?{lastAttemptAt:u.data}:{},...p.success?{matchedAt:p.data}:{},...d?{error:d}:{}}}(n.runtimeVersion,t,"string"==typeof n.id?n.id:void 0),s.workspace=Sa(ya,n.workspace,"workspace",t,"string"==typeof n.id?n.id:void 0)||{status:"unknown"},s.environmentSource=Sa(Ls,n.environmentSource,"environmentSource",t,"string"==typeof n.id?n.id:void 0),s.environmentTemplateOrigin=Sa(Fs,n.environmentTemplateOrigin,"environmentTemplateOrigin",t,"string"==typeof n.id?n.id:void 0),s.runtime=Sa(Ia.shape.runtime.unwrap(),n.runtime,"runtime",t,"string"==typeof n.id?n.id:void 0)||{labels:{}},s.target=Sa(ha,Oa(n.target??n.endpoints,["strategy","web","api","vnc","tty","logs","status"]),"target",t,"string"==typeof n.id?n.id:void 0)||{strategy:"direct-port",status:"unknown"},s.access=Sa(fa,Oa(n.access,["strategy","web","api","ws","status"]),"access",t,"string"==typeof n.id?n.id:void 0)||{strategy:"control-plane-proxy",status:"unknown"};for(const[e,i]of Object.entries(Ia.shape))Object.prototype.hasOwnProperty.call(s,e)&&!i.safeParse(s[e]).success&&i.safeParse(void 0).success&&(delete s[e],t?.({instanceId:"string"==typeof n.id?n.id:void 0,field:e}));return s}function Sa(e,t,n,i,s){if(!t||"object"!=typeof t||Array.isArray(t))return;let o=structuredClone(t),r=!1;for(let t=0;t<20;t+=1){const t=e.safeParse(o);if(t.success)return r&&i?.({instanceId:s,field:n}),t.data;let a=!1;for(const e of t.error.issues){if("unrecognized_keys"!==e.code)continue;const t=va(o,e.path);if(t&&"object"==typeof t&&!Array.isArray(t))for(const n of e.keys)Object.prototype.hasOwnProperty.call(t,n)&&(delete t[n],a=!0,r=!0)}if(!a){const r=structuredClone(o);let a=!1;for(const e of t.error.issues){if(!e.path.length||"string"!=typeof e.path.at(-1))continue;const t=va(r,e.path.slice(0,-1)),n=e.path.at(-1);t&&"object"==typeof t&&!Array.isArray(t)&&Object.prototype.hasOwnProperty.call(t,n)&&(delete t[n],a=!0)}if(a){const t=e.safeParse(r);if(t.success)return i?.({instanceId:s,field:n}),t.data}break}}i?.({instanceId:s,field:n})}function va(e,t){let n=e;for(const e of t){if(!n||"object"!=typeof n)return;n=n[e]}return n}function Oa(e,t){if(!e||"object"!=typeof e||Array.isArray(e))return e;const n=e;return Object.fromEntries(t.filter(e=>Object.prototype.hasOwnProperty.call(n,e)).map(e=>[e,n[e]]))}const Ra=c.z.object({instanceId:Es.optional(),projectId:Es.optional(),source:Lo.optional(),nodeId:Es.optional(),runtimeId:Es.optional(),imageSelection:Ds.optional(),instanceVersion:c.z.string().trim().max(80).optional(),protocolVersion:es,build:fo.optional(),controlMode:c.z.enum(["standalone","controlled"]).default("controlled"),capabilities:ps.default(rs),appInventory:Xs.optional(),target:ga.optional(),workspace:ya.default({status:"unknown"}),registrationToken:c.z.string().trim().max(240).optional(),processIncarnationId:c.z.string().trim().min(1).max(120).optional()}).strict().superRefine((e,t)=>{Zi.has(e.protocolVersion)&&!e.appInventory&&t.addIssue({code:"custom",path:["appInventory"],message:"Current protocol register payload requires appInventory."})}),za=c.z.object({status:Ia.shape.status.optional(),health:Ia.shape.health.optional(),protocolVersion:es,build:fo.optional(),capabilities:Ia.shape.capabilities.optional(),appInventory:Xs.optional(),apps:Ia.shape.apps.optional(),aiSessions:Ia.shape.aiSessions.optional(),triggers:Ia.shape.triggers.optional(),workspace:ya.optional(),target:ga.optional(),processIncarnationId:c.z.string().trim().min(1).max(120).optional()}).strict().superRefine((e,t)=>{Zi.has(e.protocolVersion)&&!e.appInventory&&t.addIssue({code:"custom",path:["appInventory"],message:"Current protocol heartbeat payload requires appInventory."})}),xa=c.z.enum(["web","telegram","wechat","dingding","lark"]);c.z.object({id:Es,channel:xa,name:c.z.string().trim().min(1).max(160),enabled:c.z.boolean().default(!1),token:c.z.string().trim().max(4096).optional(),defaultChatId:c.z.string().trim().max(240).optional(),allowedUserIds:c.z.array(c.z.string().trim().min(1).max(240)).default([]),pollIntervalMs:c.z.number().int().positive().max(6e4).default(3e3),settings:c.z.record(c.z.string(),c.z.unknown()).default({}),createdAt:As,updatedAt:As}).strict(),c.z.object({id:Es,channel:xa,bridgeId:Es.optional(),chatSessionId:c.z.string().trim().min(1).max(240),userId:c.z.string().trim().max(240).optional(),activeProjectId:Es.optional(),activeInstanceId:Es.optional(),activeAiSessionId:c.z.string().trim().min(1).max(120).optional(),lastUsedAt:As,createdAt:As,updatedAt:As}).strict(),c.z.object({source:c.z.object({type:c.z.literal("chat-gateway").default("chat-gateway"),channel:xa,bridgeId:Es.optional(),chatSessionId:c.z.string().trim().min(1).max(240),userId:c.z.string().trim().max(240).optional()}).strict(),message:c.z.object({text:c.z.string().trim().max(2e4).default(""),attachments:c.z.array(It).max(6).default([])}).strict().superRefine((e,t)=>{e.attachments.reduce((e,t)=>e+("inline"===t.source.type?t.size:0),0)>Le&&t.addIssue({code:c.z.ZodIssueCode.custom,path:["attachments"],message:"Inline attachments must be 41943040 bytes or less in total."})}),target:c.z.object({instanceId:Es,aiSessionId:c.z.string().trim().min(1).max(120)}).strict().optional()}).strict(),c.z.object({id:Es,instanceId:Es,projectId:Es.optional(),aiSessionId:c.z.string().trim().min(1).max(120),providerSessionId:c.z.string().trim().max(240).optional(),result:c.z.string().default(""),timeoutMs:c.z.number().positive().optional(),source:c.z.string().trim().max(120).optional(),kind:c.z.enum(["task","approval"]).default("task"),status:c.z.enum(["pending","unreachable"]).default("pending"),error:c.z.string().trim().max(2048).optional(),lastSeenAt:As}).strict();const Ca=c.z.string().refine(function(e){return 1===Array.from(e).length&&!/[\p{L}\p{N}\s]/u.test(e)&&"/"!==e&&"\\"!==e},"Mention trigger must be one printable non-alphanumeric character other than / or \\."),ka=c.z.string().refine(function(e){return 1===Array.from(e).length&&!/[\p{L}\p{N}\s]/u.test(e)&&"\\"!==e},"Command trigger must be one printable non-alphanumeric character other than \\.");c.z.object({publicBaseUrl:c.z.string().trim().max(2048).optional(),updateChannel:yo.default("stable"),mentionTrigger:Ca.default("@"),commandTrigger:ka.default("/"),diagnosticLogs:c.z.boolean().default(!1)}).strict().refine(e=>e.mentionTrigger!==e.commandTrigger,{path:["commandTrigger"],message:"Command and mention triggers must be different."}),c.z.object({publicBaseUrl:c.z.string().trim().max(2048).optional(),updateChannel:yo.optional(),mentionTrigger:Ca.optional(),commandTrigger:ka.optional(),diagnosticLogs:c.z.boolean().optional()}).strict();const Da=c.z.object({id:qo.shape.id.optional(),name:qo.shape.name,source:Lo,defaultImageSelection:qo.shape.defaultImageSelection,defaultNodeId:qo.shape.defaultNodeId,workspacePolicy:Po.optional(),labels:qo.shape.labels.optional()}),La={defaultRuntimeId:Qr.shape.id.optional()};Da.extend(La).strict().transform(({defaultRuntimeId:e,...t})=>({...t,source:Lo.parse(t.source)})),Da.omit({id:!0}).partial().extend(La).strict().transform(({defaultRuntimeId:e,...t})=>({...t,...t.source?{source:Lo.parse(t.source)}:{}})),c.z.object({id:Rr.shape.id.optional(),name:Rr.shape.name,description:Rr.shape.description,cover:Rr.shape.cover,reference:Rr.shape.reference,pullPolicy:Rr.shape.pullPolicy.optional(),capabilities:c.z.array(c.z.string().trim().min(1).max(80)).optional(),optionalApps:c.z.array(c.z.string().trim().min(1).max(120)).optional(),defaultEnv:Rr.shape.defaultEnv.optional(),labels:Rr.shape.labels.optional()}).strict().omit({id:!0}).partial().strict();const Pa=c.z.object({name:Bo.shape.name,endpoint:Bo.shape.endpoint,key:Bo.shape.key,model:Bo.shape.model,modelNames:Bo.shape.modelNames.optional(),mappings:$o.optional(),protocols:Bo.shape.protocols.optional(),app:Bo.shape.app,enabled:Bo.shape.enabled.optional(),order:Bo.shape.order.optional(),labels:Bo.shape.labels.optional()}).strict();Pa.omit({key:!0}).extend({key:Bo.shape.key.optional()}).strict(),Pa.partial().strict(),c.z.object({endpoint:Bo.shape.endpoint,key:Bo.shape.key.optional(),existingModelId:Bo.shape.id.optional()}).strict().extend({model:Bo.shape.model,app:Bo.shape.app.optional(),protocol:c.z.enum(["openai-responses","openai-chat-completions","anthropic-messages"]).optional()}).strict().refine(e=>Boolean(e.protocol||e.app),{message:"A model protocol is required.",path:["protocol"]});const Ma=c.z.object({mode:c.z.enum(["local-static-key","paired-hmac","proxy-binding"]).default("local-static-key"),keyId:Yr.shape.id.optional(),secret:c.z.string().trim().max(4096).optional(),pairedAt:Yr.shape.createdAt.optional(),pairing:c.z.object({status:c.z.enum(["pending","paired","expired"]).default("pending"),joinToken:c.z.string().trim().max(4096).optional(),expiresAt:Yr.shape.createdAt.optional()}).strict().optional()}).strict();function ja(e,t){let n=Ha(t);for(let t=0;t<100;t+=1){const t=e.safeParse(n);if(t.success)return t;const i=Ua(t.error.issues);let s=!1;for(const e of i){const t=$a(n,e.path);if(t&&"object"==typeof t&&!Array.isArray(t))for(const n of e.keys)Object.prototype.hasOwnProperty.call(t,n)&&(delete t[n],s=!0)}if(!s)return t}return e.safeParse(n)}function Ua(e,t=[]){const n=[];for(const i of e){if("unrecognized_keys"===i.code){n.push({code:"unrecognized_keys",keys:i.keys,path:[...t,...i.path]});continue}if("invalid_union"!==i.code||!Array.isArray(i.errors))continue;const e=i.errors.filter(e=>Array.isArray(e));if(!e.length)continue;const s=e.reduce((e,t)=>Fa(t)<Fa(e)?t:e);n.push(...Ua(s,[...t,...i.path]))}return n}function Fa(e){return e.reduce((e,t)=>{if("unrecognized_keys"===t.code)return e;if("invalid_union"!==t.code||!Array.isArray(t.errors))return e+1;const n=t.errors.filter(e=>Array.isArray(e));return e+(n.length?Math.min(...n.map(Fa)):1)},0)}function $a(e,t){let n=e;for(const e of t){if(!n||"object"!=typeof n)return;n=n[e]}return n}function Ha(e){return Array.isArray(e)?e.map(Ha):e&&"object"==typeof e?Object.getPrototypeOf(e)!==Object.prototype&&null!==Object.getPrototypeOf(e)?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Ha(t)])):e}function qa(e,t,n={}){return new Promise((i,s)=>{if(n.signal?.aborted)return void s(Object.assign(new Error(`${e} was aborted.`),{code:"RUNTIME_COMMAND_ABORTED"}));const o=l.spawn(e,t,{stdio:["ignore","pipe","pipe"],...n.env?{env:n.env}:{}}),r=[],a=[];let c=!1;const d=n.timeoutMs?setTimeout(()=>{c=!0,o.kill("SIGKILL")},n.timeoutMs):void 0;let u=!1;const p=()=>{u=!0,o.kill("SIGKILL")},m=()=>{d&&clearTimeout(d),n.signal?.removeEventListener("abort",p)};n.signal?.addEventListener("abort",p,{once:!0}),d?.unref?.(),o.stdout.on("data",e=>r.push(Buffer.from(e))),o.stderr.on("data",e=>a.push(Buffer.from(e))),o.on("error",e=>{m(),s(e)}),o.on("close",t=>{m();const o={stdout:Buffer.concat(r).toString("utf8").trim(),stderr:Buffer.concat(a).toString("utf8").trim()};if(c){const t=new Error(`${e} timed out after ${n.timeoutMs}ms`);return Object.assign(t,{statusCode:504,code:"RUNTIME_COMMAND_TIMEOUT",details:o}),void s(t)}if(u)return void s(Object.assign(new Error(`${e} was aborted.`),{code:"RUNTIME_COMMAND_ABORTED",details:o}));if(0===t)return void i(o);const d=new Error(o.stderr||`${e} exited with code ${t}`);Object.assign(d,{statusCode:502,code:"RUNTIME_EXECUTOR_FAILED",details:o}),s(d)})})}function Ba(e){try{return t.statSync(e).isFile()}catch{return!1}}c.z.object({id:Yr.shape.id.optional(),name:Yr.shape.name.optional(),connectionMode:Yr.shape.connectionMode.optional(),connectionPath:Yr.shape.connectionPath.optional(),connectionEnabled:Yr.shape.connectionEnabled.optional(),auth:Ma.optional(),joinToken:c.z.string().trim().min(1).max(4096).optional(),endpoint:Yr.shape.endpoint,controlEndpoint:Yr.shape.controlEndpoint,containerEndpoint:Yr.shape.containerEndpoint,publicWebBase:Yr.shape.publicWebBase,status:c.z.enum(["unknown","online","offline","degraded"]).optional(),health:c.z.enum(["unknown","ok","degraded","failed"]).optional(),capabilities:Yr.shape.capabilities.optional(),labels:Yr.shape.labels.optional(),lastSeenAt:Yr.shape.lastSeenAt}).strict(),c.z.object({name:Yr.shape.name.optional(),connectionMode:Yr.shape.connectionMode.unwrap().optional(),connectionPath:Yr.shape.connectionPath.unwrap().optional(),connectionEnabled:Yr.shape.connectionEnabled.unwrap().optional(),auth:Ma.optional(),endpoint:Yr.shape.endpoint,controlEndpoint:Yr.shape.controlEndpoint,containerEndpoint:Yr.shape.containerEndpoint,publicWebBase:Yr.shape.publicWebBase,status:Yr.shape.status.unwrap().optional(),health:Yr.shape.health.unwrap().optional(),capabilities:Yr.shape.capabilities.unwrap().optional(),labels:Yr.shape.labels.unwrap().optional(),lastSeenAt:Yr.shape.lastSeenAt}).strict(),c.z.object({controlPlaneUrl:c.z.string().trim().url().max(2048),joinToken:c.z.string().trim().min(1).max(4096),controlPlaneName:c.z.string().trim().min(1).max(160).optional(),activate:c.z.boolean().optional()}).strict(),c.z.object({nodeName:c.z.string().trim().min(1).max(160).optional(),expiresInMs:c.z.number().int().positive().max(36e5).optional()}).strict();const Va=[".com",".exe"];function Ga(e){return Va.includes(e.toLowerCase())}const Ka=(e,t,i={})=>new Promise((s,o)=>{if(i.signal?.aborted)return void o(Object.assign(new Error(`${e} was aborted.`),{code:"RUNTIME_COMMAND_ABORTED"}));const r=[];let a,c=!1,d=!1;const l=function(e,t={}){if("win32"!==(t.platform??process.platform)||!e)return e;const i=t.env??process.env;if(n.win32.isAbsolute(e)||/[\\/]/.test(e))return e;const s=t.isFile??Ba,o=(i.PATH??i.Path??"").split(";").map(e=>e.trim()).filter(Boolean),r=""!==n.win32.extname(e),a=r?[""]:(i.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").map(e=>e.trim()).filter(Boolean),c=r?[]:a.filter(Ga),d=r?[]:a.filter(e=>!Ga(e)),l=r?[a]:[c.length?c:Va,[...d,""]];for(const t of l)for(const i of o)for(const o of t){const t=n.win32.join(i,`${e}${o}`);if(s(t))return t}return e}(e);try{a=p.spawn(l,t,{name:"xterm-256color",cols:i.cols||120,rows:i.rows||40,cwd:process.cwd(),env:process.env})}catch(t){const n=t instanceof Error?t.message:String(t);return void o(Object.assign(new Error(l===e?`${e} could not be started: ${n}`:`${e} could not be started from ${l}: ${n}`),{code:"RUNTIME_EXECUTOR_FAILED",cause:t}))}const u=i.timeoutMs?setTimeout(()=>{c=!0,a.kill("SIGKILL")},i.timeoutMs):void 0,m=()=>{d=!0;try{a.kill("SIGKILL")}catch{}};i.signal?.addEventListener("abort",m,{once:!0}),u?.unref?.(),a.onData(e=>{r.push(e),i.onData?.(e)}),a.onExit(({exitCode:t})=>{u&&clearTimeout(u),i.signal?.removeEventListener("abort",m);const n={stdout:r.join(""),stderr:""};c?o(Object.assign(new Error(`${e} timed out after ${i.timeoutMs}ms`),{statusCode:504,code:"RUNTIME_COMMAND_TIMEOUT",details:n})):d?o(Object.assign(new Error(`${e} was aborted.`),{code:"RUNTIME_COMMAND_ABORTED",details:n})):0!==t?o(Object.assign(new Error(n.stdout.replace(/\u001b\[[0-?]*[ -/]*[@-~]/g,"").split(/\r?\n/).map(e=>e.trim()).filter(Boolean).at(-1)||`${e} exited with code ${t}`),{statusCode:502,code:"RUNTIME_EXECUTOR_FAILED",details:n})):s(n)})});function Wa(e){return e===qa?Ka:async(t,n,i={})=>{const s=await e(t,n,{timeoutMs:i.timeoutMs,signal:i.signal});return s.stdout&&i.onData?.(s.stdout),s.stderr&&i.onData?.(s.stderr),s}}class Ya{inFlight=new Map;runCommand;runTerminalCommand;constructor(e=qa,t){this.runCommand=e,this.runTerminalCommand=t||Wa(e)}ensure(e,t,n,i){const s=Rs(e),o=this.inFlight.get(s);if(o)return t&&(o.phaseListeners.add(t),o.phase&&t(o.phase)),n&&(o.terminalListeners.add(n),o.terminalTail&&n({sequence:o.terminalSequence,data:o.terminalTail,replay:!0})),this.bindAbort(o,i),o.promise;const r=new Set,a=new Set;t&&r.add(t),n&&a.add(n);const c={promise:Promise.resolve(void 0),controller:new AbortController,abortDisposers:new Set,phaseListeners:r,terminalListeners:a,terminalSequence:0,terminalTail:""};return this.bindAbort(c,i),c.promise=this.ensureOnce(s,e=>{c.phase=e,r.forEach(t=>t(e))},e=>{c.terminalSequence+=1,c.terminalTail=`${c.terminalTail}${e}`.slice(-262144);const t={sequence:c.terminalSequence,data:e};a.forEach(e=>e(t))},c.controller.signal).finally(()=>{this.inFlight.delete(s);for(const e of c.abortDisposers)e();c.abortDisposers.clear()}),this.inFlight.set(s,c),c.promise}bindAbort(e,t){if(!t)return;if(t.aborted)return void e.controller.abort();const n=()=>e.controller.abort();t.addEventListener("abort",n,{once:!0}),e.abortDisposers.add(()=>t.removeEventListener("abort",n))}async ensureOnce(e,t,n,i){t("checking-image");let s=await this.inspect(e,i).catch(e=>{if(i.aborted)throw e}),o=!1;s||(t("pulling-image"),await this.runTerminalCommand("docker",["pull",e],{cols:120,rows:40,signal:i,onData:n}),o=!0,s=await this.inspect(e,i)),t("resolving-image");const r=(a=s,Array.isArray(a.RepoDigests)?a.RepoDigests.filter(e=>"string"==typeof e):[]).find(e=>/@sha256:[a-fA-F0-9]{64}$/.test(e));var a;const c=r?.split("@").at(-1)?.toLowerCase();return{requestedReference:e,...c?{resolvedDigest:c}:{},resolvedReference:r||e,pulled:o}}async inspect(e,t){const n=await this.runCommand("docker",["image","inspect",e,"--format","{{json .}}"],{signal:t});return JSON.parse(n.stdout.trim()||"{}")}}function Xa(e){if(!e)return;const t=/^([0-9]+(?:\.[0-9]+)?)\s*(B|kB|MB|GB|TB)$/i.exec(e.trim());if(!t)return;const n=Number(t[1])*{b:1,kb:1e3,mb:1e6,gb:1e9,tb:1e12}[t[2].toLowerCase()];return Number.isSafeInteger(Math.round(n))?Math.round(n):void 0}const Ja="TASK_HANDOFF_GIT_PROVISIONING_STAGE=",Qa="TASK_HANDOFF_GIT_PROVISIONING_COMMIT=",Za="TASK_HANDOFF_GIT_PROVISIONING_ERROR=",ec=new Set(["cloning","checking-out","submodules","lfs","finalizing"]);function tc(e){const t=e.trim();if(t.startsWith(Ja)){const e=t.slice(36).trim();return ec.has(e)?{stage:e}:void 0}if(t.startsWith(Qa)){const e=t.slice(37).trim();return e?{commit:e}:void 0}if(t.startsWith(Za)){const e=t.slice(36).trim();return e?{errorCode:e}:void 0}}const nc=/\u001b\[[0-?]*[ -/]*[@-~]/g,ic=/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g;class sc{pending="";recent=[];push(e){const t=`${this.pending}${e}`.split(/(\r\n|\n|\r)/),n=t.pop()??"",i=n.length>8192;this.pending=i?"":n;let s=i?n:"";const o={display:""};for(let e=0;e<t.length;e+=2){const n=t[e],i=t[e+1]||"",r=tc(n);r?Object.assign(o,r):(s+=`${n}${i}`,this.remember(n))}return o.display=s,o}flush(){const e=this.pending;return this.pending="",tc(e)?"":(this.remember(e),e)}failureDetail(){return this.recent.filter(Boolean).at(-1)}remember(e){const t=e.replace(nc,"").replace(ic,"").trim();t&&(this.recent.push(t),this.recent.length>40&&this.recent.splice(0,this.recent.length-40))}}const oc=new Set(["entrypoint.sh","git-provision.sh","instance-launcher.sh","node-agent-unix-proxy.mjs","runtime-installer.mjs"]);function rc(){const e=("undefined"==typeof document?require("url").pathToFileURL(__filename).href:z&&"SCRIPT"===z.tagName.toUpperCase()&&z.src||new URL("cli.js",document.baseURI).href)?n.dirname(o.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(__filename).href:z&&"SCRIPT"===z.tagName.toUpperCase()&&z.src||new URL("cli.js",document.baseURI).href)):__dirname,i=[n.resolve(e,"../../../../../docker"),n.resolve(e,"../docker"),n.resolve(e,"../../docker")];return i.find(e=>t.existsSync(n.join(e,"runtime-installer.mjs")))||i[0]}const ac=c.z.record(c.z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),c.z.string()),cc=c.z.object({version:c.z.literal(1),instanceId:c.z.string().trim().min(1).max(120),instanceCredential:c.z.string().trim().min(1).max(240),environment:ac,modelCatalog:we.optional(),codexSettings:os.optional(),updatedAt:c.z.string().datetime()}).strict(),dc="private-config.json";function lc(e){return Array.isArray(e)?`[${e.map(lc).join(",")}]`:e&&"object"==typeof e?`{${Object.entries(e).filter(([,e])=>void 0!==e).sort(([e],[t])=>e<t?-1:e>t?1:0).map(([e,t])=>`${JSON.stringify(e)}:${lc(t)}`).join(",")}}`:JSON.stringify(e)??"null"}class uc{directory;constructor(e){this.directory=e.instancePrivateConfigsDir}init(){t.mkdirSync(this.directory,{recursive:!0,mode:448}),t.chmodSync(this.directory,448);for(const e of t.readdirSync(this.directory,{withFileTypes:!0})){const i=n.join(this.directory,e.name);if(e.isDirectory()){t.chmodSync(i,448);const e=n.join(i,dc);t.existsSync(e)&&t.chmodSync(e,384);continue}e.name.endsWith(".json")&&t.chmodSync(i,384)}}filePath(e){return n.join(this.directoryPath(e),dc)}directoryPath(e){return n.join(this.directory,e)}parseStored(e,t){const n=e&&"object"==typeof e&&!Array.isArray(e)?e:{},i=cc.parse({version:n.version,instanceId:n.instanceId,instanceCredential:n.instanceCredential??n.registrationToken,environment:n.environment,modelCatalog:void 0===n.modelCatalog?void 0:ve(n.modelCatalog),codexSettings:void 0===n.codexSettings?void 0:(s=n.codexSettings,os.parse(function(e){if(!e||"object"!=typeof e||Array.isArray(e))return e;const t=e,n=t.multiAgent,i=!n||"object"!=typeof n||Array.isArray(n)?n:(()=>{const e=n,t=e.defaultModel;return{...void 0===e.enabled?{}:{enabled:e.enabled},...void 0===e.maxConcurrentThreads?{}:{maxConcurrentThreads:e.maxConcurrentThreads},...void 0===t?{}:{defaultModel:!t||"object"!=typeof t||Array.isArray(t)?t:{modelEntityId:t.modelEntityId,modelName:t.modelName,..."string"==typeof t.modelUpstreamName?{modelUpstreamName:t.modelUpstreamName}:{}}},...void 0===e.defaultReasoningEffort?{}:{defaultReasoningEffort:e.defaultReasoningEffort}}})();return{...void 0===t.modelVerbosity?{}:{modelVerbosity:t.modelVerbosity},...void 0===t.personality?{}:{personality:t.personality},...void 0===n?{}:{multiAgent:i}}}(s))),updatedAt:n.updatedAt});var s;if(i.instanceId!==t)throw Object.assign(new Error(`Private config identity mismatch for instance ${t}.`),{statusCode:409,code:"INSTANCE_PRIVATE_CONFIG_IDENTITY_MISMATCH"});return i}readLayout(e,n){let i;try{i=t.readFileSync(n,"utf8")}catch(e){if(function(e){return Boolean(e&&"object"==typeof e&&"code"in e&&"ENOENT"===e.code)}(e))return{value:void 0,error:void 0};throw e}try{return{value:this.parseStored(JSON.parse(i),e),error:void 0}}catch(e){return{value:void 0,error:e}}}readMaterialized(e,t={}){const{value:n,error:i}=this.readLayout(e,this.filePath(e));if(n)return n;if(i&&!t.tolerateInvalid)throw i}inspectMaterialized(e){return this.readMaterialized(e)}put(e){const i=cc.parse(e);this.init();const s=this.filePath(i.instanceId);return t.mkdirSync(n.dirname(s),{recursive:!0,mode:448}),t.chmodSync(n.dirname(s),448),m.sync(s,`${JSON.stringify(i,null,2)}\n`,{encoding:"utf8",mode:384}),t.chmodSync(s,384),i}materialize(e,t,n,i,s){if(!t)throw Object.assign(new Error(`Instance ${e} does not have a long-lived credential.`),{statusCode:409,code:"INSTANCE_PRIVATE_CONFIG_CREDENTIAL_MISSING"});const o=cc.parse({version:1,instanceId:e,instanceCredential:t,environment:n,...i?{modelCatalog:i}:{},...s?{codexSettings:s}:{},updatedAt:(new Date).toISOString()}),r=this.readLayout(e,this.filePath(e)).value;return r&&function(e,t){const n=e=>lc({instanceId:e.instanceId,instanceCredential:e.instanceCredential,environment:e.environment,modelCatalog:e.modelCatalog,codexSettings:e.codexSettings});return n(e)===n(t)}(r,o)?r:this.put(o)}delete(e){t.rmSync(this.directoryPath(e),{recursive:!0,force:!0})}}const pc="/run/task-handoff/bootstrap",mc=`${pc}/entrypoint.sh`,hc="/bin/bash",gc="/run/task-handoff/private",fc=`${gc}/${dc}`,yc=`${pc}/runtime-installer.mjs`,Ic="/opt/task-handoff/instance-runtime",_c="/run/task-handoff/agent-runs",Ec=`${_c}/overlay`,Ac=`${_c}/shared`;function Tc(e){return`${e.replace(/[^a-zA-Z0-9_.-]/g,"-").replace(/^-+|-+$/g,"").slice(0,36)||"unknown"}-${d.createHash("sha256").update(e).digest("hex").slice(0,10)}`}function wc(e,t){return{role:"agent-run",name:`task-handoff-agent-${Tc(e)}-${Tc(t)}-runs`,mountPath:_c,labels:{"task-handoff.owner":"task-handoff","task-handoff.node-id":e,"task-handoff.runtime-id":t,"task-handoff.volume-role":"agent-run"}}}function bc(e){return wc(e.node?.id||"node_unset",e.runtime?.id||"runtime_local_docker")}function Nc(e,t){return{role:"runtime",name:`${Bc(e)}-runtime`,mountPath:Ic,labels:{"task-handoff.owner":"task-handoff","task-handoff.instance-id":e,"task-handoff.node-id":t,"task-handoff.volume-role":"runtime"}}}function Sc(e){return function(e,t,n){const i=Bc(e);return[{role:"data",suffix:"data",mountPath:"/data"},{role:"agent-home",suffix:"agent-home",mountPath:"/home/agent"},..."local-folder"===n.type?[]:[{role:"workspace",suffix:"workspace",mountPath:"/workspace"}]].map(({role:n,suffix:s,mountPath:o})=>({role:n,name:`${i}-${s}`,mountPath:o,labels:{"task-handoff.owner":"task-handoff","task-handoff.instance-id":e,"task-handoff.node-id":t,"task-handoff.volume-role":n}}))}(e.instance.id,e.node?.id||"node_unset",e.project.source)}const vc=new Set(["TASK_HANDOFF_REGISTRATION_TOKEN","OPENAI_API_KEY","OPENAI_BASE_URL","CODEX_MODEL","TASK_HANDOFF_CODEX_BASE_URL","TASK_HANDOFF_CODEX_MODEL","TASK_HANDOFF_CODEX_MODEL_ID","ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","CLAUDE_MODEL","TASK_HANDOFF_CLAUDE_MODEL","TASK_HANDOFF_CLAUDE_MODEL_ID"]);function Oc(e,t=[]){const n=e&&"object"==typeof e&&!Array.isArray(e)?e:{},i=n.Config&&"object"==typeof n.Config&&!Array.isArray(n.Config)?n.Config:n,s=new Set;for(const e of Array.isArray(i.Env)?i.Env:[]){if("string"!=typeof e)continue;const n=e.indexOf("="),i=-1===n?e:e.slice(0,n),o=-1===n?"":e.slice(n+1);vc.has(i)&&s.add(`Config.Env.${i}`),t.some(e=>e&&o.includes(e))&&s.add(`Config.Env.${i||"unknown"}`)}if(i.Labels&&"object"==typeof i.Labels&&!Array.isArray(i.Labels))for(const[e,n]of Object.entries(i.Labels))(vc.has(e)||"string"==typeof n&&t.some(e=>e&&n.includes(e)))&&s.add(`Config.Labels.${e}`);if(s.size)throw Object.assign(new Error(`Docker configuration contains instance-private values in ${[...s].sort().join(", ")}.`),{statusCode:409,code:"ENVIRONMENT_TEMPLATE_SECRET_IN_DOCKER_CONFIG",findings:[...s].sort()})}class Rc{runCommand;runTerminalCommand;publishHost;images;launcherAssetsDir;nodeAgentContainerIpcPath;portResolutionRetryDelaysMs;constructor(e=qa,t={}){this.runCommand=e,this.runTerminalCommand=t.terminalCommandRunner||Wa(e),this.images=t.imageService||new Ya(e),this.publishHost=t.publishHost||"127.0.0.1",this.launcherAssetsDir=t.launcherAssetsDir||rc(),this.nodeAgentContainerIpcPath=t.nodeAgentContainerIpcPath,this.portResolutionRetryDelaysMs=t.portResolutionRetryDelaysMs?.length?t.portResolutionRetryDelaysMs:[0,100,250,500,1e3]}async start(e){Kc(e);const t=e.instance.runtime.containerName||Bc(e.instance.id),i=await this.inspectContainerForStart(t);if(i){Hc(t,i.id,e.instance.runtime.containerId,"before start","RUNTIME_EXECUTOR_FAILED");const n=i.labels["task-handoff.instance-id"];if(n!==e.instance.id)throw Pc("RUNTIME_EXECUTOR_FAILED",`Docker container ${t} belongs to ${n||"an unknown instance"}, not ${e.instance.id}.`);await this.createRuntimeVolume(e),await this.validatePersistentVolumes(e,i.mounts);try{await this.runCommand("docker",["start",t])}catch(e){throw Pc("RUNTIME_EXECUTOR_FAILED",`Could not start Docker container ${t}.`,e)}return this.resumedContainerResult(e,t,i.id,i.labels)}if(e.instance.environmentTemplateOrigin){const t=await this.inspectEnvironmentTemplateImage(e.instance.environmentTemplateOrigin.imageId);if(t.imageId!==e.instance.environmentTemplateOrigin.imageId||t.platform!==e.instance.environmentTemplateOrigin.platform||t.architecture!==e.instance.environmentTemplateOrigin.architecture)throw Object.assign(new Error(`Environment template image identity or platform changed for instance ${e.instance.id}.`),{statusCode:409,code:"ENVIRONMENT_TEMPLATE_IMAGE_IDENTITY_MISMATCH"})}else await this.images.ensure(e.image.resolvedReference||e.image.requestedReference);if(await this.createPersistentVolumes(e),"local-folder"!==e.project.source.type){const t=e.instance.workspace.gitProvisioning?.phase;if("ready"!==t)throw Pc(jc,`Git workspace provisioning is ${t??"not scheduled"} for ${e.instance.id}.`);e.completeGitWorkspaceProvisioning?.()}let s;try{s=await this.runCommand("docker",function(e,t,i={}){const s=i.publishHost||"127.0.0.1",o=n.resolve(i.launcherAssetsDir||rc()),r=e.node?.id||"node_unset",a=e.runtime?.id||"runtime_local_docker",c=["run","-d","--name",t,"--user","0:0","--label",`task-handoff.instance-id=${e.instance.id}`,"--label",`task-handoff.project-id=${e.project.id}`,"--label",`task-handoff.node-id=${r}`,"--label",`task-handoff.runtime-id=${a}`,"--label",`task-handoff.image-id=${e.image.id}`,"--label","task-handoff.bootstrap-abi=1","--shm-size","1gb","--security-opt","seccomp=unconfined","--network","bridge","--no-healthcheck","--add-host","host.docker.internal:host-gateway","--tmpfs","/tmp:rw,nosuid,nodev,exec,mode=1777","-p",`${s}::8080`];if(!e.privateConfigPath)throw Object.assign(new Error(`Instance ${e.instance.id} private config was not materialized.`),{statusCode:409,code:"INSTANCE_PRIVATE_CONFIG_MISSING"});if(n.basename(e.privateConfigPath)!==dc)throw Object.assign(new Error(`Instance ${e.instance.id} private config path ${e.privateConfigPath} does not use the per-instance directory layout.`),{statusCode:409,code:"INSTANCE_PRIVATE_CONFIG_LAYOUT_INVALID"});c.push("--mount",`type=bind,src=${n.dirname(e.privateConfigPath)},dst=${gc},readonly`,"--mount",`type=bind,src=${o},dst=${pc},readonly`,"--entrypoint",hc);const d=i.nodeAgentContainerIpcPath?`/run/task-handoff/node-agent-transport/${n.basename(i.nodeAgentContainerIpcPath)}`:void 0;i.nodeAgentContainerIpcPath&&d&&c.push("--mount",`type=bind,src=${n.dirname(i.nodeAgentContainerIpcPath)},dst=/run/task-handoff/node-agent-transport,readonly`);for(const t of Sc(e))c.push("--mount",`type=volume,src=${t.name},dst=${t.mountPath}`);const l=Nc(e.instance.id,e.node?.id||"node_unset");c.push("--mount",`type=volume,src=${l.name},dst=${l.mountPath}`);const u=bc(e);c.push("--mount",`type=volume,src=${u.name},dst=${u.mountPath}`);const p={TASK_HANDOFF_CONTROL_MODE:"controlled",TASK_HANDOFF_NODE_AGENT_URL:d?"http://127.0.0.1:19001":e.nodeAgentUrl||e.node?.endpoint||"",...d?{TASK_HANDOFF_NODE_AGENT_SOCKET_PATH:d}:{},TASK_HANDOFF_INSTANCE_ID:e.instance.id,TASK_HANDOFF_INSTANCE_NAME:e.instance.name,TASK_HANDOFF_PROJECT_ID:e.project.id,TASK_HANDOFF_NODE_ID:r,TASK_HANDOFF_RUNTIME_ID:a,TASK_HANDOFF_IMAGE_ID:e.image.id,TASK_HANDOFF_INSTANCE_LAUNCHER:`${pc}/instance-launcher.sh`,...e.image.tag?{TASK_HANDOFF_IMAGE_TAG:e.image.tag}:{},TASK_HANDOFF_CHAT_BRIDGES:"none",TASK_HANDOFF_WORKSPACE:e.project.workspacePolicy.path||"/workspace",TASK_HANDOFF_WORKSPACE_MODE:e.project.workspacePolicy.mode,TASK_HANDOFF_INSTANCE_PRIVATE_CONFIG_PATH:fc,..."local-folder"===e.project.source.type?{}:{TASK_HANDOFF_SKIP_WORKSPACE_BOOTSTRAP:"true"}};for(const[e,t]of Object.entries(p))Vc(c,e,t);if("local-folder"===e.project.source.type)c.push("-v",`${e.project.source.path}:${e.project.workspacePolicy.path||"/workspace"}:${e.project.workspacePolicy.readOnly?"ro":"rw"}`);else{Vc(c,"TASK_HANDOFF_PROJECT_SOURCE",JSON.stringify(e.project.source)),Vc(c,"TASK_HANDOFF_WORKSPACE_POLICY",JSON.stringify(e.project.workspacePolicy));for(const[t,n]of Gc({url:e.project.source.url,ref:e.project.source.ref,clone:e.project.source.clone},{legacy:!0}))Vc(c,t,n);e.project.source.clone?.subdirectory&&Vc(c,"TASK_HANDOFF_WORKSPACE_SUBDIRECTORY",e.project.source.clone.subdirectory)}const m={...e.image.labels["task-handoff.image.profile"]?{TASK_HANDOFF_IMAGE_PROFILE:e.image.labels["task-handoff.image.profile"]}:{},TASK_HANDOFF_IMAGE_CAPABILITIES:e.image.capabilities.join(",")};for(const[t,n]of Object.entries(e.image.defaultEnv))t in m||Vc(c,t,n);for(const[e,t]of Object.entries(m))Vc(c,e,t);return c.push(i.imageReference||e.instance.environmentTemplateOrigin?.imageId||e.image.resolvedReference||e.image.requestedReference,mc,"task-handoff","web"),c}(e,t,{publishHost:this.publishHost,launcherAssetsDir:this.launcherAssetsDir,nodeAgentContainerIpcPath:this.nodeAgentContainerIpcPath}))}catch(e){throw Pc("RUNTIME_EXECUTOR_FAILED",`Could not create Docker container ${t}.`,e)}return this.bootstrapResult(e,t,s.stdout||void 0)}async provisionGitWorkspaceStreaming(e,i={}){const o=e.gitWorkspaceProvisioning;if(!o)throw Pc("GIT_WORKSPACE_PROVISIONING_MISSING",`Git workspace provisioning input is missing for ${e.instance.id}.`);const r=`${Bc(e.instance.id)}-git-provision`;await this.createPersistentVolumes(e);const a=t.mkdtempSync(n.join(s.tmpdir(),"task-handoff-git-auth-"));t.chmodSync(a,448);try{await this.runCommand("docker",["rm","-f",r],{timeoutMs:3e4}).catch(()=>({stdout:"",stderr:""})),this.materializeGitProvisioningAuth(a,o);const t=function(e,t,i,s={}){const o=e.gitWorkspaceProvisioning;if(!o||"local-folder"===e.project.source.type)throw Object.assign(new Error("Git provisioning requires a Git source and operation input."),{code:"GIT_WORKSPACE_PROVISIONING_INVALID",statusCode:400});const r=n.resolve(s.launcherAssetsDir||rc()),a=Sc(e).find(e=>"workspace"===e.role);if(!a)throw Object.assign(new Error("Git workspace volume was not found."),{code:"GIT_WORKSPACE_VOLUME_MISSING",statusCode:409});const c=["run","--rm","--name",t,"--label","task-handoff.role=git-provisioning","--label",`task-handoff.instance-id=${e.instance.id}`,"--user","0:0","--network","bridge","--security-opt","no-new-privileges","--cap-drop","ALL","--cap-add","CHOWN","--cap-add","SETUID","--cap-add","SETGID","--cap-add","DAC_OVERRIDE","--mount",`type=volume,src=${a.name},dst=/workspace`,"--mount",`type=bind,src=${r},dst=${pc},readonly`,"--tmpfs","/run/task-handoff/git-runtime:rw,nosuid,nodev,exec,mode=0700"];o.credentials.length&&c.push("--mount",`type=bind,src=${n.resolve(i)},dst=/run/task-handoff/git-auth,readonly`);const d=(e,t)=>c.push("-e",`${e}=${t}`);d("TASK_HANDOFF_INSTANCE_ID",e.instance.id);for(const[e,t]of Gc({url:o.remoteUrl,ref:o.ref,clone:o.clone},{legacy:!1}))d(e,t);return o.clone.subdirectory&&d("TASK_HANDOFF_WORKSPACE_SUBDIRECTORY",o.clone.subdirectory),c.push("--entrypoint","/bin/bash",e.instance.environmentTemplateOrigin?.imageId||e.image.resolvedReference||e.image.requestedReference,`${pc}/git-provision.sh`),c}(e,r,a,{launcherAssetsDir:this.launcherAssetsDir}),s=await this.runTerminalCommand("docker",t,{cols:120,rows:40,timeoutMs:i.timeoutMs??9e5,signal:i.signal??e.signal,onData:i.onOutput});return e.completeGitWorkspaceProvisioning?.(),s}catch(t){throw function(e,t){const n=Uc(t);return Pc(n,"GIT_WORKSPACE_PROVISIONING_TIMEOUT"===n?`Git workspace provisioning timed out for ${e}.`:"GIT_WORKSPACE_PROVISIONING_CANCELLED"===n?`Git workspace provisioning was cancelled for ${e}.`:`Could not provision Git workspace for ${e}.`)}(e.instance.id,t)}finally{await this.runCommand("docker",["rm","-f",r],{timeoutMs:3e4}).catch(()=>({stdout:"",stderr:""})),t.rmSync(a,{recursive:!0,force:!0})}}materializeGitProvisioningAuth(e,i){const s=(e,i,s)=>{const o=n.join(e,i);t.writeFileSync(o,s,{encoding:"utf8",mode:384}),t.chmodSync(o,384)};i.credentials.forEach((i,o)=>{const r=n.join(e,`credential-${o}`);if(t.mkdirSync(r,{recursive:!0,mode:448}),t.chmodSync(r,448),s(r,"scope.json",JSON.stringify(i.payload.credential.scope)),"https-token"===i.payload.secret.kind)return s(r,"username",i.payload.secret.username),void s(r,"token",i.payload.secret.token);s(r,"private-key",i.payload.secret.privateKey),s(r,"known_hosts",i.payload.secret.pinnedKnownHosts),i.payload.secret.passphrase&&s(r,"passphrase",i.payload.secret.passphrase),s(r,"ssh-askpass.sh",`#!/usr/bin/env bash\ncat /run/task-handoff/git-runtime/credential-${o}/passphrase 2>/dev/null || true\n`)})}async inspectContainerConfigSecurity(e,t){Oc(await this.runCommand("docker",["inspect","--format","{{json .}}",e]).then(e=>JSON.parse(e.stdout||"{}")).catch(t=>{throw Pc("ENVIRONMENT_TEMPLATE_CONTAINER_INSPECT_FAILED",`Could not inspect Docker container ${e}.`,t)}),t)}async inspectImageConfigSecurity(e,t){Oc(await this.runCommand("docker",["image","inspect","--format","{{json .}}",e]).then(e=>JSON.parse(e.stdout||"{}")).catch(e=>{throw Pc("ENVIRONMENT_TEMPLATE_IMAGE_INSPECT_FAILED","Could not inspect Docker image configuration.",e)}),t)}async commitEnvironmentTemplate(e,t,n){const i=await this.inspectContainerId(e);if(!i)throw Pc("ENVIRONMENT_TEMPLATE_CONTAINER_NOT_FOUND",`Docker container ${e} does not exist.`);Hc(e,i,t,"before environment template commit","ENVIRONMENT_TEMPLATE_CONTAINER_IDENTITY_MISMATCH");try{const t=(await this.runCommand("docker",["commit",e,n])).stdout.trim();if(!t)throw new Error("Docker commit did not return an image id.");return t}catch(t){throw Pc("ENVIRONMENT_TEMPLATE_COMMIT_FAILED",`Could not save Docker container ${e} as an environment template.`,t)}}async inspectEnvironmentTemplateImage(e){try{const t=await this.runCommand("docker",["image","inspect","--format","{{json .}}",e]),n=JSON.parse(t.stdout||"{}"),i="string"==typeof n.Id?n.Id:"",s=kc(n.Os),o=Dc(n.Architecture),r="number"==typeof n.Size?n.Size:Number.NaN;if(!/^sha256:[a-f0-9]{64}$/.test(i)||!s||!o||!Number.isSafeInteger(r)||r<0)throw new Error("Docker image inspection did not return a valid immutable identity.");return{imageId:i,platform:s,architecture:o,sizeBytes:r}}catch(e){throw Pc("ENVIRONMENT_TEMPLATE_IMAGE_INSPECT_FAILED","Could not inspect the committed environment template image.",e)}}async untagEnvironmentTemplate(e,t){try{const n=t||(await this.inspectEnvironmentTemplateImage(e)).imageId;return await this.runCommand("docker",["tag",n,Lc(n)]),await this.runCommand("docker",["image","rm",e]),n}catch(e){const t=Fc(e)?.toLowerCase()||"";if(t.includes("no such image")||t.includes("no such object"))return;throw Pc("ENVIRONMENT_TEMPLATE_UNTAG_FAILED","Could not remove the environment template tag.",e)}}async garbageCollectEnvironmentTemplateImage(e){try{try{await this.runCommand("docker",["image","rm",Lc(e)])}catch(e){const t=Fc(e)?.toLowerCase()||"";if(t.includes("being used by")||t.includes("is referenced")||t.includes("conflict"))return!1;if(!t.includes("no such image")&&!t.includes("no such object"))throw e}return await this.runCommand("docker",["image","rm",e]),!0}catch(e){const t=Fc(e)?.toLowerCase()||"";if(t.includes("being used by")||t.includes("is referenced")||t.includes("conflict"))return!1;if(t.includes("no such image")||t.includes("no such object"))return!0;throw Pc("ENVIRONMENT_TEMPLATE_GC_FAILED","Could not garbage collect the environment template image.",e)}}async createPersistentVolumes(e,t=new Set){const n=Nc(e.instance.id,e.node?.id||"node_unset");for(const i of[...Sc(e),n])await this.createVolume(i),await this.validateOwnedVolume(e.instance.id,i,t.has(i.name));const i=bc(e);await this.createVolume(i),await this.validateAgentRunRuntimeVolume(e,i)}async createRuntimeVolume(e){await this.createVolume(Nc(e.instance.id,e.node?.id||"node_unset"));const t=bc(e);await this.createVolume(t),await this.validateAgentRunRuntimeVolume(e,t)}async createVolume(e){const t=["volume","create"];for(const[n,i]of Object.entries(e.labels).sort(([e],[t])=>e.localeCompare(t)))t.push("--label",`${n}=${i}`);t.push(e.name);try{await this.runCommand("docker",t)}catch(t){throw Pc("INSTANCE_VOLUME_CREATE_FAILED",`Could not create managed volume ${e.name}.`,t)}}async validatePersistentVolumes(e,t){for(const n of Sc(e)){await this.validateOwnedVolume(e.instance.id,n);const i=t.find(e=>"volume"===e.type&&e.destination===n.mountPath);if(!i||i.name!==n.name)throw Object.assign(new Error(`Docker container mount for ${n.role} does not match managed volume ${n.name}.`),{statusCode:409,code:"INSTANCE_VOLUME_MOUNT_IDENTITY_MISMATCH"})}const i=Nc(e.instance.id,e.node?.id||"node_unset");await this.validateOwnedVolume(e.instance.id,i);const s=t.find(e=>"volume"===e.type&&e.destination===i.mountPath);if(!s||s.name!==i.name)throw Object.assign(new Error(`Docker container runtime mount does not match ${i.name}.`),{statusCode:409,code:"INSTANCE_VOLUME_MOUNT_IDENTITY_MISMATCH"});const o=bc(e);await this.validateAgentRunRuntimeVolume(e,o);const r=t.find(e=>e.destination===o.mountPath);if(r&&("volume"!==r.type||r.name!==o.name))throw Object.assign(new Error(`Docker Agent Run mount does not match managed volume ${o.name}.`),{statusCode:409,code:"AGENT_RUN_VOLUME_MOUNT_IDENTITY_MISMATCH"});if("local-folder"===e.project.source.type){const i=t.find(t=>t.destination===(e.project.workspacePolicy.path||"/workspace"));if(!i||"bind"!==i.type||n.resolve(i.source||"")!==n.resolve(e.project.source.path))throw Object.assign(new Error(`Docker container workspace bind does not match local folder ${e.project.source.path}.`),{statusCode:409,code:"INSTANCE_WORKSPACE_MOUNT_IDENTITY_MISMATCH"})}}async validateAgentRunRuntimeVolume(e,t){let n;try{n=await this.runCommand("docker",["volume","inspect","--format","{{json .}}",t.name])}catch(e){throw Pc("AGENT_RUN_VOLUME_INSPECT_FAILED",`Could not inspect Agent Run volume ${t.name}.`,e)}try{const i=JSON.parse(n.stdout||"{}"),s=i.Labels&&"object"==typeof i.Labels&&!Array.isArray(i.Labels)?i.Labels:{},o=i.Options&&"object"==typeof i.Options&&!Array.isArray(i.Options)?i.Options:{};if(i.Name!==t.name||"task-handoff"!==s["task-handoff.owner"]||s["task-handoff.node-id"]!==(e.node?.id||"node_unset")||s["task-handoff.runtime-id"]!==(e.runtime?.id||"runtime_local_docker")||s["task-handoff.volume-role"]!==t.role||"string"==typeof i.Driver&&"local"!==i.Driver||Object.keys(o).length>0)throw new Error("volume identity, ownership or local driver does not match")}catch(n){throw Object.assign(new Error(`Agent Run volume ${t.name} identity does not match runtime ${e.runtime?.id}.`,{cause:n}),{statusCode:409,code:"AGENT_RUN_VOLUME_IDENTITY_MISMATCH"})}}async validateOwnedVolume(e,t,n=!1){let i;try{i=await this.runCommand("docker",["volume","inspect","--format","{{json .}}",t.name])}catch(e){throw Pc("INSTANCE_VOLUME_INSPECT_FAILED",`Could not inspect managed volume ${t.name}.`,e)}try{const s=JSON.parse(i.stdout||"{}"),o=s.Labels&&"object"==typeof s.Labels&&!Array.isArray(s.Labels)?s.Labels:{},r=s.Name===t.name&&"task-handoff"===o["task-handoff.owner"]&&o["task-handoff.instance-id"]===e&&o["task-handoff.volume-role"]===t.role,a=n&&s.Name===t.name&&0===Object.keys(o).length;if(!r&&!a)throw new Error("volume name or ownership labels do not match")}catch(n){throw Object.assign(new Error(`Managed volume ${t.name} identity does not match instance ${e}.`,{cause:n}),{statusCode:409,code:"INSTANCE_VOLUME_IDENTITY_MISMATCH"})}}async runningResult(e,t,n){const i=await this.publishedEndpoint(t),s=e.node?.id||"node_unset",o=e.runtime?.id||"runtime_local_docker";return{status:"registering",health:"unknown",connectionStatus:"online",agentStatus:"unknown",targetStatus:"unknown",uiAccessStatus:"unknown",target:{strategy:"direct-port",status:"reachable",...i},workspace:{mode:e.project.workspacePolicy.mode,status:"pending",path:e.project.workspacePolicy.path},runtime:{...e.instance.runtime,kind:"docker",containerName:t,...n?{containerId:n}:{},labels:{...e.instance.runtime.labels,"task-handoff.instance-id":e.instance.id,"task-handoff.project-id":e.project.id,"task-handoff.node-id":s,"task-handoff.runtime-id":o,"task-handoff.image-id":e.image.id}}}}async resumedContainerResult(e,t,n,i){const s=this.bootstrapResult(e,t,n);return{...s,target:{...s.target,...await this.publishedEndpoint(t)},runtime:{...s.runtime,labels:{...e.instance.runtime.labels,...i}}}}async publishedEndpoint(e){const t=`http://127.0.0.1:${await this.containerPort(e,"8080/tcp")}`;return{web:t,api:`${t}/api`}}async resolveInstanceWeb(e){const t=e.instance.runtime.containerName||Bc(e.instance.id),n=await this.inspectContainerId(t);if(!n)throw Pc("INSTANCE_RUNTIME_ENDPOINT_UNAVAILABLE",`Docker container ${t} does not exist.`);return Hc(t,n,e.instance.runtime.containerId,"while resolving its web endpoint","INSTANCE_RUNTIME_ENDPOINT_UNAVAILABLE"),(await this.publishedEndpoint(t)).web}async resolveNodeAgentUrl(e){const t=e.nodeAgentUrl||e.node?.endpoint||"";if(!this.nodeAgentContainerIpcPath)return t;const i=e.instance.runtime.containerName||Bc(e.instance.id),s=await this.inspectContainerForStart(i);if(!s)return t;if(Hc(i,s.id,e.instance.runtime.containerId,"while resolving its node-agent transport","RUNTIME_EXECUTOR_FAILED"),s.labels["task-handoff.instance-id"]!==e.instance.id)throw Pc("RUNTIME_EXECUTOR_FAILED",`Docker container ${i} does not belong to ${e.instance.id}.`);const o=n.dirname(n.resolve(this.nodeAgentContainerIpcPath));return s.mounts.some(e=>"bind"===e.type&&"/run/task-handoff/node-agent-transport"===e.destination&&n.resolve(e.source||"")===o)?"http://127.0.0.1:19001":t}bootstrapResult(e,t,n){return{status:"starting",health:"unknown",connectionStatus:"unknown",agentStatus:"unknown",targetStatus:"unknown",uiAccessStatus:"unknown",target:{strategy:"direct-port",status:"unknown"},workspace:{mode:e.project.workspacePolicy.mode,status:"pending",path:e.project.workspacePolicy.path},runtime:{...e.instance.runtime,kind:"docker",containerName:t,...n?{containerId:n}:{},labels:{...e.instance.runtime.labels,"task-handoff.bootstrap-abi":"1"}}}}async stop(e){const t=e.instance.runtime.containerName||Bc(e.instance.id);try{await this.runCommand("docker",["stop",t])}catch(e){if(!$c(e))throw Pc("RUNTIME_EXECUTOR_FAILED",`Could not stop Docker container ${t}.`,e)}return{status:"stopped",health:"unknown",connectionStatus:"offline",target:{...e.instance.target,status:"unknown"},runtime:e.instance.runtime}}async restart(e,t){Kc(e);const n=e.instance.runtime.containerName||Bc(e.instance.id),i=await this.inspectContainerId(n);if(!i)throw Pc("INSTANCE_RUNTIME_RESTART_FAILED",`Docker container ${n} does not exist.`);Hc(n,i,t,"before restart","INSTANCE_RUNTIME_RESTART_FAILED"),await this.runCommand("docker",["restart",n]);const s=await this.inspectContainerId(n);if(!s||s!==i)throw Pc("INSTANCE_RUNTIME_RESTART_FAILED",`Docker container identity changed while restarting ${n}.`);return Hc(n,s,t,"after restart","INSTANCE_RUNTIME_RESTART_FAILED"),this.runningResult(e,n,s)}async delete(e,t){const n=e.instance.runtime.containerName||Bc(e.instance.id),i=await this.inspectContainerForStart(n),s=new Set;if(i){Hc(n,i.id,e.instance.runtime.containerId,"before delete","RUNTIME_EXECUTOR_FAILED");const t=i.labels["task-handoff.instance-id"];if(t!==e.instance.id)throw Pc("RUNTIME_EXECUTOR_FAILED",`Docker container ${n} belongs to ${t||"an unknown instance"}, not ${e.instance.id}.`);for(const t of Sc(e))i.mounts.some(e=>"volume"===e.type&&e.name===t.name&&e.destination===t.mountPath)&&s.add(t.name);try{await this.runCommand("docker",["rm","-f",i.id])}catch(e){if(!$c(e))throw Pc("RUNTIME_EXECUTOR_FAILED",`Could not delete Docker container ${n}.`,e)}}const o=[];for(const n of Sc(e))if(t.deleteVolumes)try{const t=await this.inspectVolumeForDelete(n.name);if(!t){o.push({role:n.role,name:n.name,mountPath:n.mountPath,status:"missing"});continue}const i=t.name===n.name&&"task-handoff"===t.labels["task-handoff.owner"]&&t.labels["task-handoff.instance-id"]===e.instance.id&&t.labels["task-handoff.volume-role"]===n.role,r=s.has(n.name)&&t.name===n.name&&0===Object.keys(t.labels).length;if(!i&&!r)throw Object.assign(new Error(`Managed volume ${n.name} ownership does not match instance ${e.instance.id}.`),{code:"INSTANCE_VOLUME_IDENTITY_MISMATCH"});await this.runCommand("docker",["volume","rm",n.name]),o.push({role:n.role,name:n.name,mountPath:n.mountPath,status:"deleted"})}catch(e){o.push({role:n.role,name:n.name,mountPath:n.mountPath,status:"failed",error:{code:"object"==typeof e&&e&&"code"in e&&"string"==typeof e.code?e.code:"INSTANCE_VOLUME_DELETE_FAILED",message:e instanceof Error?e.message:String(e)}})}else o.push({role:n.role,name:n.name,mountPath:n.mountPath,status:"retained"});return await this.deleteRuntimeVolume(e),Bs.parse({instanceId:e.instance.id,containerDeleted:!0,completed:o.every(e=>"failed"!==e.status),deletedVolumes:o.filter(e=>"deleted"===e.status||"missing"===e.status),retainedVolumes:o.filter(e=>"retained"===e.status),volumeResults:o})}async deleteRuntimeVolume(e){const t=Nc(e.instance.id,e.node?.id||"node_unset"),n=await this.inspectVolumeForDelete(t.name);if(n){if(n.name!==t.name||"task-handoff"!==n.labels["task-handoff.owner"]||n.labels["task-handoff.instance-id"]!==e.instance.id||"runtime"!==n.labels["task-handoff.volume-role"])throw Pc("INSTANCE_VOLUME_IDENTITY_MISMATCH",`Runtime volume ${t.name} ownership does not match instance ${e.instance.id}.`);try{await this.runCommand("docker",["volume","rm",t.name])}catch(e){throw Pc("INSTANCE_VOLUME_DELETE_FAILED",`Could not delete runtime volume ${t.name}.`,e)}}}async inspectVolumeForDelete(e){try{const t=await this.runCommand("docker",["volume","inspect","--format","{{json .}}",e]),n=JSON.parse(t.stdout||"{}");return{name:"string"==typeof n.Name?n.Name:"",labels:n.Labels&&"object"==typeof n.Labels&&!Array.isArray(n.Labels)?Object.fromEntries(Object.entries(n.Labels).filter(e=>"string"==typeof e[1])):{}}}catch(t){if(function(e){const t=Fc(e)?.toLowerCase()||"";return t.includes("no such volume")||t.includes("no such object")}(t))return;throw Pc("INSTANCE_VOLUME_INSPECT_FAILED",`Could not inspect managed volume ${e}.`,t)}}async installRuntime(e){const t=await this.installRuntimeRelease(e);Hc(e.containerName,t,e.expectedContainerId,"before runtime restart","INSTANCE_RUNTIME_RESTART_FAILED");try{await this.runCommand("docker",["restart",t])}catch(t){throw Pc("INSTANCE_RUNTIME_RESTART_FAILED",`Could not restart Docker container ${e.containerName}.`,t)}const n=await this.inspectContainerId(e.containerName);if(!n||n!==t)throw Pc("INSTANCE_RUNTIME_RESTART_FAILED",`Docker container identity changed while updating ${e.containerName}.`);return Hc(e.containerName,n,e.expectedContainerId,"after runtime restart","INSTANCE_RUNTIME_RESTART_FAILED"),this.inspectRuntimeVersion(e.containerName)}async installRuntimeRelease(e){const t=await this.inspectContainerId(e.containerName);if(!t)throw Pc("INSTANCE_RUNTIME_INSTALL_FAILED",`Docker container ${e.containerName} does not exist.`);Hc(e.containerName,t,e.expectedContainerId,"before runtime install","INSTANCE_RUNTIME_INSTALL_FAILED");const n=`/opt/task-handoff/instance-runtime/incoming/task-handoff-runtime-${i=e.identity.version,i.replace(/[^0-9A-Za-z.+_-]/g,"-")}-${e.identity.sha256.slice(0,12)}.tar.gz`;var i;await this.runCommand("docker",["exec","--user","0",t,"install","-d","-o","root","-g","root","-m","0755","/opt/task-handoff/instance-runtime/incoming"]),await this.runCommand("docker",["cp",e.artifactPath,`${t}:${n}`]);try{await this.runCommand("docker",["exec","--user","0",t,"node",yc,"install","--artifact",n,"--version",e.identity.version,"--sha256",e.identity.sha256,"--platform",e.identity.platform,"--arch",e.identity.arch,"--launcher-abi",String(e.identity.launcherAbi)])}catch(t){throw Pc("INSTANCE_RUNTIME_INSTALL_FAILED",`Could not install controlled-instance ${e.identity.version} in ${e.containerName}.`,t)}finally{await this.runCommand("docker",["exec","--user","0",t,"rm","-f",n]).catch(()=>({stdout:"",stderr:""}))}const s=await this.inspectContainerId(e.containerName);if(!s||s!==t)throw Pc("INSTANCE_RUNTIME_INSTALL_FAILED",`Docker container identity changed while installing ${e.containerName}.`);return Hc(e.containerName,s,e.expectedContainerId,"after runtime install","INSTANCE_RUNTIME_INSTALL_FAILED"),t}async inspectRuntimeVersion(e){const t=await this.inspectContainerId(e);if(!t)return{};const n=await this.runCommand("docker",["exec","--user","agent",e,"node",yc,"verify-active"]).catch(()=>{});if(!n?.stdout)return{containerId:t};try{const e=ja(Io,JSON.parse(n.stdout));return e.success?{containerId:t,...e.data}:{containerId:t}}catch{return{containerId:t}}}async runtimeState(e){try{return"true"===(await this.runCommand("docker",["inspect","--format","{{.State.Running}}",e],{timeoutMs:5e3})).stdout.trim()?"running":"stopped"}catch(e){return $c(e)?"absent":"unknown"}}async inspectRuntimeTarget(e){let t,n;if(e){const i=await this.runCommand("docker",["inspect","--format","{{json .}}",e]).then(e=>JSON.parse(e.stdout.trim()||"{}")).catch(()=>{});if(t=i?.Platform,"string"==typeof i?.Image&&i.Image){const e=await this.runCommand("docker",["image","inspect","--format","{{json .}}",i.Image]).then(e=>JSON.parse(e.stdout.trim()||"{}")).catch(()=>{});t=e?.Os||t,n=e?.Architecture}}if(!t||!n){const e=await this.runCommand("docker",["info","--format","{{json .}}"]).then(e=>JSON.parse(e.stdout.trim()||"{}")).catch(e=>{throw Pc("INSTANCE_BASE_RUNTIME_INCOMPATIBLE","Could not inspect the Docker runtime target.",e)});t||=e.OSType,n||=e.Architecture}const i=kc(t),s=Dc(n);if(!i||!s)throw Pc("INSTANCE_BASE_RUNTIME_INCOMPATIBLE",`Docker reported an unsupported runtime target ${String(t||"unknown")}/${String(n||"unknown")}.`);return{platform:i,arch:s,launcherAbi:1}}async installRuntimeReleaseWithRecovery(e){const t=e.containerName,i=await this.inspectContainerForStart(t);if(!i)throw Pc("INSTANCE_RUNTIME_INSTALL_FAILED",`Docker container ${t} does not exist.`);if(Hc(t,i.id,e.expectedContainerId,"before runtime install recovery","INSTANCE_RUNTIME_INSTALL_FAILED"),i.running)return await this.installRuntimeLauncher(t,i.id),void await this.installRuntimeRelease({...e,expectedContainerId:i.id});if(!i.image)throw Pc("INSTANCE_RUNTIME_INSTALL_FAILED",`Docker container ${t} does not expose its immutable image identity.`);const s="/run/task-handoff/runtime-rescue-artifact.tar.gz",o=[`test -r ${mc}`,`test -r ${pc}/instance-launcher.sh`,`test -r ${yc}`,`install -d -o root -g root -m 0755 ${Ic} ${Ic}/releases ${Ic}/staging ${Ic}/incoming`,`chown -R root:root ${Ic}`,`chmod -R go-w ${Ic}`,`node ${yc} install --artifact "$1" --version "$2" --sha256 "$3" --platform "$4" --arch "$5" --launcher-abi "$6"`].join("; ");try{await this.runCommand("docker",["run","--rm","--user","0:0","--volumes-from",i.id,"--mount",`type=bind,source=${n.resolve(e.artifactPath)},target=${s},readonly`,"--entrypoint",hc,i.image,"-ceu",o,"task-handoff-runtime-rescue",s,e.identity.version,e.identity.sha256,e.identity.platform,e.identity.arch,String(e.identity.launcherAbi)])}catch(n){throw Pc("INSTANCE_RUNTIME_INSTALL_FAILED",`Could not rescue controlled-instance ${e.identity.version} in stopped container ${t}.`,n)}const r=await this.inspectContainerForStart(t);if(!r)throw Pc("INSTANCE_RUNTIME_INSTALL_FAILED",`Docker container ${t} disappeared during runtime install recovery.`);if(Hc(t,r.id,i.id,"after runtime install recovery","INSTANCE_RUNTIME_INSTALL_FAILED"),r.running)throw Pc("INSTANCE_RUNTIME_INSTALL_FAILED",`Stopped Docker container ${t} changed lifecycle state during runtime install recovery.`)}async installRuntimeLauncher(e,t){const n=await this.inspectContainerId(e);if(!n)throw Pc("INSTANCE_BASE_RUNTIME_INCOMPATIBLE",`Docker container ${e} does not exist.`);Hc(e,n,t,"before runtime launcher install","INSTANCE_BASE_RUNTIME_INCOMPATIBLE");try{await this.runCommand("docker",["exec","--user","0",n,"bash","-ceu",`test -r ${mc}; test -r ${pc}/instance-launcher.sh; test -r ${yc}; install -d -o root -g root -m 0755 /opt/task-handoff/instance-runtime /opt/task-handoff/instance-runtime/releases /opt/task-handoff/instance-runtime/staging /opt/task-handoff/instance-runtime/incoming; chown -R root:root /opt/task-handoff/instance-runtime; chmod -R go-w /opt/task-handoff/instance-runtime`])}catch(t){throw Pc("INSTANCE_BASE_RUNTIME_INCOMPATIBLE",`Could not install the runtime launcher in ${e}.`,t)}const i=await this.inspectContainerId(e);if(i!==n)throw Pc("INSTANCE_BASE_RUNTIME_INCOMPATIBLE",`Docker container identity changed while installing the runtime launcher in ${e}.`);Hc(e,i,t,"after runtime launcher install","INSTANCE_BASE_RUNTIME_INCOMPATIBLE")}async inspectContainerId(e){try{return(await this.runCommand("docker",["inspect","--format","{{.Id}}",e])).stdout.trim()||void 0}catch(t){if($c(t))return;throw Pc("RUNTIME_EXECUTOR_FAILED",`Could not inspect Docker container ${e}.`,t)}}async inspectContainerForStart(e){let t;try{t=await this.runCommand("docker",["inspect","--format","{{json .}}",e])}catch(t){if($c(t))return;throw Pc("RUNTIME_EXECUTOR_FAILED",`Could not inspect Docker container ${e}.`,t)}try{const e=JSON.parse(t.stdout||"{}");if("string"!=typeof e.Id||!e.Id)throw new Error("Docker inspect did not return a container id.");const n=e.Config?.Labels&&"object"==typeof e.Config.Labels&&!Array.isArray(e.Config.Labels)?Object.fromEntries(Object.entries(e.Config.Labels).filter(e=>"string"==typeof e[1])):{},i=Array.isArray(e.Mounts)?e.Mounts.flatMap(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return[];const t=e,n="volume"===t.Type||"bind"===t.Type?t.Type:void 0,i="string"==typeof t.Destination?t.Destination:void 0;return n&&i?[{type:n,destination:i,name:"string"==typeof t.Name?t.Name:void 0,source:"string"==typeof t.Source?t.Source:void 0}]:[]}):[],s=Array.isArray(e.Config?.Entrypoint)?e.Config.Entrypoint.filter(e=>"string"==typeof e):"string"==typeof e.Config?.Entrypoint?[e.Config.Entrypoint]:[],o=Array.isArray(e.Config?.Cmd)?e.Config.Cmd.filter(e=>"string"==typeof e):"string"==typeof e.Config?.Cmd?[e.Config.Cmd]:[];return{id:e.Id,image:"string"==typeof e.Image?e.Image:void 0,running:!0===e.State?.Running,entrypoint:s,command:o,labels:n,mounts:i}}catch(t){throw Pc("RUNTIME_EXECUTOR_FAILED",`Docker returned invalid inspection data for ${e}.`,t)}}async containerPort(e,t){let n,i=!1;for(const s of this.portResolutionRetryDelaysMs){s>0&&await Cc(s);try{const n=zc((await this.runCommand("docker",["port",e,t])).stdout);if(n)return n}catch(e){n=e}try{const n=xc((await this.runCommand("docker",["inspect","--format","{{json .NetworkSettings.Ports}}",e])).stdout,t);if(i=!0,n)return n}catch(e){n=e}}if(i)throw Pc("RUNTIME_EXECUTOR_FAILED",`Docker container ${e} does not publish ${t}.`);throw Pc("RUNTIME_EXECUTOR_FAILED",`Could not resolve the published port for Docker container ${e}.`,n)}}function zc(e){const t=e.split(/\r?\n/).find(Boolean);return t?.match(/:(\d+)$/)?.[1]}function xc(e,t){const n=JSON.parse(e||"null");if(!n||"object"!=typeof n||Array.isArray(n))return;const i=n[t];if(Array.isArray(i))for(const e of i){if(!e||"object"!=typeof e||Array.isArray(e))continue;const t=e.HostPort;if("string"==typeof t&&/^\d+$/.test(t))return t}}function Cc(e){return new Promise(t=>setTimeout(t,e))}function kc(e){return"linux"===e||"darwin"===e?e:"windows"===e||"win32"===e?"win32":void 0}function Dc(e){return"amd64"===e||"x86_64"===e||"x64"===e?"x64":"arm64"===e||"aarch64"===e?"arm64":void 0}function Lc(e){return`task-handoff/environment-image:${e.replace(/^sha256:/,"")}`}function Pc(e,t,n){const i=Fc(n),s=new Error(i?`${t} Cause: ${i}`:t,void 0===n?void 0:{cause:n});return Object.assign(s,{statusCode:502,code:e}),s}const Mc=new Set(["AUTHENTICATION_REJECTED","CLONE_FAILED","CREDENTIAL_AMBIGUOUS","CREDENTIAL_MISSING","HOST_KEY_REQUIRED","LFS_FAILED","REF_NOT_FOUND","REMOTE_UNSUPPORTED","SSH_AGENT_UNAVAILABLE","SUBDIRECTORY_NOT_FOUND","WORKSPACE_NOT_EMPTY","WORKSPACE_OWNERSHIP_MISMATCH"]),jc="GIT_WORKSPACE_PROVISIONING_PENDING";function Uc(e){const t=e&&"object"==typeof e?e:void 0,n="string"==typeof t?.code?t.code:"";if("RUNTIME_COMMAND_TIMEOUT"===n)return"GIT_WORKSPACE_PROVISIONING_TIMEOUT";if("RUNTIME_COMMAND_ABORTED"===n)return"GIT_WORKSPACE_PROVISIONING_CANCELLED";const i=Fc(e)||"",s=i.match(/TASK_HANDOFF_GIT_PROVISIONING_ERROR=([A-Z_]+)/)?.[1];return`GIT_WORKSPACE_PROVISIONING_${s&&Mc.has(s)?s:"FAILED"}`}function Fc(e){if(!e||"object"!=typeof e)return void 0===e?void 0:String(e);const t=e,n=t.details?.stderr||t.details?.stdout;return"string"==typeof n&&n.trim()?n.trim():"string"==typeof t.message&&t.message.trim()?t.message.trim():void 0}function $c(e){const t=Fc(e)?.toLowerCase()||"";return t.includes("no such container")||t.includes("no such object")}function Hc(e,t,n,i,s){if(n&&t!==n)throw Pc(s,`Docker container ${e} identity mismatch ${i}: expected ${n}, got ${t}.`)}async function qc(e=qa){return async function(e=qa){return(await e("docker",["images","--digests","--format","{{json .}}"])).stdout.split(/\r?\n/).map(e=>e.trim()).filter(Boolean).map(e=>{const t=JSON.parse(e),n=t.Repository||"<none>",i=t.Tag||"<none>",s=t.ID||t.IDShort||"",o="<none>"!==n&&"<none>"!==i?`${n}:${i}`:s,r="<none>"!==n&&t.Digest&&"<none>"!==t.Digest?[`${n}@${t.Digest}`]:[];return{repository:n,tag:i,id:s,createdSince:t.CreatedSince,size:t.Size,sizeBytes:Xa(t.Size),reference:o,repoDigests:r}}).filter(e=>Boolean(e.reference))}(e)}function Bc(e){return`task-handoff-${e.replace(/[^a-zA-Z0-9_.-]/g,"-")}`}function Vc(e,t,n){e.push("-e",`${t}=${n}`)}function Gc(e,t){const n="commit"===e.ref.type?"":e.ref.name,i="commit"===e.ref.type?e.ref.commit:"",s=e.clone?.depth?String(e.clone.depth):"",o=e.clone?.submodules?"true":"false",r=e.clone?.lfs?"true":"false",a=[["TASK_HANDOFF_WORKSPACE_GIT_URL",e.url],["TASK_HANDOFF_WORKSPACE_GIT_REF",n],["TASK_HANDOFF_WORKSPACE_GIT_COMMIT",i],["TASK_HANDOFF_WORKSPACE_GIT_DEPTH",s],["TASK_HANDOFF_WORKSPACE_GIT_SUBMODULES",o],["TASK_HANDOFF_WORKSPACE_GIT_LFS",r]];return t.legacy?a.concat([["TASK_HANDOFF_GIT_URL",e.url],["TASK_HANDOFF_GIT_REF",n],["TASK_HANDOFF_GIT_DEPTH",s],["TASK_HANDOFF_GIT_SUBMODULES",o],["TASK_HANDOFF_GIT_LFS",r]]):a}function Kc(e){if("local-folder"===e.project.source.type&&e.project.source.ownerNodeId&&e.project.source.ownerNodeId!==e.node.id){const e=new Error("Local folder projects can only start on the node that owns the folder.");throw Object.assign(e,{statusCode:400,code:"LOCAL_FOLDER_REQUIRES_OWNER_NODE"}),e}if(!e.image.requestedReference?.trim()){const e=new Error("Image profile must reference a registered image.");throw Object.assign(e,{statusCode:400,code:"IMAGE_PROFILE_INVALID"}),e}}const Wc="manifest.json",Yc=c.z.enum(["docker","kubernetes","local"]),Xc=c.z.record(c.z.string().trim().min(2).max(35),c.z.string().trim().min(1).max(160)),Jc=c.z.string().trim().min(1).max(105).regex(/^[a-z0-9][a-z0-9._-]*$/),Qc=c.z.string().trim().min(1).max(160),Zc=c.z.array(Yc).min(1).max(3),ed=c.z.object({schemaVersion:c.z.literal(1),id:Jc,name:Qc,localizedNames:Xc.optional(),runtimes:Zc,contentDigest:c.z.string().trim().regex(/^[a-f0-9]{64}$/)}).strict(),td=c.z.object({name:c.z.string().trim().min(1).max(64).regex(/^[a-z0-9][a-z0-9._-]*$/),targetDir:c.z.string().trim().min(1).max(512).optional()}).strict();function nd(e,t,n){return Object.assign(new Error(t),{code:e,statusCode:500,...n?{details:n}:{}})}function id(){const e=("undefined"==typeof document?require("url").pathToFileURL(__filename).href:z&&"SCRIPT"===z.tagName.toUpperCase()&&z.src||new URL("cli.js",document.baseURI).href)?n.dirname(o.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(__filename).href:z&&"SCRIPT"===z.tagName.toUpperCase()&&z.src||new URL("cli.js",document.baseURI).href)):__dirname,i=[n.resolve(e,"../../../../../builtin-projects"),n.resolve(e,"../builtin-projects"),n.resolve(e,"../../builtin-projects")];return i.find(sd)||i.find(e=>t.existsSync(e))||i[0]}function sd(e){try{return t.readdirSync(e,{withFileTypes:!0}).some(i=>i.isDirectory()&&t.existsSync(n.join(e,i.name,Wc)))}catch{return!1}}function od(e){const i=[],s=o=>{const r=o?n.join(e,o):e;for(const a of t.readdirSync(r,{withFileTypes:!0}).sort((e,t)=>e.name.localeCompare(t.name))){const r=o?`${o}/${a.name}`:a.name;if(a.isDirectory()){s(r);continue}if(!a.isFile())continue;const c=n.join(e,...r.split("/")),l=t.statSync(c);i.push({path:r,absolutePath:c,mode:511&l.mode,sha256:d.createHash("sha256").update(t.readFileSync(c)).digest("hex"),bytes:l.size})}};return s(""),i.sort((e,t)=>e.path.localeCompare(t.path))}function rd(e){const t=d.createHash("sha256");for(const n of e)t.update(`${n.path}\0${n.sha256}\n`);return t.digest("hex")}function ad(e){const i=n.join(e,Wc);let s;try{s=JSON.parse(t.readFileSync(i,"utf8"))}catch(t){throw nd("BUILTIN_PROJECT_MANIFEST_INVALID",`Built-in project manifest ${i} could not be read as JSON.`,{root:e,cause:t instanceof Error?t.message:String(t)})}const o=ed.safeParse(s);if(!o.success)throw nd("BUILTIN_PROJECT_MANIFEST_INVALID",`Built-in project manifest ${i} does not match the current schema.`,{root:e,issues:o.error.issues});return o.data}c.z.object({schemaVersion:c.z.literal(1),id:Jc,name:Qc,localizedNames:Xc.optional(),runtimes:Zc,skill:td.optional()}).strict();const cd=".task-handoff",dd="initialized.json",ld=c.z.object({schemaVersion:c.z.literal(1),projectId:c.z.string().trim().min(1).max(120),contentDigest:c.z.string().trim().regex(/^[a-f0-9]{64}$/),instanceId:c.z.string().trim().min(1).max(120).optional(),createdAt:c.z.string().trim().min(1).max(64)}).strict();function ud(e){try{const i=JSON.parse(t.readFileSync(function(e){return n.join(e,cd,dd)}(e),"utf8")),s=ld.safeParse(i);return s.success?s.data:void 0}catch{return}}function pd(e,t={}){return Object.assign(new Error(`Built-in project target ${e} already contains content this product did not initialize.`),{statusCode:409,code:"BUILTIN_PROJECT_TARGET_NOT_EMPTY",details:{targetDir:e,...t}})}function md(e){return`folder_builtin_${e}`}function hd(e,t){return n.join(e,t)}function gd(e){const i=e.definitions.filter(e=>e.runtimes.includes("local")).sort((e,t)=>e.id.localeCompare(t.id)),s=new Map(i.map(e=>[md(e.id),e])),o=t=>{const n=ud(hd(e.targetsDir,t.id));return n?.projectId===t.id?((t,n)=>Do.parse({id:md(t.id),nodeId:e.nodeId,name:t.name,path:hd(e.targetsDir,t.id),origin:"builtin",...t.localizedNames?{localizedNames:t.localizedNames}:{},labels:{},createdAt:n.createdAt,updatedAt:n.createdAt}))(t,n):void 0};return{list:()=>i.flatMap(e=>{const t=o(e);return t?[t]:[]}),get(e){const t=s.get(e);return t?o(t):void 0},owns:e=>s.has(e),prepare:()=>i.map(i=>function(e,i){const s=hd(i,e.id);try{const i=function(e,i,s={}){const o=ud(i);if(o)return{status:"already-initialized",targetDir:i,projectId:o.projectId,contentDigest:o.contentDigest};const r=t.existsSync(i);if(r){if(!t.statSync(i).isDirectory())throw pd(i,{reason:"target-is-not-a-directory"});if(a=i,0!==t.readdirSync(a).length)throw pd(i,{reason:"target-is-not-empty"})}var a;const c=n.dirname(i);t.mkdirSync(c,{recursive:!0,mode:493});const d=t.mkdtempSync(n.join(c,`.${n.basename(i)}.staging-`));try{for(const i of e.files){const e=n.join(d,...i.path.split("/"));t.mkdirSync(n.dirname(e),{recursive:!0,mode:493}),t.writeFileSync(e,t.readFileSync(i.absolutePath),{mode:i.mode}),t.chmodSync(e,i.mode)}const o={schemaVersion:1,projectId:e.id,contentDigest:e.contentDigest,...s.instanceId?{instanceId:s.instanceId}:{},createdAt:s.createdAt||(new Date).toISOString()};t.mkdirSync(n.join(d,cd),{recursive:!0,mode:493}),t.writeFileSync(n.join(d,cd,dd),`${JSON.stringify(o,null,2)}\n`,{mode:420}),r&&t.rmdirSync(i),t.renameSync(d,i)}catch(e){throw t.rmSync(d,{recursive:!0,force:!0}),e}return{status:"initialized",targetDir:i,projectId:e.id,contentDigest:e.contentDigest,filesWritten:e.files.length}}(e,s);return i.projectId!==e.id?{projectId:e.id,status:"failed",targetDir:s,code:"BUILTIN_PROJECT_TARGET_OWNED",message:`Built-in project target ${s} is marked as ${i.projectId}.`}:{projectId:e.id,status:i.status,targetDir:s,..."initialized"===i.status?{filesWritten:i.filesWritten}:{}}}catch(t){return{projectId:e.id,status:"failed",targetDir:s,code:t.code||"BUILTIN_PROJECT_INITIALIZATION_FAILED",message:t instanceof Error?t.message:String(t)}}}(i,e.targetsDir))}}const fd="app.sessions";c.z.object({type:c.z.literal("snapshot"),data:c.z.string(),pendingEscape:c.z.string(),cols:c.z.number().int().positive(),rows:c.z.number().int().positive()}).passthrough();const yd="app-session.snapshot",Id="app-session.patch",_d="app-session.removed",Ed=c.z.enum(["created","starting","running","stopping","stopped","exited","failed","closed","terminated","unknown"]),Ad=c.z.enum(["tty","vnc","web"]);c.z.object({mode:Ad,url:c.z.string().trim().min(1).max(4096),token:c.z.string().trim().min(1).max(512),expiresAt:c.z.string().datetime()}).strict(),c.z.object({revoked:c.z.boolean()}).strict();const Td=c.z.object({name:c.z.string().trim().min(1).max(240),size:c.z.number().int().nonnegative(),updatedAt:c.z.string().datetime(),truncated:c.z.boolean(),content:c.z.string()}).strict();c.z.object({sessionId:c.z.string().trim().min(1).max(160),logDir:c.z.string().trim().min(1).max(1024),maxBytes:c.z.number().int().positive(),files:c.z.array(Td).max(256)}).strict();const wd=new Set(["stopped","failed","exited","closed","terminated"]),bd=c.z.object({type:c.z.enum(["app-session","provider-session","adapter-key"]),id:c.z.string().trim().min(1).max(240),agent:c.z.string().trim().min(1).max(80).optional(),adapter:c.z.string().trim().min(1).max(80).optional(),key:c.z.string().trim().min(1).max(240).optional()}).strict(),Nd=c.z.record(c.z.string(),c.z.unknown()).and(c.z.object({id:c.z.string().trim().min(1).max(160),appId:c.z.string().trim().min(1).max(160).optional(),title:c.z.string().trim().max(240).optional(),kind:c.z.string().trim().max(80).optional(),status:Ed.default("unknown"),bindings:c.z.array(bd).max(40).default([]),workspace:c.z.object({cwd:c.z.string().trim().max(4096).optional()}).strict().optional(),createdAt:c.z.string().datetime().optional(),updatedAt:c.z.string().datetime().optional()})),Sd=c.z.object({runningCount:c.z.number().int().min(0).default(0),problemCount:c.z.number().int().min(0).default(0),sessions:c.z.array(Nd).default([]),updatedAt:c.z.string().datetime()}).strict(),vd=c.z.object({streamId:c.z.string().trim().min(1).max(240),revision:c.z.number().int().min(0),lastEventAt:c.z.string().datetime(),snapshot:Sd}).strict();Sd.pick({runningCount:!0,problemCount:!0,updatedAt:!0}).extend({revision:c.z.number().int().min(0).optional()});const Od=c.z.enum(["app-session-created","app-session-updated","app-session-deleted","app-session-recovered","control-action","heartbeat-sync","startup"]),Rd=c.z.object({streamId:c.z.string().trim().min(1).max(240),instanceId:c.z.string().trim().min(1).max(160),nodeId:c.z.string().trim().min(1).max(160).optional(),revision:c.z.number().int().min(0),previousRevision:c.z.number().int().min(0).optional(),traceId:c.z.string().trim().min(1).max(160),generatedAt:c.z.string().datetime(),reason:Od}).strict(),zd=c.z.object({meta:Rd,snapshot:Sd}).strict(),xd=c.z.object({meta:Rd,session:Nd}).strict(),Cd=c.z.object({meta:Rd,sessionId:c.z.string().trim().min(1).max(160),tombstone:Nd.optional(),expiresAt:c.z.string().datetime().optional()}).strict();function kd(e,t=(new Date).toISOString()){const n=e.map(e=>function(e){const t=Ld("string"==typeof e.status?e.status:void 0),n="string"==typeof e.id?e.id:"",i=function(e){const t=Fd(e.workspace),n=Fd(e.tty),i=Fd(e.launch),s=Fd(e.ai),o=Fd(s.claude),r=$d(t.cwd)||$d(n.cwd)||$d(o.cwd)||$d(i.cwd);return r?{cwd:r}:void 0}(e),{workspace:s,...o}=e;return Nd.parse({...o,status:t,bindings:Ud([...(r=e.bindings,Array.isArray(r)?r.flatMap(e=>{const t=bd.safeParse(e);return t.success?[t.data]:[]}):[]),...n?[{type:"app-session",id:n}]:[],...jd(e)]),...i?{workspace:i}:{}});var r}(e));return Sd.parse({runningCount:n.filter(e=>"running"===e.status).length,problemCount:n.filter(e=>"failed"===e.status).length,sessions:n,updatedAt:t})}function Dd(e,t=(new Date).toISOString()){return kd(e.filter(e=>Pd("string"==typeof e.status?e.status:void 0)),t)}function Ld(e){const t=(e||"unknown").trim().toLowerCase();return"ended"===t?"closed":"terminating"===t?"stopping":Ed.options.includes(t)?t:"unknown"}function Pd(e){return!wd.has(Ld(e))}function Md(e){return"app-session"===e.type?`app:${e.id}`:"provider-session"===e.type?`provider:${e.agent||""}:${e.id}`:`adapter:${e.adapter||""}:${e.key||e.id}`}function jd(e){const t=Fd(e.ai),n=Fd(t.claude),i=Fd(t.appServer),s=Fd(e.launch),o=[],r=$d(Fd(s.aiSessionResume).providerSessionId),a="codex"===e.appId||"claude"===e.appId||"opencode"===e.appId?e.appId:void 0;a&&r&&o.push({type:"provider-session",agent:a,id:r});const c=$d(n.short);c&&o.push({type:"adapter-key",adapter:"claude",agent:"claude",id:`short:${c}`,key:`short:${c}`});const d=$d(n.providerSessionId);d&&o.push({type:"provider-session",agent:"claude",id:d});const l=Array.isArray(t.threadIds)?t.threadIds.filter(e=>"string"==typeof e&&Boolean(e.trim())):[],u=$d(t.activeThreadId);for(const e of[...new Set([u,...l].filter(Boolean))])o.push({type:"provider-session",agent:"codex",id:e});const p=$d(i.socketPath),m=$d(i.endpoint),h=p?`socket:${p}`:m?`endpoint:${m}`:"";return h&&o.push({type:"adapter-key",adapter:"codex-app-server",agent:"codex",id:h,key:h}),o}function Ud(e){const t=new Map;for(const n of e)t.set(Md(n),n);return[...t.values()]}function Fd(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}function $d(e){return"string"==typeof e&&e.trim()?e.trim():""}c.z.object({streamId:c.z.string().trim().min(1).max(240),instanceId:c.z.string().trim().min(1).max(160),sinceRevision:c.z.number().int().min(0),latestRevision:c.z.number().int().min(0),earliestRetainedRevision:c.z.number().int().min(0),syncRequired:c.z.boolean().default(!1),events:c.z.array(c.z.discriminatedUnion("type",[c.z.object({type:c.z.literal(yd),payload:zd}).strict(),c.z.object({type:c.z.literal(Id),payload:xd}).strict(),c.z.object({type:c.z.literal(_d),payload:Cd}).strict()])).default([])}).strict();const Hd="2026-08-25",qd=c.z.object({nodeId:c.z.string().optional(),instanceId:c.z.string().optional()}).passthrough(),Bd=c.z.object({v:c.z.literal(1),id:c.z.string().min(1),seq:c.z.number().finite(),type:c.z.string().min(1),topic:c.z.string().min(1),createdAt:c.z.string().datetime(),payload:c.z.unknown(),replay:c.z.literal(!0).optional(),scope:qd.optional()}).passthrough(),Vd=c.z.object({v:c.z.literal(Hd),id:c.z.string().min(1),type:c.z.string().min(1),createdAt:c.z.string().datetime(),payload:c.z.unknown(),topic:c.z.string().min(1).optional(),replay:c.z.literal(!0).optional(),scope:qd.optional()}).passthrough();function Gd(e){return e.startsWith("ai-session.")||e.startsWith("ai.session.")?"ai.sessions":e.startsWith("app-session.")?"app.sessions":e.startsWith("app.management")?"apps":e.startsWith("trigger.")?"triggers":e.startsWith("instance.")?"instances":e.startsWith("node.")?"nodes":e.startsWith("project.")?"projects":e.startsWith("model.")?"models":e.startsWith("image.")?"images":e.startsWith("market.")?"market":e.startsWith("story.")?"stories":e.startsWith("agent.")?"agents":"system"}c.z.discriminatedUnion("v",[Bd,Vd]),c.z.object({v:c.z.literal(1),type:c.z.literal("ping"),sentAt:c.z.string().datetime()}).strict(),c.z.object({v:c.z.literal(1),type:c.z.literal("pong"),sentAt:c.z.string().datetime(),receivedAt:c.z.string().datetime()}).strict();const Kd=c.z.object({replaySince:c.z.string().datetime().optional(),messageDeltas:c.z.object({allInstances:c.z.boolean().default(!1),instanceIds:c.z.array(c.z.string().trim().min(1).max(160)).max(1e3).default([])}).default({allInstances:!1,instanceIds:[]}),timelineAllSessions:c.z.boolean().default(!1),timelineSessions:c.z.array(c.z.object({instanceId:c.z.string().trim().min(1).max(160),sessionId:c.z.string().trim().min(1).max(120)})).max(1e3).default([])}),Wd=c.z.enum(["ai.sessions","app.sessions"]),Yd=c.z.object({topic:Wd,instanceId:c.z.string().trim().min(1).max(160),streamId:c.z.string().trim().min(1).max(240),latestRevision:c.z.number().int().min(0),earliestRetainedRevision:c.z.number().int().min(0)}).strict(),Xd=c.z.object({protocolVersion:c.z.literal(1),streams:c.z.array(Yd)}).strict();function Jd(e,t=Math.random){const n=Math.max(1,Math.floor(e));if(1===n)return 0;if(2===n)return 250;const i=Math.min(6e4,250*2**(n-2));return Math.min(6e4,Math.round(i*(.75+.5*t())))}class Qd{retryNumber=0;random;constructor(e=Math.random){this.random=e}get attempts(){return this.retryNumber}next(){return this.retryNumber+=1,{attempt:this.retryNumber,delay:Jd(this.retryNumber,this.random)}}reset(){this.retryNumber=0}}class Zd{backoff;timer;constructor(e=Math.random){this.backoff=new Qd(e)}get pending(){return Boolean(this.timer)}get attempts(){return this.backoff.attempts}schedule(e,t={}){if(this.timer)return;const n=this.backoff.next(),i=t.setTimeoutFn||setTimeout;return this.timer=i(()=>{this.timer=void 0,e()},n.delay),n}reset(e=clearTimeout){this.timer&&e(this.timer),this.timer=void 0,this.backoff.reset()}cancel(e=clearTimeout){this.timer&&e(this.timer),this.timer=void 0}}class el extends Zd{}function tl(e,t=6e4){const n=[];for(let i=0;i<e.length;i+=t)n.push(e.slice(i,i+t));return n}const nl=262144,il=4194304;class sl{sockets=new Map;socketUrls=new Map;retries=new Map;outputs=new Set;outputSubscriptions=new Map;outputEnvelopeVersions=new Map;outputHierarchy=new Map;outputDiagnostics=new Map;aiSessionProjectionByInstance=new Map;appSessionProjectionByInstance=new Map;sessionStreamsHelloByInstance=new Map;sessionAuthorityReplayedOutputs=new Set;pendingAiSessionAuthorityByOutput=new Map;pendingAiSessionAuthorityFlush=new Map;eventTransportCongestion;imagePullTerminalByInstance=new Map;gitProvisioningTerminalByInstance=new Map;state;token;logger;safetyIntervalMs;lastAiSessionEventByInstance=new Map;lastAppSessionEventByInstance=new Map;timer;stopped=!1;reconnectAttempts=0;safetyReconciliations=0;localSequence=0;outputSequence=0;createSocket;setIntervalFn;clearIntervalFn;setTimeoutFn;clearTimeoutFn;constructor(e,t,n={}){var i;this.state=e,this.token=t,this.logger=n.logger,this.safetyIntervalMs=(i=n.safetyIntervalMs,Math.min(6e4,Math.max(3e4,i??45e3))),this.createSocket=n.createSocket||((e,t)=>new h(e,t)),this.setIntervalFn=n.setIntervalFn||setInterval,this.clearIntervalFn=n.clearIntervalFn||clearInterval,this.setTimeoutFn=n.setTimeoutFn||setTimeout,this.clearTimeoutFn=n.clearTimeoutFn||clearTimeout}start(){this.stopped=!1,this.sync(),this.timer=this.setIntervalFn(()=>{this.safetyReconciliations+=1,this.sync()},this.safetyIntervalMs)}stop(){this.stopped=!0,this.timer&&(this.clearIntervalFn(this.timer),this.timer=void 0);for(const e of this.sockets.values())e.close();this.sockets.clear(),this.socketUrls.clear();for(const e of this.retries.values())e.timer.cancel();this.retries.clear(),this.outputs.clear(),this.outputSubscriptions.clear(),this.outputEnvelopeVersions.clear(),this.outputHierarchy.clear(),this.outputDiagnostics.clear();for(const e of this.pendingAiSessionAuthorityFlush.values())this.clearTimeoutFn(e);this.pendingAiSessionAuthorityFlush.clear(),this.pendingAiSessionAuthorityByOutput.clear(),this.aiSessionProjectionByInstance.clear(),this.appSessionProjectionByInstance.clear(),this.sessionStreamsHelloByInstance.clear(),this.sessionAuthorityReplayedOutputs.clear()}addOutput(e,t={}){let n;this.outputs.add(e),this.outputDiagnostics.set(e,{outputId:"event_output_"+ ++this.outputSequence,kind:t.expectsTransientSubscription?"events-websocket":void 0!==t.legacyFallbackMs?"reverse-tunnel":"legacy"}),this.outputSubscriptions.set(e,t.expectsTransientSubscription?Kd.parse({}):void 0),this.outputEnvelopeVersions.set(e,1),this.outputHierarchy.set(e,Yi.parse(void 0)),t.expectsTransientSubscription||void 0===t.legacyFallbackMs||(n=this.setTimeoutFn(()=>{n=void 0,this.outputs.has(e)&&void 0===this.outputSubscriptions.get(e)&&(this.replaySessionAuthority(e),this.syncNow())},t.legacyFallbackMs));let i=!1;const s=()=>{if(i)return;i=!0,this.outputs.delete(e),this.outputSubscriptions.delete(e),this.outputEnvelopeVersions.delete(e),this.outputHierarchy.delete(e),this.outputDiagnostics.delete(e),this.sessionAuthorityReplayedOutputs.delete(e);const t=this.pendingAiSessionAuthorityFlush.get(e);t&&this.clearTimeoutFn(t),this.pendingAiSessionAuthorityFlush.delete(e),this.pendingAiSessionAuthorityByOutput.delete(e),this.refreshEventTransportRecovery(),n&&clearTimeout(n),this.stopped||this.syncNow()};e.on("close",s),e.on("error",s);for(const t of this.state.listInstances()){const n=ol(t);n?this.sendForwarded(e,this.createEvent(Ta,n,{instanceId:t.id})):this.logger?.warn?.({instanceId:t.id},"instance.lifecycle.snapshot.invalid")}for(const[t,n]of this.imagePullTerminalByInstance)tl(n.tail).forEach((i,s)=>this.sendForwarded(e,this.createEvent(Dr,{...n.output,sequence:n.output.sequence+s,data:i,...0===s?{replay:!0}:{}},{instanceId:t}))),n.finished&&this.sendForwarded(e,this.createEvent(Lr,n.finished,{instanceId:t}));for(const[t,n]of this.gitProvisioningTerminalByInstance)tl(n.tail).forEach((i,s)=>this.sendForwarded(e,this.createEvent($r,{...n.output,sequence:n.output.sequence+s,data:i,...0===s?{replay:!0}:{}},{instanceId:t}))),n.finished&&this.sendForwarded(e,this.createEvent(Hr,n.finished,{instanceId:t}));return(t.expectsTransientSubscription||void 0===t.legacyFallbackMs)&&(this.replaySessionAuthority(e),this.syncNow()),s}setOutputSubscription(e,t,n,i){if(!this.outputs.has(e))return!1;const s=Kd.safeParse(t),o=Yi.safeParse(i);if(!s.success||!o.success)return!1;this.outputSubscriptions.set(e,s.data),this.outputEnvelopeVersions.set(e,n===Hd?Hd:1),this.outputHierarchy.set(e,o.data),this.replaySessionAuthority(e),this.syncNow();for(const[e,t]of this.sockets)this.sendInstanceSubscription(e,t);return!0}publish(e,t,n={}){this.rememberImagePullTerminal(e,t),this.rememberGitProvisioningTerminal(e,t);const i=this.createEvent(e,t,n);for(const e of this.outputs)this.sendForwarded(e,i)}rememberImagePullTerminal(e,t){if(e===Dr){const e=ja(Mr,t);if(!e.success)return;const n=e.data,i=this.imagePullTerminalByInstance.get(n.instanceId);if(i&&n.generation<i.output.generation)return;const s=i?.output.generation===n.generation,o=n.replay||!s?n.data:`${i.tail}${n.data}`.slice(-262144);return void this.imagePullTerminalByInstance.set(n.instanceId,{output:n,tail:o})}if(e===Lr){const e=ja(jr,t);if(!e.success)return;const n=e.data,i=this.imagePullTerminalByInstance.get(n.instanceId);i?.output.generation===n.generation&&(i.finished=n)}}rememberGitProvisioningTerminal(e,t){if(e===$r){const e=ja(Br,t);if(!e.success)return;const n=e.data,i=this.gitProvisioningTerminalByInstance.get(n.instanceId);if(i&&n.generation<i.output.generation)return;const s=i?.output.generation===n.generation,o=n.replay||!s?n.data:`${i.tail}${n.data}`.slice(-262144);return void this.gitProvisioningTerminalByInstance.set(n.instanceId,{output:n,tail:o})}if(e===Hr){const e=ja(Vr,t);if(!e.success)return;const n=e.data,i=this.gitProvisioningTerminalByInstance.get(n.instanceId);i?.output.generation===n.generation&&(i.finished=n)}}publishInstanceLifecycle(e){this.publish(Ta,function(e){return wa.parse(rl(e))}(e),{instanceId:e.id});const t=this.imagePullTerminalByInstance.get(e.id);"ready"===e.imageProvisioning?.phase&&"succeeded"===t?.finished?.outcome&&this.imagePullTerminalByInstance.delete(e.id);const n=this.gitProvisioningTerminalByInstance.get(e.id);"ready"===e.workspace.gitProvisioning?.phase&&"succeeded"===n?.finished?.outcome&&this.gitProvisioningTerminalByInstance.delete(e.id)}createEvent(e,t,n){const i=++this.localSequence;return{v:1,id:`node_evt_${Date.now().toString(36)}_${i.toString(36)}`,seq:i,type:e,topic:Gd(e),createdAt:(new Date).toISOString(),payload:t,scope:n}}sendForwarded(e,t){const n=cl(t),i=n?function(e,t){return t?.subagents||e.type===Ue?e:e.type===Me?{...e,payload:{...e.payload,snapshot:_n(e.payload.snapshot,t)}}:{...e,payload:{...e.payload,upserted:e.payload.upserted.map(e=>In(e,t))}}}(n,this.outputHierarchy.get(e)):void 0,s=i&&i.payload!==t.payload?{...t,payload:i.payload}:t,o=t.type===Fe?mn.safeParse(t.payload):void 0,r=t.type===He?gn.safeParse(t.payload):void 0,a=this.outputEnvelopeVersions.get(e)===Hd?function(e,t,n={}){const i=e.scope?n.publicScope&&e.scope.instanceId?{instanceId:e.scope.instanceId}:e.scope:void 0;return{v:Hd,id:e.id,type:e.type,createdAt:e.createdAt,payload:void 0===n.payload?e.payload:n.payload,...e.topic!==Gd(e.type)?{topic:e.topic}:{},...e.replay?{replay:!0}:{},...i&&Object.keys(i).length?{scope:i}:{}}}(s,0,{...o?.success?{payload:(c=o.data,hn.parse({sessionId:c.sessionId,turnId:c.turnId,itemId:c.itemId,delta:c.delta,generatedAt:c.generatedAt}))}:{},...r?.success?{payload:yn(r.data)}:{}}):s;var c;const d=JSON.stringify({type:"node-agent.event.forwarded",event:a});this.sendOutput(e,d,s)}sendOutput(e,t,n){const i=Buffer.byteLength(t,"utf8"),s=n?.topic===fd?"app-session":n?.topic===Pe?"ai-session":void 0,o=s?{...this.outputDiagnostics.get(e),instanceId:n.scope?.instanceId,eventType:n.type,...al(n.payload)}:void 0;if(e.readyState!==h.OPEN)return o&&this.logger?.warn?.({...o,readyState:e.readyState,outcome:"not-open"},`${s}.event.output.rejected`),!1;if(n&&this.shouldCoalesceAiSessionAuthority(e,n)&&this.deferAiSessionAuthority(e,n))return!0;if(n&&dl(n)&&i>il){if(n.type!==Me&&this.deferAiSessionAuthority(e,n))return!0;this.observeEventTransportCongestion(e,!1,i),o&&this.logger?.warn?.({...o,bufferedAmount:e.bufferedAmount,bytes:i,maxBytes:il,outcome:"payload-too-large"},`${s}.event.output.rejected`);try{e.close(1009,"AI Session authority event exceeds the transport limit.")}catch{}return!1}if(e.bufferedAmount+i>16777216){this.observeEventTransportCongestion(e,!1),o&&this.logger?.warn?.({...o,bufferedAmount:e.bufferedAmount,outcome:"backpressure"},`${s}.event.output.rejected`);try{e.close(1013,"Event consumer is too slow.")}catch{}return!1}try{return e.send(t),o&&this.logger?.info?.({...o,bufferedAmount:e.bufferedAmount,bytes:i,outcome:"queued"},`${s}.event.output.queued`),!0}catch(t){o&&this.logger?.warn?.({...o,error:t instanceof Error?t.message:String(t),outcome:"send-failed"},`${s}.event.output.rejected`);try{e.close(1011,"Event delivery failed.")}catch{}return!1}}shouldCoalesceAiSessionAuthority(e,t){if(!dl(t))return!1;const n=t.scope?.instanceId;return!!n&&(!!this.pendingAiSessionAuthorityByOutput.get(e)?.has(n)||e.bufferedAmount>=nl)}deferAiSessionAuthority(e,t){const n=t.scope?.instanceId,i=n?this.aiSessionProjectionByInstance.get(n):void 0;if(!n||!i)return!1;const s=function(e,t){const n=cl(e);return n?n.payload.meta.streamId!==t.streamId||n.payload.meta.revision!==t.revision?void 0:ln.parse({meta:n.payload.meta,snapshot:t.snapshot}):void 0}(t,i);if(!s)return!1;const o=this.pendingAiSessionAuthorityByOutput.get(e)||new Map;return o.set(n,{...t,type:Me,topic:Pe,payload:s}),this.pendingAiSessionAuthorityByOutput.set(e,o),this.observeEventTransportCongestion(e,!0),this.logger?.info?.({...this.outputDiagnostics.get(e),instanceId:n,eventType:t.type,...al(s),bufferedAmount:e.bufferedAmount,outcome:"coalesced-latest"},"ai-session.event.output.coalesced"),this.scheduleAiSessionAuthorityFlush(e),!0}scheduleAiSessionAuthorityFlush(e){if(this.pendingAiSessionAuthorityFlush.has(e))return;const t=this.setTimeoutFn(()=>{this.pendingAiSessionAuthorityFlush.delete(e),this.flushAiSessionAuthority(e)},25);t.unref?.(),this.pendingAiSessionAuthorityFlush.set(e,t)}flushAiSessionAuthority(e){const t=this.pendingAiSessionAuthorityByOutput.get(e);if(!t?.size)return void this.pendingAiSessionAuthorityByOutput.delete(e);if(e.readyState!==h.OPEN)return void this.pendingAiSessionAuthorityByOutput.delete(e);const[n,i]=t.entries().next().value;e.bufferedAmount>=nl?this.scheduleAiSessionAuthorityFlush(e):(t.delete(n),t.size||this.pendingAiSessionAuthorityByOutput.delete(e),this.sendForwarded(e,i),this.refreshEventTransportRecovery(),t.size&&this.scheduleAiSessionAuthorityFlush(e))}observeEventTransportCongestion(e,t,n=0){const i=(new Date).toISOString(),s=Math.max(0,Math.floor(e.bufferedAmount)),o=this.eventTransportCongestion;this.eventTransportCongestion={congestedSince:o?.recoveredAt?i:o?.congestedSince||i,lastCongestedAt:i,peakBufferedBytes:Math.max(o?.recoveredAt?0:o?.peakBufferedBytes||0,s),coalescedEvents:(o?.recoveredAt?0:o?.coalescedEvents||0)+(t?1:0),oversizedEvents:(o?.recoveredAt?0:o?.oversizedEvents||0)+(n>0?1:0),peakEventBytes:Math.max(o?.recoveredAt?0:o?.peakEventBytes||0,n)}}eventTransportIsCongested(){return!![...this.pendingAiSessionAuthorityByOutput.values()].some(e=>e.size>0)||[...this.outputs].some(e=>e.readyState===h.OPEN&&e.bufferedAmount>=nl)}refreshEventTransportRecovery(){const e=this.eventTransportCongestion;!e||e.recoveredAt||this.eventTransportIsCongested()||(e.recoveredAt=(new Date).toISOString())}eventTransportHealth(){this.refreshEventTransportRecovery();const e=[...this.outputs].filter(e=>e.readyState===h.OPEN),t=e.reduce((e,t)=>Math.max(e,Math.max(0,Math.floor(t.bufferedAmount))),0),n=this.eventTransportIsCongested();let i=this.eventTransportCongestion;return i?.recoveredAt&&Date.now()-Date.parse(i.recoveredAt)>3e5&&(this.eventTransportCongestion=void 0,i=void 0),{status:n?"congested":i?"recovering":"healthy",activeOutputs:e.length,bufferedBytes:t,peakBufferedBytes:i?.peakBufferedBytes||t,coalescedEvents:i?.coalescedEvents||0,oversizedEvents:i?.oversizedEvents||0,peakEventBytes:i?.peakEventBytes||0,...n&&i?{congestedSince:i.congestedSince}:{},...i?{lastCongestedAt:i.lastCongestedAt}:{}}}syncNow(){this.sync()}diagnostics(){const e=[...this.outputSubscriptions.values()];return{reconnectAttempts:this.reconnectAttempts,safetyReconciliations:this.safetyReconciliations,activeConnections:this.sockets.size,pendingRetries:[...this.retries.values()].filter(e=>e.timer.pending).length,safetyIntervalMs:this.safetyIntervalMs,eventTransport:this.eventTransportHealth(),transientDemand:{legacyOutputs:e.filter(e=>void 0===e).length,scopedOutputs:e.filter(e=>void 0!==e).length,messageDeltaAllInstances:e.some(e=>e?.messageDeltas.allInstances),messageDeltaInstanceCount:new Set(e.flatMap(e=>e?.messageDeltas.instanceIds||[])).size,timelineAllSessions:e.some(e=>e?.timelineAllSessions),timelineSessionCount:new Set(e.flatMap(e=>e?.timelineSessions.map(e=>JSON.stringify([e.instanceId,e.sessionId]))||[])).size}}}sync(){const e=new Set(this.state.listInstances().map(e=>e.id));for(const t of this.aiSessionProjectionByInstance.keys())e.has(t)||this.aiSessionProjectionByInstance.delete(t);for(const t of this.appSessionProjectionByInstance.keys())e.has(t)||this.appSessionProjectionByInstance.delete(t);for(const t of this.sessionStreamsHelloByInstance.keys())e.has(t)||this.sessionStreamsHelloByInstance.delete(t);for(const t of this.imagePullTerminalByInstance.keys())e.has(t)||this.imagePullTerminalByInstance.delete(t);for(const t of this.gitProvisioningTerminalByInstance.keys())e.has(t)||this.gitProvisioningTerminalByInstance.delete(t);if(!this.outputs.size){for(const e of this.sockets.values())e.close();this.sockets.clear(),this.socketUrls.clear();for(const e of this.retries.values())e.timer.cancel();return void this.retries.clear()}const t=new Set;for(const e of this.state.listInstances()){const n=ll(e);if(!n)continue;t.add(e.id);const i=this.retries.get(e.id);i?.timer.pending&&i.url!==n&&(i.timer.cancel(),this.retries.delete(e.id)),this.socketUrls.get(e.id)!==n&&this.sockets.has(e.id)&&(this.sockets.get(e.id)?.close(),this.sockets.delete(e.id)),this.sockets.has(e.id)||this.retries.get(e.id)?.timer.pending||this.connect(e.id,n)}for(const[e,n]of this.sockets)if(!t.has(e)){n.close(),this.sockets.delete(e),this.socketUrls.delete(e);const t=this.retries.get(e);t?.timer.cancel(),this.retries.delete(e)}for(const[e,n]of this.retries)t.has(e)||(n.timer.cancel(),this.retries.delete(e),this.socketUrls.delete(e))}connect(e,t){const n=this.token?{authorization:`Bearer ${this.token}`}:void 0,i=this.createSocket(t,{headers:n});this.sockets.set(e,i),this.socketUrls.set(e,t),i.on("open",()=>{const n=this.retries.get(e);this.retries.set(e,{timer:n?.timer||new el,url:t}),i.readyState===h.OPEN&&(this.sendInstanceSubscription(e,i),this.logger?.info?.({instanceId:e,url:t},"ai-session.event.forward.connect"),this.logger?.info?.({instanceId:e,url:t},"app-session.event.forward.connect"))}),i.on("message",t=>{const n=function(e,t){try{const n=function(e,t={}){if(!e||"object"!=typeof e||Array.isArray(e))return;const n=e,i="string"==typeof n.type?n.type:"";if(!i)return;const s=n.scope&&"object"==typeof n.scope&&!Array.isArray(n.scope)?n.scope:{};return{v:1,id:"string"==typeof n.id?n.id:`event_${Date.now().toString(36)}`,seq:"number"==typeof n.seq&&Number.isFinite(n.seq)?n.seq:0,type:i,topic:"string"==typeof n.topic?n.topic:Gd(i),createdAt:"string"==typeof n.createdAt?n.createdAt:(new Date).toISOString(),payload:"payload"in n?n.payload:{},...!0===n.replay?{replay:!0}:{},scope:{...t,...s}}}(JSON.parse(String(e)),{instanceId:t});if(!n||"events.connected"===n.type)return;if(n.type===Fe){const e=function(e,t){const n=hn.safeParse(e);return n.success?mn.parse({instanceId:t,...n.data}):mn.parse(e)}(n.payload,t);return{...n,payload:e,scope:{...n.scope,instanceId:t}}}if(n.type===He){const e=function(e,t){const n=fn.safeParse(e);return n.success?gn.parse({instanceId:t,...n.data}):gn.parse(e)}(n.payload,t);return{...n,payload:e,scope:{...n.scope,instanceId:t}}}return{...n,scope:{...n.scope,instanceId:t}}}catch{return}}(t,e);if(n){if("streams.hello"===n.type){const t=ja(Xd,n.payload);if(!t.success)return this.logger?.warn?.({instanceId:e,issues:t.error.issues},"session-stream.handshake.invalid"),void i.close(1002,"Incompatible session stream handshake.");this.retries.get(e)?.timer.reset(),this.sessionStreamsHelloByInstance.set(e,t.data);const s=JSON.stringify({type:"node-agent.streams.hello",instanceId:e,payload:t.data});for(const e of this.outputs)this.sendOutput(e,s);return}this.recordAiSessionEvent(e,n),this.recordAppSessionEvent(e,n);for(const e of this.outputs)this.outputAccepts(e,n)&&this.sendForwarded(e,n)}}),i.on("close",()=>{this.sockets.get(e)===i&&(this.sockets.delete(e),this.socketUrls.delete(e),this.scheduleReconnect(e))}),i.on("error",()=>{this.logger?.warn?.({instanceId:e,url:t},"ai-session.event.forward.error"),this.logger?.warn?.({instanceId:e,url:t},"app-session.event.forward.error"),i.close()})}sendInstanceSubscription(e,t){if(t.readyState!==h.OPEN)return;const n=[...this.outputs].map(e=>this.outputSubscriptions.get(e));if(n.some(e=>void 0===e))return void t.send(JSON.stringify({v:1,type:"subscribe",eventEnvelopeVersion:Hd,aiSessionHierarchy:{subagents:!0},topics:[Pe,"app.sessions","apps","instances"]}));const i=n.some(t=>t.messageDeltas.allInstances||t.messageDeltas.instanceIds.includes(e)),s=n.some(e=>e.timelineAllSessions),o=[...new Set(n.flatMap(t=>t.timelineSessions.filter(t=>t.instanceId===e).map(e=>e.sessionId)))],r=n.map(e=>e.replaySince).filter(e=>Boolean(e)).sort()[0];t.send(JSON.stringify({v:1,type:"subscribe",eventEnvelopeVersion:Hd,aiSessionHierarchy:{subagents:!0},topics:[Me,je,Ue,...i?[Fe]:[],...s||o.length?[$e,He]:[],"app.sessions","apps","instances"],aiSessionTransient:{...r?{replaySince:r}:{},messageDeltas:{allInstances:i,instanceIds:[]},timelineAllSessions:s,timelineSessions:o.map(t=>({instanceId:e,sessionId:t}))}}))}outputAccepts(e,t){const n=this.outputSubscriptions.get(e);return!n||function(e,t){if(!e)return!0;if("ai-session.message-delta"!==t.type&&"ai-session.timeline-item"!==t.type&&"ai-session.timeline-item-delta"!==t.type)return!0;const n=t.payload&&"object"==typeof t.payload&&!Array.isArray(t.payload)?t.payload:{},i=String(n.instanceId||t.scope?.instanceId||"");return"ai-session.message-delta"===t.type?e.messageDeltas.allInstances||e.messageDeltas.instanceIds.includes(i):e.timelineAllSessions||e.timelineSessions.some(e=>e.instanceId===i&&e.sessionId===n.sessionId)}(n,t)}scheduleReconnect(e){const t=this.state.listInstances().find(t=>t.id===e),n=t&&ll(t);if(!n||!this.outputs.size)return;const i=this.retries.get(e)??{timer:new el};if(i.timer.pending)return;i.url=n;const s=i.timer.schedule(()=>{this.sockets.has(e)||this.connect(e,n)},{setTimeoutFn:this.setTimeoutFn});s&&(this.reconnectAttempts+=1,this.logger?.info?.({instanceId:e,url:n,attempt:s.attempt,delay:s.delay,reconnectAttempts:this.reconnectAttempts},"session-stream.connection.reconnect-scheduled")),this.retries.set(e,i)}recordAiSessionEvent(e,t){if(t.topic!==Pe)return;if(t.type===Fe||t.type===$e||t.type===He)return;const n=cl(t);if(n){const t=function(e,t){const{meta:n}=t.payload;if(t.type===Me)return e?.streamId===n.streamId&&n.revision===e.revision?{kind:"duplicate",projection:e}:e?.streamId===n.streamId&&n.revision<e.revision?{kind:"stale",projection:e}:{kind:"applied",projection:an.parse({streamId:n.streamId,revision:n.revision,lastEventAt:n.generatedAt,snapshot:t.payload.snapshot})};if(!e||e.streamId!==n.streamId)return{kind:"snapshot-required",projection:e,streamId:n.streamId};if(n.revision===e.revision)return{kind:"duplicate",projection:e};if(n.revision<e.revision)return{kind:"stale",projection:e};if(n.revision!==e.revision+1||n.previousRevision!==e.revision)return{kind:"gap",projection:e,expectedRevision:e.revision+1,receivedRevision:n.revision};const i=new Map(e.snapshot.sessions.map(e=>[e.id,e]));if(t.type===je){for(const e of t.payload.upserted)i.set(e.id,e);for(const e of t.payload.removed)i.delete(e)}else for(const e of t.payload.sessionIds)i.delete(e);const s=[...i.values()],o=rn.parse({runningCount:s.filter(e=>"running"===e.status).length,waitingCount:s.filter(e=>"waiting"===e.status).length,staleCount:e.snapshot.staleCount,sessions:s,updatedAt:n.generatedAt});return{kind:"applied",projection:an.parse({streamId:n.streamId,revision:n.revision,lastEventAt:n.generatedAt,snapshot:o})}}(this.aiSessionProjectionByInstance.get(e),n);"applied"!==t.kind&&"duplicate"!==t.kind&&"stale"!==t.kind||this.aiSessionProjectionByInstance.set(e,t.projection)}const i=al(t.payload),s=this.lastAiSessionEventByInstance.get(e);s?.streamId===i.streamId&&void 0!==s.revision&&void 0!==i.revision&&i.revision>s.revision+1&&this.logger?.warn?.({instanceId:e,traceId:i.traceId,streamId:i.streamId,previousRevision:s.revision,revision:i.revision},"ai-session.event.forward.gap"),this.lastAiSessionEventByInstance.set(e,{streamId:i.streamId??s?.streamId,revision:i.revision??s?.revision}),this.logger?.info?.({instanceId:e,traceId:i.traceId,eventType:t.type,streamId:i.streamId,revision:i.revision},"ai-session.event.forward.message")}recordAppSessionEvent(e,t){if(t.topic!==fd)return;const n=function(e){const t=e.type===yd?zd:e.type===Id?xd:e.type===_d?Cd:void 0;if(!t)return;const n=ja(t,e.payload);return n.success?{type:e.type,payload:n.data}:void 0}(t);if(n){const t=function(e,t){const{meta:n}=t.payload;if(t.type===yd)return e?.streamId===n.streamId&&n.revision===e.revision?{kind:"duplicate",projection:e}:e?.streamId===n.streamId&&n.revision<e.revision?{kind:"stale",projection:e}:{kind:"applied",projection:vd.parse({streamId:n.streamId,revision:n.revision,lastEventAt:n.generatedAt,snapshot:Dd(t.payload.snapshot.sessions,t.payload.snapshot.updatedAt)})};if(!e||e.streamId!==n.streamId)return{kind:"snapshot-required",projection:e,streamId:n.streamId};if(n.revision===e.revision)return{kind:"duplicate",projection:e};if(n.revision<e.revision)return{kind:"stale",projection:e};if(n.revision!==e.revision+1||n.previousRevision!==e.revision)return{kind:"gap",projection:e,expectedRevision:e.revision+1,receivedRevision:n.revision};const i=[...e.snapshot.sessions];if(t.type===Id){const e=i.findIndex(e=>e.id===t.payload.session.id);Pd(t.payload.session.status)?e<0?i.push(t.payload.session):i[e]=t.payload.session:e>=0&&i.splice(e,1)}else{const e=i.findIndex(e=>e.id===t.payload.sessionId);e>=0&&i.splice(e,1)}const s=kd(i,n.generatedAt);return{kind:"applied",projection:vd.parse({streamId:n.streamId,revision:n.revision,lastEventAt:n.generatedAt,snapshot:s})}}(this.appSessionProjectionByInstance.get(e),n);"applied"!==t.kind&&"duplicate"!==t.kind&&"stale"!==t.kind||this.appSessionProjectionByInstance.set(e,t.projection)}const i=al(t.payload),s=this.lastAppSessionEventByInstance.get(e);s?.streamId===i.streamId&&void 0!==s.revision&&void 0!==i.revision&&i.revision>s.revision+1&&this.logger?.warn?.({instanceId:e,traceId:i.traceId,streamId:i.streamId,previousRevision:s.revision,revision:i.revision},"app-session.event.forward.gap"),this.lastAppSessionEventByInstance.set(e,{streamId:i.streamId??s?.streamId,revision:i.revision??s?.revision}),this.logger?.info?.({instanceId:e,traceId:i.traceId,eventType:t.type,streamId:i.streamId,revision:i.revision},"app-session.event.forward.message")}replaySessionAuthority(e){if(!this.sessionAuthorityReplayedOutputs.has(e)&&e.readyState===h.OPEN){this.sessionAuthorityReplayedOutputs.add(e);for(const[t,n]of this.sessionStreamsHelloByInstance){const i=n.streams.map(e=>{const n=e.topic===Pe?this.aiSessionProjectionByInstance.get(t):this.appSessionProjectionByInstance.get(t);return n?n.streamId!==e.streamId?{...e,streamId:n.streamId,latestRevision:n.revision,earliestRetainedRevision:n.revision}:{...e,latestRevision:Math.max(e.latestRevision,n.revision)}:e});this.sendOutput(e,JSON.stringify({type:"node-agent.streams.hello",instanceId:t,payload:{...n,streams:i}}))}for(const[t,n]of this.aiSessionProjectionByInstance)this.sendForwarded(e,this.createEvent(Me,{meta:{streamId:n.streamId,instanceId:t,revision:n.revision,traceId:`ais_replay_${Date.now().toString(36)}`,generatedAt:n.lastEventAt,reason:"startup"},snapshot:n.snapshot},{instanceId:t}));for(const[t,n]of this.appSessionProjectionByInstance)this.sendForwarded(e,this.createEvent(yd,{meta:{streamId:n.streamId,instanceId:t,revision:n.revision,traceId:`aps_replay_${Date.now().toString(36)}`,generatedAt:n.lastEventAt,reason:"startup"},snapshot:n.snapshot},{instanceId:t}))}}}function ol(e){const t=wa.safeParse(rl(e));return t.success?t.data:void 0}function rl(e){return{instanceId:e.id,revision:e.stateRevision,updatedAt:e.updatedAt,status:e.status,health:e.health,connectionStatus:e.connectionStatus,accessStatus:"online"===e.connectionStatus||"online"===e.agentStatus?"reachable":"endpoint-unreachable",imageProvisioning:e.imageProvisioning,workspace:e.workspace,runtime:e.runtime,runtimeVersion:e.runtimeVersion,ready:e.ready,lastHeartbeatAt:e.lastHeartbeatAt}}function al(e){const t=e&&"object"==typeof e&&!Array.isArray(e)?e:{},n=t.meta&&"object"==typeof t.meta&&!Array.isArray(t.meta)?t.meta:{};return{streamId:"string"==typeof n.streamId?n.streamId:void 0,revision:"number"==typeof n.revision?n.revision:void 0,traceId:"string"==typeof n.traceId?n.traceId:void 0}}function cl(e){const t=e.type===Me?ln:e.type===je?un:e.type===Ue?pn:void 0;if(!t)return;const n=ja(t,e.payload);return n.success?{type:e.type,payload:n.data}:void 0}function dl(e){return e.topic===Pe&&(e.type===Me||e.type===je||e.type===Ue)}function ll(e){if(!function(e){return!1!==e.ready&&(!e.runtimeVersion||["matched","failed"].includes(e.runtimeVersion.phase))}(e))return;const t=e.target?.api||e.target?.web;if(t)try{const e=new URL("/api/events",t);return e.searchParams.set("aiSessionTransient","1"),e.searchParams.set("aiSessionAuthoritySnapshot","1"),e.searchParams.set("aiSessionHierarchy","subagents"),e.protocol="https:"===e.protocol?"wss:":"ws:",e.toString()}catch{return}}const ul=new Set(["provisioning","starting","registering","registered","running","unhealthy"]),pl=JSON.stringify({id:"{{.ID}}",name:"{{.Name}}",cpu:"{{.CPUPerc}}",memory:"{{.MemUsage}}",memoryPercent:"{{.MemPerc}}",network:"{{.NetIO}}",blockIo:"{{.BlockIO}}",pids:"{{.PIDs}}"});class ml{snapshots=new Map;runCommand;targets;publish;intervalMs;timer;inFlight;pendingTargets=new Map;collectingTargets=new Map;constructor(e,t,n,i=3e3){this.runCommand=e,this.targets=t,this.publish=n,this.intervalMs=i}start(){this.collect().catch(()=>{}),this.timer=setInterval(()=>{this.collect().catch(()=>{})},this.intervalMs)}stop(){this.timer&&clearInterval(this.timer),this.timer=void 0}async snapshot(e){const t=this.targets().find(t=>t.id===e);if(!t)return;if(!ul.has(t.status))return _l(t.id);const n=this.snapshots.get(e);return n&&Date.now()-Date.parse(n.sampledAt)<=this.intervalMs?n:(await this.collect([t]),this.snapshots.get(e))}async collect(e){const t=e||this.targets();if(!e){const e=new Set(t.map(e=>e.id));for(const t of this.snapshots.keys())e.has(t)||this.snapshots.delete(t)}for(const e of t){const t=hl(e);this.collectingTargets.get(e.id)!==t&&this.pendingTargets.set(e.id,e)}this.inFlight||(this.inFlight=this.drain().finally(()=>{this.inFlight=void 0})),await this.inFlight}async drain(){for(;this.pendingTargets.size;){const e=[...this.pendingTargets.values()];this.pendingTargets.clear();for(const t of e)this.collectingTargets.set(t.id,hl(t));try{await this.collectOnce(e)}finally{for(const t of e)this.collectingTargets.delete(t.id)}}}async collectOnce(e){const t=e.filter(e=>ul.has(e.status)&&(e.runtime.containerId||e.runtime.containerName));for(const t of e.filter(e=>ul.has(e.status)&&!e.runtime.containerId&&!e.runtime.containerName))this.update(El(t.id));for(const t of e.filter(e=>!ul.has(e.status)))this.update(_l(t.id));if(!t.length)return;const n=t.map(e=>e.runtime.containerId||e.runtime.containerName),i=(new Date).toISOString();try{const e=await this.runCommand("docker",["stats","--no-stream","--format",pl,...n],{timeoutMs:5e3});this.applyDockerOutput(t,e.stdout,i)}catch(e){if(1===t.length)return void this.update(Al(t[0].id,i,e instanceof Error?e.message:String(e)));await Promise.all(t.map(async e=>{const t=e.runtime.containerId||e.runtime.containerName;try{const n=await this.runCommand("docker",["stats","--no-stream","--format",pl,t],{timeoutMs:5e3});this.applyDockerOutput([e],n.stdout,i)}catch(t){this.update(Al(e.id,i,t instanceof Error?t.message:String(t)))}}))}}applyDockerOutput(e,t,n){const i=function(e,t=(new Date).toISOString()){const n=new Map;for(const i of e.split(/\r?\n/).filter(Boolean)){let e;try{e=JSON.parse(i)}catch{continue}const s=Il(e.id),o=Il(e.name),r=s||o;if(!r)continue;const a=gl(Il(e.memory)),c=gl(Il(e.network)),d=gl(Il(e.blockIo)),l=ia.parse({instanceId:r,runtimeKind:"docker",state:"available",sampledAt:t,cpu:fl(e.cpu,"usagePercent"),memory:a?{usageBytes:a[0],...void 0!==a[1]?{limitBytes:a[1]}:{},...fl(e.memoryPercent,"usagePercent")}:void 0,network:c?{rxBytes:c[0],txBytes:c[1]||0}:void 0,blockIo:d?{readBytes:d[0],writeBytes:d[1]||0}:void 0,pids:yl(e.pids)});s&&n.set(s,l),o&&n.set(o,l)}return n}(t,n);for(const t of e){const e=[t.runtime.containerId,t.runtime.containerName].filter(Boolean),s=[...i.entries()].find(([t])=>e.some(e=>e===t||e.startsWith(t)||t.startsWith(e)))?.[1];this.update(s?{...s,instanceId:t.id}:Al(t.id,n,"Container metrics were not returned by Docker."))}}update(e){const t=ia.parse(e);this.snapshots.set(t.instanceId,t),this.publish?.(t)}}function hl(e){return[e.status,e.runtime.containerId||"",e.runtime.containerName||""].join("\0")}function gl(e){if(!e)return;const[t,n]=e.split("/").map(e=>function(e){const t=e.trim().match(/^([0-9]+(?:\.[0-9]+)?)\s*([kmgtpe]?i?b)$/i);if(!t)return;const n=Number(t[1]),i=t[2].toLowerCase(),s=i.includes("i"),o="b"===i[0]?"":i[0],r=o?"kmgtpe".indexOf(o)+1:0;return Math.round(n*(s?1024:1e3)**r)}(e||""));return void 0===t?void 0:[t,n]}function fl(e,t){const n=Number(Il(e).replace(/%$/,""));return Number.isFinite(n)&&n>=0?{[t]:n}:void 0}function yl(e){const t=Number(Il(e));return Number.isFinite(t)&&t>=0?t:void 0}function Il(e){return"string"==typeof e||"number"==typeof e?String(e).trim():""}function _l(e){return{instanceId:e,runtimeKind:"docker",state:"stopped",sampledAt:(new Date).toISOString()}}function El(e){return{instanceId:e,runtimeKind:"docker",state:"pending",sampledAt:(new Date).toISOString()}}function Al(e,t,n){return{instanceId:e,runtimeKind:"docker",state:"unavailable",sampledAt:t,error:n.slice(0,2048)}}function Tl(e,t,n){return Object.assign(new Error(e),{statusCode:t,code:n})}function wl(e){const i=n.resolve(e);let s;try{s=t.statSync(i)}catch(e){const t=e&&"object"==typeof e?e.code:void 0;if("ENOENT"===t||"ENOTDIR"===t)throw Tl(`Folder ${i} was not found.`,404,"NODE_FOLDER_PATH_NOT_FOUND");throw Tl(`Folder ${i} is not accessible.`,403,"NODE_FOLDER_PATH_UNREADABLE")}if(!s.isDirectory())throw Tl(`Path ${i} is not a folder.`,400,"NODE_FOLDER_PATH_NOT_DIRECTORY");try{t.accessSync(i,t.constants.R_OK|t.constants.X_OK)}catch{throw Tl(`Folder ${i} is not accessible.`,403,"NODE_FOLDER_PATH_UNREADABLE")}return i}function bl(e){try{return t.statSync(e).isDirectory()}catch{return!1}}function Nl(){if("win32"!==process.platform)return[n.parse(n.resolve(process.cwd())).root];const e=n.parse(n.resolve(process.cwd())).root,t=Array.from({length:26},(e,t)=>`${String.fromCharCode(65+t)}:\\`);return[...new Set([e,...t])].filter(bl)}function Sl(){const e=n.resolve(s.homedir()),t=Nl().map(e=>n.resolve(e));return[...bl(e)?[{kind:"home",name:n.basename(e)||e,path:e}]:[],...t.map(e=>({kind:"root",name:e,path:e}))]}function vl(e,i){let s;try{s=t.statSync(e)}catch{return}if(!s.isDirectory())return;const o=n.resolve(e),r=n.basename(o)||o;let a=[];try{a=i>0?t.readdirSync(o,{withFileTypes:!0}):[]}catch{a=[]}const c=i>0?a.filter(e=>e.isDirectory()||e.isSymbolicLink()&&bl(n.join(o,e.name))).sort((e,t)=>e.name.localeCompare(t.name)).slice(0,80).flatMap(e=>{const t=vl(n.join(o,e.name),i-1);return t?[t]:[]}):[];return{name:r,path:o,children:c}}function Ol(e){return(e.path?[wl(e.path)]:Nl()).flatMap(t=>{const n=vl(t,e.depth);return n?[n]:[]})}function Rl(){return process.env.TASK_HANDOFF_NODE_AGENT_DATA_DIR||n.join(s.homedir(),".config","task-handoff","node-agent")}function zl(e=Rl()){const t=n.resolve(e);return{dataDir:t,identityPath:n.join(t,"identity.json"),settingsPath:n.join(t,"runtime-settings.json"),localFoldersDir:n.join(t,"local-folders"),builtinProjectTargetsDir:n.join(t,"builtin-projects"),nodeRuntimesDir:n.join(t,"node-runtimes"),controlledInstancesDir:n.join(t,"controlled-instances"),environmentTemplatesDir:n.join(t,"environment-templates"),instancePrivateConfigsDir:n.join(t,"instance-private-configs"),nodeModelsDir:n.join(t,"models"),modelAssignmentsDir:n.join(t,"model-assignments"),modelEnvironmentsDir:n.join(t,"model-environments"),gitCredentialPayloadsDir:n.join(t,"git-credentials","payloads"),gitCredentialAssignmentsDir:n.join(t,"git-credentials","assignments"),gitCredentialAuthorizationSetsDir:n.join(t,"git-credentials","authorization-sets"),gitWorkspaceProvisioningIntentsDir:n.join(t,"git-credentials","workspace-provisioning-intents"),updatesDir:n.join(t,"updates"),dockerBootstrapDir:n.join(t,"docker-bootstrap"),wslDir:n.join(t,"wsl"),wslDistrosDir:n.join(t,"wsl","distros"),wslBaseTemplateCacheDir:n.join(t,"wsl","base-templates"),wslDistroIndexPath:n.join(t,"wsl","distros.json"),logsDir:n.join(t,"logs"),databasePath:n.join(t,"node-agent.sqlite"),storyRegistryDir:n.join(t,"story-registry"),storyAutomationsDir:n.join(t,"story-automations"),storyContentDir:n.join(t,"stories"),storyMutationsDir:n.join(t,".story-mutations"),storyTrashDir:n.join(t,".story-trash")}}function xl(e,t){const i=n.extname(e);return`${i?e.slice(0,-i.length):e}.${t}${i}`}function Cl(e,n=10485760,i=2){if(!t.existsSync(e))return!1;const s=t.lstatSync(e);if(!s.isFile()||s.isSymbolicLink()||s.size<=n)return!1;if(i>0){!function(e,n){if(!(n<=0)){t.rmSync(xl(e,n),{force:!0});for(let i=n-1;i>=1;i-=1){const n=xl(e,i);t.existsSync(n)&&t.renameSync(n,xl(e,i+1))}}}(e,i);const s=function(e,n){const i=t.statSync(e),s=Math.min(i.size,n),o=Buffer.allocUnsafe(s),r=t.openSync(e,"r");let a=0;try{for(;a<s;){const e=t.readSync(r,o,a,s-a,i.size-s+a);if(0===e)break;a+=e}}finally{t.closeSync(r)}return a===s?o:o.subarray(0,a)}(e,n);t.writeFileSync(xl(e,1),s,{mode:384})}return t.truncateSync(e,0),t.chmodSync(e,384),!0}class kl{logsDir;localInstancesRoot;localInstancesTrashRoot;privateConfigsDir;options;constructor(e,t={}){this.options=t,this.logsDir=e.logsDir,this.localInstancesRoot=n.join(e.dataDir,"local-instances"),this.localInstancesTrashRoot=n.join(e.dataDir,"local-instances-trash"),this.privateConfigsDir=e.instancePrivateConfigsDir}run(e){this.capNodeAgentLogs();const n=new Set(e);if(this.removeOrphanPrivateConfigs(n),t.existsSync(this.localInstancesRoot)){ge(this.localInstancesRoot);for(const e of t.readdirSync(this.localInstancesRoot,{withFileTypes:!0}))e.isDirectory()&&!e.isSymbolicLink()&&(n.has(e.name)?this.capControlledInstanceLogs(e.name):this.retire(e.name))}return function(e){if(!t.existsSync(e.trashRoot))return[];const n=e.nowMs??Date.now(),i=e.retentionMs??le,s=[];for(const o of t.readdirSync(e.trashRoot,{withFileTypes:!0})){const r=he(e.trashRoot,o.name);try{const e=me(o.name);if(void 0===e||e+i>n)continue;const a=t.lstatSync(r);a.isSymbolicLink()?t.unlinkSync(r):a.isDirectory()?t.rmSync(r,{recursive:!0,force:!0}):t.unlinkSync(r),s.push(r)}catch(t){e.logger?.("retired persistence entry cleanup failed",{path:r,error:t instanceof Error?t.message:String(t)})}}return s}({trashRoot:this.localInstancesTrashRoot,retentionMs:this.options.retentionMs??le,nowMs:this.now(),logger:this.options.logger})}capActiveInstanceLogs(e){for(const t of e)this.capControlledInstanceLogs(t)}capNodeAgentLogs(){const e=[];for(const t of["node-agent.out.log","node-agent.err.log"]){const i=n.join(this.logsDir,t);try{Cl(i)&&e.push(i)}catch(e){this.options.logger?.("node-agent log rotation failed",{filePath:i,error:e instanceof Error?e.message:String(e)})}}return e}capControlledInstanceLogs(e){const t=n.resolve(this.localInstancesRoot,e);if(n.dirname(t)!==n.resolve(this.localInstancesRoot))return[];const i=n.join(t,"logs"),s=[];for(const t of["controlled-instance.out.log","controlled-instance.err.log"]){const o=n.join(i,t);try{Cl(o)&&s.push(o)}catch(t){this.options.logger?.("controlled instance log rotation failed",{instanceId:e,filePath:o,error:t instanceof Error?t.message:String(t)})}}return s}retire(e){try{return function(e){const n=he(e.sourceRoot,e.entryName);if(!t.existsSync(n))return;const i=t.lstatSync(n);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`Retention source must be a real directory: ${n}`);ge(e.trashRoot);const s=e.nowMs??Date.now();let o=0,r=ue(e.entryName,s);for(;t.existsSync(he(e.trashRoot,r));)o+=1,r=ue(`${o}-${e.entryName}`,s);const a=he(e.trashRoot,r);return t.renameSync(n,a),a}({sourceRoot:this.localInstancesRoot,entryName:e,trashRoot:this.localInstancesTrashRoot,nowMs:this.now()})}catch(t){return void this.options.logger?.("local instance persistence retirement failed",{instanceId:e,error:t instanceof Error?t.message:String(t)})}}removeOrphanPrivateConfigs(e){if(t.existsSync(this.privateConfigsDir))for(const i of t.readdirSync(this.privateConfigsDir,{withFileTypes:!0})){if(i.isSymbolicLink())continue;const s=i.isDirectory();if(!(s||i.isFile()&&i.name.endsWith(".json")))continue;const o=s?i.name:i.name.slice(0,-5);if(e.has(o))continue;const r=n.join(this.privateConfigsDir,i.name);try{s?(this.options.removeDirectory||(e=>t.rmSync(e,{recursive:!0,force:!0})))(r):(this.options.removeFile||(e=>t.rmSync(e,{force:!0})))(r)}catch(e){this.options.logger?.("orphan instance private config cleanup failed",{instanceId:o,filePath:r,error:e instanceof Error?e.message:String(e)})}}}now(){return this.options.now?.()??Date.now()}}function Dl(e,t=process.platform){const i=n.resolve(e),s=d.createHash("sha256").update(i).digest("hex").slice(0,16);return"win32"===t?`\\\\.\\pipe\\task-handoff-node-agent-${s}`:n.join("/tmp",`task-handoff-node-agent-${process.getuid?.()??"user"}`,`${s}.sock`)}function Ll(e,i=process.platform){if("win32"!==i){t.mkdirSync(n.dirname(e),{recursive:!0,mode:448});try{t.chmodSync(n.dirname(e),448)}catch{}try{t.unlinkSync(e)}catch(e){if("ENOENT"!==e.code)throw e}}}async function Pl(e,t,n={}){const s=n.method||"GET",o="string"==typeof n.body||n.body instanceof Buffer?n.body:void 0===n.body||null===n.body?void 0:String(n.body),r=new Headers(n.headers||{});return void 0===o||r.has("content-length")||r.set("content-length",String(Buffer.byteLength(o))),new Promise((a,c)=>{const d=i.request({socketPath:e,method:s,path:`/api/node-agent${t}`,headers:Object.fromEntries(r.entries())},e=>{const t=e.statusCode||500;a(new Response("HEAD"!==s&&204!==t&&205!==t&&304!==t?f.Readable.toWeb(e):null,{status:t,headers:e.headers}))});d.on("error",c);const l=()=>d.destroy(new DOMException("The operation was aborted.","AbortError"));n.signal?.aborted?l():n.signal?.addEventListener("abort",l,{once:!0}),d.once("close",()=>n.signal?.removeEventListener("abort",l)),void 0!==o&&d.write(o),d.end()})}const Ml="runtime-manifest.json";class jl extends Error{code;retryable;constructor(e,t,n){super(t,void 0===n?.cause?void 0:{cause:n.cause}),this.name="RuntimeArtifactError",this.code=e,this.retryable=n?.retryable??!1}}async function Ul(e,t=""){const i=[],s=await y.readdir(n.join(e,t),{withFileTypes:!0});for(const o of s){const s=t?n.posix.join(t,o.name):o.name;if(!t&&s===Ml)continue;const r=n.join(e,...s.split("/"));if(o.isDirectory()){i.push(...await Ul(e,s));continue}if(o.isSymbolicLink()){const t=await y.readlink(r);if(n.isAbsolute(t))throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`Runtime payload symlink is absolute: ${s}`);const o=n.resolve(n.dirname(r),t),a=n.relative(n.resolve(e),o);if(!a||".."===a||a.startsWith(`..${n.sep}`)||n.isAbsolute(a))throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`Runtime payload symlink escapes the artifact: ${s}`);if(!await y.lstat(o).catch(()=>{}))throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`Runtime payload symlink is broken: ${s}`);i.push({absolutePath:r,relativePath:s,kind:"symlink",target:t,size:Buffer.byteLength(t)});continue}if(!o.isFile())throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`Runtime payload contains unsupported entry: ${s}`);const a=await y.lstat(r);i.push({absolutePath:r,relativePath:s,kind:"file",size:a.size})}return i}async function Fl(e){const n=(await Ul(e)).sort((e,t)=>function(e,t){return Buffer.compare(Buffer.from(e,"utf8"),Buffer.from(t,"utf8"))}(e.relativePath,t.relativePath)),i=d.createHash("sha256");for(const e of n){if(i.update("file"===e.kind?"F":"L","ascii"),i.update(Buffer.from(e.relativePath,"utf8")),i.update(Buffer.from([0])),i.update(Buffer.from(String(e.size),"ascii")),i.update(Buffer.from([0])),"file"===e.kind)for await(const n of t.createReadStream(e.absolutePath))i.update(n);else i.update(Buffer.from(e.target,"utf8"));i.update(Buffer.from([0]))}return i.digest("hex")}function $l(e){for(const[t,n]of[["version",e.version],["platform",e.platform],["arch",e.arch]])if(!/^[0-9A-Za-z._-]+$/.test(n))throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`Invalid runtime artifact ${t}: ${n}`);return`${e.version}-${e.platform}-${e.arch}`}function Hl(e,t){return`${$l(e)}-${e.sha256}-${t}`}async function ql(e){const n=d.createHash("sha256");for await(const i of t.createReadStream(e))n.update(i);return n.digest("hex")}class Bl{#e;#t;#n=new Map;constructor(e){this.#e=e.cacheDir,this.#t=e.fetchImpl??fetch}resolve(e,t){const n=Io.parse(e);if(!/^[a-f0-9]{64}$/.test(t.archiveSha256))throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID","Runtime archive SHA-256 is invalid.");if((t.archiveUrl?1:0)+(t.archivePath?1:0)!=1)throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID","Runtime artifact source must specify exactly one archive location.");const i=Hl(n,t.archiveSha256),s=this.#n.get(i);if(s)return s;const o=this.#i(n,t).finally(()=>this.#n.delete(i));return this.#n.set(i,o),o}async#i(e,i){if(!/^[a-f0-9]{64}$/.test(i.archiveSha256))throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID","Runtime archive SHA-256 is invalid.");const s=Hl(e,i.archiveSha256),o=n.join(this.#e,"archives"),r=n.join(o,`${s}.tar.gz`);if(await y.mkdir(o,{recursive:!0}),await this.#s(r,e,i.archiveSha256))return{identity:e,archivePath:r,cacheHit:!0};await y.rm(r,{force:!0});const a=n.join(o,`.${s}.${d.randomUUID()}.part`);try{const n=await y.open(a,"wx");if(i.archivePath)await I.pipeline(t.createReadStream(i.archivePath),n.createWriteStream());else{const e=await this.#t(i.archiveUrl);if(!e.ok||!e.body)throw await n.close(),new jl("INSTANCE_RUNTIME_ARTIFACT_UNAVAILABLE",`Runtime artifact download failed with HTTP ${e.status}.`,{retryable:e.status>=500});await I.pipeline(e.body,n.createWriteStream())}if(await ql(a)!==i.archiveSha256)throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID","Downloaded runtime archive SHA-256 does not match release metadata.");return await this.#o(a,e),await y.rename(a,r),{identity:e,archivePath:r,cacheHit:!1}}catch(e){if(e instanceof jl)throw e;throw new jl("INSTANCE_RUNTIME_ARTIFACT_UNAVAILABLE","Could not download runtime artifact.",{cause:e,retryable:!0})}finally{await y.rm(a,{force:!0})}}async#s(e,t,n){try{return await ql(e)===n&&(await this.#o(e,t),!0)}catch{return!1}}async#o(e,t){const i=n.join(this.#e,"validation",`${$l(t)}-${d.randomUUID()}`);try{await async function(e,t){await y.mkdir(t,{recursive:!0});try{await _.extract({file:e,cwd:t,strict:!0,preservePaths:!1,filter:(e,t)=>{const i=n.posix.normalize(e.replace(/^\.\//,""));if(!i||".."===i||i.startsWith("../")||n.posix.isAbsolute(i))throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`Runtime archive entry escapes the artifact root: ${e}`);const s=t.type;if("File"!==s&&"OldFile"!==s&&"Directory"!==s&&"SymbolicLink"!==s)throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`Runtime archive contains unsupported entry type ${s??"unknown"}: ${e}`);return!0}})}catch(e){throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID","Could not extract runtime artifact safely.",{cause:e})}}(e,i),await async function(e,t,i){const s=await async function(e){let t;try{t=JSON.parse(await y.readFile(n.join(e,Ml),"utf8"))}catch(e){throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID","Runtime artifact manifest is missing or invalid JSON.",{cause:e})}const i=ja(Io,t);if(!i.success)throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`Runtime artifact manifest is invalid: ${i.error.message}`);return i.data}(e);if(function(e,t){for(const n of["packageName","version","platform","arch","formatVersion","launcherAbi","entrypoint","sha256"])if(e[n]!==t[n])throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`Runtime artifact ${"sha256"===n?"SHA-256":n} mismatch: expected ${t[n]}, got ${e[n]}.`)}(s,t),1!==s.formatVersion)throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`Unsupported runtime artifact format ${s.formatVersion}.`);if(i?.platform&&"universal"!==s.platform&&s.platform!==i.platform)throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`Runtime artifact platform ${s.platform} does not match ${i.platform}.`);if(i?.arch&&"universal"!==s.arch&&s.arch!==i.arch)throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`Runtime artifact architecture ${s.arch} does not match ${i.arch}.`);if(void 0!==i?.launcherAbi&&s.launcherAbi>i.launcherAbi)throw new jl("INSTANCE_BASE_RUNTIME_INCOMPATIBLE",`Runtime requires launcher ABI ${s.launcherAbi}, but the base runtime provides ${i.launcherAbi}.`);const o=function(e,t){if(!e||e.includes("\\")||n.posix.isAbsolute(e))throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`${t} must be a non-empty POSIX relative path.`);const i=n.posix.normalize(e);if("."===i||".."===i||i.startsWith("../"))throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`${t} escapes the runtime root.`);return i}(s.entrypoint,"Runtime entrypoint"),r=await y.lstat(n.join(e,...o.split("/"))).catch(()=>{});if(!r?.isFile())throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`Runtime entrypoint is missing: ${o}`);const a=await Fl(e);if(a!==s.sha256)throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`Runtime payload SHA-256 mismatch: expected ${s.sha256}, got ${a}.`);return s}(i,t,{platform:t.platform,arch:t.arch})}finally{await y.rm(i,{recursive:!0,force:!0})}}}async function Vl(e,t,i,s=fetch){if("linux"!==t||!["x64","arm64"].includes(i))throw new jl("INSTANCE_BASE_RUNTIME_INCOMPATIBLE",`Managed controlled-instance updates require a Linux x64 or arm64 target, received ${t}/${i}.`);const o=await async function(e){const t=`controlled-instance-runtime-${e}-linux-universal`,i=function(){const e=process.env.TASK_HANDOFF_BUNDLED_RUNTIME_DIR?.trim();return n.resolve(e||n.join(n.dirname(process.argv[1]||process.cwd()),"..","runtime-artifacts"))}();try{const[s,o]=await Promise.all([y.readFile(n.join(i,`${t}.manifest.json`),"utf8"),y.readFile(n.join(i,`${t}.tar.gz.sha256`),"utf8")]),r=ja(Io,JSON.parse(s));if(!r.success||r.data.version!==e||"linux"!==r.data.platform||"universal"!==r.data.arch)throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`Bundled controlled-instance ${e} has an invalid Linux manifest.`);const a=o.trim().split(/\s+/)[0]?.toLowerCase();if(!a||!/^[a-f0-9]{64}$/.test(a))throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`Bundled controlled-instance ${e} has an invalid archive checksum.`);return{identity:r.data,source:{archivePath:n.join(i,`${t}.tar.gz`),archiveSha256:a}}}catch(t){if("ENOENT"===t.code)return;if(t instanceof jl)throw t;throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`Could not read bundled controlled-instance ${e}.`,{cause:t})}}(e);if(o)return o;const r=`controlled-instance-runtime-${e}-linux-universal`,a=function(e){const t=process.env.TASK_HANDOFF_RUNTIME_RELEASE_BASE_URL?.trim();return t?t.replaceAll("{version}",e).replace(/\/$/,""):`https://github.com/edgestorage/task-handoff/releases/download/v${e}`}(e),c=`${a}/${r}.manifest.json`,d=`${a}/${r}.tar.gz`,l=`${a}/${r}.tar.gz.sha256`,[u,p]=await Promise.all([s(c),s(l)]).catch(t=>{throw new jl("INSTANCE_RUNTIME_ARTIFACT_UNAVAILABLE",`Could not read release metadata for controlled-instance ${e}.`,{cause:t,retryable:!0})});if(!u.ok||!p.ok)throw new jl("INSTANCE_RUNTIME_ARTIFACT_UNAVAILABLE",`Release metadata for controlled-instance ${e} is unavailable (manifest HTTP ${u.status}, checksum HTTP ${p.status}).`,{retryable:u.status>=500||p.status>=500});let m;try{m=await u.json()}catch(t){throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`Release manifest for controlled-instance ${e} is not valid JSON.`,{cause:t})}const h=ja(Io,m);if(!h.success)throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`Release manifest for controlled-instance ${e} is invalid: ${h.error.message}`);if(h.data.version!==e||"linux"!==h.data.platform||"universal"!==h.data.arch)throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`Release identity mismatch: requested ${e}-linux-universal, received ${h.data.version}-${h.data.platform}-${h.data.arch}.`);const g=(await p.text()).trim().split(/\s+/)[0]?.toLowerCase();if(!g||!/^[a-f0-9]{64}$/.test(g))throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`Release checksum for controlled-instance ${e} is invalid.`);return{identity:h.data,source:{archiveUrl:d,archiveSha256:g}}}class Gl{store;desiredVersion;hooks;inFlight=new Map;requests=new Map;cancelled=new Set;now;delay;drainTimeoutMs;drainRequestRetryMs;verificationTimeoutMs;pollIntervalMs;maxAttempts;retryBaseDelayMs;retryMaxDelayMs;constructor(e,t,n,i={}){this.store=e,this.desiredVersion=t,this.hooks=n,this.now=i.now||(()=>new Date),this.delay=i.delay||(e=>new Promise(t=>setTimeout(t,e))),this.drainTimeoutMs=i.drainTimeoutMs??3e5,this.drainRequestRetryMs=function(e){if(!Number.isFinite(e)||e<=0)throw new TypeError("drainRequestRetryMs must be a positive finite number.");return e}(i.drainRequestRetryMs??1e3),this.verificationTimeoutMs=i.verificationTimeoutMs??6e4,this.pollIntervalMs=i.pollIntervalMs??250,this.maxAttempts=function(e){if(!Number.isInteger(e)||e<=0)throw new TypeError("maxAttempts must be a positive integer.");return e}(i.maxAttempts??3),this.retryBaseDelayMs=iu(i.retryBaseDelayMs??1e3,"retryBaseDelayMs"),this.retryMaxDelayMs=iu(i.retryMaxDelayMs??3e4,"retryMaxDelayMs")}schedule(e,t={}){const n=this.requests.get(e)||{startRequested:!1,resumeCancelled:!1};n.startRequested||=!0===t.startRequested,n.resumeCancelled||=!0===t.resumeCancelled||!0===t.startRequested,n.resumeCancelled&&this.cancelled.delete(e),this.requests.set(e,n);const i=this.inFlight.get(e);if(i)return i;const s=Promise.resolve().then(()=>this.reconcile(e,n)).finally(()=>{this.inFlight.delete(e),this.requests.delete(e)});return this.inFlight.set(e,s),s}isRunning(e){return this.inFlight.has(e)}cancel(e){return this.cancelled.add(e),this.inFlight.get(e)}async reconcile(e,t){let n=this.requireInstance(e);const i=this.desiredVersion();if(this.cancelled.has(e)&&!t.resumeCancelled)return this.storePhase(n,"pending");if(Xl(n))return this.storePhase(n,"pending");const s=n.runtimeVersion?.desiredVersion!==i||t.startRequested||Ql(n)?0:this.remainingRetryDelayMs(n.runtimeVersion);if(s>0&&(await this.delay(s),n=this.requireInstance(e),this.cancelled.has(e)))return this.storePhase(n,"pending");const o=Kl(n),r=o===i&&(await(this.hooks.isInstalled?.(n,i))??!0);if(this.cancelled.has(e))return this.storePhase(this.requireInstance(e),"pending");if(o===i&&r)return this.storeState(n,{desiredVersion:i,actualVersion:o,phase:"matched",attempt:n.runtimeVersion?.attempt||0,matchedAt:this.timestamp()},!Ql(n)&&"failed"!==n.health);if(n=this.storeState(n,function(e,t,n,i=!1){const s=e.runtimeVersion,o=s?.desiredVersion===t&&"matched"!==s.phase;return{desiredVersion:t,...n?{actualVersion:n}:{},phase:"pending",attempt:o?s.attempt:0,error:(o?s.error:void 0)||(n!==t||i?Zl(t,n):eu("INSTANCE_RUNTIME_VERIFICATION_FAILED",`Controlled-instance ${t} is running, but the active runtime artifact does not match the desired release identity.`,t,n,!0))}}(n,i,o,r)),Ql(n)&&!t.startRequested)return n;let a=!1,c=0;try{for(;c<this.maxAttempts;){if(this.cancelled.has(e))return this.storePhase(this.requireInstance(e),"pending");let s;try{if(n=this.requireInstance(e),Yl(n))if(n=this.storePhase(n,"draining"),await this.runtimeIsRunning(n)){const t=this.now().getTime()+this.drainTimeoutMs;let i=!1;for(;!i;){if(i=!1!==await(this.hooks.beginDrain?.(n)),i){a=!0;break}if(this.cancelled.has(e))return this.storePhase(this.requireInstance(e),"pending");const s=t-this.now().getTime();if(s<=0)break;await this.delay(Math.min(this.drainRequestRetryMs,s)),n=this.requireInstance(e)}if(n=this.requireInstance(e),!i||Wl(n)){const s=Math.max(0,t-this.now().getTime()),o=i&&await this.waitUntil(e,s,e=>!Wl(e));if(n=this.requireInstance(e),!o){if(this.cancelled.has(e))return this.storePhase(n,"pending");await(this.hooks.onForcedDrain?.(n))}}}else await(this.hooks.onDrainSkipped?.(n));if(n=this.storePhase(this.requireInstance(e),"installing",!0),c+=1,await this.hooks.install(n,i),this.cancelled.has(e)||Ql(this.requireInstance(e))&&!t.startRequested)return this.storePhase(this.requireInstance(e),"pending");if(n=this.storePhase(this.requireInstance(e),"restarting"),await this.hooks.restart(n),this.cancelled.has(e))return this.storePhase(this.requireInstance(e),"pending");n=this.storePhase(this.requireInstance(e),"verifying");const s=await this.waitUntil(e,this.verificationTimeoutMs,e=>Kl(e)===i);if(this.cancelled.has(e))return this.storePhase(this.requireInstance(e),"pending");if(!s)throw eu("INSTANCE_RUNTIME_VERIFICATION_FAILED",`Instance ${e} did not register controlled-instance ${i} after restart.`,i,Kl(this.requireInstance(e)),!0);const o=this.requireInstance(e);if(this.hooks.isInstalled&&!await this.hooks.isInstalled(o,i))throw eu("INSTANCE_RUNTIME_VERIFICATION_FAILED",`Instance ${e} reported controlled-instance ${i}, but its active runtime release is missing.`,i,Kl(o),!0);return this.storeState(o,{desiredVersion:i,actualVersion:i,phase:"matched",attempt:o.runtimeVersion?.attempt||1,matchedAt:this.timestamp()},!Ql(o)&&"failed"!==o.health)}catch(t){if(this.cancelled.has(e))return this.storePhase(this.requireInstance(e),"pending");s=tu(t,i,Kl(this.store.get(e)))}n=this.requireInstance(e);const o=n.runtimeVersion?.attempt||1;if(!s.retryable||c>=this.maxAttempts)return this.storeBatchFailure(n,i,o>=this.maxAttempts&&s.retryable?nu(i,Kl(n),this.maxAttempts,s):s);n=this.storeState(n,{desiredVersion:i,...Kl(n)?{actualVersion:Kl(n)}:{},phase:"pending",attempt:o,lastAttemptAt:this.timestamp(),error:s}),await this.delay(this.retryDelayMs(o))}return this.storeBatchFailure(n,i,nu(i,Kl(n),this.maxAttempts,n.runtimeVersion?.error))}finally{a&&await(this.hooks.endDrain?.(this.requireInstance(e)))}}storeBatchFailure(e,t,n){const i=Kl(e);return this.storeState(e,{desiredVersion:t,...i?{actualVersion:i}:{},phase:"pending",attempt:e.runtimeVersion?.attempt||0,lastAttemptAt:this.timestamp(),error:n})}retryDelayMs(e){return Math.min(this.retryMaxDelayMs,this.retryBaseDelayMs*2**Math.max(0,e-1))}async runtimeIsRunning(e){if(!this.hooks.isRuntimeRunning)return!0;try{return!1!==await this.hooks.isRuntimeRunning(e)}catch{return!0}}remainingRetryDelayMs(e){if(!e?.error||!e.lastAttemptAt)return 0;const t=Date.parse(e.lastAttemptAt);return Number.isFinite(t)?Math.max(0,t+this.retryDelayMs(e.attempt||1)-this.now().getTime()):0}storePhase(e,t,n=!1){const i=this.desiredVersion(),s=Kl(e),o=e.runtimeVersion?.desiredVersion===i?e.runtimeVersion.error:void 0;return this.storeState(e,{desiredVersion:i,...s?{actualVersion:s}:{},phase:t,attempt:(e.runtimeVersion?.attempt||0)+(n?1:0),lastAttemptAt:this.timestamp(),...o?{error:o}:"pending"===t?{error:Zl(i,s)}:{}},"restarting"!==t&&void 0)}storeState(e,t,n){const i=this.store.get(e.id)||e;return this.store.put(Ia.parse({...i,runtimeVersion:t,...void 0===n?{}:{ready:n},updatedAt:this.timestamp()}))}async waitUntil(e,t,n){const i=this.now().getTime()+t;for(;;){const t=this.store.get(e);if(t&&n(t))return!0;if(this.cancelled.has(e))return!1;if(this.now().getTime()>=i)return!1;await this.delay(Math.min(this.pollIntervalMs,Math.max(0,i-this.now().getTime())))}}requireInstance(e){const t=this.store.get(e);if(!t)throw new Error(`Instance ${e} was removed during runtime reconciliation.`);return t}timestamp(){return this.now().toISOString()}}function Kl(e){return e?.build?.packageVersion||e?.instanceVersion}function Wl(e){return e.apps.runningCount>0||e.aiSessions.runningCount>0}function Yl(e){return Boolean(Kl(e))||"online"===e.connectionStatus||"online"===e.agentStatus||Wl(e)}function Xl(e){return Boolean(e.imageProvisioning&&"ready"!==e.imageProvisioning.phase)}function Jl(e){const t=e.workspace?.gitProvisioning;return Boolean(t&&"ready"!==t.phase)}function Ql(e){return["created","stopped","failed"].includes(e.status)}function Zl(e,t){return eu("INSTANCE_RUNTIME_VERSION_MISMATCH",`Expected controlled-instance ${e}, received ${t||"an unknown version"}.`,e,t,!0)}function eu(e,t,n,i,s){return{code:e,message:t,expectedVersion:n,...i?{actualVersion:i}:{},retryable:s}}function tu(e,t,n){if(e&&"object"==typeof e&&"code"in e&&"message"in e){const i=e,s=_o.shape.code.safeParse(i.code);if(s.success&&"string"==typeof i.message)return eu(s.data,i.message,t,n,"boolean"!=typeof i.retryable||i.retryable)}return eu("INSTANCE_RUNTIME_INSTALL_FAILED",e instanceof Error?e.message:String(e),t,n,!0)}function nu(e,t,n,i){const s=i?.message?` Last error: ${i.message}`:"";return eu(i?.code||"INSTANCE_RUNTIME_INSTALL_FAILED",`Runtime convergence paused after ${n} attempts and will retry.${s}`,e,t,!0)}function iu(e,t){if(!Number.isFinite(e)||e<0)throw new TypeError(`${t} must be a nonnegative finite number.`);return e}function su(e,n=448){t.mkdirSync(e,{recursive:!0,mode:n}),t.chmodSync(e,n)}function ou(e,i,s={}){const o=s.directoryMode??448,r=s.fileMode??384;su(n.dirname(e),o),m.sync(e,`${JSON.stringify(i,null,2)}\n`,{encoding:"utf8",mode:r}),t.chmodSync(e,r)}function ru(e,t){console.warn(JSON.stringify({message:e,...t}))}function au(e){return e&&"object"==typeof e&&"issues"in e?{issues:e.issues}:{error:e instanceof Error?e.message:String(e)}}function cu(e,n){const i=n.logger||ru;let s;try{s=JSON.parse(t.readFileSync(e,"utf8"))}catch(t){if(n.rejectInvalid)throw t;return void i("stored JSON could not be read",{filePath:e,...au(t)})}if(!n.schema)return s;const o=n.sanitize?n.sanitize(s):s,r=n.schema.safeParse(o);if(r.success)return r.data;if(n.rejectInvalid)throw r.error;const a="strip"in n.schema&&"function"==typeof n.schema.strip?n.schema.strip().safeParse(o):void 0;if(a?.success)return i("unknown stored fields were ignored",{filePath:e,issues:r.error.issues}),a.data;i("stored record failed validation and was isolated",{filePath:e,issues:r.error.issues})}function du(e){return fr(e)}function lu(){return d.randomBytes(24).toString("base64url")}class uu{directory;options;permissionsInitialized=!1;constructor(e,t={}){this.directory=e,this.options=t}init(){if(this.permissionsInitialized&&t.existsSync(this.directory))return;su(this.directory,this.options.directoryMode??448);const e=this.options.fileMode??384;for(const i of t.readdirSync(this.directory).filter(e=>e.endsWith(".json")))t.chmodSync(n.join(this.directory,i),e);this.permissionsInitialized=!0}filePath(e){return n.join(this.directory,`${e}.json`)}list(){return this.init(),t.readdirSync(this.directory).filter(e=>e.endsWith(".json")).sort().flatMap(e=>{const t=cu(n.join(this.directory,e),this.options);return t?[t]:[]})}get(e){this.init();const n=this.filePath(e);return t.existsSync(n)?cu(n,this.options):void 0}put(e){const t=this.options.sanitize?this.options.sanitize(e):e,n=this.options.schema?this.options.schema.parse(t):t;return ou(this.filePath(n.id),n,this.options),n}patch(e,t){const n=this.get(e);if(!n)return;const i={...n,...t,id:n.id,createdAt:n.createdAt,updatedAt:(new Date).toISOString()};return this.put(i)}delete(e){const n=this.filePath(e);return!!t.existsSync(n)&&(t.unlinkSync(n),!0)}}class pu{filePathValue;defaults;options;constructor(e,t,n={}){this.filePathValue=e,this.defaults=t,this.options=n}init(){su(n.dirname(this.filePathValue),this.options.directoryMode??448),t.existsSync(this.filePathValue)?t.chmodSync(this.filePathValue,this.options.fileMode??384):this.put(this.defaults())}get(){return this.init(),t.existsSync(this.filePathValue)?cu(this.filePathValue,this.options)??this.defaults():this.defaults()}put(e){const t=this.options.sanitize?this.options.sanitize(e):e,n=this.options.schema?this.options.schema.parse(t):t;return ou(this.filePathValue,n,this.options),n}}T.sqliteTable("na_migration_ledger",{id:T.text("id").primaryKey(),checksum:T.text("checksum").notNull(),appliedAt:T.text("applied_at").notNull(),details:T.text("details",{mode:"json"}).$type().notNull()});const mu=T.sqliteTable("na_stories",{id:T.text("id").primaryKey(),title:T.text("title").notNull(),description:T.text("description"),createdAt:T.text("created_at").notNull(),updatedAt:T.text("updated_at").notNull(),archivedAt:T.text("archived_at"),maxIdleAiSessions:T.integer("max_idle_ai_sessions").notNull().default(5),nextDocumentSequence:T.integer("next_document_sequence").notNull().default(1),agentToolsContent:T.integer("agent_tools_content",{mode:"boolean"}).notNull().default(!0),agentToolsActions:T.integer("agent_tools_actions",{mode:"boolean"}).notNull().default(!1),agentToolsAutomations:T.integer("agent_tools_automations",{mode:"boolean"}).notNull().default(!1),agentToolsAiSessions:T.integer("agent_tools_ai_sessions",{mode:"boolean"}).notNull().default(!1),agentToolsDecisions:T.integer("agent_tools_decisions",{mode:"boolean"}).notNull().default(!1)},e=>[T.check("na_stories_max_idle_check",A.sql`${e.maxIdleAiSessions} BETWEEN 1 AND 50`),T.check("na_stories_next_document_sequence_check",A.sql`${e.nextDocumentSequence} > 0`),T.check("na_stories_agent_tools_content_check",A.sql`${e.agentToolsContent} IN (0, 1)`),T.check("na_stories_agent_tools_actions_check",A.sql`${e.agentToolsActions} IN (0, 1)`),T.check("na_stories_agent_tools_automations_check",A.sql`${e.agentToolsAutomations} IN (0, 1)`),T.check("na_stories_agent_tools_ai_sessions_check",A.sql`${e.agentToolsAiSessions} IN (0, 1)`),T.check("na_stories_agent_tools_decisions_check",A.sql`${e.agentToolsDecisions} IN (0, 1)`),T.index("na_stories_created_idx").on(e.createdAt)]),hu=T.sqliteTable("na_story_decisions",{id:T.text("id").primaryKey(),storyId:T.text("story_id").notNull().references(()=>mu.id,{onDelete:"cascade"}),sessionId:T.text("session_id").notNull(),turnId:T.text("turn_id"),question:T.text("question").notNull(),options:T.text("options_json",{mode:"json"}).$type().notNull().default([]),allowFreeText:T.integer("allow_free_text",{mode:"boolean"}).notNull().default(!0),context:T.text("context"),status:T.text("status",{enum:["pending","decided","cancelled","expired"]}).notNull(),revision:T.integer("revision").notNull(),response:T.text("response"),selectedOptionId:T.text("selected_option_id"),decidedTurnId:T.text("decided_turn_id"),expiredReason:T.text("expired_reason_json",{mode:"json"}).$type(),resumeState:T.text("resume_state",{enum:["resuming"]}),resumeAttemptedAt:T.text("resume_attempted_at"),createdAt:T.text("created_at").notNull(),updatedAt:T.text("updated_at").notNull(),decidedAt:T.text("decided_at")},e=>[T.uniqueIndex("na_story_decisions_session_turn_uq").on(e.storyId,e.sessionId,e.turnId).where(A.sql`${e.turnId} IS NOT NULL`),T.index("na_story_decisions_story_idx").on(e.storyId,e.createdAt),T.index("na_story_decisions_session_idx").on(e.sessionId,e.status),T.check("na_story_decisions_revision_check",A.sql`${e.revision} >= 1`),T.check("na_story_decisions_allow_free_text_check",A.sql`${e.allowFreeText} IN (0, 1)`)]),gu=T.sqliteTable("na_story_actions",{storyId:T.text("story_id").notNull().references(()=>mu.id,{onDelete:"cascade"}),id:T.text("id").notNull(),title:T.text("title").notNull(),promptTemplate:T.text("prompt_template").notNull(),targetInstanceId:T.text("target_instance_id"),sessionPreset:T.text("session_preset_json",{mode:"json"}).$type(),displayOrder:T.integer("display_order").notNull()},e=>[T.primaryKey({columns:[e.storyId,e.id]}),T.index("na_story_actions_order_idx").on(e.storyId,e.displayOrder,e.id)]),fu=T.sqliteTable("na_story_documents",{storyId:T.text("story_id").notNull().references(()=>mu.id,{onDelete:"cascade"}),storyPath:T.text("story_path").notNull(),title:T.text("title").notNull(),indexedSequence:T.integer("indexed_sequence").notNull(),displayOrder:T.integer("display_order").notNull()},e=>[T.primaryKey({columns:[e.storyId,e.storyPath]}),T.uniqueIndex("na_story_documents_sequence_uq").on(e.storyId,e.indexedSequence),T.index("na_story_documents_page_idx").on(e.storyId,e.indexedSequence,e.storyPath),T.index("na_story_documents_display_idx").on(e.storyId,e.displayOrder,e.storyPath),T.check("na_story_documents_sequence_check",A.sql`${e.indexedSequence} > 0`)]),yu=T.sqliteTable("na_story_automations",{id:T.text("id").primaryKey(),storyId:T.text("story_id").notNull(),actionId:T.text("action_id").notNull(),schedule:T.text("schedule_json",{mode:"json"}).$type().notNull(),enabled:T.integer("enabled",{mode:"boolean"}).notNull(),policy:T.text("policy_json",{mode:"json"}).$type().notNull(),scheduleAnchorAt:T.text("schedule_anchor_at").notNull(),createdAt:T.text("created_at").notNull(),updatedAt:T.text("updated_at").notNull()},e=>[T.foreignKey({columns:[e.storyId,e.actionId],foreignColumns:[gu.storyId,gu.id],name:"na_story_automations_action_fk"}).onDelete("restrict"),T.index("na_story_automations_story_idx").on(e.storyId),T.index("na_story_automations_enabled_idx").on(e.enabled)]),Iu=T.sqliteTable("na_story_automation_runs",{id:T.text("id").primaryKey(),automationId:T.text("automation_id").notNull().references(()=>yu.id,{onDelete:"cascade"}),eventType:T.text("event_type",{enum:["manual","schedule"]}).notNull(),status:T.text("status",{enum:["queued","dispatching","running","completed","failed","skipped"]}).notNull(),scheduledFor:T.text("scheduled_for").notNull(),targetInstanceId:T.text("target_instance_id").notNull(),aiSessionId:T.text("ai_session_id"),error:T.text("error_json",{mode:"json"}).$type(),queuedAt:T.text("queued_at").notNull(),startedAt:T.text("started_at"),completedAt:T.text("completed_at"),executionKey:T.text("execution_key").notNull(),requestFingerprint:T.text("request_fingerprint").notNull(),executionInput:T.text("execution_input_json",{mode:"json"}).$type().notNull()},e=>[T.uniqueIndex("na_story_automation_runs_execution_key_uq").on(e.executionKey),T.index("na_story_automation_runs_automation_time_idx").on(e.automationId,e.queuedAt),T.index("na_story_automation_runs_status_idx").on(e.status,e.scheduledFor)]),_u=T.sqliteTable("na_story_file_mutations",{id:T.text("id").primaryKey(),storyId:T.text("story_id").notNull().references(()=>mu.id,{onDelete:"restrict"}),operation:T.text("operation",{enum:["write","rename","delete"]}).notNull(),storyPath:T.text("story_path").notNull(),nextStoryPath:T.text("next_story_path"),title:T.text("title"),temporaryName:T.text("temporary_name"),backupName:T.text("backup_name"),phase:T.text("phase",{enum:["receiving","prepared","files-staged","database-committed","cleanup"]}).notNull(),createdAt:T.text("created_at").notNull(),updatedAt:T.text("updated_at").notNull()},e=>[T.index("na_story_file_mutations_story_idx").on(e.storyId,e.createdAt)]),Eu=T.sqliteTable("na_story_deletion_intents",{storyId:T.text("story_id").primaryKey(),phase:T.text("phase",{enum:["prepared","files-staged","database-committed","cleanup"]}).notNull(),trashName:T.text("trash_name"),createdAt:T.text("created_at").notNull(),updatedAt:T.text("updated_at").notNull()}),Au=["health","connectionStatus","agentStatus","targetStatus","uiAccessStatus","ready","protocolVersion","instanceVersion","build","runtimeVersion","capabilities","appInventory","target","access","apps","aiSessions","triggers","runtime","lastHeartbeatAt"];function Tu(e){return JSON.stringify(e??null)}function wu(e){return JSON.parse(String(e))}function bu(e,t){if(e.isTransaction)return t();e.exec("BEGIN IMMEDIATE");try{const n=t();return e.exec("COMMIT"),n}catch(t){throw e.exec("ROLLBACK"),t}}class Nu{client;constructor(e){this.client=e}get(){return this.client.prepare("SELECT node_id, created_at, updated_at FROM na_node_identity WHERE singleton_key = 1").get()}ensure(e,t){const n=this.get();if(n&&n.node_id!==e)throw Du("NODE_AGENT_IDENTITY_MISMATCH",`Stored node identity ${n.node_id} does not match ${e}.`);return n||this.client.prepare("INSERT INTO na_node_identity (singleton_key, node_id, created_at, updated_at) VALUES (1, ?, ?, ?)").run(e,t,t),this.get()}}class Su{client;constructor(e){this.client=e}list(){return this.client.prepare("SELECT * FROM na_local_folders ORDER BY id").all().map(xu)}get(e){const t=this.client.prepare("SELECT * FROM na_local_folders WHERE id = ?").get(e);return t?xu(t):void 0}put(e){const t=Do.parse(Ks(e));return this.client.prepare("INSERT INTO na_local_folders (id, node_id, name, path, labels_json, created_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(id) DO UPDATE SET node_id=excluded.node_id, name=excluded.name, path=excluded.path,\n labels_json=excluded.labels_json, updated_at=excluded.updated_at").run(t.id,t.nodeId,t.name,t.path,Tu(t.labels),t.createdAt,t.updatedAt),t}delete(e){return Number(this.client.prepare("DELETE FROM na_local_folders WHERE id = ?").run(e).changes)>0}}class vu{client;constructor(e){this.client=e}list(){return this.client.prepare("SELECT * FROM na_runtimes ORDER BY id").all().map(Cu)}get(e){const t=this.client.prepare("SELECT * FROM na_runtimes WHERE id = ?").get(e);return t?Cu(t):void 0}put(e){const t=Qr.parse(e);return this.client.prepare("INSERT INTO na_runtimes (id, node_id, name, type, status, access_strategy, capabilities_json, labels_json, created_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(id) DO UPDATE SET node_id=excluded.node_id, name=excluded.name, type=excluded.type,\n status=excluded.status, access_strategy=excluded.access_strategy, capabilities_json=excluded.capabilities_json,\n labels_json=excluded.labels_json, updated_at=excluded.updated_at").run(t.id,t.nodeId,t.name,t.type,t.status,t.accessStrategy,Tu(t.capabilities),Tu(t.labels),t.createdAt,t.updatedAt),t}delete(e){try{return Number(this.client.prepare("DELETE FROM na_runtimes WHERE id = ?").run(e).changes)>0}catch(t){if(String(t).includes("FOREIGN KEY constraint failed"))throw Du("NODE_RUNTIME_IN_USE",`Runtime ${e} is used by a controlled instance.`,409);throw t}}}class Ou{client;constructor(e){this.client=e}list(){return this.client.prepare("SELECT i.*, o.health, o.connection_status, o.ready, o.observed_json,\n o.last_heartbeat_at, o.updated_at AS observation_updated_at\n FROM na_instances i LEFT JOIN na_instance_observations o ON o.instance_id = i.id ORDER BY i.id").all().map(e=>ku(this.client,e))}get(e){const t=this.client.prepare("SELECT i.*, o.health, o.connection_status, o.ready, o.observed_json,\n o.last_heartbeat_at, o.updated_at AS observation_updated_at\n FROM na_instances i LEFT JOIN na_instance_observations o ON o.instance_id = i.id WHERE i.id = ?").get(e);return t?ku(this.client,t):void 0}put(e){const t=Ia.parse(Na(e));return bu(this.client,()=>{const e=this.client.prepare("SELECT state_revision, registration_credential FROM na_instances WHERE id = ?").get(t.id),n=Math.max(t.stateRevision||0,Number(e?.state_revision)||0)+1,i=t.registrationToken||e?.registration_credential,s=function(e){const t={...e};for(const e of Au)delete t[e];for(const e of["id","nodeId","runtimeId","name","status","stateRevision","processIncarnationId","registrationToken","createdAt","updatedAt"])delete t[e];return t}({...t,stateRevision:n}),o=zu(t),r="local-folder"===t.source.type?t.source.localFolderId:void 0,a=r&&this.client.prepare("SELECT 1 AS present FROM na_local_folders WHERE id = ?").get(r)?r:void 0;return this.client.prepare("INSERT INTO na_instances\n (id, node_id, runtime_id, source_local_folder_id, name, status, state_revision, process_incarnation_id,\n registration_credential, desired_json, created_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(id) DO UPDATE SET node_id=excluded.node_id, runtime_id=excluded.runtime_id,\n source_local_folder_id=excluded.source_local_folder_id, name=excluded.name, status=excluded.status,\n state_revision=excluded.state_revision, process_incarnation_id=excluded.process_incarnation_id,\n registration_credential=excluded.registration_credential, desired_json=excluded.desired_json,\n updated_at=excluded.updated_at").run(t.id,t.nodeId,t.runtimeId,a??null,t.name,t.status,n,t.processIncarnationId??null,i??null,Tu(s),t.createdAt,t.updatedAt),this.client.prepare("INSERT INTO na_instance_observations\n (instance_id, health, connection_status, ready, observed_json, last_heartbeat_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(instance_id) DO UPDATE SET health=excluded.health, connection_status=excluded.connection_status,\n ready=excluded.ready, observed_json=excluded.observed_json, last_heartbeat_at=excluded.last_heartbeat_at,\n updated_at=excluded.updated_at").run(t.id,t.health,t.connectionStatus,t.ready?1:0,Tu(o),t.lastHeartbeatAt??null,t.updatedAt),this.get(t.id)})}putObservation(e){const t=Ia.parse(Na(e));return bu(this.client,()=>{const e=this.client.prepare("SELECT state_revision, registration_credential FROM na_instances WHERE id = ?").get(t.id);if(!e)throw Du("NODE_INSTANCE_NOT_FOUND",`Instance ${t.id} was not found.`,404);const n=Math.max(t.stateRevision||0,Number(e.state_revision)||0)+1,i=t.registrationToken||e.registration_credential;return this.client.prepare("UPDATE na_instances SET status = ?, state_revision = ?, process_incarnation_id = ?,\n registration_credential = ?, updated_at = ? WHERE id = ?").run(t.status,n,t.processIncarnationId??null,i??null,t.updatedAt,t.id),this.client.prepare("INSERT INTO na_instance_observations\n (instance_id, health, connection_status, ready, observed_json, last_heartbeat_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(instance_id) DO UPDATE SET health=excluded.health, connection_status=excluded.connection_status,\n ready=excluded.ready, observed_json=excluded.observed_json, last_heartbeat_at=excluded.last_heartbeat_at,\n updated_at=excluded.updated_at").run(t.id,t.health,t.connectionStatus,t.ready?1:0,Tu(zu(t)),t.lastHeartbeatAt??null,t.updatedAt),this.get(t.id)})}delete(e){return Number(this.client.prepare("DELETE FROM na_instances WHERE id = ?").run(e).changes)>0}}function Ru(e){return{nodeIdentity:new Nu(e),localFolders:new Su(e),runtimes:new vu(e),instances:new Ou(e)}}function zu(e){return Object.fromEntries(Au.flatMap(t=>void 0===e[t]?[]:[[t,e[t]]]))}function xu(e){return Do.parse({id:e.id,nodeId:e.node_id,name:e.name,path:e.path,labels:wu(e.labels_json),createdAt:e.created_at,updatedAt:e.updated_at})}function Cu(e){return Qr.parse({id:e.id,nodeId:e.node_id,name:e.name,type:e.type,status:e.status,accessStrategy:e.access_strategy,capabilities:wu(e.capabilities_json),labels:wu(e.labels_json),createdAt:e.created_at,updatedAt:e.updated_at})}function ku(e,t){const n=wu(t.desired_json),i=t.observed_json?wu(t.observed_json):{},s=e.prepare("SELECT * FROM na_instance_model_assignments WHERE instance_id = ?").get(String(t.id)),o=s?e.prepare("SELECT model_id FROM na_instance_model_entities WHERE instance_id = ? ORDER BY display_order").all(String(t.id)).map(e=>String(e.model_id)):void 0,r=s?{modelEntityIds:o,...s.legacy_codex_model_id?{codexModelHash:String(s.legacy_codex_model_id)}:{},...s.legacy_claude_model_id?{claudeModelHash:String(s.legacy_claude_model_id)}:{},...s.legacy_opencode_model_id?{opencodeModelHash:String(s.legacy_opencode_model_id)}:{}}:n.modelSelection;return Ia.parse({...n,...i,modelSelection:r,id:t.id,nodeId:t.node_id,runtimeId:t.runtime_id,name:t.name,status:t.status,stateRevision:t.state_revision,processIncarnationId:t.process_incarnation_id||void 0,registrationToken:t.registration_credential||void 0,health:t.health||"unknown",connectionStatus:t.connection_status||"unknown",ready:Boolean(t.ready),lastHeartbeatAt:t.last_heartbeat_at||void 0,createdAt:t.created_at,updatedAt:t.updated_at})}function Du(e,t,n=409){return Object.assign(new Error(t),{code:e,statusCode:n})}function Lu(e){return JSON.stringify(e??null)}function Pu(e){return JSON.parse(String(e))}class Mu{client;constructor(e){this.client=e}list(){return this.client.prepare("SELECT * FROM na_models ORDER BY display_order, id").all().map(Fu)}get(e){const t=this.client.prepare("SELECT * FROM na_models WHERE id = ?").get(e);return t?Fu(t):void 0}put(e){const t=Vo.parse(e);return this.client.prepare("INSERT INTO na_models\n (id, name, endpoint, key, model, app, enabled, display_order, model_names_json, mappings_json, protocols_json, labels_json, created_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(id) DO UPDATE SET name=excluded.name, endpoint=excluded.endpoint, key=excluded.key,\n model=excluded.model, app=excluded.app, enabled=excluded.enabled, display_order=excluded.display_order,\n model_names_json=excluded.model_names_json, mappings_json=excluded.mappings_json, protocols_json=excluded.protocols_json,\n labels_json=excluded.labels_json, updated_at=excluded.updated_at").run(t.id,t.name,t.endpoint,t.key,t.model,t.app,t.enabled?1:0,t.order,Lu(cr(t.modelNames)),Lu(t.mappings),Lu(t.protocols),Lu(t.labels),t.createdAt,t.updatedAt),t}rename(e,t){this.client.prepare("UPDATE na_models SET id = ? WHERE id = ?").run(t,e)}delete(e){try{return Number(this.client.prepare("DELETE FROM na_models WHERE id = ?").run(e).changes)>0}catch(t){if(String(t).includes("FOREIGN KEY constraint failed")){const t=this.referenceIds(e);throw Object.assign(new Error(`Model ${e} is assigned to ${t.length} instance${1===t.length?"":"s"}.`),{statusCode:409,code:"NODE_MODEL_IN_USE",instanceIds:t})}throw t}}referenceIds(e){return this.client.prepare("SELECT DISTINCT instance_id FROM (\n SELECT instance_id FROM na_instance_model_entities WHERE model_id = ?\n UNION ALL SELECT instance_id FROM na_instance_model_assignments WHERE legacy_codex_model_id = ?\n UNION ALL SELECT instance_id FROM na_instance_model_assignments WHERE legacy_claude_model_id = ?\n UNION ALL SELECT instance_id FROM na_instance_model_assignments WHERE legacy_opencode_model_id = ?\n ) ORDER BY instance_id").all(e,e,e,e).map(e=>String(e.instance_id))}}class ju{client;constructor(e){this.client=e}get(e){const t=this.client.prepare("SELECT * FROM na_instance_model_assignments WHERE instance_id = ?").get(e);if(!t)return;const n=this.client.prepare("SELECT model_id FROM na_instance_model_entities WHERE instance_id = ? ORDER BY display_order").all(e).map(e=>String(e.model_id));return Wo.parse({instanceId:e,modelEntityIds:n,codexModelHash:t.legacy_codex_model_id||void 0,claudeModelHash:t.legacy_claude_model_id||void 0,opencodeModelHash:t.legacy_opencode_model_id||void 0,updatedAt:t.updated_at})}put(e){const t=Wo.parse(e);return this.transaction(()=>{this.client.prepare("INSERT INTO na_instance_model_assignments\n (instance_id, legacy_codex_model_id, legacy_claude_model_id, legacy_opencode_model_id, updated_at)\n VALUES (?, ?, ?, ?, ?)\n ON CONFLICT(instance_id) DO UPDATE SET legacy_codex_model_id=excluded.legacy_codex_model_id,\n legacy_claude_model_id=excluded.legacy_claude_model_id,\n legacy_opencode_model_id=excluded.legacy_opencode_model_id, updated_at=excluded.updated_at").run(t.instanceId,t.codexModelHash??null,t.claudeModelHash??null,t.opencodeModelHash??null,t.updatedAt),this.client.prepare("DELETE FROM na_instance_model_entities WHERE instance_id = ?").run(t.instanceId);const e=this.client.prepare("INSERT INTO na_instance_model_entities (instance_id, model_id, display_order) VALUES (?, ?, ?)");for(const[n,i]of t.modelEntityIds.entries())e.run(t.instanceId,i,n)}),this.get(t.instanceId)}delete(e){return Number(this.client.prepare("DELETE FROM na_instance_model_assignments WHERE instance_id = ?").run(e).changes)>0}transaction(e){if(this.client.isTransaction)return e();this.client.exec("BEGIN IMMEDIATE");try{const t=e();return this.client.exec("COMMIT"),t}catch(e){throw this.client.exec("ROLLBACK"),e}}}function Uu(e){return{models:new Mu(e),assignments:new ju(e),transaction(t){if(e.isTransaction)return t();e.exec("BEGIN IMMEDIATE");try{const n=t();return e.exec("COMMIT"),n}catch(t){throw e.exec("ROLLBACK"),t}}}}function Fu(e){const t=rr(Pu(e.model_names_json),"modelNames",t=>{console.warn(JSON.stringify({message:"unknown or invalid stored node model name entry was sanitized",modelId:e.id,field:t.field}))}),n=rr(Pu(e.mappings_json??"[]"),"mappings",t=>{console.warn(JSON.stringify({message:"unknown or invalid stored node model request mapping was sanitized",modelId:e.id,field:t.field}))}),i=Vo.parse({id:e.id,name:e.name,endpoint:e.endpoint,key:e.key,model:e.model,modelNames:t,mappings:n,protocols:Pu(e.protocols_json),app:e.app,enabled:Boolean(e.enabled),order:e.display_order,labels:Pu(e.labels_json),createdAt:e.created_at,updatedAt:e.updated_at});return{...i,modelNames:ar(i.modelNames,i.model,{renumber:!1}),mappings:dr(i.mappings,{renumber:!1})}}const $u=2e3,Hu=32e3,qu=c.z.string().trim().min(1).max(120).regex(/^[a-zA-Z0-9][a-zA-Z0-9_.:-]*$/),Bu=qu,Vu=c.z.string().regex(/^[a-f0-9]{64}$/),Gu=c.z.enum(["overlay-copy-on-write","worktree"]),Ku=c.z.enum(["instance","container","local-runtime"]),Wu=Object.freeze([{workspaceMaterializer:"overlay-copy-on-write",processSandbox:"instance"}]),Yu=c.z.object({workspaceMaterializer:Gu.default("overlay-copy-on-write"),processSandbox:Ku.default("instance")}).strict();function Xu(e){return Wu.some(t=>t.workspaceMaterializer===e.workspaceMaterializer&&t.processSandbox===e.processSandbox)}const Ju=c.z.object({id:Bu,revision:Vu,name:c.z.string().trim().min(1).max(120),description:c.z.string().trim().max($u).default(""),appendedPrompt:c.z.string().max(Hu).default(""),targetInstanceId:qu,cwdFolderId:qu,providerId:qu,modelEntityId:qu.optional(),modelName:c.z.string().trim().min(1).max(120).optional(),modelUpstreamName:c.z.string().trim().min(1).max(240).optional(),reasoningEffort:c.z.string().trim().min(1).max(120).optional(),permissionMode:c.z.string().trim().min(1).max(120).optional(),executionPolicy:Yu,createdAt:c.z.string().datetime(),updatedAt:c.z.string().datetime()}).strict(),Qu={name:c.z.string().trim().min(1).max(120),description:c.z.string().trim().max($u).default(""),appendedPrompt:c.z.string().max(Hu).default(""),targetInstanceId:qu,cwdFolderId:qu,providerId:qu,modelEntityId:qu.optional(),modelName:c.z.string().trim().min(1).max(120).optional(),modelUpstreamName:c.z.string().trim().min(1).max(240).optional(),reasoningEffort:c.z.string().trim().min(1).max(120).optional(),permissionMode:c.z.string().trim().min(1).max(120).optional(),executionPolicy:Yu.optional()},Zu=c.z.object(Qu).strict(),ep=c.z.object({expectedRevision:Vu,name:Qu.name.optional(),description:c.z.string().trim().max($u).nullable().optional(),appendedPrompt:c.z.string().max(Hu).nullable().optional(),targetInstanceId:Qu.targetInstanceId.optional(),cwdFolderId:Qu.cwdFolderId.optional(),providerId:Qu.providerId.optional(),modelEntityId:qu.nullable().optional(),modelName:c.z.string().trim().min(1).max(120).nullable().optional(),modelUpstreamName:c.z.string().trim().min(1).max(240).nullable().optional(),reasoningEffort:c.z.string().trim().min(1).max(120).nullable().optional(),permissionMode:c.z.string().trim().min(1).max(120).nullable().optional(),executionPolicy:Qu.executionPolicy}).strict(),tp=c.z.object({agents:c.z.array(Ju)}).strict(),np=c.z.object({id:Bu,deleted:c.z.literal(!0),deletedOrchestrationIds:c.z.array(c.z.string().trim().min(1).max(160)).default([])}).strict();c.z.object({agents:c.z.array(c.z.object({nodeId:qu,agent:Ju}).strict()),unavailableNodeIds:c.z.array(qu).default([])}).strict();const ip=["AGENT_DEFINITION_INVALID_INPUT","AGENT_DEFINITION_NOT_FOUND","AGENT_DEFINITION_REVISION_CONFLICT","AGENT_DEFINITION_TARGET_INSTANCE_UNKNOWN","AGENT_DEFINITION_FOLDER_UNKNOWN","AGENT_DEFINITION_PROVIDER_UNSUPPORTED","AGENT_DEFINITION_POLICY_UNSUPPORTED"],sp=c.z.enum(ip),op=c.z.object({code:c.z.literal("AGENT_DEFINITION_REVISION_CONFLICT"),expectedRevision:Vu,actualRevision:Vu}).strict();c.z.union([op,c.z.object({code:sp}).strict()]);const rp=c.z.object({agentId:Bu,change:c.z.enum(["created","updated","deleted"]),revision:Vu.optional(),definition:Ju.optional()}).strict();c.z.object({nodeId:qu,event:rp}).strict();const ap=Ju.strip().extend({executionPolicy:Yu.strip()});c.z.object({agents:c.z.array(ap)}).strip(),c.z.object({agents:c.z.array(c.z.object({nodeId:qu,agent:ap}).strip()),unavailableNodeIds:c.z.array(c.z.string().trim().min(1).max(120)).default([])}).strip();const cp=c.z.object({agentId:Bu,change:c.z.enum(["created","updated","deleted"]),revision:Vu.optional(),definition:ap.optional()}).strip();c.z.object({nodeId:qu,event:cp}).strip();const dp=new WeakMap;function lp(e,t){const n=function(e){const t=dp.get(e);if(t)return t;const n={depth:0,afterCommit:[]};return dp.set(e,n),n}(e);if(e.isTransaction){n.depth+=1;try{return t()}finally{n.depth-=1}}e.exec("BEGIN IMMEDIATE"),n.depth+=1;try{const i=t();if(e.exec("COMMIT"),n.depth-=1,0===n.depth){const e=n.afterCommit.splice(0);for(const t of e)t()}return i}catch(t){throw e.exec("ROLLBACK"),n.depth-=1,0===n.depth&&(n.afterCommit.length=0),t}}function up(e,t){const n=dp.get(e);n&&0!==n.depth?n.afterCommit.push(t):t()}const pp=200,mp="default:",hp=c.z.string().trim().min(1).max(160).regex(/^[a-zA-Z0-9][a-zA-Z0-9_.:-]*$/),gp=hp,fp=c.z.string().regex(/^[a-f0-9]{64}$/);function yp(e){return`${mp}${Bu.parse(e)}`}function Ip(e){if(!function(e){return e.startsWith(mp)}(e))return;const t=e.slice(8);return Bu.safeParse(t).success?t:void 0}const _p=c.z.object({fromAgentId:Bu,toAgentId:Bu}).strict(),Ep=c.z.object({id:gp,revision:fp,name:c.z.string().trim().min(1).max(120),agentIds:c.z.array(Bu).min(1).max(50),edges:c.z.array(_p).max(pp),createdAt:c.z.string().datetime(),updatedAt:c.z.string().datetime()}).strict(),Ap=c.z.object({name:c.z.string().trim().min(1).max(120),agentIds:c.z.array(Bu).min(1).max(50),edges:c.z.array(_p).max(pp).default([])}).strict(),Tp=c.z.object({expectedRevision:fp,name:c.z.string().trim().min(1).max(120).optional(),agentIds:c.z.array(Bu).min(1).max(50).optional(),edges:c.z.array(_p).max(pp).optional()}).strict(),wp=c.z.object({orchestrations:c.z.array(Ep)}).strict(),bp=c.z.object({id:gp,deleted:c.z.literal(!0)}).strict();c.z.object({orchestrations:c.z.array(c.z.object({nodeId:hp,orchestration:Ep}).strict()),unavailableNodeIds:c.z.array(hp).default([])}).strict();const Np=c.z.enum(["AGENT_ORCHESTRATION_NOT_FOUND","AGENT_ORCHESTRATION_REVISION_CONFLICT","AGENT_ORCHESTRATION_INVALID_GRAPH","AGENT_ORCHESTRATION_AGENT_UNKNOWN","AGENT_ORCHESTRATION_CYCLE","AGENT_ORCHESTRATION_DEFAULT_PROTECTED"]),Sp=c.z.object({code:c.z.literal("AGENT_ORCHESTRATION_CYCLE"),cycle:c.z.array(Bu).min(2)}).strict(),vp=c.z.object({code:c.z.literal("AGENT_ORCHESTRATION_REVISION_CONFLICT"),expectedRevision:fp,actualRevision:fp}).strict();c.z.union([Sp,vp,c.z.object({code:Np}).strict()]);const Op=c.z.object({orchestrationId:gp,change:c.z.enum(["created","updated","deleted"]),revision:fp.optional(),orchestration:Ep.optional()}).strict();function Rp(e,t){return e.agentIds.includes(t)}function zp(e){return{agentIds:[...new Set(e.agentIds)].sort(),edges:[...new Map(e.edges.map(e=>[`${e.fromAgentId}${e.toAgentId}`,e])).values()].sort((e,t)=>e.fromAgentId===t.fromAgentId?e.toAgentId.localeCompare(t.toAgentId):e.fromAgentId.localeCompare(t.fromAgentId))}}c.z.object({nodeId:hp,event:Op}).strict();const xp=Ep.strip().extend({agentIds:c.z.array(Bu).max(50).default([]),edges:c.z.array(_p).max(pp).default([])});c.z.object({orchestrations:c.z.array(xp)}).strip(),c.z.object({orchestrations:c.z.array(c.z.object({nodeId:c.z.string().trim().min(1).max(160),orchestration:xp}).strip()),unavailableNodeIds:c.z.array(c.z.string().trim().min(1).max(160)).default([])}).strip();const Cp=c.z.object({orchestrationId:gp,change:c.z.enum(["created","updated","deleted"]),revision:fp.optional(),orchestration:xp.optional()}).strip();c.z.object({nodeId:c.z.string().trim().min(1).max(160),event:Cp}).strip();const kp=c.z.string().trim().min(1).max(120).regex(/^[a-zA-Z0-9][a-zA-Z0-9_.:-]*$/),Dp=kp,Lp=kp,Pp=c.z.number().int().nonnegative(),Mp=Object.freeze({maxMembers:16,maxDepth:4,maxConcurrency:4}),jp=32e3,Up=c.z.enum(["queued","preparing","running","finalizing","completed","failed","cancelled"]),Fp=c.z.object({kind:c.z.enum(["control-plane-user","standalone-operator"]),subjectId:kp,authorizationRevision:c.z.number().int().nonnegative().optional()}).strict(),$p=c.z.object({source:c.z.literal("story-session").optional(),initiatingInstanceId:kp,initiatingAiSessionId:kp,storyId:kp,authorizationSubject:Fp.optional()}).strict(),Hp=c.z.object({source:c.z.literal("control-plane"),authorizationSubject:Fp.optional()}).strict(),qp=c.z.union([$p,Hp]),Bp=c.z.object({maxMembers:c.z.number().int().positive(),maxDepth:c.z.number().int().nonnegative(),maxConcurrency:c.z.number().int().positive()}).strict(),Vp=c.z.object({prompt:c.z.string().trim().min(1).max(128e3)}).strict(),Gp=c.z.object({agentRevision:Vu,targetInstanceId:kp,cwdFolderId:kp,appendedPrompt:c.z.string().max(32e3),providerId:kp,modelEntityId:kp.optional(),modelName:c.z.string().trim().min(1).max(120).optional(),modelUpstreamName:c.z.string().trim().min(1).max(240).optional(),reasoningEffort:c.z.string().trim().min(1).max(120).optional(),permissionMode:c.z.string().trim().min(1).max(120).optional(),executionPolicy:Yu}).strict(),Kp=c.z.object({code:c.z.string().trim().min(1).max(120),message:c.z.string().trim().min(1).max(4e3),retryable:c.z.boolean().default(!1),details:c.z.record(c.z.string(),c.z.unknown()).optional()}).strict(),Wp=c.z.object({text:c.z.string().max(128e3),truncated:c.z.boolean().default(!1),source:c.z.literal("provider-final-message").default("provider-final-message")}).strict(),Yp=c.z.object({status:c.z.enum(["pending","delivered","failed"]),attempts:c.z.number().int().nonnegative(),updatedAt:c.z.string().datetime(),deliveredAt:c.z.string().datetime().optional(),error:Kp.optional()}).strict(),Xp=c.z.object({runId:Dp,status:c.z.enum(["completed","failed","cancelled"]),result:c.z.object({text:c.z.string().max(jp),truncated:c.z.boolean()}).strict().optional(),error:Kp.optional()}).strict().superRefine((e,t)=>{"completed"!==e.status||e.result||t.addIssue({code:c.z.ZodIssueCode.custom,message:"A completed Agent Run tool result requires result text."}),"completed"===e.status||e.error||t.addIssue({code:c.z.ZodIssueCode.custom,message:"A failed or cancelled Agent Run tool result requires an error."})}),Jp=c.z.object({status:c.z.enum(["pending","completed","retrying","manual-intervention"]),attempts:c.z.number().int().nonnegative(),message:c.z.string().max(4e3).optional(),updatedAt:c.z.string().datetime()}).strict(),Qp=c.z.object({runtimeId:kp,state:c.z.enum(["preparing","active","retained","expiring","delete-retrying","expired","manual-intervention"]),usageBytes:c.z.number().int().nonnegative(),quotaBytes:c.z.number().int().positive(),expiresAt:c.z.string().datetime().optional()}).strict(),Zp=c.z.object({memberId:Lp,runId:Dp,agentId:Bu,parentMemberId:Lp.optional(),instanceId:kp,aiSessionId:kp.optional(),role:c.z.enum(["root","callee"]),depth:c.z.number().int().nonnegative(),status:Up,input:Vp.optional(),executionSnapshot:Gp,result:Wp.optional(),error:Kp.optional(),createdAt:c.z.string().datetime(),updatedAt:c.z.string().datetime(),completedAt:c.z.string().datetime().optional()}).strict(),em=c.z.object({runId:Dp,sequence:c.z.number().int().positive(),timestamp:c.z.string().datetime(),kind:c.z.string().trim().min(1).max(120),memberId:Lp.optional(),data:c.z.record(c.z.string(),c.z.unknown()).default({})}).strict(),tm=c.z.object({runId:Dp,clientRequestId:kp,revision:Pp,status:Up,input:Vp.optional(),provenance:qp,orchestrationId:gp,rootMemberId:Lp,budget:Bp,result:Wp.optional(),resultDelivery:Yp.optional(),error:Kp.optional(),cleanup:Jp.optional(),sharedSpace:Qp.optional(),members:c.z.array(Zp).optional(),timeline:c.z.array(em).optional(),createdAt:c.z.string().datetime(),updatedAt:c.z.string().datetime(),completedAt:c.z.string().datetime().optional()}).strict(),nm=c.z.object({clientRequestId:kp,orchestrationId:gp,entryAgentId:Bu.optional(),input:Vp,provenance:qp,budget:Bp.optional()}).strict();c.z.object({clientRequestId:kp,orchestrationId:gp,entryAgentId:Bu.optional(),input:Vp,budget:Bp.optional()}).strict();const im=c.z.object({expectedRevision:Pp.optional()}).strict(),sm=c.z.object({runs:c.z.array(tm)}).strict(),om=["AGENT_RUN_NOT_FOUND","AGENT_RUN_MEMBER_NOT_FOUND","AGENT_RUN_IDEMPOTENCY_CONFLICT","AGENT_RUN_REVISION_CONFLICT","AGENT_RUN_INITIATING_INSTANCE_UNKNOWN","AGENT_RUN_ORCHESTRATION_UNKNOWN","AGENT_RUN_ENTRY_REQUIRED","AGENT_RUN_ENTRY_INVALID","AGENT_RUN_INVOCATION_FORBIDDEN","AGENT_RUN_EXECUTION_UNSUPPORTED","AGENT_RUN_ALREADY_TERMINAL"];c.z.enum(om);const rm=c.z.object({runId:Dp,revision:Pp,run:tm}).strict(),am=c.z.object({runId:Dp,memberId:Lp,revision:Pp,member:Zp}).strict();c.z.object({runs:c.z.array(c.z.object({nodeId:kp,run:tm}).strict()),unavailableNodeIds:c.z.array(kp).default([])}).strict(),c.z.object({nodeId:kp,event:c.z.union([rm,am])}).strict();const cm=Zp.strip().extend({input:Vp.strip().optional(),executionSnapshot:Gp.strip(),result:Wp.strip().optional(),error:Kp.strip().optional()}),dm=em.strip(),lm=tm.strip().extend({orchestrationId:gp.optional(),input:Vp.strip().optional(),provenance:c.z.union([$p.strip().extend({authorizationSubject:Fp.strip().optional()}),Hp.strip().extend({authorizationSubject:Fp.strip().optional()})]),budget:Bp.strip(),result:Wp.strip().optional(),resultDelivery:Yp.strip().extend({error:Kp.strip().optional()}).optional(),error:Kp.strip().optional(),cleanup:Jp.strip().optional(),sharedSpace:Qp.strip().optional(),members:c.z.array(cm).optional(),timeline:c.z.array(dm).optional()}).transform(e=>{const t=e.orchestrationId??(()=>{const t=(e.members??[]).find(t=>t.memberId===e.rootMemberId);if(!t)throw new Error("An Agent Run without an orchestration binding requires its root member to normalize.");return yp(t.agentId)})();return{...e,orchestrationId:t}}),um=c.z.object({runId:Dp,revision:Pp,run:lm}).strip(),pm=c.z.object({runId:Dp,memberId:Lp,revision:Pp,member:cm}).strip();c.z.object({nodeId:kp,event:c.z.union([um,pm])}).strip();const mm=new Set(["completed","failed","cancelled"]),hm={queued:["preparing","finalizing"],preparing:["running","finalizing"],running:["finalizing"],finalizing:["completed","failed","cancelled"],completed:[],failed:[],cancelled:[]};function gm(e){return e??(new Date).toISOString()}function fm(e){return`${e}_${d.randomBytes(10).toString("hex")}`}function ym(e){return JSON.stringify(e)}function Im(e){try{return JSON.parse(String(e))}catch{return}}function _m(e,t,n,i){return Object.assign(new Error(t),{code:e,statusCode:n,...i?{details:i}:{}})}function Em(e,t){if(t.targetInstanceId!==e)throw _m("AGENT_RUN_SNAPSHOT_INSTANCE_MISMATCH","The member instance does not match its immutable execution snapshot.",409,{instanceId:e,snapshotInstanceId:t.targetInstanceId})}class Am{client;constructor(e){this.client=e}transaction(e){return lp(this.client,e)}create(e){return lp(this.client,()=>{const t=this.getByClientRequestId(e.clientRequestId);if(t){const n=t.members?.find(e=>e.memberId===t.rootMemberId);if(t.orchestrationId===e.orchestrationId&&n?.agentId===e.root.agentId&&n.instanceId===e.root.instanceId&&w.isDeepStrictEqual(n.executionSnapshot,e.root.executionSnapshot)&&w.isDeepStrictEqual(t.input,e.input)&&w.isDeepStrictEqual(t.provenance,e.provenance)&&w.isDeepStrictEqual(t.budget,e.budget))return t;throw _m("AGENT_RUN_IDEMPOTENCY_CONFLICT","The client request id is already associated with a different Agent Run request.",409,{clientRequestId:e.clientRequestId,runId:t.runId})}Em(e.root.instanceId,e.root.executionSnapshot);const n=fm("run"),i=fm("member"),s=gm(e.timestamp);return this.client.prepare("INSERT INTO na_agent_runs\n (run_id, client_request_id, revision, status, input_json, provenance_json, orchestration_id, root_member_id, budget_json,\n result_json, error_json, cleanup_json, created_at, updated_at, completed_at)\n VALUES (?, ?, 0, 'queued', ?, ?, ?, ?, ?, NULL, NULL, NULL, ?, ?, NULL)").run(n,e.clientRequestId,ym(e.input),ym(e.provenance),e.orchestrationId,i,ym(e.budget),s,s),this.client.prepare("INSERT INTO na_agent_run_members\n (member_id, run_id, client_request_id, agent_id, parent_member_id, instance_id, ai_session_id, role, depth, status,\n input_json, execution_snapshot_json, result_json, error_json, created_at, updated_at, completed_at)\n VALUES (?, ?, ?, ?, NULL, ?, ?, 'root', 0, 'queued', ?, ?, NULL, NULL, ?, ?, NULL)").run(i,n,e.clientRequestId,e.root.agentId,e.root.instanceId,e.root.aiSessionId??null,ym(e.root.input??e.input),ym(e.root.executionSnapshot),s,s),this.require(n)})}list(){return this.client.prepare("SELECT run_id FROM na_agent_runs ORDER BY created_at DESC, run_id DESC").all().map(e=>this.require(String(e.run_id)))}get(e){const t=this.client.prepare("SELECT * FROM na_agent_runs WHERE run_id = ?").get(e);return t?this.runFromRow(t):void 0}getByClientRequestId(e){const t=this.client.prepare("SELECT * FROM na_agent_runs WHERE client_request_id = ?").get(e);return t?this.runFromRow(t):void 0}addMember(e){return lp(this.client,()=>{const t=this.require(e.runId);if(mm.has(t.status))throw _m("AGENT_RUN_TERMINAL","A terminal run cannot accept another member.",409,{runId:e.runId,status:t.status});const n=this.getMember(e.runId,e.parentMemberId);if(!n)throw _m("AGENT_RUN_PARENT_MEMBER_NOT_FOUND","The parent member does not belong to this run.",404,{runId:e.runId,parentMemberId:e.parentMemberId});const i=this.client.prepare("SELECT * FROM na_agent_run_members WHERE run_id = ? AND client_request_id = ?").get(e.runId,e.clientRequestId);if(i){const t=this.memberFromRow(i);if(t.parentMemberId===e.parentMemberId&&t.agentId===e.agentId&&t.instanceId===e.instanceId&&w.isDeepStrictEqual(t.input,e.input)&&w.isDeepStrictEqual(t.executionSnapshot,e.executionSnapshot))return t;throw _m("AGENT_RUN_MEMBER_IDEMPOTENCY_CONFLICT","The member client request id is already associated with another invocation.",409,{runId:e.runId,clientRequestId:e.clientRequestId,memberId:t.memberId})}if(Number(this.client.prepare("SELECT COUNT(*) AS count FROM na_agent_run_members WHERE run_id = ?").get(e.runId).count)>=t.budget.maxMembers)throw _m("AGENT_RUN_MEMBER_BUDGET_EXCEEDED","The run member budget is exhausted.",409,{runId:e.runId,maxMembers:t.budget.maxMembers});const s=n.depth+1;if(s>t.budget.maxDepth)throw _m("AGENT_RUN_DEPTH_BUDGET_EXCEEDED","The run call depth budget is exhausted.",409,{runId:e.runId,maxDepth:t.budget.maxDepth,requestedDepth:s});Em(e.instanceId,e.executionSnapshot);const o=fm("member"),r=gm(e.timestamp);return this.client.prepare("INSERT INTO na_agent_run_members\n (member_id, run_id, client_request_id, agent_id, parent_member_id, instance_id, ai_session_id, role, depth, status,\n input_json, execution_snapshot_json, result_json, error_json, created_at, updated_at, completed_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, 'callee', ?, 'queued', ?, ?, NULL, NULL, ?, ?, NULL)").run(o,e.runId,e.clientRequestId,e.agentId,e.parentMemberId,e.instanceId,e.aiSessionId??null,s,ym(e.input),ym(e.executionSnapshot),r,r),this.bumpRevision(e.runId,r),this.requireMember(e.runId,o)})}getMember(e,t){const n=this.client.prepare("SELECT * FROM na_agent_run_members WHERE run_id = ? AND member_id = ?").get(e,t);return n?this.memberFromRow(n):void 0}transitionRun(e,t){return lp(this.client,()=>{const n=this.require(e);this.assertTransition(n.status,t.status,{runId:e});const i=gm(t.timestamp),s="result"in t?t.result??void 0:n.result,o="resultDelivery"in t?t.resultDelivery??void 0:n.resultDelivery,r="error"in t?t.error??void 0:n.error,a="cleanup"in t?t.cleanup??void 0:n.cleanup,c=mm.has(t.status)?n.completedAt??i:void 0;return t.status!==n.status||ym(s??null)!==ym(n.result??null)||ym(o??null)!==ym(n.resultDelivery??null)||ym(r??null)!==ym(n.error??null)||ym(a??null)!==ym(n.cleanup??null)?(this.client.prepare("UPDATE na_agent_runs SET status = ?, revision = revision + 1,\n result_json = ?, result_delivery_json = ?, error_json = ?, cleanup_json = ?, updated_at = ?, completed_at = ? WHERE run_id = ?").run(t.status,s?ym(s):null,o?ym(o):null,r?ym(r):null,a?ym(a):null,i,c??null,e),this.require(e)):n})}transitionMember(e,t,n){return lp(this.client,()=>{const i=this.requireMember(e,t);this.assertTransition(i.status,n.status,{runId:e,memberId:t});const s=gm(n.timestamp),o="result"in n?n.result??void 0:i.result,r="error"in n?n.error??void 0:i.error,a="aiSessionId"in n?n.aiSessionId??void 0:i.aiSessionId,c=mm.has(n.status)?i.completedAt??s:void 0;return n.status!==i.status||ym(o??null)!==ym(i.result??null)||ym(r??null)!==ym(i.error??null)||a!==i.aiSessionId?(this.client.prepare("UPDATE na_agent_run_members SET status = ?, result_json = ?, error_json = ?,\n ai_session_id = ?, updated_at = ?, completed_at = ? WHERE run_id = ? AND member_id = ?").run(n.status,o?ym(o):null,r?ym(r):null,a??null,s,c??null,e,t),this.bumpRevision(e,s),this.requireMember(e,t)):i})}appendTimeline(e){return lp(this.client,()=>{if(this.require(e.runId),e.memberId&&!this.getMember(e.runId,e.memberId))throw _m("AGENT_RUN_TIMELINE_MEMBER_NOT_FOUND","The timeline member does not belong to this run.",404,{runId:e.runId,memberId:e.memberId});const t=Number(this.client.prepare("SELECT COALESCE(MAX(sequence), 0) + 1 AS sequence FROM na_agent_run_timeline WHERE run_id = ?").get(e.runId).sequence),n=gm(e.timestamp);this.client.prepare("INSERT INTO na_agent_run_timeline\n (run_id, sequence, timestamp, kind, member_id, data_json) VALUES (?, ?, ?, ?, ?, ?)").run(e.runId,t,n,e.kind,e.memberId??null,ym(e.data??{})),this.bumpRevision(e.runId,n);const i=this.client.prepare("SELECT * FROM na_agent_run_timeline WHERE run_id = ? AND sequence = ?").get(e.runId,t);return this.timelineFromRow(i)})}bumpRevision(e,t){this.client.prepare("UPDATE na_agent_runs SET revision = revision + 1, updated_at = ? WHERE run_id = ?").run(t,e)}assertTransition(e,t,n){if(!function(e,t){return e===t||hm[e].includes(t)}(e,t))throw _m("AGENT_RUN_STATUS_TRANSITION_INVALID",`Cannot transition Agent Run status from ${e} to ${t}.`,409,{...n,from:e,to:t})}require(e){const t=this.get(e);if(!t)throw _m("AGENT_RUN_NOT_FOUND","Agent Run was not found.",404,{runId:e});return t}requireMember(e,t){const n=this.getMember(e,t);if(!n)throw _m("AGENT_RUN_MEMBER_NOT_FOUND","Agent Run member was not found.",404,{runId:e,memberId:t});return n}runFromRow(e){const t=String(e.run_id),n=this.client.prepare("SELECT * FROM na_agent_run_members WHERE run_id = ? ORDER BY created_at, member_id").all(t).map(e=>this.memberFromRow(e)),i=this.client.prepare("SELECT * FROM na_agent_run_timeline WHERE run_id = ? ORDER BY sequence").all(t).map(e=>this.timelineFromRow(e)),s=null==e.orchestration_id||0===String(e.orchestration_id).length?(()=>{const t=n.find(t=>t.memberId===String(e.root_member_id));return t?yp(t.agentId):void 0})():String(e.orchestration_id);try{return o={runId:t,clientRequestId:e.client_request_id,revision:e.revision,status:e.status,input:null==e.input_json?void 0:Im(e.input_json),provenance:Im(e.provenance_json),orchestrationId:s,rootMemberId:e.root_member_id,budget:Im(e.budget_json),result:null==e.result_json?void 0:Im(e.result_json),resultDelivery:null==e.result_delivery_json?void 0:Im(e.result_delivery_json),error:null==e.error_json?void 0:Im(e.error_json),cleanup:null==e.cleanup_json?void 0:Im(e.cleanup_json),members:n,timeline:i,createdAt:e.created_at,updatedAt:e.updated_at,completedAt:e.completed_at??void 0},lm.parse(o)}catch(e){throw _m("NODE_AGENT_AGENT_RUN_INVALID","Stored Agent Run cannot be parsed with the current model.",500,{runId:t,cause:e instanceof Error?e.message:String(e)})}var o}memberFromRow(e){try{return t={memberId:e.member_id,runId:e.run_id,agentId:e.agent_id,parentMemberId:e.parent_member_id??void 0,instanceId:e.instance_id,aiSessionId:e.ai_session_id??void 0,role:e.role,depth:e.depth,status:e.status,input:null==e.input_json?void 0:Im(e.input_json),executionSnapshot:Im(e.execution_snapshot_json),result:null==e.result_json?void 0:Im(e.result_json),error:null==e.error_json?void 0:Im(e.error_json),createdAt:e.created_at,updatedAt:e.updated_at,completedAt:e.completed_at??void 0},cm.parse(t)}catch(t){throw _m("NODE_AGENT_AGENT_RUN_MEMBER_INVALID","Stored Agent Run member cannot be parsed with the current model.",500,{runId:e.run_id,memberId:e.member_id,cause:t instanceof Error?t.message:String(t)})}var t}timelineFromRow(e){try{return t={runId:e.run_id,sequence:e.sequence,timestamp:e.timestamp,kind:e.kind,memberId:e.member_id??void 0,data:Im(e.data_json)},dm.parse(t)}catch(t){throw _m("NODE_AGENT_AGENT_RUN_TIMELINE_INVALID","Stored Agent Run timeline entry cannot be parsed with the current model.",500,{runId:e.run_id,sequence:e.sequence,cause:t instanceof Error?t.message:String(t)})}var t}}const Tm=new Set(["id","name","revision","created_at","updated_at"]),wm=/^[a-f0-9]{64}$/;function bm(e){const t=zp(e);return d.createHash("sha256").update((n=[e.name,t.agentIds,t.edges],JSON.stringify(n??null))).digest("hex");var n}class Nm{client;diagnostic;constructor(e){this.client=e}setDiagnostic(e){this.diagnostic=e}transaction(e){return lp(this.client,e)}afterCommit(e){up(this.client,e)}list(){return this.client.prepare("SELECT * FROM na_agent_orchestrations ORDER BY name COLLATE NOCASE ASC, id ASC").all().map(e=>this.orchestrationFromRow(e))}get(e){const t=this.client.prepare("SELECT * FROM na_agent_orchestrations WHERE id = ?").get(e);return t?this.orchestrationFromRow(t):void 0}idsReferencingAgent(e){return this.client.prepare("SELECT DISTINCT orchestration_id FROM na_agent_orchestration_agents WHERE agent_id = ? ORDER BY orchestration_id").all(e).map(e=>String(e.orchestration_id))}insert(e,t){return lp(this.client,()=>{const n=Sm(e);return this.client.prepare("INSERT INTO na_agent_orchestrations (id, name, revision, created_at, updated_at)\n VALUES (?, ?, ?, ?, ?)").run(e.id,n.name,bm(n),t,t),this.replaceGraph(e.id,n,t),this.requireOrchestration(e.id)})}update(e,t,n,i){return lp(this.client,()=>{const s=this.get(e);if(!s)return{status:"missing"};if(s.revision!==t)return{status:"revision-conflict",orchestration:s};const o=Sm(n);return this.client.prepare("UPDATE na_agent_orchestrations SET name = ?, revision = ?, updated_at = ? WHERE id = ?").run(o.name,bm(o),i,e),this.replaceGraph(e,o,i),{status:"updated",orchestration:this.requireOrchestration(e)}})}delete(e){return lp(this.client,()=>Number(this.client.prepare("DELETE FROM na_agent_orchestrations WHERE id = ?").run(e).changes)>0)}deleteMany(e){e.length&&lp(this.client,()=>{const t=this.client.prepare("DELETE FROM na_agent_orchestrations WHERE id = ?");for(const n of[...new Set(e)])t.run(n)})}replaceGraph(e,t,n){this.client.prepare("DELETE FROM na_agent_orchestration_agents WHERE orchestration_id = ?").run(e),this.client.prepare("DELETE FROM na_agent_orchestration_edges WHERE orchestration_id = ?").run(e);const i=this.client.prepare("INSERT INTO na_agent_orchestration_agents (orchestration_id, agent_id, created_at) VALUES (?, ?, ?)");for(const s of t.agentIds)i.run(e,s,n);const s=this.client.prepare("INSERT INTO na_agent_orchestration_edges (orchestration_id, from_agent_id, to_agent_id, created_at) VALUES (?, ?, ?, ?)");for(const i of t.edges)s.run(e,i.fromAgentId,i.toAgentId,n)}requireOrchestration(e){const t=this.get(e);if(!t)throw Object.assign(new Error(`Agent orchestration ${e} was not found after the write.`),{code:"AGENT_ORCHESTRATION_NOT_FOUND",statusCode:404});return t}orchestrationFromRow(e){const t=String(e.id),n=Object.keys(e).filter(e=>!Tm.has(e));n.length&&this.diagnostic?.("Agent orchestration row contains unknown columns; they are ignored on read.",{orchestrationId:t,columns:n});const i=this.client.prepare("SELECT agent_id FROM na_agent_orchestration_agents WHERE orchestration_id = ? ORDER BY agent_id").all(t).map(e=>String(e.agent_id)),s=this.client.prepare("SELECT from_agent_id, to_agent_id FROM na_agent_orchestration_edges WHERE orchestration_id = ? ORDER BY from_agent_id, to_agent_id").all(t).map(e=>({fromAgentId:String(e.from_agent_id),toAgentId:String(e.to_agent_id)})),o=Sm({name:String(e.name),agentIds:i,edges:s}),r=wm.test(String(e.revision))?String(e.revision):bm(o);try{return a={id:t,revision:r,name:o.name,agentIds:o.agentIds,edges:o.edges,createdAt:e.created_at,updatedAt:e.updated_at},xp.parse(a)}catch(e){throw Object.assign(new Error("Stored agent orchestration cannot be parsed with the current model.",{cause:e}),{code:"NODE_AGENT_AGENT_ORCHESTRATION_INVALID",statusCode:500})}var a}}function Sm(e){const t=zp(e);return{name:e.name,agentIds:t.agentIds,edges:t.edges}}const vm=new Set(["story_id","agent_id","orchestration_id","created_at"]);function Om(e){const t=[...new Map(e.map(e=>[`${e.agentId}${e.orchestrationId}`,e])).values()].sort((e,t)=>e.agentId===t.agentId?e.orchestrationId.localeCompare(t.orchestrationId):e.agentId.localeCompare(t.agentId));return d.createHash("sha256").update(JSON.stringify(t.map(e=>[e.agentId,e.orchestrationId]))).digest("hex")}class Rm{client;diagnostic;constructor(e){this.client=e}setDiagnostic(e){this.diagnostic=e}get(e){const t=this.client.prepare("SELECT * FROM na_story_agent_entries WHERE story_id = ? ORDER BY agent_id, orchestration_id").all(e);for(const n of t){const t=Object.keys(n).filter(e=>!vm.has(e));t.length&&this.diagnostic?.("Story Agent entry row contains unknown columns; they are ignored on read.",{storyId:e,agentId:n.agent_id,columns:t})}const n=t.map(e=>({agentId:String(e.agent_id),orchestrationId:String(e.orchestration_id)}));return{storyId:e,revision:Om(n),entries:n}}replace(e,t,n=(new Date).toISOString()){return lp(this.client,()=>{const i=[...new Map(t.map(e=>[`${e.agentId}${e.orchestrationId}`,e])).values()].sort((e,t)=>e.agentId===t.agentId?e.orchestrationId.localeCompare(t.orchestrationId):e.agentId.localeCompare(t.agentId));this.client.prepare("DELETE FROM na_story_agent_entries WHERE story_id = ?").run(e);const s=this.client.prepare("INSERT INTO na_story_agent_entries (story_id, agent_id, orchestration_id, created_at) VALUES (?, ?, ?, ?)");for(const t of i)s.run(e,t.agentId,t.orchestrationId,n);return this.get(e)})}}function zm(e){return JSON.stringify(e??{})}function xm(e){try{const t=JSON.parse(String(e));return t&&"object"==typeof t&&!Array.isArray(t)?t:{}}catch{return{}}}function Cm(e,t,n){return Object.assign(new Error(t),{code:e,statusCode:409,...n?{details:n}:{}})}class km{client;constructor(e){this.client=e}ensureSharedSpace(e){const t=this.getSharedSpace(e.runId);if(t){if(t.runtimeId!==e.runtimeId||t.generationId!==e.generationId||t.quotaBytes!==e.quotaBytes)throw Cm("AGENT_RUN_SHARED_SPACE_IDENTITY_MISMATCH","The existing shared space has different runtime ownership.",{runId:e.runId});return t}const n=e.timestamp??(new Date).toISOString();return this.client.prepare("INSERT INTO na_agent_run_shared_spaces\n (run_id, runtime_id, generation_id, state, quota_bytes, usage_bytes, diagnostics_json, created_at, updated_at)\n VALUES (?, ?, ?, 'preparing', ?, 0, '{}', ?, ?)").run(e.runId,e.runtimeId,e.generationId,e.quotaBytes,n,n),this.getSharedSpace(e.runId)}getSharedSpace(e){const t=this.client.prepare("SELECT * FROM na_agent_run_shared_spaces WHERE run_id = ?").get(e);return t?this.sharedSpaceFromRow(t):void 0}listSharedSpaces(e={}){const t=[],n=[];e.runtimeId&&(t.push("runtime_id = ?"),n.push(e.runtimeId)),e.expiredBefore&&(t.push("expires_at IS NOT NULL AND expires_at <= ?"),n.push(e.expiredBefore));const i=t.length?` WHERE ${t.join(" AND ")}`:"";return this.client.prepare(`SELECT * FROM na_agent_run_shared_spaces${i} ORDER BY updated_at, run_id`).all(...n).map(e=>this.sharedSpaceFromRow(e))}runtimeSharedSpaceUsage(e,t){const n=t?this.client.prepare("SELECT COALESCE(SUM(usage_bytes), 0) AS usage FROM na_agent_run_shared_spaces WHERE runtime_id = ? AND run_id != ? AND state NOT IN ('expired','manual-intervention')").get(e,t):this.client.prepare("SELECT COALESCE(SUM(usage_bytes), 0) AS usage FROM na_agent_run_shared_spaces WHERE runtime_id = ? AND state NOT IN ('expired','manual-intervention')").get(e);return Number(n?.usage??0)}updateSharedSpace(e,t){const n=this.getSharedSpace(e);if(!n)throw Cm("AGENT_RUN_SHARED_SPACE_NOT_FOUND","The Agent Run shared space was not found.",{runId:e});const i=t.timestamp??(new Date).toISOString();return this.client.prepare("UPDATE na_agent_run_shared_spaces SET state = ?, usage_bytes = ?, expires_at = ?,\n diagnostics_json = ?, updated_at = ? WHERE run_id = ?").run(t.state??n.state,t.usageBytes??n.usageBytes,null===t.expiresAt?null:t.expiresAt??n.expiresAt??null,zm(t.diagnostics??n.diagnostics),i,e),this.getSharedSpace(e)}register(e){const t=this.client.prepare("SELECT * FROM na_agent_run_resources WHERE run_id = ? AND kind = ? AND backend_identity = ?").get(e.runId,e.kind,e.backendIdentity);if(t){const n=this.resourceFromRow(t);if(n.memberId!==e.memberId||n.instanceId!==e.instanceId||n.runtimeId!==e.runtimeId||n.generationId!==e.generationId)throw Cm("AGENT_RUN_RESOURCE_IDENTITY_MISMATCH","The existing runtime resource has different ownership.",{resourceId:n.resourceId});return n}const n=e.timestamp??(new Date).toISOString(),i=`resource_${d.randomBytes(10).toString("hex")}`;return this.client.prepare("INSERT INTO na_agent_run_resources\n (resource_id, run_id, member_id, instance_id, runtime_id, kind, generation_id, backend_identity,\n phase, cleanup_attempts, metadata_json, created_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'preparing', 0, ?, ?, ?)").run(i,e.runId,e.memberId??null,e.instanceId??null,e.runtimeId,e.kind,e.generationId,e.backendIdentity,zm(e.metadata),n,n),this.get(i)}get(e){const t=this.client.prepare("SELECT * FROM na_agent_run_resources WHERE resource_id = ?").get(e);return t?this.resourceFromRow(t):void 0}listForRun(e){return this.client.prepare("SELECT * FROM na_agent_run_resources WHERE run_id = ? ORDER BY created_at, resource_id").all(e).map(e=>this.resourceFromRow(e))}listActiveForInstance(e){return this.client.prepare("SELECT * FROM na_agent_run_resources WHERE instance_id = ?\n AND phase NOT IN ('deleted','manual-intervention') ORDER BY created_at, resource_id").all(e).map(e=>this.resourceFromRow(e))}transition(e,t,n={}){const i=this.get(e);if(!i)throw Cm("AGENT_RUN_RESOURCE_NOT_FOUND","The Agent Run resource was not found.",{resourceId:e});return this.client.prepare("UPDATE na_agent_run_resources SET phase = ?, cleanup_attempts = ?, metadata_json = ?,\n updated_at = ? WHERE resource_id = ?").run(t,i.cleanupAttempts+(n.incrementCleanupAttempts?1:0),zm(n.metadata??i.metadata),n.timestamp??(new Date).toISOString(),e),this.get(e)}sharedSpaceFromRow(e){return{runId:String(e.run_id),runtimeId:String(e.runtime_id),generationId:String(e.generation_id),state:e.state,quotaBytes:Number(e.quota_bytes),usageBytes:Number(e.usage_bytes),expiresAt:null==e.expires_at?void 0:String(e.expires_at),diagnostics:xm(e.diagnostics_json),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}resourceFromRow(e){return{resourceId:String(e.resource_id),runId:String(e.run_id),memberId:null==e.member_id?void 0:String(e.member_id),instanceId:null==e.instance_id?void 0:String(e.instance_id),runtimeId:String(e.runtime_id),kind:e.kind,generationId:String(e.generation_id),backendIdentity:String(e.backend_identity),phase:e.phase,cleanupAttempts:Number(e.cleanup_attempts),metadata:xm(e.metadata_json),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}}const Dm=new Set(["id","name","description","appended_prompt","target_instance_id","cwd_folder_id","provider_id","model_entity_id","model_name","model_upstream_name","reasoning_effort","permission_mode","execution_policy_json","revision","created_at","updated_at"]);function Lm(e){return JSON.stringify(e??null)}function Pm(e){try{return JSON.parse(String(e))}catch{return}}function Mm(e){return d.createHash("sha256").update(Lm([e.name,e.description,e.appendedPrompt,e.targetInstanceId,e.cwdFolderId,e.providerId,e.modelEntityId??null,e.modelName??null,e.modelUpstreamName??null,e.reasoningEffort??null,e.permissionMode??null,e.executionPolicy.workspaceMaterializer,e.executionPolicy.processSandbox])).digest("hex")}class jm{client;diagnostic;constructor(e){this.client=e}setDiagnostic(e){this.diagnostic=e}transaction(e){return lp(this.client,e)}afterCommit(e){up(this.client,e)}list(){return this.client.prepare("SELECT * FROM na_agent_definitions ORDER BY name COLLATE NOCASE ASC, id ASC").all().map(e=>this.definitionFromRow(e))}get(e){const t=this.client.prepare("SELECT * FROM na_agent_definitions WHERE id = ?").get(e);if(t)return this.definitionFromRow(t)}insert(e,t){return lp(this.client,()=>{const n=Mm(e);return this.client.prepare("INSERT INTO na_agent_definitions\n (id, name, description, appended_prompt, target_instance_id, cwd_folder_id, provider_id,\n model_entity_id, model_name, model_upstream_name, reasoning_effort, permission_mode, execution_policy_json,\n revision, created_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(e.id,e.name,e.description,e.appendedPrompt,e.targetInstanceId,e.cwdFolderId,e.providerId,e.modelEntityId??null,e.modelName??null,e.modelUpstreamName??null,e.reasoningEffort??null,e.permissionMode??null,Lm(e.executionPolicy),n,t,t),this.requireDefinition(e.id)})}update(e,t,n,i){return lp(this.client,()=>{const s=this.get(e);if(!s)return{status:"missing"};if(s.revision!==t)return{status:"revision-conflict",definition:s};const o=Mm(n);return this.client.prepare("UPDATE na_agent_definitions SET\n name = ?, description = ?, appended_prompt = ?, target_instance_id = ?, cwd_folder_id = ?, provider_id = ?,\n model_entity_id = ?, model_name = ?, model_upstream_name = ?, reasoning_effort = ?, permission_mode = ?, execution_policy_json = ?,\n revision = ?, updated_at = ?\n WHERE id = ?").run(n.name,n.description,n.appendedPrompt,n.targetInstanceId,n.cwdFolderId,n.providerId,n.modelEntityId??null,n.modelName??null,n.modelUpstreamName??null,n.reasoningEffort??null,n.permissionMode??null,Lm(n.executionPolicy),o,i,e),{status:"updated",definition:this.requireDefinition(e)}})}delete(e){return lp(this.client,()=>Number(this.client.prepare("DELETE FROM na_agent_definitions WHERE id = ?").run(e).changes)>0)}requireDefinition(e){const t=this.get(e);if(!t)throw Object.assign(new Error(`Agent definition ${e} was not found after the write.`),{code:"AGENT_DEFINITION_NOT_FOUND",statusCode:404});return t}definitionFromRow(e){const t=Object.keys(e).filter(e=>!Dm.has(e));return t.length&&this.diagnostic?.("Agent definition row contains unknown columns; they are ignored on read.",{agentId:e.id,columns:t}),function(e){try{return function(e){return ap.parse(e)}(e)}catch(e){throw Object.assign(new Error("Stored agent definition cannot be parsed with the current model.",{cause:e}),{code:"NODE_AGENT_AGENT_DEFINITION_INVALID",statusCode:500})}}({id:e.id,name:e.name,description:e.description??"",appendedPrompt:e.appended_prompt??"",targetInstanceId:e.target_instance_id,cwdFolderId:e.cwd_folder_id,providerId:e.provider_id,modelEntityId:e.model_entity_id??void 0,modelName:e.model_name??void 0,modelUpstreamName:e.model_upstream_name??void 0,reasoningEffort:e.reasoning_effort??void 0,permissionMode:e.permission_mode??void 0,executionPolicy:Pm(e.execution_policy_json),revision:e.revision,createdAt:e.created_at,updatedAt:e.updated_at})}}class Um{client;constructor(e){this.client=e}readIdentity(){const e=this.client.prepare("SELECT node_id, created_at, updated_at FROM na_node_identity WHERE singleton_key = 1").get();if(!e)return;const t=this.client.prepare("SELECT * FROM na_control_plane_pairings ORDER BY updated_at, key_id").all().map(e=>({id:String(e.control_plane_id),keyId:String(e.key_id),...e.name?{name:String(e.name)}:{},secret:String(e.secret),pairedAt:String(e.paired_at),...e.revoked_at?{revokedAt:String(e.revoked_at)}:{},updatedAt:String(e.updated_at)})),n=this.client.prepare("SELECT * FROM na_control_plane_connections ORDER BY updated_at, id").all().map(e=>({id:String(e.id),pairingKeyId:String(e.pairing_key_id),...e.name?{name:String(e.name)}:{},url:String(e.normalized_url),enabled:Boolean(e.enabled),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}));return{nodeId:String(e.node_id),createdAt:String(e.created_at),updatedAt:String(e.updated_at),controlPlanePairings:t,controlPlaneConnections:n}}writeIdentity(e){return this.transaction(()=>{const t=this.readIdentity();if(t&&t.nodeId!==e.nodeId)throw n=`Stored node identity ${t.nodeId} does not match ${e.nodeId}.`,Object.assign(new Error(n),{code:"NODE_AGENT_IDENTITY_MISMATCH",statusCode:409});var n;this.client.prepare("INSERT INTO na_node_identity (singleton_key, node_id, created_at, updated_at) VALUES (1, ?, ?, ?)\n ON CONFLICT(singleton_key) DO UPDATE SET updated_at=excluded.updated_at").run(e.nodeId,e.createdAt,e.updatedAt);const i=(e.controlPlanePairings||[]).map(e=>e.keyId),s=(e.controlPlaneConnections||[]).map(e=>e.id);$m(this.client,"na_control_plane_connections","id",s),$m(this.client,"na_control_plane_pairings","key_id",i);const o=this.client.prepare("INSERT INTO na_control_plane_pairings\n (key_id, control_plane_id, name, secret, paired_at, revoked_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(key_id) DO UPDATE SET control_plane_id=excluded.control_plane_id, name=excluded.name,\n secret=excluded.secret, paired_at=excluded.paired_at, revoked_at=excluded.revoked_at, updated_at=excluded.updated_at");for(const t of e.controlPlanePairings||[])o.run(t.keyId,t.id,t.name??null,t.secret,t.pairedAt,t.revokedAt??null,t.updatedAt);const r=this.client.prepare("INSERT INTO na_control_plane_connections\n (id, pairing_key_id, name, normalized_url, enabled, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(id) DO UPDATE SET pairing_key_id=excluded.pairing_key_id, name=excluded.name,\n normalized_url=excluded.normalized_url, enabled=excluded.enabled, updated_at=excluded.updated_at");for(const t of e.controlPlaneConnections||[])r.run(t.id,t.pairingKeyId,t.name??null,Fm(t.url),t.enabled?1:0,t.createdAt,t.updatedAt);return this.readIdentity()})}listOperations(e){return(e?.length?this.client.prepare(`SELECT * FROM na_control_plane_connection_operations WHERE phase IN (${e.map(()=>"?").join(",")}) ORDER BY created_at`).all(...e):this.client.prepare("SELECT * FROM na_control_plane_connection_operations ORDER BY created_at").all()).map(Hm)}putOperation(e){return this.client.prepare("INSERT INTO na_control_plane_connection_operations\n (id, kind, phase, requested_json, pairing_key_id, connection_id, replaced_connections_json, error_json, created_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(id) DO UPDATE SET phase=excluded.phase, pairing_key_id=excluded.pairing_key_id,\n connection_id=excluded.connection_id, replaced_connections_json=excluded.replaced_connections_json,\n error_json=excluded.error_json, updated_at=excluded.updated_at").run(e.id,e.kind,e.phase,JSON.stringify(e.requested),e.pairingKeyId??null,e.connectionId??null,JSON.stringify(e.replacedConnections),e.error?JSON.stringify(e.error):null,e.createdAt,e.updatedAt),e}deleteOperation(e){return Number(this.client.prepare("DELETE FROM na_control_plane_connection_operations WHERE id = ?").run(e).changes)>0}transaction(e){if(this.client.isTransaction)return e();this.client.exec("BEGIN IMMEDIATE");try{const t=e();return this.client.exec("COMMIT"),t}catch(e){throw this.client.exec("ROLLBACK"),e}}}function Fm(e){return new URL(e).toString().replace(/\/$/,"")}function $m(e,t,n,i){i.length?e.prepare(`DELETE FROM ${t} WHERE ${n} NOT IN (${i.map(()=>"?").join(",")})`).run(...i):e.exec(`DELETE FROM ${t}`)}function Hm(e){return{id:String(e.id),kind:String(e.kind),phase:e.phase,requested:JSON.parse(String(e.requested_json)),...e.pairing_key_id?{pairingKeyId:String(e.pairing_key_id)}:{},...e.connection_id?{connectionId:String(e.connection_id)}:{},replacedConnections:JSON.parse(String(e.replaced_connections_json)),...e.error_json?{error:JSON.parse(String(e.error_json))}:{},createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}class qm{client;constructor(e){this.client=e}listPayloads(){return this.client.prepare("SELECT * FROM na_git_credential_payloads ORDER BY credential_id").all().map(Vm)}getPayload(e){const t=this.client.prepare("SELECT * FROM na_git_credential_payloads WHERE credential_id = ?").get(e);return t?Vm(t):void 0}putPayload(e){const t=Ii.parse(e.payload);return this.client.prepare("INSERT INTO na_git_credential_payloads\n (credential_id, revision, public_json, secret_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)\n ON CONFLICT(credential_id) DO UPDATE SET revision=excluded.revision, public_json=excluded.public_json,\n secret_json=excluded.secret_json, updated_at=excluded.updated_at").run(e.id,t.credential.revision,JSON.stringify(t.credential),JSON.stringify(t.secret),e.createdAt,e.updatedAt),{...e,payload:t}}deletePayload(e){return Number(this.client.prepare("DELETE FROM na_git_credential_payloads WHERE credential_id = ?").run(e).changes)>0}collectUnreferencedPayloads(){return Number(this.client.prepare("DELETE FROM na_git_credential_payloads\n WHERE NOT EXISTS (SELECT 1 FROM na_git_authorization_members m WHERE m.credential_id = na_git_credential_payloads.credential_id)").run().changes)}listAuthorizations(){return this.client.prepare("SELECT * FROM na_git_authorization_sets ORDER BY instance_id").all().map(e=>this.authorizationFromRow(e))}getAuthorization(e){const t=this.client.prepare("SELECT * FROM na_git_authorization_sets WHERE instance_id = ?").get(e);return t?this.authorizationFromRow(t):void 0}putAuthorization(e){const t=_i.parse({instanceId:e.instanceId,generation:e.generation,credentialIds:e.credentialIds,updatedAt:e.updatedAt});return this.transaction(()=>{this.client.prepare("INSERT INTO na_git_authorization_sets (instance_id, generation, created_at, updated_at)\n VALUES (?, ?, ?, ?) ON CONFLICT(instance_id) DO UPDATE SET generation=excluded.generation, updated_at=excluded.updated_at").run(t.instanceId,t.generation,e.createdAt,t.updatedAt),this.client.prepare("DELETE FROM na_git_authorization_members WHERE instance_id = ?").run(t.instanceId);const n=this.client.prepare("INSERT INTO na_git_authorization_members (instance_id, credential_id, display_order) VALUES (?, ?, ?)");for(const[e,i]of t.credentialIds.entries())n.run(t.instanceId,i,e);return this.getAuthorization(t.instanceId)})}putAuthorizationCas(e){const t=_i.parse({instanceId:e.instanceId,generation:e.generation,credentialIds:e.credentialIds,updatedAt:e.updatedAt});return this.transaction(()=>{const n=this.getAuthorization(t.instanceId);if(n&&n.generation>t.generation)throw Bm("GIT_CREDENTIAL_REVISION_STALE",`Refusing stale authorization set revision for ${t.instanceId}.`);if(n&&n.generation===t.generation){if(JSON.stringify(n.credentialIds)!==JSON.stringify(t.credentialIds))throw Bm("GIT_CREDENTIAL_REVISION_CONFLICT",`Refusing conflicting authorization set revision for ${t.instanceId}.`);return n}for(const e of t.credentialIds)if(!this.getPayload(e))throw Bm("GIT_CREDENTIAL_PAYLOAD_MISSING",`Credential payload ${e} is not deployed.`);if(n){const e=this.client.prepare("UPDATE na_git_authorization_sets\n SET generation = ?, updated_at = ? WHERE instance_id = ? AND generation < ?").run(t.generation,t.updatedAt,t.instanceId,t.generation).changes;if(1!==Number(e))throw Bm("GIT_CREDENTIAL_REVISION_STALE",`Authorization set ${t.instanceId} changed concurrently.`)}else this.client.prepare("INSERT INTO na_git_authorization_sets (instance_id, generation, created_at, updated_at)\n VALUES (?, ?, ?, ?)").run(t.instanceId,t.generation,e.createdAt,t.updatedAt);this.client.prepare("DELETE FROM na_git_authorization_members WHERE instance_id = ?").run(t.instanceId);const i=this.client.prepare("INSERT INTO na_git_authorization_members (instance_id, credential_id, display_order) VALUES (?, ?, ?)");for(const[e,n]of t.credentialIds.entries())i.run(t.instanceId,n,e);return this.getAuthorization(t.instanceId)})}deleteAuthorization(e){return Number(this.client.prepare("DELETE FROM na_git_authorization_sets WHERE instance_id = ?").run(e).changes)>0}listProvisioning(){return this.client.prepare("SELECT * FROM na_git_workspace_provisioning ORDER BY instance_id").all().map(Gm)}getProvisioning(e){const t=this.client.prepare("SELECT * FROM na_git_workspace_provisioning WHERE instance_id = ?").get(e);return t?Gm(t):void 0}putProvisioning(e){const t="pending"===e.status?e.input.operationId:e.operationId;return this.client.prepare("INSERT INTO na_git_workspace_provisioning\n (instance_id, status, operation_id, input_json, created_at, updated_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(instance_id) DO UPDATE SET status=excluded.status, operation_id=excluded.operation_id,\n input_json=excluded.input_json, updated_at=excluded.updated_at, expires_at=excluded.expires_at").run(e.id,e.status,t,"pending"===e.status?JSON.stringify(e.input):null,e.createdAt,e.updatedAt,e.expiresAt),this.getProvisioning(e.id)}deleteProvisioning(e){return Number(this.client.prepare("DELETE FROM na_git_workspace_provisioning WHERE instance_id = ?").run(e).changes)>0}deleteExpiredProvisioning(e){return Number(this.client.prepare("DELETE FROM na_git_workspace_provisioning WHERE expires_at <= ?").run(e).changes)}consumeProvisioning(e,t,n,i){return this.transaction(()=>{const s=this.client.prepare("UPDATE na_git_workspace_provisioning\n SET status = 'consumed', input_json = NULL, updated_at = ?, expires_at = ?\n WHERE instance_id = ? AND operation_id = ? AND status = 'pending'").run(n,i,e,t).changes;if(1===Number(s))return!0;const o=this.getProvisioning(e);return"consumed"===o?.status&&o.operationId===t})}authorizationFromRow(e){const t=this.client.prepare("SELECT credential_id FROM na_git_authorization_members WHERE instance_id = ? ORDER BY display_order").all(String(e.instance_id)).map(e=>String(e.credential_id));return{id:String(e.instance_id),instanceId:String(e.instance_id),generation:Number(e.generation),credentialIds:t,createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}transaction(e){if(this.client.isTransaction)return e();this.client.exec("BEGIN IMMEDIATE");try{const t=e();return this.client.exec("COMMIT"),t}catch(e){throw this.client.exec("ROLLBACK"),e}}}function Bm(e,t){return Object.assign(new Error(t),{code:e,statusCode:409})}function Vm(e){return{id:String(e.credential_id),payload:Ii.parse({credential:JSON.parse(String(e.public_json)),secret:JSON.parse(String(e.secret_json))}),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Gm(e){const t={id:String(e.instance_id),createdAt:String(e.created_at),updatedAt:String(e.updated_at),expiresAt:String(e.expires_at)};return"pending"===e.status?{...t,status:"pending",input:vi.parse(JSON.parse(String(e.input_json)))}:{...t,status:"consumed",operationId:String(e.operation_id)}}class Km{tail=Promise.resolve();accepting=!0;run(e){if(!this.accepting)return Promise.reject(ih("NODE_AGENT_REPOSITORY_QUIESCING","Node Agent storage is shutting down.",503));const t=this.tail.then(e,e);return this.tail=t.then(()=>{},()=>{}),t}async barrier(){await this.tail}stopAccepting(){this.accepting=!1}}function Wm(e){const t=e.db,n=new Km,i=new E.AsyncLocalStorage;let s=!1;const o=()=>{if(s)throw ih("NODE_AGENT_REPOSITORY_CLOSED","Node Agent storage is closed.",503)},r=async e=>(o(),i.getStore()||await n.barrier(),e()),a=async e=>(o(),i.getStore()?e():n.run(e));let c;var d;return c={stories:Ym(t,r,a),actions:Xm(t,r,a),documents:Jm(t,r,a),automations:Qm(t,r,a),runs:Zm(t,r,a),decisions:eh(t,r,a),fileMutations:th(t,r,a),deletionIntents:nh(t,r,a),topology:Ru(e.client),model:Uu(e.client),agents:(d=e.client,{definitions:new jm(d),orchestrations:new Nm(d),runs:new Am(d),storyEntries:new Rm(d),resources:new km(d)}),access:new Um(e.client),git:new qm(e.client),transaction:async t=>i.getStore()?t(c):a(async()=>{e.client.exec("BEGIN IMMEDIATE");try{const n=await i.run(!0,()=>t(c));return e.client.exec("COMMIT"),n}catch(t){throw e.client.exec("ROLLBACK"),t}}),transactionSync:t=>{if(o(),e.client.isTransaction)return t(c);e.client.exec("BEGIN IMMEDIATE");try{const n=t(c);return e.client.exec("COMMIT"),n}catch(t){throw e.client.exec("ROLLBACK"),t}},stopAccepting(){n.stopAccepting()},async drain(){await n.barrier()},async checkpoint(){await n.barrier(),await e.checkpoint()},async close(){s||(n.stopAccepting(),await n.barrier(),await e.checkpoint(),s=!0,await e.close())}},c}function Ym(e,t,n){return{list:()=>t(()=>e.select().from(mu).orderBy(A.desc(mu.createdAt),A.asc(mu.id))),get:async n=>t(async()=>(await e.select().from(mu).where(A.eq(mu.id,n)).limit(1))[0]),insert:async t=>n(async()=>(await e.insert(mu).values(t),t)),update:async(t,i)=>n(async()=>(await e.update(mu).set(i).where(A.eq(mu.id,t)),(await e.select().from(mu).where(A.eq(mu.id,t)).limit(1))[0])),delete:async t=>n(async()=>Number((await e.delete(mu).where(A.eq(mu.id,t))).changes)>0)}}function Xm(e,t,n){return{list:n=>t(()=>e.select().from(gu).where(A.eq(gu.storyId,n)).orderBy(A.asc(gu.displayOrder),A.asc(gu.id))),replace:async(t,i)=>n(async()=>{const n=i.map(e=>e.id);n.length?await e.delete(gu).where(A.and(A.eq(gu.storyId,t),A.notInArray(gu.id,n))):await e.delete(gu).where(A.eq(gu.storyId,t));for(const t of i)await e.insert(gu).values(t).onConflictDoUpdate({target:[gu.storyId,gu.id],set:{title:t.title,promptTemplate:t.promptTemplate,targetInstanceId:t.targetInstanceId,sessionPreset:t.sessionPreset,displayOrder:t.displayOrder}});return i})}}function Jm(e,t,n){return{list:n=>t(()=>e.select().from(fu).where(A.eq(fu.storyId,n)).orderBy(A.asc(fu.displayOrder),A.asc(fu.storyPath))),get:async(n,i)=>t(async()=>(await e.select().from(fu).where(A.and(A.eq(fu.storyId,n),A.eq(fu.storyPath,i))).limit(1))[0]),page:async(n,i,s)=>t(async()=>{const t=Number((await e.select({value:A.count()}).from(fu).where(A.eq(fu.storyId,n)))[0]?.value??0);return{items:await e.select({title:fu.title,storyPath:fu.storyPath}).from(fu).where(A.eq(fu.storyId,n)).orderBy(A.desc(fu.indexedSequence),A.asc(fu.storyPath)).limit(s).offset((i-1)*s),totalItems:t}}),insert:async t=>n(async()=>(await e.insert(fu).values(t),t)),update:async(t,i,s)=>n(async()=>{await e.update(fu).set(s).where(A.and(A.eq(fu.storyId,t),A.eq(fu.storyPath,i)))}),replacePath:async(t,i,s)=>n(async()=>{await e.delete(fu).where(A.and(A.eq(fu.storyId,t),A.eq(fu.storyPath,i))),await e.insert(fu).values(s)}),reorder:async(t,i)=>n(async()=>{for(const[n,s]of i.entries())await e.update(fu).set({displayOrder:n}).where(A.and(A.eq(fu.storyId,t),A.eq(fu.storyPath,s)))}),delete:async(t,i)=>n(async()=>Number((await e.delete(fu).where(A.and(A.eq(fu.storyId,t),A.eq(fu.storyPath,i)))).changes)>0)}}function Qm(e,t,n){return{list:n=>t(()=>n?e.select().from(yu).where(A.eq(yu.storyId,n)).orderBy(A.asc(yu.createdAt),A.asc(yu.id)):e.select().from(yu).orderBy(A.asc(yu.createdAt),A.asc(yu.id))),get:async n=>t(async()=>(await e.select().from(yu).where(A.eq(yu.id,n)).limit(1))[0]),insert:async t=>n(async()=>(await e.insert(yu).values(t),t)),update:async(t,i)=>n(async()=>(await e.update(yu).set(i).where(A.eq(yu.id,t)),(await e.select().from(yu).where(A.eq(yu.id,t)).limit(1))[0])),referencingActions:async(n,i)=>i.length?t(()=>e.select().from(yu).where(A.and(A.eq(yu.storyId,n),A.inArray(yu.actionId,i)))):[],delete:async t=>n(async()=>Number((await e.delete(yu).where(A.eq(yu.id,t))).changes)>0),deleteForStory:async t=>n(async()=>{await e.delete(yu).where(A.eq(yu.storyId,t))})}}function Zm(e,t,n){const i=["queued","dispatching","running"];return{list:n=>t(()=>e.select().from(Iu).where(A.eq(Iu.automationId,n)).orderBy(A.desc(Iu.queuedAt))),get:async n=>t(async()=>(await e.select().from(Iu).where(A.eq(Iu.id,n)).limit(1))[0]),byExecutionKey:async n=>t(async()=>(await e.select().from(Iu).where(A.eq(Iu.executionKey,n)).limit(1))[0]),pending:()=>t(()=>e.select().from(Iu).where(A.inArray(Iu.status,[...i])).orderBy(A.asc(Iu.queuedAt))),activeForStory:async n=>t(()=>e.select({run:Iu}).from(Iu).innerJoin(yu,A.eq(Iu.automationId,yu.id)).where(A.and(A.eq(yu.storyId,n),A.inArray(Iu.status,[...i]))).then(e=>e.map(e=>e.run))),insert:async t=>n(async()=>(await e.insert(Iu).values(t),t)),update:async(t,i)=>n(async()=>(await e.update(Iu).set(i).where(A.eq(Iu.id,t)),(await e.select().from(Iu).where(A.eq(Iu.id,t)).limit(1))[0])),trimTerminal:async(t,i)=>n(async()=>{const n=await e.select({id:Iu.id}).from(Iu).where(A.and(A.eq(Iu.automationId,t),A.inArray(Iu.status,["completed","failed","skipped"]))).orderBy(A.desc(Iu.queuedAt)).limit(2147483647).offset(i);n.length&&await e.delete(Iu).where(A.inArray(Iu.id,n.map(e=>e.id)))})}}function eh(e,t,n){return{list:n=>t(()=>e.select().from(hu).where(A.eq(hu.storyId,n)).orderBy(A.desc(hu.createdAt),A.asc(hu.id))),listPendingBySession:n=>t(()=>e.select().from(hu).where(A.and(A.eq(hu.sessionId,n),A.eq(hu.status,"pending"))).orderBy(A.asc(hu.createdAt),A.asc(hu.id))),get:async n=>t(async()=>(await e.select().from(hu).where(A.eq(hu.id,n)).limit(1))[0]),bySessionTurn:async(n,i,s)=>t(async()=>(await e.select().from(hu).where(A.and(A.eq(hu.storyId,n),A.eq(hu.sessionId,i),A.eq(hu.turnId,s))).limit(1))[0]),insert:async t=>n(async()=>(await e.insert(hu).values(t),t)),updateIfRevision:async(t,i,s)=>n(async()=>{await e.update(hu).set(s).where(A.and(A.eq(hu.id,t),A.eq(hu.revision,i)));const n=(await e.select().from(hu).where(A.eq(hu.id,t)).limit(1))[0];return n&&n.revision!==i?n:void 0}),update:async(t,i)=>n(async()=>(await e.update(hu).set(i).where(A.eq(hu.id,t)),(await e.select().from(hu).where(A.eq(hu.id,t)).limit(1))[0])),expirePendingForSession:async(t,i,s)=>n(async()=>(await e.update(hu).set({status:"expired",revision:A.sql`${hu.revision} + 1`,expiredReason:i,updatedAt:s}).where(A.and(A.eq(hu.sessionId,t),A.eq(hu.status,"pending"))),e.select().from(hu).where(A.and(A.eq(hu.sessionId,t),A.eq(hu.status,"expired"),A.eq(hu.updatedAt,s)))))}}function th(e,t,n){return{list:()=>t(()=>e.select().from(_u).orderBy(A.asc(_u.createdAt))),get:async n=>t(async()=>(await e.select().from(_u).where(A.eq(_u.id,n)).limit(1))[0]),insert:async t=>n(async()=>(await e.insert(_u).values(t),t)),update:async(t,i)=>n(async()=>{await e.update(_u).set(i).where(A.eq(_u.id,t))}),delete:async t=>n(async()=>{await e.delete(_u).where(A.eq(_u.id,t))})}}function nh(e,t,n){return{list:()=>t(()=>e.select().from(Eu).orderBy(A.asc(Eu.createdAt))),get:async n=>t(async()=>(await e.select().from(Eu).where(A.eq(Eu.storyId,n)).limit(1))[0]),put:async t=>n(async()=>(await e.insert(Eu).values(t).onConflictDoUpdate({target:Eu.storyId,set:{phase:t.phase,trashName:t.trashName,updatedAt:t.updatedAt}}),t)),delete:async t=>n(async()=>{await e.delete(Eu).where(A.eq(Eu.storyId,t))})}}function ih(e,t,n){return Object.assign(new Error(t),{code:e,statusCode:n})}function sh(e,t,n={}){return{id:e,sql:t,checksum:d.createHash("sha256").update(t).digest("hex"),...n.foreignKeysOff?{foreignKeysOff:!0}:{}}}const oh=[sh("0001_story_domain","\nCREATE TABLE na_stories (\n id TEXT PRIMARY KEY NOT NULL, title TEXT NOT NULL, description TEXT,\n created_at TEXT NOT NULL, updated_at TEXT NOT NULL, archived_at TEXT,\n max_idle_ai_sessions INTEGER NOT NULL DEFAULT 5 CHECK(max_idle_ai_sessions BETWEEN 1 AND 50),\n next_document_sequence INTEGER NOT NULL DEFAULT 1 CHECK(next_document_sequence > 0)\n);\nCREATE INDEX na_stories_created_idx ON na_stories(created_at);\nCREATE TABLE na_story_actions (\n story_id TEXT NOT NULL REFERENCES na_stories(id) ON DELETE CASCADE, id TEXT NOT NULL,\n title TEXT NOT NULL, prompt_template TEXT NOT NULL, target_instance_id TEXT,\n session_preset_json TEXT, display_order INTEGER NOT NULL,\n PRIMARY KEY(story_id, id)\n);\nCREATE INDEX na_story_actions_order_idx ON na_story_actions(story_id, display_order, id);\nCREATE TABLE na_story_documents (\n story_id TEXT NOT NULL REFERENCES na_stories(id) ON DELETE CASCADE, story_path TEXT NOT NULL,\n title TEXT NOT NULL, indexed_sequence INTEGER NOT NULL CHECK(indexed_sequence > 0), display_order INTEGER NOT NULL,\n PRIMARY KEY(story_id, story_path)\n);\nCREATE UNIQUE INDEX na_story_documents_sequence_uq ON na_story_documents(story_id, indexed_sequence);\nCREATE INDEX na_story_documents_page_idx ON na_story_documents(story_id, indexed_sequence, story_path);\nCREATE INDEX na_story_documents_display_idx ON na_story_documents(story_id, display_order, story_path);\nCREATE TABLE na_story_automations (\n id TEXT PRIMARY KEY NOT NULL, story_id TEXT NOT NULL, action_id TEXT NOT NULL,\n schedule_json TEXT NOT NULL, enabled INTEGER NOT NULL, policy_json TEXT NOT NULL,\n schedule_anchor_at TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL,\n CONSTRAINT na_story_automations_action_fk FOREIGN KEY(story_id, action_id)\n REFERENCES na_story_actions(story_id, id) ON DELETE RESTRICT\n);\nCREATE INDEX na_story_automations_story_idx ON na_story_automations(story_id);\nCREATE INDEX na_story_automations_enabled_idx ON na_story_automations(enabled);\nCREATE TABLE na_story_automation_runs (\n id TEXT PRIMARY KEY NOT NULL, automation_id TEXT NOT NULL REFERENCES na_story_automations(id) ON DELETE CASCADE,\n event_type TEXT NOT NULL CHECK(event_type IN ('manual','schedule')),\n status TEXT NOT NULL CHECK(status IN ('queued','dispatching','running','completed','failed','skipped')),\n scheduled_for TEXT NOT NULL, target_instance_id TEXT NOT NULL, ai_session_id TEXT, error_json TEXT,\n queued_at TEXT NOT NULL, started_at TEXT, completed_at TEXT,\n execution_key TEXT NOT NULL, request_fingerprint TEXT NOT NULL, execution_input_json TEXT NOT NULL\n);\nCREATE UNIQUE INDEX na_story_automation_runs_execution_key_uq ON na_story_automation_runs(execution_key);\nCREATE INDEX na_story_automation_runs_automation_time_idx ON na_story_automation_runs(automation_id, queued_at);\nCREATE INDEX na_story_automation_runs_status_idx ON na_story_automation_runs(status, scheduled_for);\nCREATE TABLE na_story_file_mutations (\n id TEXT PRIMARY KEY NOT NULL, story_id TEXT NOT NULL REFERENCES na_stories(id) ON DELETE RESTRICT,\n operation TEXT NOT NULL CHECK(operation IN ('write','rename','delete')), story_path TEXT NOT NULL,\n next_story_path TEXT, title TEXT, temporary_name TEXT, backup_name TEXT,\n phase TEXT NOT NULL CHECK(phase IN ('receiving','prepared','files-staged','database-committed','cleanup')),\n created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE INDEX na_story_file_mutations_story_idx ON na_story_file_mutations(story_id, created_at);\nCREATE TABLE na_story_deletion_intents (\n story_id TEXT PRIMARY KEY NOT NULL,\n phase TEXT NOT NULL CHECK(phase IN ('prepared','files-staged','database-committed','cleanup')),\n trash_name TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\n"),sh("0002_p0_state_domains","\nCREATE TABLE na_node_identity (\n singleton_key INTEGER PRIMARY KEY NOT NULL DEFAULT 1 CHECK(singleton_key = 1),\n node_id TEXT NOT NULL UNIQUE, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE TABLE na_local_folders (\n id TEXT PRIMARY KEY NOT NULL, node_id TEXT NOT NULL REFERENCES na_node_identity(node_id) ON DELETE RESTRICT ON UPDATE CASCADE,\n name TEXT NOT NULL, path TEXT NOT NULL, labels_json TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL,\n UNIQUE(node_id, path)\n);\nCREATE TABLE na_runtimes (\n id TEXT PRIMARY KEY NOT NULL, node_id TEXT NOT NULL REFERENCES na_node_identity(node_id) ON DELETE RESTRICT ON UPDATE CASCADE,\n name TEXT NOT NULL, type TEXT NOT NULL CHECK(type IN ('docker','kubernetes','local')),\n status TEXT NOT NULL CHECK(status IN ('unknown','online','offline','degraded')), access_strategy TEXT NOT NULL,\n capabilities_json TEXT NOT NULL, labels_json TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE INDEX na_runtimes_node_type_idx ON na_runtimes(node_id, type);\nCREATE TABLE na_instances (\n id TEXT PRIMARY KEY NOT NULL, node_id TEXT NOT NULL REFERENCES na_node_identity(node_id) ON DELETE RESTRICT ON UPDATE CASCADE,\n runtime_id TEXT NOT NULL REFERENCES na_runtimes(id) ON DELETE RESTRICT ON UPDATE CASCADE,\n source_local_folder_id TEXT REFERENCES na_local_folders(id) ON DELETE SET NULL ON UPDATE CASCADE,\n name TEXT NOT NULL, status TEXT NOT NULL, state_revision INTEGER NOT NULL DEFAULT 0 CHECK(state_revision >= 0),\n process_incarnation_id TEXT, registration_credential TEXT, desired_json TEXT NOT NULL,\n created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE INDEX na_instances_runtime_idx ON na_instances(runtime_id);\nCREATE INDEX na_instances_status_idx ON na_instances(status, updated_at);\nCREATE TABLE na_instance_observations (\n instance_id TEXT PRIMARY KEY NOT NULL REFERENCES na_instances(id) ON DELETE CASCADE ON UPDATE CASCADE,\n health TEXT NOT NULL, connection_status TEXT NOT NULL, ready INTEGER NOT NULL,\n observed_json TEXT NOT NULL, last_heartbeat_at TEXT, updated_at TEXT NOT NULL\n);\nCREATE INDEX na_instance_observations_connection_idx ON na_instance_observations(connection_status, updated_at);\nCREATE TABLE na_models (\n id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, endpoint TEXT NOT NULL, key TEXT NOT NULL, model TEXT NOT NULL,\n app TEXT NOT NULL CHECK(app IN ('codex','claude','opencode')), enabled INTEGER NOT NULL,\n display_order INTEGER NOT NULL, model_names_json TEXT NOT NULL, protocols_json TEXT NOT NULL,\n labels_json TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE INDEX na_models_order_idx ON na_models(display_order, id);\nCREATE TABLE na_instance_model_assignments (\n instance_id TEXT PRIMARY KEY NOT NULL REFERENCES na_instances(id) ON DELETE CASCADE ON UPDATE CASCADE,\n legacy_codex_model_id TEXT REFERENCES na_models(id) ON DELETE RESTRICT ON UPDATE CASCADE,\n legacy_claude_model_id TEXT REFERENCES na_models(id) ON DELETE RESTRICT ON UPDATE CASCADE,\n legacy_opencode_model_id TEXT REFERENCES na_models(id) ON DELETE RESTRICT ON UPDATE CASCADE,\n updated_at TEXT NOT NULL\n);\nCREATE TABLE na_instance_model_entities (\n instance_id TEXT NOT NULL REFERENCES na_instance_model_assignments(instance_id) ON DELETE CASCADE ON UPDATE CASCADE,\n model_id TEXT NOT NULL REFERENCES na_models(id) ON DELETE RESTRICT ON UPDATE CASCADE,\n display_order INTEGER NOT NULL, PRIMARY KEY(instance_id, model_id), UNIQUE(instance_id, display_order)\n);\nCREATE TABLE na_control_plane_pairings (\n key_id TEXT PRIMARY KEY NOT NULL, control_plane_id TEXT NOT NULL UNIQUE, name TEXT, secret TEXT NOT NULL,\n paired_at TEXT NOT NULL, revoked_at TEXT, updated_at TEXT NOT NULL\n);\nCREATE TABLE na_control_plane_connections (\n id TEXT PRIMARY KEY NOT NULL,\n pairing_key_id TEXT NOT NULL REFERENCES na_control_plane_pairings(key_id) ON DELETE RESTRICT ON UPDATE CASCADE,\n name TEXT, normalized_url TEXT NOT NULL UNIQUE, enabled INTEGER NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE TABLE na_control_plane_connection_operations (\n id TEXT PRIMARY KEY NOT NULL, kind TEXT NOT NULL,\n phase TEXT NOT NULL CHECK(phase IN ('prepared','remote-accepted','committed','failed')),\n requested_json TEXT NOT NULL, pairing_key_id TEXT, connection_id TEXT, replaced_connections_json TEXT NOT NULL,\n error_json TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE INDEX na_control_plane_connection_operations_phase_idx ON na_control_plane_connection_operations(phase, updated_at);\nCREATE TABLE na_git_credential_payloads (\n credential_id TEXT PRIMARY KEY NOT NULL, revision INTEGER NOT NULL CHECK(revision >= 0),\n public_json TEXT NOT NULL, secret_json TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE TABLE na_git_authorization_sets (\n instance_id TEXT PRIMARY KEY NOT NULL REFERENCES na_instances(id) ON DELETE CASCADE ON UPDATE CASCADE,\n generation INTEGER NOT NULL CHECK(generation >= 0), created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE TABLE na_git_authorization_members (\n instance_id TEXT NOT NULL REFERENCES na_git_authorization_sets(instance_id) ON DELETE CASCADE ON UPDATE CASCADE,\n credential_id TEXT NOT NULL REFERENCES na_git_credential_payloads(credential_id) ON DELETE RESTRICT ON UPDATE CASCADE,\n display_order INTEGER NOT NULL, PRIMARY KEY(instance_id, credential_id), UNIQUE(instance_id, display_order)\n);\nCREATE TABLE na_git_workspace_provisioning (\n instance_id TEXT PRIMARY KEY NOT NULL REFERENCES na_instances(id) ON DELETE CASCADE ON UPDATE CASCADE,\n status TEXT NOT NULL CHECK(status IN ('pending','consumed')), operation_id TEXT NOT NULL, input_json TEXT,\n created_at TEXT NOT NULL, updated_at TEXT NOT NULL, expires_at TEXT NOT NULL,\n CHECK((status = 'pending' AND input_json IS NOT NULL) OR (status = 'consumed' AND input_json IS NULL))\n);\nCREATE INDEX na_git_workspace_provisioning_expiry_idx ON na_git_workspace_provisioning(expires_at);\n"),sh("0003_story_agent_tool_policy","\nALTER TABLE na_stories ADD COLUMN agent_tools_content INTEGER NOT NULL DEFAULT 1 CHECK(agent_tools_content IN (0, 1));\nALTER TABLE na_stories ADD COLUMN agent_tools_actions INTEGER NOT NULL DEFAULT 0 CHECK(agent_tools_actions IN (0, 1));\nALTER TABLE na_stories ADD COLUMN agent_tools_automations INTEGER NOT NULL DEFAULT 0 CHECK(agent_tools_automations IN (0, 1));\nALTER TABLE na_stories ADD COLUMN agent_tools_ai_sessions INTEGER NOT NULL DEFAULT 0 CHECK(agent_tools_ai_sessions IN (0, 1));\n"),sh("0004_agent_definition_domain","\nCREATE TABLE na_agent_definitions (\n id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, description TEXT NOT NULL DEFAULT '',\n appended_prompt TEXT NOT NULL DEFAULT '', target_instance_id TEXT NOT NULL, cwd_folder_id TEXT NOT NULL,\n provider_id TEXT NOT NULL, model_entity_id TEXT, model_name TEXT, reasoning_effort TEXT, permission_mode TEXT,\n execution_policy_json TEXT NOT NULL, revision TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE INDEX na_agent_definitions_target_instance_idx ON na_agent_definitions(target_instance_id);\nCREATE INDEX na_agent_definitions_updated_idx ON na_agent_definitions(updated_at);\nCREATE TABLE na_agent_callable_relations (\n agent_id TEXT NOT NULL, callable_agent_id TEXT NOT NULL, created_at TEXT NOT NULL,\n PRIMARY KEY (agent_id, callable_agent_id),\n FOREIGN KEY (agent_id) REFERENCES na_agent_definitions(id) ON DELETE CASCADE ON UPDATE CASCADE\n);\nCREATE INDEX na_agent_callable_relations_target_idx ON na_agent_callable_relations(callable_agent_id);\n"),sh("0005_agent_run_domain","\nCREATE TABLE na_agent_runs (\n run_id TEXT PRIMARY KEY NOT NULL, client_request_id TEXT NOT NULL UNIQUE,\n revision INTEGER NOT NULL DEFAULT 0 CHECK(revision >= 0),\n status TEXT NOT NULL CHECK(status IN ('queued','preparing','running','finalizing','completed','failed','cancelled')),\n provenance_json TEXT NOT NULL, root_member_id TEXT NOT NULL, budget_json TEXT NOT NULL,\n result_json TEXT, error_json TEXT, cleanup_json TEXT,\n created_at TEXT NOT NULL, updated_at TEXT NOT NULL, completed_at TEXT\n);\nCREATE INDEX na_agent_runs_status_updated_idx ON na_agent_runs(status, updated_at);\nCREATE TABLE na_agent_run_members (\n member_id TEXT PRIMARY KEY NOT NULL, run_id TEXT NOT NULL, agent_id TEXT NOT NULL,\n parent_member_id TEXT, instance_id TEXT NOT NULL, ai_session_id TEXT,\n role TEXT NOT NULL CHECK(role IN ('root','callee')), depth INTEGER NOT NULL CHECK(depth >= 0),\n status TEXT NOT NULL CHECK(status IN ('queued','preparing','running','finalizing','completed','failed','cancelled')),\n execution_snapshot_json TEXT NOT NULL, result_json TEXT, error_json TEXT,\n created_at TEXT NOT NULL, updated_at TEXT NOT NULL, completed_at TEXT,\n FOREIGN KEY (run_id) REFERENCES na_agent_runs(run_id) ON DELETE CASCADE ON UPDATE CASCADE,\n FOREIGN KEY (parent_member_id) REFERENCES na_agent_run_members(member_id) ON DELETE RESTRICT ON UPDATE CASCADE\n);\nCREATE INDEX na_agent_run_members_run_idx ON na_agent_run_members(run_id, created_at, member_id);\nCREATE INDEX na_agent_run_members_parent_idx ON na_agent_run_members(parent_member_id);\nCREATE TABLE na_agent_run_timeline (\n run_id TEXT NOT NULL, sequence INTEGER NOT NULL CHECK(sequence > 0), timestamp TEXT NOT NULL,\n kind TEXT NOT NULL, member_id TEXT, data_json TEXT NOT NULL,\n PRIMARY KEY (run_id, sequence),\n FOREIGN KEY (run_id) REFERENCES na_agent_runs(run_id) ON DELETE CASCADE ON UPDATE CASCADE,\n FOREIGN KEY (member_id) REFERENCES na_agent_run_members(member_id) ON DELETE RESTRICT ON UPDATE CASCADE\n);\n"),sh("0006_story_agent_entry_authorization","\nCREATE TABLE na_story_agent_entries (\n story_id TEXT NOT NULL, agent_id TEXT NOT NULL, created_at TEXT NOT NULL,\n PRIMARY KEY (story_id, agent_id),\n FOREIGN KEY (story_id) REFERENCES na_stories(id) ON DELETE CASCADE ON UPDATE CASCADE\n);\nCREATE INDEX na_story_agent_entries_agent_idx ON na_story_agent_entries(agent_id);\n"),sh("0007_agent_run_result_delivery","\nALTER TABLE na_agent_runs ADD COLUMN result_delivery_json TEXT;\n"),sh("0008_agent_run_resource_ownership","\nCREATE UNIQUE INDEX na_agent_run_members_run_member_uq ON na_agent_run_members(run_id, member_id);\nCREATE TABLE na_agent_run_shared_spaces (\n run_id TEXT PRIMARY KEY NOT NULL, runtime_id TEXT NOT NULL, generation_id TEXT NOT NULL,\n state TEXT NOT NULL CHECK(state IN ('preparing','active','retained','expiring','delete-retrying','expired','manual-intervention')),\n quota_bytes INTEGER NOT NULL CHECK(quota_bytes > 0), usage_bytes INTEGER NOT NULL DEFAULT 0 CHECK(usage_bytes >= 0),\n expires_at TEXT, diagnostics_json TEXT NOT NULL DEFAULT '{}', created_at TEXT NOT NULL, updated_at TEXT NOT NULL,\n FOREIGN KEY (run_id) REFERENCES na_agent_runs(run_id) ON DELETE CASCADE ON UPDATE CASCADE,\n FOREIGN KEY (runtime_id) REFERENCES na_runtimes(id) ON DELETE RESTRICT ON UPDATE CASCADE\n);\nCREATE INDEX na_agent_run_shared_spaces_runtime_expiry_idx ON na_agent_run_shared_spaces(runtime_id, expires_at);\nCREATE TABLE na_agent_run_resources (\n resource_id TEXT PRIMARY KEY NOT NULL, run_id TEXT NOT NULL, member_id TEXT, instance_id TEXT, runtime_id TEXT NOT NULL,\n kind TEXT NOT NULL CHECK(kind IN ('provider-thread','overlay-mount','overlay-run-directory','shared-space-directory','helper-container','sandbox-container')),\n generation_id TEXT NOT NULL, backend_identity TEXT NOT NULL,\n phase TEXT NOT NULL CHECK(phase IN ('preparing','ready','deleting','delete-retrying','deleted','manual-intervention')),\n cleanup_attempts INTEGER NOT NULL DEFAULT 0 CHECK(cleanup_attempts >= 0), metadata_json TEXT NOT NULL DEFAULT '{}',\n created_at TEXT NOT NULL, updated_at TEXT NOT NULL,\n FOREIGN KEY (run_id) REFERENCES na_agent_runs(run_id) ON DELETE CASCADE ON UPDATE CASCADE,\n FOREIGN KEY (run_id, member_id) REFERENCES na_agent_run_members(run_id, member_id) ON DELETE CASCADE ON UPDATE CASCADE,\n UNIQUE (run_id, kind, backend_identity)\n);\nCREATE INDEX na_agent_run_resources_run_phase_idx ON na_agent_run_resources(run_id, phase);\n"),sh("0009_agent_run_input","\nALTER TABLE na_agent_runs ADD COLUMN input_json TEXT;\n"),sh("0010_agent_run_member_input","\nALTER TABLE na_agent_run_members ADD COLUMN input_json TEXT;\n"),sh("0011_agent_run_member_request_identity","\nALTER TABLE na_agent_run_members ADD COLUMN client_request_id TEXT;\nCREATE UNIQUE INDEX na_agent_run_members_request_uq ON na_agent_run_members(run_id, client_request_id)\n WHERE client_request_id IS NOT NULL;\n"),sh("0012_agent_orchestration_domain","\nCREATE TABLE na_agent_orchestrations (\n id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL,\n revision TEXT NOT NULL DEFAULT '', created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE TABLE na_agent_orchestration_agents (\n orchestration_id TEXT NOT NULL, agent_id TEXT NOT NULL, created_at TEXT NOT NULL,\n PRIMARY KEY (orchestration_id, agent_id),\n FOREIGN KEY (orchestration_id) REFERENCES na_agent_orchestrations(id) ON DELETE CASCADE ON UPDATE CASCADE\n);\nCREATE INDEX na_agent_orchestration_agents_agent_idx ON na_agent_orchestration_agents(agent_id);\nCREATE TABLE na_agent_orchestration_edges (\n orchestration_id TEXT NOT NULL, from_agent_id TEXT NOT NULL, to_agent_id TEXT NOT NULL, created_at TEXT NOT NULL,\n PRIMARY KEY (orchestration_id, from_agent_id, to_agent_id),\n FOREIGN KEY (orchestration_id) REFERENCES na_agent_orchestrations(id) ON DELETE CASCADE ON UPDATE CASCADE\n);\nCREATE INDEX na_agent_orchestration_edges_from_idx ON na_agent_orchestration_edges(from_agent_id);\n\nINSERT INTO na_agent_orchestrations (id, name, revision, created_at, updated_at)\n SELECT 'default:' || id, name, '', updated_at, updated_at FROM na_agent_definitions;\nWITH RECURSIVE reach(origin, node) AS (\n SELECT id, id FROM na_agent_definitions\n UNION\n SELECT reach.origin, relation.callable_agent_id\n FROM reach JOIN na_agent_callable_relations relation ON relation.agent_id = reach.node\n)\nINSERT INTO na_agent_orchestration_agents (orchestration_id, agent_id, created_at)\n SELECT DISTINCT 'default:' || origin, node, strftime('%Y-%m-%dT%H:%M:%fZ','now') FROM reach;\nWITH RECURSIVE reach(origin, node) AS (\n SELECT id, id FROM na_agent_definitions\n UNION\n SELECT reach.origin, relation.callable_agent_id\n FROM reach JOIN na_agent_callable_relations relation ON relation.agent_id = reach.node\n)\nINSERT OR IGNORE INTO na_agent_orchestration_edges (orchestration_id, from_agent_id, to_agent_id, created_at)\n SELECT DISTINCT 'default:' || reach.origin, relation.agent_id, relation.callable_agent_id, strftime('%Y-%m-%dT%H:%M:%fZ','now')\n FROM reach JOIN na_agent_callable_relations relation ON relation.agent_id = reach.node;\nDROP TABLE na_agent_callable_relations;\n\nCREATE TABLE na_story_agent_entries_v2 (\n story_id TEXT NOT NULL, agent_id TEXT NOT NULL, orchestration_id TEXT NOT NULL, created_at TEXT NOT NULL,\n PRIMARY KEY (story_id, agent_id, orchestration_id),\n FOREIGN KEY (story_id) REFERENCES na_stories(id) ON DELETE CASCADE ON UPDATE CASCADE\n);\nINSERT INTO na_story_agent_entries_v2 (story_id, agent_id, orchestration_id, created_at)\n SELECT story_id, agent_id, 'default:' || agent_id, created_at FROM na_story_agent_entries;\nDROP TABLE na_story_agent_entries;\nALTER TABLE na_story_agent_entries_v2 RENAME TO na_story_agent_entries;\nCREATE INDEX na_story_agent_entries_agent_idx ON na_story_agent_entries(agent_id);\n\nALTER TABLE na_agent_runs ADD COLUMN orchestration_id TEXT;\nUPDATE na_agent_runs SET orchestration_id = (\n SELECT 'default:' || agent_id FROM na_agent_run_members WHERE member_id = na_agent_runs.root_member_id\n) WHERE orchestration_id IS NULL;\n"),sh("0013_model_request_mappings","\nALTER TABLE na_models ADD COLUMN mappings_json TEXT NOT NULL DEFAULT '[]';\n"),sh("0014_story_decision_domain","\nALTER TABLE na_stories ADD COLUMN agent_tools_decisions INTEGER NOT NULL DEFAULT 0 CHECK(agent_tools_decisions IN (0, 1));\nCREATE TABLE na_story_decisions (\n id TEXT PRIMARY KEY NOT NULL,\n story_id TEXT NOT NULL REFERENCES na_stories(id) ON DELETE CASCADE,\n session_id TEXT NOT NULL,\n turn_id TEXT,\n question TEXT NOT NULL,\n options_json TEXT NOT NULL DEFAULT '[]',\n allow_free_text INTEGER NOT NULL DEFAULT 1 CHECK(allow_free_text IN (0, 1)),\n context TEXT,\n status TEXT NOT NULL CHECK(status IN ('pending','decided','cancelled','expired')),\n revision INTEGER NOT NULL CHECK(revision >= 1),\n response TEXT,\n selected_option_id TEXT,\n decided_turn_id TEXT,\n expired_reason_json TEXT,\n -- node-agent 私有续接账本:仅用于旧实例不支持发送幂等键时的显式重试判定,不进入公共决策模型或 UI。\n resume_state TEXT CHECK(resume_state IS NULL OR resume_state = 'resuming'),\n resume_attempted_at TEXT,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n decided_at TEXT\n);\nCREATE UNIQUE INDEX na_story_decisions_session_turn_uq ON na_story_decisions(story_id, session_id, turn_id)\n WHERE turn_id IS NOT NULL;\nCREATE INDEX na_story_decisions_story_idx ON na_story_decisions(story_id, created_at);\nCREATE INDEX na_story_decisions_session_idx ON na_story_decisions(session_id, status);\n"),sh("0015_agent_definition_model_identity","\nALTER TABLE na_agent_definitions ADD COLUMN model_upstream_name TEXT;\n"),sh("0016_runtime_type_wsl","\nCREATE TABLE na_runtimes_wsl (\n id TEXT PRIMARY KEY NOT NULL, node_id TEXT NOT NULL REFERENCES na_node_identity(node_id) ON DELETE RESTRICT ON UPDATE CASCADE,\n name TEXT NOT NULL, type TEXT NOT NULL CHECK(type IN ('docker','kubernetes','local','wsl')),\n status TEXT NOT NULL CHECK(status IN ('unknown','online','offline','degraded')), access_strategy TEXT NOT NULL,\n capabilities_json TEXT NOT NULL, labels_json TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nINSERT INTO na_runtimes_wsl (id, node_id, name, type, status, access_strategy, capabilities_json, labels_json, created_at, updated_at)\n SELECT id, node_id, name, type, status, access_strategy, capabilities_json, labels_json, created_at, updated_at FROM na_runtimes;\nDROP TABLE na_runtimes;\nALTER TABLE na_runtimes_wsl RENAME TO na_runtimes;\nCREATE INDEX na_runtimes_node_type_idx ON na_runtimes(node_id, type);\n",{foreignKeysOff:!0})],rh=c.z.string().trim().min(1).max(160),ah=c.z.string().datetime(),ch=c.z.string().min(1).max(4096),dh=c.z.string().trim().url().max(2048),lh=c.z.object({id:rh,keyId:rh,name:c.z.string().trim().min(1).max(160).optional(),secret:ch,pairedAt:ah,revokedAt:ah.optional(),updatedAt:ah}).strip(),uh=c.z.object({id:rh,pairingKeyId:rh,name:c.z.string().trim().min(1).max(160).optional(),url:dh,enabled:c.z.boolean().default(!0),createdAt:ah,updatedAt:ah}).strip(),ph=c.z.object({controlPlaneName:c.z.string().trim().min(1).max(160).optional(),controlPlaneUrl:c.z.string().trim().max(2048).optional(),expiresInMs:c.z.number().int().positive().max(36e5).optional()}).strict(),mh=c.z.object({joinToken:c.z.string().trim().min(1).max(4096),controlPlaneId:c.z.string().trim().min(1).max(160).optional(),controlPlaneName:c.z.string().trim().min(1).max(160).optional()}).strict(),hh=c.z.object({controlPlaneUrl:c.z.string().trim().url().max(2048),joinToken:c.z.string().trim().min(1).max(4096),controlPlaneName:c.z.string().trim().min(1).max(160).optional(),activate:c.z.boolean().optional()}).strict(),gh=new Set(["nodeId","createdAt","updatedAt","pairingInvites","controlPlanePairings","controlPlaneConnections","remoteControlPlanes"]),fh=new Set(["id","keyId","name","secret","pairedAt","revokedAt","updatedAt"]),yh=new Set(["id","pairingKeyId","name","url","enabled","createdAt","updatedAt"]),Ih=new Set(["id","keyId","name","url","secret","pairedAt","updatedAt","active"]);function _h(e,t){console.warn(JSON.stringify({message:e,...t}))}function Eh(e,t){return Object.assign(new Error(e,void 0===t?void 0:{cause:t}),{code:"NODE_AGENT_IDENTITY_INVALID"})}function Ah(e,t){return Object.keys(e).filter(e=>!t.has(e))}function Th(e,t,n){const i=ah.safeParse(e);return i.success?i.data:(n("invalid node agent identity timestamp was replaced",{field:t}),de())}function wh(e,t=_h){if(!e||"object"!=typeof e||Array.isArray(e))throw Eh("Node agent identity must be a JSON object.");const n=e,i=rh.safeParse(n.nodeId);if(!i.success)throw Eh("Node agent identity has an invalid nodeId.",i.error);const s=i.data,o=Ah(n,gh);o.length&&t("unknown node agent identity fields were ignored",{fields:o}),Array.isArray(n.pairingInvites)&&n.pairingInvites.length&&t("persisted node agent pairing invites were discarded",{count:n.pairingInvites.length});const r=Array.isArray(n.remoteControlPlanes)?n.remoteControlPlanes.flatMap(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return[];const n=e,i=Ah(n,Ih);i.length&&t("unknown legacy node agent remote control-plane fields were ignored",{fields:i});const s=lh.safeParse(n);if(!s.success)return t("invalid legacy node agent control-plane pairing was ignored",{issues:s.error.issues}),[];const o=n.url?uh.safeParse({id:`connection_${s.data.keyId}`,pairingKeyId:s.data.keyId,name:n.name,url:n.url,enabled:!1!==n.active,createdAt:s.data.pairedAt,updatedAt:s.data.updatedAt}):void 0;return[{pairing:s.data,...o?.success?{connection:o.data}:{}}]}):[],a=(e,n,i,s)=>Array.isArray(e)?e.flatMap(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return t(`invalid node agent ${s} was ignored`,{}),[];const o=Ah(e,n);o.length&&t(`unknown node agent ${s} fields were ignored`,{fields:o});const r=i.safeParse(e);return r.success?[r.data]:(t(`invalid node agent ${s} was ignored`,{issues:r.error.issues}),[])}):[];return{nodeId:s,createdAt:Th(n.createdAt,"createdAt",t),updatedAt:Th(n.updatedAt,"updatedAt",t),controlPlanePairings:n.controlPlanePairings?a(n.controlPlanePairings,fh,lh,"control-plane pairing"):r.map(e=>e.pairing),controlPlaneConnections:n.controlPlaneConnections?a(n.controlPlaneConnections,yh,uh,"control-plane connection"):r.flatMap(e=>e.connection?[e.connection]:[])}}function bh(e){const t={app:Vo.shape.app.parse(e.app),endpoint:Vo.shape.endpoint.parse(e.endpoint),key:Vo.shape.key.parse(e.key),model:Vo.shape.model.parse(e.model)};return`mdl_${d.createHash("sha256").update(JSON.stringify(t)).digest("hex")}`}const Nh="1000_import_v0_0_28_p0",Sh=d.createHash("sha256").update(JSON.stringify({sourceTag:"v0.0.28",plannerVersion:3,domains:["identity","folders","runtimes","instances","models","assignments","model-environments","git"],transaction:"begin-immediate"})).digest("hex"),vh=["id","nodeId","name","path","defaultImageSelection","labels","createdAt","updatedAt"],Oh=["id","nodeId","name","type","status","accessStrategy","capabilities","labels","createdAt","updatedAt"],Rh=["id","name","endpoint","key","model","modelNames","mappings","protocols","app","enabled","order","labels","createdAt","updatedAt"],zh=["instanceId","modelEntityIds","codexModelHash","claudeModelHash","opencodeModelHash","updatedAt"],xh=["id","payload","createdAt","updatedAt"],Ch=["id","instanceId","generation","credentialIds","createdAt","updatedAt"],kh=["id","instanceId","credentialId","credentialRevision","assignmentRevision","status","authorizedAt","createdAt","updatedAt"],Dh=["id","status","operationId","input","createdAt","updatedAt","expiresAt"];function Lh(e,i,s={}){const o=e.prepare("SELECT checksum FROM na_migration_ledger WHERE id = ?").get(Nh);if(o){if(o.checksum!==Sh)throw Kh("ledger","Legacy P0 migration checksum mismatch.");return void $h(i,s.rename)}const r=[],a=function(e,i){const s=[],o=new Set,r=(e,o)=>function(e,i,s,o){return t.existsSync(e)?t.readdirSync(e).filter(e=>e.endsWith(".json")).sort().flatMap(r=>{const a=n.join(e,r);let c;try{c=t.readFileSync(a,"utf8")}catch(e){throw Kh(a,"Legacy JSON could not be accessed.",e)}const l={filePath:a,value:void 0,digest:d.createHash("sha256").update(c).digest("hex")};s.push(l);try{return l.value=JSON.parse(c),[l]}catch{return i.push({source:a,field:"unreadable-record"}),o?.(a),[]}}):[]}(e,i,s,o);return{...{folders:r(e.localFoldersDir),runtimes:r(e.nodeRuntimesDir),instances:r(e.controlledInstancesDir,e=>o.add(n.basename(e,".json"))),privateConfigs:r(e.instancePrivateConfigsDir),models:r(e.nodeModelsDir),assignments:r(e.modelAssignmentsDir),modelEnvironments:r(e.modelEnvironmentsDir),gitPayloads:r(e.gitCredentialPayloadsDir),gitAssignments:r(e.gitCredentialAssignmentsDir),gitAuthorizations:r(e.gitCredentialAuthorizationSetsDir),gitProvisioning:r(e.gitWorkspaceProvisioningIntentsDir)},allFiles:s,isolatedInstanceIds:o}}(i,r),l=a.allFiles.length>0,u=function(e){let n;try{n=t.lstatSync(e)}catch(t){if("ENOENT"===t.code)return;throw Kh(e,"Legacy JSON could not be accessed.",t)}if(!n.isFile())throw Kh(e,"Legacy JSON must be a regular file.");return function(e){try{const n=t.readFileSync(e,"utf8");return{filePath:e,value:JSON.parse(n),digest:d.createHash("sha256").update(n).digest("hex")}}catch(t){throw Kh(e,"Legacy JSON could not be read.",t)}}(e)}(i.identityPath);if(l&&!u)throw Kh(i.identityPath,"Legacy P0 data requires a node identity.");try{const t=u?wh(u.value,(e,t)=>r.push({source:i.identityPath,field:String(t.field||t.fields||"legacy")})):void 0,s=a.folders.map(e=>(Gh(e,vh,r),Mh(e,Do,Ks(e.value)))),o=a.runtimes.map(e=>(Gh(e,Oh,r),Mh(e,Qr.strip(),e.value))),d=new Map(Ph(a.privateConfigs,a.isolatedInstanceIds,r).map(e=>{const t=qh(e.value);return[n.basename(e.filePath,".json"),Bh(t.instanceCredential??t.registrationToken)]})),l=a.instances.map(e=>{const t=ba(e.value,t=>r.push({source:e.filePath,field:t.field}));if(!t.success)throw jh(e,t.error);return{...t.data,registrationToken:t.data.registrationToken||d.get(t.data.id)}}),p=a.models.flatMap(e=>{const t=qh(e.value);Gh(e,Rh,r);const i=Mh(e,Vo,Vh(t,["id","name","endpoint","key","model","modelNames","mappings","protocols","app","enabled","order","labels","createdAt","updatedAt"]));return n.basename(e.filePath,".json")!==i.id||bh(i)!==i.id?(r.push({source:e.filePath,field:"identity-or-content-hash"}),[]):[Vo.parse({...i,modelNames:i.modelNames.length?i.modelNames:[{name:i.model,order:0}],protocols:i.protocols.length?i.protocols:[(s=i.app,"claude"===s?"anthropic-messages":"opencode"===s?"openai-chat-completions":"openai-responses")]})];var s}),m=Ph(a.assignments,a.isolatedInstanceIds,r).map(e=>{const t=qh(e.value);return Gh(e,zh,r),Mh(e,Wo,Vh(t,["instanceId","modelEntityIds","codexModelHash","claudeModelHash","opencodeModelHash","updatedAt"]))});!function(e,t,i,s){const o=new Set(t.map(e=>e.id)),r=new Map(s.map(e=>[e.instanceId,e])),a=new Map(i.map(e=>[e.id,e]));let d=i.reduce((e,t)=>Math.max(e,t.order),0)+100;for(const l of e){const e=n.basename(l.filePath,".json");if(!o.has(e))throw Kh(l.filePath,`Legacy model environment references missing instance ${e}.`);if(r.has(e))continue;const u=c.z.record(c.z.string(),c.z.string()).safeParse(l.value);if(!u.success)throw jh(l,u.error);const p=u.data,m=new Set(["OPENAI_API_KEY","OPENAI_BASE_URL","CODEX_MODEL","TASK_HANDOFF_CODEX_BASE_URL","TASK_HANDOFF_CODEX_MODEL","ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","CLAUDE_MODEL","TASK_HANDOFF_CLAUDE_MODEL"]);if(Object.keys(p).some(e=>!m.has(e)))throw Kh(l.filePath,"Legacy model environment contains an unknown field.");const h=[],g={};for(const n of["codex","claude"]){const s=p["codex"===n?"OPENAI_API_KEY":"ANTHROPIC_API_KEY"],o="codex"===n?p.TASK_HANDOFF_CODEX_BASE_URL||p.OPENAI_BASE_URL:p.ANTHROPIC_BASE_URL,r="codex"===n?p.TASK_HANDOFF_CODEX_MODEL||p.CODEX_MODEL:p.TASK_HANDOFF_CLAUDE_MODEL||p.CLAUDE_MODEL;if(!s&&!o&&!r)continue;if(!s||!o||!r)throw Kh(l.filePath,`Legacy ${n} model environment is incomplete.`);const c=bh({app:n,endpoint:o,key:s,model:r});if(!a.has(c)){const l=t.find(t=>t.id===e).updatedAt,u=Vo.parse({id:c,name:`Migrated ${"codex"===n?"Codex":"Claude"} model`,endpoint:o,key:s,model:r,app:n,enabled:!0,order:d,labels:{migratedFrom:"instance-model-environment"},createdAt:l,updatedAt:l});d+=100,i.push(u),a.set(c,u)}h.push(c),"codex"===n?g.codexModelHash=c:g.claudeModelHash=c}if(!h.length)throw Kh(l.filePath,"Legacy model environment has no complete model configuration.");const f=Wo.parse({instanceId:e,modelEntityIds:h,...g,updatedAt:t.find(t=>t.id===e).updatedAt});s.push(f),r.set(e,f)}}(Ph(a.modelEnvironments,a.isolatedInstanceIds,r),l,p,m);const h=new Map,g=e=>{let t=h.get(e);return t||(t=Ir(e)?e:_r(e),h.set(e,t)),t},f=p.map(e=>Vo.parse({...e,id:g(e.id)})),y=m.map(e=>Wo.parse({...e,modelEntityIds:e.modelEntityIds.map(g),codexModelHash:e.codexModelHash?g(e.codexModelHash):e.codexModelHash,claudeModelHash:e.claudeModelHash?g(e.claudeModelHash):e.claudeModelHash,opencodeModelHash:e.opencodeModelHash?g(e.opencodeModelHash):e.opencodeModelHash})),I=l.map(e=>({...e,modelSelection:{...e.modelSelection,modelEntityIds:e.modelSelection.modelEntityIds?.map(g),codexModelHash:e.modelSelection.codexModelHash?g(e.modelSelection.codexModelHash):e.modelSelection.codexModelHash,claudeModelHash:e.modelSelection.claudeModelHash?g(e.modelSelection.claudeModelHash):e.modelSelection.claudeModelHash,opencodeModelHash:e.modelSelection.opencodeModelHash?g(e.modelSelection.opencodeModelHash):e.modelSelection.opencodeModelHash}})),_=a.gitPayloads.map(e=>{const t=qh(e.value);return Gh(e,xh,r),{id:Bh(t.id),payload:Mh(e,Ii,t.payload),createdAt:Bh(t.createdAt),updatedAt:Bh(t.updatedAt)}}),E=function(e,t){const n=new Map(e.map(e=>[e.instanceId,e]));for(const e of new Set(t.map(e=>e.instanceId))){if(n.has(e))continue;const i=t.filter(t=>t.instanceId===e).sort((e,t)=>e.credentialId.localeCompare(t.credentialId)),s=i.map(e=>e.updatedAt).sort().at(-1);n.set(e,{id:e,instanceId:e,generation:Math.max(0,...i.map(e=>e.assignmentRevision)),credentialIds:i.filter(e=>"revoking"!==e.status&&"revoked"!==e.status).map(e=>e.credentialId),createdAt:s,updatedAt:s})}return[...n.values()].sort((e,t)=>e.instanceId.localeCompare(t.instanceId))}(Ph(a.gitAuthorizations,a.isolatedInstanceIds,r).map(e=>{const t=qh(e.value);Gh(e,Ch,r);const n=Mh(e,_i,Vh(t,["instanceId","generation","credentialIds","updatedAt"]));return{...n,id:n.instanceId,createdAt:Bh(t.createdAt)}}),Ph(a.gitAssignments,a.isolatedInstanceIds,r).map(e=>{const t=qh(e.value);return Gh(e,kh,r),Mh(e,yi,Vh(t,["instanceId","credentialId","credentialRevision","assignmentRevision","status","authorizedAt","updatedAt"]))})),A=Ph(a.gitProvisioning,a.isolatedInstanceIds,r).map(e=>(Gh(e,Dh,r),function(e){const t=qh(e.value),n={id:Bh(t.id),createdAt:Bh(t.createdAt),updatedAt:Bh(t.updatedAt),expiresAt:Bh(t.expiresAt)};if("consumed"===t.status)return{...n,status:"consumed",operationId:Bh(t.operationId)};const i=function(e){const t=Oi(e),n=Oi(t?.ref),i=Oi(t?.clone),s=Array.isArray(t?.credentials)?t.credentials.map(e=>{const t=Oi(e),n=Oi(t?.payload),i=function(e){const t=Oi(e),n=Oi(t?.scope);return pi.safeParse({...Ri(t,["id","name","kind","secretSet","status","revision","createdAt","updatedAt"]),scope:Ri(n,["scheme","host","port","pathPrefix"])})}(n?.credential),s=Oi(n?.secret);return{...Ri(t,["operationId","retention"]),payload:{credential:i.success?i.data:n?.credential,secret:Ri(s,"https-token"===s?.kind?["kind","username","token"]:["kind","privateKey","passphrase","pinnedKnownHosts"])}}}):t?.credentials;return vi.safeParse({...Ri(t,["operationId","instanceId","remoteUrl"]),ref:Ri(n,["type","name","commit"]),clone:Ri(i,["depth","submodules","lfs","subdirectory"]),credentials:s})}(t.input);if(!i.success)throw jh(e,i.error);const s=vi.parse(i.data);return{...n,id:s.instanceId,status:"pending",input:s}}(e)));!function(e){const t=e.identity?.nodeId,n=Uh("local folder",e.folders.map(e=>e.id)),i=Uh("runtime",e.runtimes.map(e=>e.id)),s=Uh("instance",e.instances.map(e=>e.id)),o=Uh("model",e.models.map(e=>e.id)),r=Uh("Git credential payload",e.payloads.map(e=>e.id));Uh("model assignment",e.assignments.map(e=>e.instanceId)),Uh("Git authorization",e.authorizations.map(e=>e.instanceId)),Uh("Git provisioning",e.provisioning.map(e=>e.id));for(const n of[...e.folders,...e.runtimes])if(!t||n.nodeId!==t)throw Fh("node-identity",n.id,n.nodeId,"Legacy topology record references a different or missing node identity.");for(const s of e.instances){if(!t||s.nodeId!==t)throw Fh("node-identity",s.id,s.nodeId,"Legacy instance references a different or missing node identity.");if(!i.has(s.runtimeId))throw Fh("runtime",s.id,s.runtimeId,"Legacy instance references a missing runtime.");if("local-folder"===s.source.type&&s.source.localFolderId&&!n.has(s.source.localFolderId))throw Fh("local-folder",s.id,s.source.localFolderId,"Legacy instance references a missing local folder.")}for(const t of e.privateConfigInstanceIds)if(!s.has(t))throw Fh("instance",t,t,"Legacy private config references a missing instance.");for(const t of e.assignments){if(!s.has(t.instanceId))throw Fh("instance",t.instanceId,t.instanceId,"Legacy model assignment references a missing instance.");for(const e of new Set([...t.modelEntityIds,t.codexModelHash,t.claudeModelHash,t.opencodeModelHash].filter(e=>Boolean(e))))if(!o.has(e))throw Fh("model",t.instanceId,e,"Legacy model assignment references a missing model.")}for(const t of e.payloads)if(t.id!==t.payload.credential.id)throw Fh("Git credential payload",t.id,t.payload.credential.id,"Legacy Git credential wrapper and payload ids do not match.");for(const t of e.authorizations){if(!s.has(t.instanceId))throw Fh("instance",t.instanceId,t.instanceId,"Legacy Git authorization references a missing instance.");for(const e of t.credentialIds)if(!r.has(e))throw Fh("Git credential payload",t.instanceId,e,"Legacy Git authorization references a missing credential payload.")}for(const t of e.provisioning)if(!s.has(t.id))throw Fh("instance",t.id,t.id,"Legacy Git provisioning references a missing instance.");if(e.identity){const t=Uh("Control Plane pairing",e.identity.controlPlanePairings.map(e=>e.keyId));Uh("Control Plane connection",e.identity.controlPlaneConnections.map(e=>e.id));const n=new Set;for(const i of e.identity.controlPlaneConnections){if(!t.has(i.pairingKeyId))throw Fh("Control Plane pairing",i.id,i.pairingKeyId,"Legacy connection references a missing pairing.");const e=new URL(i.url).toString().replace(/\/$/,"");if(n.has(e))throw Fh("Control Plane URL",i.id,e,"Legacy connections contain a duplicate normalized URL.");n.add(e)}}}({identity:t,folders:s,runtimes:o,instances:I,privateConfigInstanceIds:[...d.keys()],models:f,assignments:y,payloads:_,authorizations:E,provisioning:A}),e.exec("BEGIN IMMEDIATE");try{const n=new Um(e),i=Ru(e),c=Uu(e),d=new qm(e);t&&n.writeIdentity(t);for(const e of s)i.localFolders.put(e);for(const e of o)i.runtimes.put(e);for(const e of I)i.instances.put(e);for(const e of f)c.models.put(e);for(const e of y)c.assignments.put(e);for(const e of _)d.putPayload(e);for(const e of E)d.putAuthorization(e);for(const e of A)d.putProvisioning(e);const h={sourceTag:"v0.0.28",counts:{identities:t?1:0,folders:s.length,runtimes:o.length,instances:l.length,models:p.length,assignments:m.length,pairings:t?.controlPlanePairings?.length||0,connections:t?.controlPlaneConnections?.length||0,gitPayloads:_.length,gitAuthorizations:E.length,gitProvisioning:A.length},inputDigest:Hh([...u?[u]:[],...a.allFiles]),warningCount:r.length};e.prepare("INSERT INTO na_migration_ledger (id, checksum, applied_at, details) VALUES (?, ?, ?, ?)").run(Nh,Sh,(new Date).toISOString(),JSON.stringify(h)),e.exec("COMMIT")}catch(t){throw e.exec("ROLLBACK"),t}}catch(e){if(e&&"object"==typeof e&&"code"in e&&"NODE_AGENT_LEGACY_MIGRATION_FAILED"===e.code)throw e;throw Kh("p0","Legacy P0 data failed validation.",e)}$h(i,s.rename);for(const e of r)console.warn(JSON.stringify({message:"legacy node agent field was ignored",...e}))}function Ph(e,t,i){return e.filter(e=>{const s=qh(e.value),o="string"==typeof s.instanceId?s.instanceId:n.basename(e.filePath,".json");return!t.has(o)||(i.push({source:e.filePath,field:"isolated-instance-owner"}),!1)})}function Mh(e,t,n){const i=t.safeParse(n);if(!i.success)throw jh(e,i.error);return i.data}function jh(e,t){return Kh(e.filePath,"Legacy record is missing a required field or has an invalid type.",void 0,{issues:t.issues.map(e=>({path:e.path.join("."),code:e.code}))})}function Uh(e,t){const n=new Set;for(const i of t){if(n.has(i))throw Kh(e,`Legacy ${e} id is duplicated.`,void 0,{recordId:i});n.add(i)}return n}function Fh(e,t,n,i){return Kh(e,i,void 0,{relation:e,recordId:t,referencedId:n})}function $h(e,n=t.renameSync){const i=[e.identityPath,e.localFoldersDir,e.nodeRuntimesDir,e.controlledInstancesDir,e.nodeModelsDir,e.modelAssignmentsDir,e.gitCredentialPayloadsDir,e.modelEnvironmentsDir,e.gitCredentialAssignmentsDir,e.gitCredentialAuthorizationSetsDir,e.gitWorkspaceProvisioningIntentsDir];for(const e of i){if(!t.existsSync(e))continue;const i=`${e}.migrated-v0.0.28`;let s=i;for(let e=1;t.existsSync(s);e+=1)s=`${i}.${e}`;try{n(e,s)}catch(t){console.warn(JSON.stringify({message:"legacy node agent persistence archive failed",source:e,target:s,error:t instanceof Error?t.message:String(t)}))}}}function Hh(e){const t=d.createHash("sha256");for(const i of[...e].sort((e,t)=>e.filePath.localeCompare(t.filePath)))t.update(n.basename(i.filePath)),t.update(i.digest);return t.digest("hex")}function qh(e){if(!e||"object"!=typeof e||Array.isArray(e))throw Kh("record","Legacy record must be an object.");return e}function Bh(e){if("string"!=typeof e||!e)throw Kh("record","Legacy record is missing a required string.");return e}function Vh(e,t){return Object.fromEntries(t.flatMap(t=>Object.prototype.hasOwnProperty.call(e,t)?[[t,e[t]]]:[]))}function Gh(e,t,n){const i=qh(e.value),s=new Set(t);for(const t of Object.keys(i).filter(e=>!s.has(e)).sort())n.push({source:e.filePath,field:t})}function Kh(e,t,n,i={}){return Object.assign(new Error(t,void 0===n?void 0:{cause:n}),{code:"NODE_AGENT_LEGACY_MIGRATION_FAILED",statusCode:500,details:{source:e,...i}})}function Wh(e,t){return Object.assign(new Error(`Node Agent database ${e} failed: ${t instanceof Error?t.message:String(t)}`,{cause:t}),{code:"NODE_AGENT_DATABASE_STARTUP_FAILED",statusCode:500,details:{phase:e,recovery:"Restore or remove the invalid node-agent.sqlite before restarting the Node Agent."}})}function Yh(e,t){const n=e.prepare(t).get();return n?Object.values(n)[0]:void 0}function Xh(e){for(const n of[e.databasePath,`${e.databasePath}-wal`,`${e.databasePath}-shm`])t.existsSync(n)&&t.chmodSync(n,384)}function Jh(e,i={}){try{!function(e=process.versions.node){const[t,n]=e.split(".").map(Number);if(24!==t||n<15)throw new Error(`Node.js 24.15 or newer within the Node.js 24 release line is required; received ${e}.`)}()}catch(e){throw Wh("runtime",e)}let s;t.mkdirSync(n.dirname(e.databasePath),{recursive:!0,mode:448}),t.chmodSync(n.dirname(e.databasePath),448);try{if(s=new b.DatabaseSync(e.databasePath),function(e,t){e.exec("PRAGMA foreign_keys = ON"),e.exec("PRAGMA busy_timeout = 5000"),e.exec("PRAGMA journal_mode = WAL"),e.exec("PRAGMA synchronous = FULL");const n=Number(Yh(e,"PRAGMA application_id"));if(0===n)e.exec("PRAGMA application_id = 1414024769");else if(1414024769!==n)throw new Error(`Unexpected application_id ${n}.`);if(1!==Number(Yh(e,"PRAGMA foreign_keys")))throw new Error("foreign_keys could not be enabled.");if("wal"!==String(Yh(e,"PRAGMA journal_mode")).toLowerCase())throw new Error("WAL could not be enabled.");if(5e3!==Number(Yh(e,"PRAGMA busy_timeout")))throw new Error("busy_timeout=5000 could not be enabled.");if(2!==Number(Yh(e,"PRAGMA synchronous")))throw new Error("synchronous=FULL could not be enabled.");if("ok"!==String(Yh(e,"PRAGMA quick_check")))throw new Error("quick_check failed.");Xh(t)}(s,e),function(e){e.exec("CREATE TABLE IF NOT EXISTS na_migration_ledger (\n id TEXT PRIMARY KEY NOT NULL, checksum TEXT NOT NULL, applied_at TEXT NOT NULL, details TEXT NOT NULL\n )");const t=e.prepare("SELECT checksum FROM na_migration_ledger WHERE id = ?"),n=e.prepare("INSERT INTO na_migration_ledger (id, checksum, applied_at, details) VALUES (?, ?, ?, ?)"),i=e=>n.run(e.id,e.checksum,(new Date).toISOString(),JSON.stringify({domain:"node-agent-story"}));let s=!1;const o=()=>{e.exec("BEGIN IMMEDIATE"),s=!0},r=()=>{e.exec("COMMIT"),s=!1};o();try{for(const n of oh){const s=t.get(n.id);if(s){if(s.checksum!==n.checksum)throw new Error(`Migration checksum mismatch for ${n.id}.`)}else{if(n.foreignKeysOff){if(r(),e.exec("PRAGMA foreign_keys = OFF"),0!==Number(Yh(e,"PRAGMA foreign_keys")))throw new Error(`foreign_keys could not be disabled for migration ${n.id}.`);o(),e.exec(n.sql);const t=e.prepare("PRAGMA foreign_key_check").all();if(t.length)throw new Error(`Migration ${n.id} left ${t.length} foreign key violation(s).`);if(i(n),r(),e.exec("PRAGMA foreign_keys = ON"),1!==Number(Yh(e,"PRAGMA foreign_keys")))throw new Error(`foreign_keys could not be restored after migration ${n.id}.`);o();continue}e.exec(n.sql),i(n)}}r()}catch(t){throw(()=>{if(s)try{e.exec("ROLLBACK")}finally{s=!1}})(),t}}(s),Lh(s,e,i.legacyMigration),"ok"!==String(Yh(s,"PRAGMA quick_check")))throw new Error("post-migration quick_check failed.");Xh(e);const t=N.drizzle({client:s});let n=!1;return{db:t,client:s,async checkpoint(){n||(s.exec("PRAGMA wal_checkpoint(TRUNCATE)"),Xh(e))},async close(){n||(n=!0,s.close())}}}catch(e){try{s?.close()}catch{}throw Wh(s?"initialize":"connect",e)}}function Qh(e){return e.protocols?.length?[...new Set(e.protocols)]:"claude"===e.app?["anthropic-messages"]:"opencode"===e.app?["openai-chat-completions"]:["openai-responses"]}function Zh(e,t,n){return`rly_${d.createHash("sha256").update(`${e}\0${t}\0${n}`).digest("hex").slice(0,16)}`}function eg(e,t,n,i){return`${e.replace(/\/+$/,"")}${function(e,t,n){return`/api/node-agent/model-relay/instances/${e}/routes/${Zh(e,t,n)}/v1`}(t,n,i)}`}function tg(e){const t=/^\/api\/node-agent\/model-relay\/instances\/([^/]+)\/routes\/([^/]+)\/v1(?:\/(.*))?$/.exec(e);if(!t)return;let n;try{n=decodeURIComponent(t[1])}catch{return}return{instanceId:n,routeId:t[2],operationPath:`/${t[3]||""}`}}function ng(e,t,n){return Object.assign(new Error(n),{statusCode:e,code:t})}class ig{registry;constructor(e){this.registry=e}relayEnabled(){return this.registry.modelRelayEnabled()}instance(e){return this.registry.instance(e)}resolveRoute(e,t){if(!this.registry.modelRelayEnabled())throw ng(503,"MODEL_RELAY_DISABLED","The node model relay is disabled.");let n;try{n=this.registry.instance(e)}catch{throw ng(404,"MODEL_RELAY_ROUTE_NOT_FOUND","The requested model relay route does not exist.")}if(!fs(n.capabilities))throw ng(409,"MODEL_RELAY_UNSUPPORTED",`Instance ${e} does not consume node model relay routes.`);if(!this.registry.assignment(e))throw ng(404,"MODEL_RELAY_ROUTE_NOT_FOUND","The requested model relay route does not exist.");for(const i of this.registry.assignedModelIds(e)){const s=this.registry.getModel(i);if(s)for(const o of Qh(s))if(Zh(e,i,o)===t){if(!s.enabled)throw ng(409,"MODEL_RELAY_ENTITY_DISABLED",`Model ${i} is disabled.`);if(!ys(n.capabilities,o))throw ng(409,"MODEL_RELAY_UNSUPPORTED",`Instance ${e} does not consume ${o} relay routes.`);return{instance:n,model:s,protocol:o,routeId:t}}}throw ng(404,"MODEL_RELAY_ROUTE_NOT_FOUND","The requested model relay route does not exist.")}resolveUpstreamModelName(e,t){const n=ar(e.modelNames,e.model);if(n.some(e=>e.upstreamName===t))return t;const i=n.filter(e=>e.name===t);if(i.length>1)throw ng(409,"MODEL_RELAY_AMBIGUOUS_MODEL_NAME",`Model name ${JSON.stringify(t)} is ambiguous on this relay route.`);if(i.length)return i[0].upstreamName;const s=dr(e.mappings).filter(e=>e.name===t);if(s.length>1)throw ng(409,"MODEL_RELAY_AMBIGUOUS_MODEL_NAME",`Model name ${JSON.stringify(t)} is ambiguous on this relay route.`);if(s.length)return s[0].upstreamName;if("passthrough"===this.registry.modelRelayUnknownModelPolicy())return t;throw ng(400,"MODEL_RELAY_UNKNOWN_MODEL_NAME",`Model name ${JSON.stringify(t)} is not assigned to this relay route.`)}}class sg{models;assignments;transaction;nodeId;instances;modelRelay;constructor(e,t,n,i,s){this.nodeId=t,this.instances=n,this.modelRelay=s;const o=i||Wm(Jh(e)).model;this.models=o.models,this.assignments=o.assignments,this.transaction=o.transaction.bind(o)}init(){}upgradeModelIdentity(e){if(this.models.get(e))return Ir(e)?e:this.renameModel(e,_r(e));const t=Ir(e)?e:_r(e),n=this.legacyReplicaFor(t);return n?this.renameModel(n.id,t):t}legacyReplicaFor(e){return this.models.list().find(t=>!Ir(t.id)&&_r(t.id)===e)}renameModel(e,t){if(e===t)return t;if(!this.models.get(t))return this.models.rename(e,t),t;for(const n of this.instances.list()){const i=this.assignments.get(n.id);i&&this.assignmentModelIds(i).includes(e)&&this.assignments.put(Wo.parse({...i,modelEntityIds:[...new Set(i.modelEntityIds.map(n=>n===e?t:n))],codexModelHash:i.codexModelHash===e?t:i.codexModelHash,claudeModelHash:i.claudeModelHash===e?t:i.claudeModelHash,opencodeModelHash:i.opencodeModelHash===e?t:i.opencodeModelHash,updatedAt:de()}))}return this.models.delete(e),t}mintModelEntityId(){let e=yr();for(;this.models.get(e);)e=yr();return e}modelRelayEnabled(){return!0===this.modelRelay?.enabled()}modelRelayUnknownModelPolicy(){return this.modelRelay?.unknownModelPolicy()??"passthrough"}instance(e){return this.instances.require(e)}assignment(e){return this.assignments.get(e)}assignedModelIds(e){const t=this.assignments.get(e);return t?this.assignmentModelIds(t):[]}getModel(e){return this.models.get(e)||(Ir(e)?this.legacyReplicaFor(e):this.models.get(_r(e)))}isMappedModel(e){return dr(e.mappings).length>0}assignedInstanceIds(){return this.instances.list().flatMap(e=>{const t=this.assignments.get(e.id);return t&&this.assignmentModelIds(t).length?[e.id]:[]})}mappedAssignmentInstanceIds(){return this.instances.list().flatMap(e=>{if(!fs(e.capabilities))return[];const t=this.assignments.get(e.id);if(!t)return[];const n=this.assignmentModelIds(t).some(e=>{const t=this.models.get(e);return Boolean(t&&this.isMappedModel(t))});return n?[e.id]:[]})}list(){const e=new Map;for(const t of this.instances.list()){const n=this.assignments.get(t.id);for(const t of new Set([...n?.modelEntityIds||[],n?.codexModelHash,n?.claudeModelHash,n?.opencodeModelHash]))t&&e.set(t,(e.get(t)||0)+1)}return this.models.list().map(t=>this.toPublic(t,e.get(t.id)||0))}create(e){const t=de(),n=ag(e.modelNames,e.model),i={...e,model:n[0].name,modelNames:n,mappings:dr(e.mappings),protocols:e.protocols?.length?e.protocols:rg(e.app)},s=this.mintModelEntityId(),o=Vo.parse({...i,id:s,enabled:e.enabled??!0,order:e.order??this.nextOrder(),labels:e.labels||{},createdAt:t,updatedAt:t});return this.toPublic(this.models.put(o),this.referenceIds(s).length)}deploy(e){const t=ag(e.modelNames,e.model),n=dr(e.mappings),i={...e,model:t[0].name,modelNames:t,mappings:n,protocols:e.protocols?.length?e.protocols:rg(e.app)},s=Ir(e.id)?e.id:_r(e.id),o=this.transaction(()=>this.upgradeModelIdentity(s)),r=this.models.get(o),a=this.models.put(Vo.parse({...i,id:o,createdAt:r?.createdAt||i.createdAt}));return this.toPublic(a,this.referenceIds(a.id).length)}update(e,t){const n=this.transaction(()=>this.upgradeModelIdentity(e)),i=this.requireModel(n),s=t.modelNames?.length?ag(t.modelNames,t.model||i.model):t.model?ag(void 0,t.model):ag(i.modelNames,i.model),o=t.protocols?.length?t.protocols:i.protocols?.length?i.protocols:rg(t.app||i.app),r=void 0!==t.mappings?dr(t.mappings):dr(i.mappings),a=Vo.parse({...i,...t,key:t.key?.trim()?t.key:i.key,protocols:o,model:s[0].name,modelNames:s,mappings:r,createdAt:i.createdAt,updatedAt:de()}),c=this.models.put(Vo.parse({...a,id:n}));return this.toPublic(c,this.referenceIds(n).length)}delete(e){const t=this.requireModel(e),n=this.referenceIds(t.id);if(n.length)throw Object.assign(new Error(`Model ${t.id} is assigned to ${n.length} instance${1===n.length?"":"s"}.`),{statusCode:409,code:"NODE_MODEL_IN_USE",instanceIds:n});return this.models.delete(t.id)}resolveProbeKey(e,t){const n=t?.trim()||(e?this.requireModel(e).key:"");if(!n)throw Object.assign(new Error("An API key is required to contact the model endpoint."),{statusCode:400,code:"MODEL_API_KEY_REQUIRED"});return n}assign(e,t){const n=this.instances.require(e);for(const e of t.modelEntityIds)this.validateEntityRef(e);if(void 0!==t.modelSelection.modelEntityIds&&JSON.stringify(t.modelSelection.modelEntityIds)!==JSON.stringify(t.modelEntityIds))throw Object.assign(new Error("Ordered model entity selection does not match its node assignment."),{statusCode:400,code:"NODE_MODEL_SELECTION_MISMATCH"});if(this.validateRef("codex",t.codexModelHash),this.validateRef("claude",t.claudeModelHash),this.validateRef("opencode",t.opencodeModelHash),void 0!==t.modelSelection.codexModelHash&&(t.modelSelection.codexModelHash??void 0)!==t.codexModelHash)throw Object.assign(new Error("Codex model selection does not match its node assignment."),{statusCode:400,code:"NODE_MODEL_SELECTION_MISMATCH"});if(void 0!==t.modelSelection.claudeModelHash&&(t.modelSelection.claudeModelHash??void 0)!==t.claudeModelHash)throw Object.assign(new Error("Claude model selection does not match its node assignment."),{statusCode:400,code:"NODE_MODEL_SELECTION_MISMATCH"});if(void 0!==t.modelSelection.opencodeModelHash&&(t.modelSelection.opencodeModelHash??void 0)!==t.opencodeModelHash)throw Object.assign(new Error("OpenCode model selection does not match its node assignment."),{statusCode:400,code:"NODE_MODEL_SELECTION_MISMATCH"});const i=Wo.parse({instanceId:e,modelEntityIds:t.modelEntityIds,codexModelHash:t.codexModelHash,claudeModelHash:t.claudeModelHash,opencodeModelHash:t.opencodeModelHash,updatedAt:de()});return this.transaction(()=>({assignment:this.assignments.put(i),instance:this.instances.put(Ia.parse({...n,modelSelection:t.modelSelection,updatedAt:de()}))}))}resolvedEnvironment(e){const t=this.assignments.get(e);if(!t)return{};const n=this.instances.has(e)?this.instances.require(e):void 0;if(n&&this.usesRelayProjection(n))return this.relayEnvironment(n,t);const i=e=>t.modelEntityIds.find(t=>{const n=this.requireModel(t);return this.modelSupportsApp(n,e)});return{...this.environmentForRef("codex",i("codex")||t.codexModelHash),...this.environmentForRef("claude",i("claude")||t.claudeModelHash),...this.environmentForOpenCode(t)}}usesRelayProjection(e){return Boolean(this.modelRelay?.enabled()&&fs(e.capabilities))}relayEnvironment(e,t){const n=this.modelRelay?.originFor(e)||"",i=e.registrationToken,s=t.modelEntityIds.map(e=>{const t=this.requireModel(e);return this.validateEntityRef(e),t}),o=(t,i)=>ys(e.capabilities,i)&&n?eg(n,e.id,t.id,i):void 0,r={},a=s.find(e=>this.modelSupportsApp(e,"claude")&&o(e,"anthropic-messages"));if(a&&i){const e=o(a,"anthropic-messages"),t=ag(a.modelNames,a.model).slice().sort((e,t)=>e.order-t.order||e.name.localeCompare(t.name))[0];t&&(r.ANTHROPIC_API_KEY=i,r.ANTHROPIC_BASE_URL=e,r.TASK_HANDOFF_CLAUDE_MODEL=be(t))}const c=s.filter(e=>this.modelSupportsApp(e,"opencode")&&o(e,"openai-chat-completions"));if(c.length&&i){const e=c[0],t=ag(e.modelNames,e.model).slice().sort((e,t)=>e.order-t.order||e.name.localeCompare(t.name))[0],n=Object.fromEntries(c.map(e=>[`task-handoff-${e.id}`,og(e,ag(e.modelNames,e.model).map(e=>be(e)),{baseUrl:o(e,"openai-chat-completions"),apiKey:i})]));r.TASK_HANDOFF_OPENCODE_CONFIG_CONTENT=JSON.stringify({$schema:"https://opencode.ai/config.json",model:`task-handoff-${e.id}/${t?be(t):e.model}`,provider:n})}return r}privateCatalog(e){const t=this.assignments.get(e),n=t?.updatedAt||de(),i=(t?.modelEntityIds||[]).map(e=>{const t=this.requireModel(e);return this.validateEntityRef(e),t}),s=this.instances.has(e)?this.instances.require(e):void 0;if(s&&this.usesRelayProjection(s)){const t=this.modelRelay?.originFor(s)||"";return we.parse({protocolVersion:Ie,instanceId:e,entities:i.map(n=>{const i=n.protocols?.length?n.protocols:rg(n.app);return{id:n.id,protocols:i,modelNames:cr(ag(n.modelNames,n.model)),routes:i.filter(e=>ys(s.capabilities,e)).map(i=>({protocol:i,baseUrl:eg(t,e,n.id,i)}))}}).filter(e=>e.routes.length>0),updatedAt:n})}return we.parse({protocolVersion:"2026-08-27",instanceId:e,entities:i.flatMap(e=>[{id:e.id,endpoint:e.endpoint,key:e.key,protocols:e.protocols?.length?e.protocols:rg(e.app),modelNames:cr(ag(e.modelNames,e.model))}]),updatedAt:n})}privateSecretValues(e){const t=this.assignments.get(e);return t?[...new Set(this.assignmentModelIds(t).map(e=>this.models.get(e)?.key).filter(e=>Boolean(e)))]:[]}deleteInstanceMetadata(e){this.assignments.delete(e)}referencingInstanceIds(e){return this.requireModel(e),this.referenceIds(e)}merge(e,t){const n=this.requireModel(e),i=this.requireModel(t);if(n.id===i.id)throw Object.assign(new Error("A model cannot be merged into itself."),{statusCode:400,code:"NODE_MODEL_MERGE_SAME"});this.validateEntityRef(i.id);for(const e of["codex","claude","opencode"])if(this.modelSupportsApp(n,e)&&!this.modelSupportsApp(i,e))throw Object.assign(new Error(`Model ${i.id} does not support the ${e} runtime protocol required by ${n.id}.`),{statusCode:409,code:"NODE_MODEL_MERGE_APP_MISMATCH"});const s=this.referenceIds(n.id);return this.transaction(()=>{for(const e of s){const t=this.instances.require(e),s=this.assignments.get(e);if(!s)continue;const o=[...new Set(s.modelEntityIds.map(e=>e===n.id?i.id:e))],r=(e,t)=>t&&t!==n.id?t:o.find(t=>this.modelSupportsApp(this.requireModel(t),e)),a=r("codex",s.codexModelHash),c=r("claude",s.claudeModelHash),d=r("opencode",s.opencodeModelHash);this.assignments.put(Wo.parse({instanceId:e,modelEntityIds:o,codexModelHash:a,claudeModelHash:c,opencodeModelHash:d,updatedAt:de()})),this.instances.put(Ia.parse({...t,modelSelection:{...t.modelSelection,modelEntityIds:o,codexModelHash:a??null,claudeModelHash:c??null,opencodeModelHash:d??null},updatedAt:de()}))}this.models.delete(n.id)}),{merged:!0,reassignedInstances:s}}validateRef(e,t){if(!t)return;const n=this.requireModel(t);if(!this.modelSupportsApp(n,e))throw Object.assign(new Error(`Model ${n.id} does not support the ${e} runtime protocol.`),{statusCode:400,code:"NODE_MODEL_APP_MISMATCH"});if(!n.enabled)throw Object.assign(new Error(`Model ${n.id} is disabled.`),{statusCode:409,code:"NODE_MODEL_DISABLED"})}modelSupportsApp(e,t){const n="claude"===t?"anthropic-messages":"opencode"===t?"openai-chat-completions":"openai-responses";return e.protocols?.length?e.protocols.includes(n):e.app===t}validateEntityRef(e){const t=this.requireModel(e);if(!t.enabled)throw Object.assign(new Error(`Model ${t.id} is disabled.`),{statusCode:409,code:"NODE_MODEL_DISABLED"});if(!t.protocols?.length&&!rg(t.app).length)throw Object.assign(new Error(`Model ${t.id} does not expose a supported protocol.`),{statusCode:400,code:"NODE_MODEL_PROTOCOL_UNSUPPORTED"})}assignmentModelIds(e){return[...new Set([...e.modelEntityIds||[],e.codexModelHash,e.claudeModelHash,e.opencodeModelHash].filter(e=>Boolean(e)))]}environmentForRef(e,t){if(!t)return{};this.validateRef(e,t);const n=this.requireModel(t),i=be(ag(n.modelNames,n.model)[0]);return"codex"===e?{OPENAI_API_KEY:n.key,OPENAI_BASE_URL:n.endpoint,TASK_HANDOFF_CODEX_BASE_URL:n.endpoint,TASK_HANDOFF_CODEX_MODEL:i}:{ANTHROPIC_API_KEY:n.key,ANTHROPIC_BASE_URL:n.endpoint,TASK_HANDOFF_CLAUDE_MODEL:i}}environmentForOpenCode(e){const t=e.modelEntityIds.map(e=>this.requireModel(e)).filter(e=>this.modelSupportsApp(e,"opencode"));if(!t.length)return{};const n=t[0],i=e=>ag(e.modelNames,e.model).map(e=>be(e)),s=i(n)[0],o=Object.fromEntries(t.map(e=>[`task-handoff-${e.id}`,og(e,i(e))]));if(e.opencodeModelHash){const t=this.requireModel(e.opencodeModelHash);o["task-handoff"]=og(t,i(t))}return{TASK_HANDOFF_OPENCODE_CONFIG_CONTENT:JSON.stringify({$schema:"https://opencode.ai/config.json",model:`task-handoff-${n.id}/${s}`,provider:o})}}requireModel(e){const t=this.getModel(e);if(!t)throw Object.assign(new Error(`Model ${e} was not found on node ${this.nodeId}.`),{statusCode:404,code:"NODE_MODEL_NOT_FOUND"});return t}referenceIds(e){return this.instances.list().filter(t=>{const n=this.assignments.get(t.id);return n?.modelEntityIds.includes(e)||n?.codexModelHash===e||n?.claudeModelHash===e||n?.opencodeModelHash===e}).map(e=>e.id)}toPublic(e,t){const{key:n,...i}=e;return Ko.parse({...i,modelNames:cr(e.modelNames),keyPreview:n.length<=8?"set":`${n.slice(0,4)}...${n.slice(-4)}`,keySet:!0,referenceCount:t,revision:lr(e)})}nextOrder(){return this.models.list().reduce((e,t)=>Math.max(e,t.order),0)+100}}function og(e,t,n){return{npm:"@ai-sdk/openai-compatible",name:e.name,options:n?{baseURL:n.baseUrl,apiKey:n.apiKey}:{baseURL:e.endpoint,apiKey:e.key},models:Object.fromEntries(t.map(t=>[t,{name:e.name,variants:Object.fromEntries(["none","minimal","low","medium","high","xhigh","max","ultra"].map(e=>[e,{reasoningEffort:e}]))}]))}}function rg(e){return"claude"===e?["anthropic-messages"]:"opencode"===e?["openai-chat-completions"]:["openai-responses"]}function ag(e,t){return ar(e,t)}const cg=!0;class dg{enabledValue=cg;unknownModelPolicyValue="passthrough";enabled(){return this.enabledValue}unknownModelPolicy(){return this.unknownModelPolicyValue}set(e){this.enabledValue=e.enabled,this.unknownModelPolicyValue=e.unknownModelPolicy}}class lg{settings;registry;relaySwitch;constructor(e){this.settings=e.settings,this.registry=e.registry,this.relaySwitch=e.relaySwitch}restore(){const e=this.effective();return this.relaySwitch.set({enabled:e.enabled,unknownModelPolicy:e.unknownModelPolicy}),e}effective(){const e=this.settings.get().modelRelay;return{enabled:e?.enabled??cg,unknownModelPolicy:e?.unknownModelPolicy??"passthrough",source:e?"persisted":"default"}}enabled(){return this.relaySwitch.enabled()}update(e){const t=la.parse(e);t.enabled||this.assertDisableAllowed();const n=t.unknownModelPolicy??this.effective().unknownModelPolicy;return this.settings.put({...this.settings.get(),version:1,modelRelay:{enabled:t.enabled,unknownModelPolicy:n}}),this.relaySwitch.set({enabled:t.enabled,unknownModelPolicy:n}),this.effective()}assertDisableAllowed(){const e=this.registry.mappedAssignmentInstanceIds();if(e.length)throw Object.assign(new Error(`Cannot disable the node model relay while ${e.length} instance${1===e.length?"":"s"} use a model name mapping.`),{statusCode:409,code:"NODE_MODEL_RELAY_IN_USE",details:{instanceIds:e}})}}function ug(e,t){if(!e)return!0;const n=S.valid(e),i=S.valid(t);return n&&i?S.gt(i,n):e!==t}function pg(){return process.env.TASK_HANDOFF_NPM_COMMAND||"npm"}function mg(e,i){const s=n.join(e,...i.split("/"),"package.json");try{const e=JSON.parse(t.readFileSync(s,"utf8"));if(e.name!==i||"string"!=typeof e.version||!e.version.trim())throw new Error(`Installed package manifest is invalid: ${s}`);return{name:i,version:e.version.trim()}}catch(e){if("ENOENT"===e.code)return;throw e}}async function hg(e,i){const s=i?function(e){const i=function(e){let t=n.resolve(e);for(;t!==n.dirname(t);){if("node_modules"===n.basename(t)&&"lib"===n.basename(n.dirname(t)))return n.dirname(n.dirname(t));t=n.dirname(t)}}(e);if(!i)return;let s,o=n.resolve(e);for(;o!==n.dirname(o);){try{const e=JSON.parse(t.readFileSync(n.join(o,"package.json"),"utf8"));if("@task-handoff/node-agent"===e.name&&"string"==typeof e.version&&e.version.trim()&&(s=e.version.trim()),"@task-handoff/server"===e.name&&"string"==typeof e.version&&e.version.trim())return{packageName:"@task-handoff/server",currentVersion:e.version.trim(),relatedCurrentVersions:s?[s]:[],installPrefix:i}}catch(e){if("ENOENT"!==e.code)throw e}o=n.dirname(o)}return s?{packageName:"@task-handoff/node-agent",currentVersion:s,relatedCurrentVersions:[],installPrefix:i}:void 0}(i):void 0;if(s)return s;const o=(await e(pg(),["root","--global"])).stdout.trim();if(!o)throw new Error("npm did not return its global module root.");const r=(await e(pg(),["prefix","--global"])).stdout.trim();if(!n.isAbsolute(r))throw new Error(`npm did not return an absolute global prefix: ${r||"empty"}`);const a=mg(o,"@task-handoff/server"),c=mg(o,"@task-handoff/node-agent");return a?{packageName:"@task-handoff/server",currentVersion:a.version,relatedCurrentVersions:c?[c.version]:[],installPrefix:r}:{packageName:"@task-handoff/node-agent",currentVersion:c?.version,relatedCurrentVersions:[],installPrefix:r}}function gg(e){if(!e||"object"!=typeof e||Array.isArray(e))return e;const t=e,n="string"==typeof t.updatedAt?t.updatedAt:de(),i=t.target&&"object"==typeof t.target&&!Array.isArray(t.target)?t.target:void 0,s="controlled-instance"===i?.component,o={updating:"updating-node",downloading:"updating-node",installing:"updating-node",restarting:"restarting-node",completed:"succeeded",success:"succeeded",error:"failed"},r=new Set(["queued","updating-node","restarting-node","converging-instances","succeeded","degraded","failed"]),a="string"==typeof t.status?t.status:"queued",c=s?"failed":r.has(a)?a:o[a]||"failed",d="string"==typeof t.toVersion&&t.toVersion?t.toVersion:"unknown",l=Ao.strip().safeParse(t.impact).success?Ao.strip().parse(t.impact):{runningInstanceCount:0,stoppedInstanceCount:0,activeInstanceCount:0,restartInstanceCount:0,runningInstanceIds:[],stoppedInstanceIds:[],activeInstanceIds:[]},u=s?{code:"LEGACY_INSTANCE_UPDATE_RETIRED",message:"Independent controlled-instance update jobs were retired in favor of Node reconciliation.",retryable:!1}:"failed"!==c||t.error||r.has(a)||a in o?"string"==typeof t.error?{code:"NODE_UPDATE_FAILED",message:t.error,retryable:!1}:_o.strip().safeParse(t.error).success?_o.strip().parse(t.error):t.error&&"object"==typeof t.error?{code:"NODE_UPDATE_FAILED",message:"string"==typeof t.error.message?t.error.message:"Stored update job contained an unknown error.",retryable:!1}:void 0:{code:"NODE_UPDATE_FAILED",message:`Stored update job used an unknown status: ${a}.`,retryable:!1},{target:p,error:m,...h}=t,g={phase:"succeeded"===c?"succeeded":"failed"===c?"failed":c||"queued",desiredVersion:d,expectedInstanceIds:[],expectedInstanceCount:0,matchedInstanceCount:0,pendingInstanceCount:0,failedInstanceCount:s||"failed"===c?1:0,deferredInstanceCount:0},f=To.strip().safeParse(t.rollout);return{...h,source:"npm",status:c,impact:l,runtimeArtifacts:Array.isArray(t.runtimeArtifacts)?t.runtimeArtifacts.flatMap(e=>{const t=Io.strip().safeParse(e);return t.success?[t.data]:[]}):[],rollout:f.success?f.data:g,...u?{error:u}:{},...s?{completedAt:t.completedAt||n}:{}}}class fg{records;constructor(e){this.records=new uu(e.updatesDir,{schema:No,sanitize:gg})}init(){this.records.init()}list(){return this.records.list().sort((e,t)=>t.createdAt.localeCompare(e.createdAt))}create(e,t){const n=de();return this.records.put(No.parse({id:du("update"),nodeId:e,source:t.source,channel:t.channel,fromVersion:t.currentVersion,toVersion:t.availableVersion,artifactRef:t.artifactRef,runtimeArtifacts:t.runtimeArtifacts,impact:t.impact,status:"queued",rollout:{phase:"queued",desiredVersion:t.availableVersion,expectedInstanceIds:[],expectedInstanceCount:0,matchedInstanceCount:0,pendingInstanceCount:0,failedInstanceCount:0,deferredInstanceCount:0},createdAt:n,updatedAt:n}))}patch(e,t){const n=this.records.get(e);if(!n)throw Object.assign(new Error(`Update job ${e} was not found.`),{statusCode:404,code:"UPDATE_JOB_NOT_FOUND"});return this.records.put(No.parse({...n,...t,id:e,createdAt:n.createdAt,updatedAt:de()}))}reconcileServerUpdates(e,t={}){if(t.processStarted)for(const e of this.list().filter(e=>"queued"===e.status))this.patch(e.id,{status:"failed",rollout:{...e.rollout,phase:"failed"},error:{code:"NODE_UPDATE_FAILED",message:"The node agent restarted before the update worker claimed this job.",retryable:!0},completedAt:de()});for(const n of this.list().filter(e=>["updating-node","restarting-node","converging-instances"].includes(e.status)))t.processStarted&&["restarting-node","converging-instances"].includes(n.status)&&e!==n.toVersion?this.patch(n.id,{status:"failed",rollout:{...n.rollout,phase:"failed",nodeVersion:e},error:{code:"NODE_UPDATE_FAILED",message:`Node agent restarted with version ${e}, expected ${n.toVersion}.`,retryable:!1},completedAt:de()}):e===n.toVersion&&this.patch(n.id,{status:"succeeded",rollout:{...n.rollout,phase:"succeeded",nodeVersion:e,expectedInstanceIds:[],expectedInstanceCount:0,matchedInstanceCount:0,pendingInstanceCount:0,failedInstanceCount:0,deferredInstanceCount:0},error:void 0,completedAt:de()})}}class yg{records;constructor(e){this.records=new uu(e.environmentTemplatesDir,{schema:Js,sanitize:e=>function(e,t){if(!e||"object"!=typeof e||Array.isArray(e))return e;const n=e,i=new Set(["id","name","sourceInstanceId","nodeId","imageId","internalTag","platform","architecture","sizeBytes","status","error","createdAt","updatedAt"]),s="string"==typeof n.id?n.id:void 0;for(const e of Object.keys(n))i.has(e)||t?.({templateId:s,field:e});const o=Oa(n,[...i]);if(n.error&&"object"==typeof n.error&&!Array.isArray(n.error)){const e=n.error;for(const n of Object.keys(e))["code","message","phase"].includes(n)||t?.({templateId:s,field:`error.${n}`});o.error=Oa(e,["code","message","phase"])}return o}(e,e=>{console.warn(JSON.stringify({message:"unknown stored environment template field was ignored",...e}))})})}init(){this.records.init();for(const e of this.records.list())"creating"===e.status&&this.records.put(Js.parse({...e,status:"failed",error:{code:"ENVIRONMENT_TEMPLATE_CREATION_INTERRUPTED",message:"Environment template creation was interrupted by a node-agent restart.",phase:"recovery"},updatedAt:de()}))}list(){return this.records.list()}get(e){return this.records.get(e)}put(e){return this.records.put(Js.parse(e))}patch(e,t){return this.records.patch(e,t)}delete(e){return this.records.delete(e)}}const Ig=c.z.object({id:c.z.string().trim().min(1).max(120),status:c.z.literal("pending"),input:vi,createdAt:c.z.string().datetime(),updatedAt:c.z.string().datetime(),expiresAt:c.z.string().datetime()}).strict();class _g{repository;workspaceProvisioningTtlMs;workspaceProvisioningCleanupTimer;constructor(e,t={}){this.workspaceProvisioningTtlMs=t.workspaceProvisioningTtlMs??864e5,this.repository=t.repository||Wm(Jh(e)).git}init(){this.repository.deleteExpiredProvisioning((new Date).toISOString()),this.scheduleWorkspaceProvisioningCleanup()}putPayload(e){const t=Ii.parse(e),n=this.repository.getPayload(t.credential.id);if(n&&n.payload.credential.revision>t.credential.revision)throw function(e,t){return Object.assign(new Error(`Refusing stale payload revision for ${t}.`),{code:"GIT_CREDENTIAL_REVISION_STALE",statusCode:409})}(0,t.credential.id);if(n&&n.payload.credential.revision===t.credential.revision&&JSON.stringify(n.payload)!==JSON.stringify(t))throw function(e,t){return Object.assign(new Error(`Refusing conflicting payload revision for ${t}.`),{code:"GIT_CREDENTIAL_REVISION_CONFLICT",statusCode:409})}(0,t.credential.id);const i=(new Date).toISOString();return this.repository.putPayload({id:t.credential.id,payload:t,createdAt:n?.createdAt||i,updatedAt:i}).payload}getPayload(e){return this.repository.getPayload(e)?.payload}putAuthorizationSet(e){const t=_i.parse(e),n=this.repository.getAuthorization(t.instanceId),i=(new Date).toISOString();return this.publicAuthorizationSet(this.repository.putAuthorizationCas({id:t.instanceId,...t,createdAt:n?.createdAt||i}))}getAuthorizationSet(e){const t=this.repository.getAuthorization(e);return t?this.publicAuthorizationSet(t):{instanceId:e,generation:0,credentialIds:[],updatedAt:new Date(0).toISOString()}}resolve(e,t){const n=this.getAuthorizationSet(e).credentialIds.flatMap(e=>{const t=this.getPayload(e);return t?[t]:[]}),i=zi(t,n.map(e=>({id:e.credential.id,kind:e.credential.kind,scope:e.credential.scope,status:e.credential.status,pinnedKnownHosts:"ssh-key"===e.secret.kind&&Boolean(e.secret.pinnedKnownHosts.trim())}))),s="unique"===i.status?n.find(e=>e.credential.id===i.credential.id):void 0;return{match:i,payload:s}}removePayload(e){if(this.repository.listAuthorizations().some(t=>t.credentialIds.includes(e)))throw Object.assign(new Error(`Credential payload ${e} is still authorized.`),{code:"GIT_CREDENTIAL_PAYLOAD_IN_USE",statusCode:409});return this.repository.deletePayload(e)}collectUnreferencedPayloads(){return this.repository.collectUnreferencedPayloads()}removeInstance(e){const t=this.repository.deleteAuthorization(e)?1:0;return this.repository.deleteProvisioning(e),this.scheduleWorkspaceProvisioningCleanup(),t}putWorkspaceProvisioning(e){const t=vi.parse(e);if(!Eg(t))throw Object.assign(new Error("Only operation-only Git provisioning may be persisted."),{code:"GIT_CREDENTIAL_PROVISIONING_RETENTION_INVALID",statusCode:400});const n=this.repository.getProvisioning(t.instanceId);if("consumed"===n?.status&&n.operationId===t.operationId)return t;const i=(new Date).toISOString(),s=Ig.parse(this.repository.putProvisioning({id:t.instanceId,status:"pending",input:t,createdAt:n?.createdAt||i,updatedAt:i,expiresAt:new Date(Date.now()+this.workspaceProvisioningTtlMs).toISOString()})).input;return this.scheduleWorkspaceProvisioningCleanup(),s}getWorkspaceProvisioning(e){const t=this.repository.getProvisioning(e);if(t&&"pending"===t.status)return!Eg(t.input)||Date.parse(t.expiresAt)<=Date.now()?(this.repository.deleteProvisioning(e),void this.scheduleWorkspaceProvisioningCleanup()):t.input}removeWorkspaceProvisioning(e){const t=this.repository.deleteProvisioning(e);return this.scheduleWorkspaceProvisioningCleanup(),t}discardPendingWorkspaceProvisioning(e){const t=this.repository.getProvisioning(e);return!(!t||"pending"!==t.status)&&this.removeWorkspaceProvisioning(e)}completeWorkspaceProvisioning(e,t){const n=(new Date).toISOString(),i=this.repository.consumeProvisioning(e,t,n,new Date(Date.now()+6048e5).toISOString());return this.scheduleWorkspaceProvisioningCleanup(),i}workspaceProvisioningStatus(e){const t=this.repository.getProvisioning(e);if(t){if(!(Date.parse(t.expiresAt)<=Date.now()))return"pending"===t.status?{status:t.status,operationId:t.input.operationId}:{status:t.status,operationId:t.operationId};this.removeWorkspaceProvisioning(e)}}scheduleWorkspaceProvisioningCleanup(){this.workspaceProvisioningCleanupTimer&&clearTimeout(this.workspaceProvisioningCleanupTimer),this.workspaceProvisioningCleanupTimer=void 0;const e=Math.min(...this.repository.listProvisioning().map(e=>Date.parse(e.expiresAt)));Number.isFinite(e)&&(this.workspaceProvisioningCleanupTimer=setTimeout(()=>{this.workspaceProvisioningCleanupTimer=void 0;const e=Date.now();this.repository.deleteExpiredProvisioning(new Date(e).toISOString()),this.scheduleWorkspaceProvisioningCleanup()},Math.min(2147483647,Math.max(0,e-Date.now()))),this.workspaceProvisioningCleanupTimer.unref?.())}publicAuthorizationSet(e){const{id:t,createdAt:n,...i}=e;return _i.parse(i)}}function Eg(e){return e.credentials.length>0&&e.credentials.every(e=>"operation-only"===e.retention)}const Ag=function(e,t=process.env,n=e){let i;return()=>{const s=t.TASK_HANDOFF_VERSION?.trim();return s||(i||=k(e,t,n),i)}}("@task-handoff/node-agent",process.env,"@task-handoff/control-plane");function Tg(){return Ag()}function wg(e,t){return{code:"INSTANCE_RUNTIME_VERSION_MISMATCH",message:`Expected controlled-instance ${e}, received ${t||"an unknown version"}.`,expectedVersion:e,...t?{actualVersion:t}:{},retryable:!0}}function bg(e){const t=Tg();return e===t?{desiredVersion:t,actualVersion:e,phase:"matched",attempt:0,matchedAt:(new Date).toISOString()}:{desiredVersion:t,...e?{actualVersion:e}:{},phase:"pending",attempt:0,error:wg(t,e)}}function Ng(e,t,n=!0){if(!n){const n=Tg(),i=e.runtimeVersion;return"matched"===i?.phase&&i.desiredVersion===n&&i.actualVersion===t?i:bg(t)}const i=Tg(),s=e.runtimeVersion;if(!s||s.desiredVersion!==i)return bg(t);const o="INSTANCE_RUNTIME_VERSION_MISMATCH"!==s.error?.code?s.error:t===i?void 0:wg(i,t);return Eo.parse({...s,desiredVersion:i,...t?{actualVersion:t}:{actualVersion:void 0},..."pending"===s.phase?{error:o||(t!==i?wg(i,t):void 0)}:{}})}const Sg={requiresImage:!1,supportsControlledInstanceApi:!0,supportsContainerLifecycle:!1,supportsAppSessions:!0,supportsHostSessions:!0,artifactKind:"none",isolation:"none"};function vg(e){return"local"===e?{...Sg}:{}}function Og(e,t={}){return{...t,...vg(e)}}function Rg(e){return"none"!==e.capabilities.artifactKind}const zg=c.z.object({version:c.z.literal(1),externalListener:oa,modelRelay:da.optional(),wslRuntime:c.z.object({enabled:c.z.boolean()}).strict().optional()}).strict();function xg(e){return"all-ipv4"===e?"0.0.0.0":"127.0.0.1"}function Cg(e,t){return oa.parse({bindScope:"0.0.0.0"===e.trim()?"all-ipv4":"loopback",port:t})}function kg(e){if(!e||"object"!=typeof e||Array.isArray(e))return e;const t=e,n=t.externalListener&&"object"==typeof t.externalListener&&!Array.isArray(t.externalListener)?t.externalListener:{},i=t.modelRelay,s=t.wslRuntime,o=Object.keys(t).filter(e=>"version"!==e&&"externalListener"!==e&&"modelRelay"!==e&&"wslRuntime"!==e),r=Object.keys(n).filter(e=>"bindScope"!==e&&"port"!==e);let a,c,d;if(void 0!==i)if(i&&"object"==typeof i&&!Array.isArray(i)&&"boolean"==typeof i.enabled){const e=i,t=Object.keys(e).filter(e=>"enabled"!==e&&"unknownModelPolicy"!==e),n=e.unknownModelPolicy,s=void 0!==n&&"passthrough"!==n&&"reject"!==n;t.length&&console.warn(JSON.stringify({message:"unknown stored node agent runtime setting fields were ignored",filePath:"runtime-settings.json",fields:t.map(e=>`modelRelay.${e}`)})),s&&console.warn(JSON.stringify({message:"invalid stored node agent model relay unknown model policy was normalized to passthrough",filePath:"runtime-settings.json",field:"modelRelay.unknownModelPolicy"})),a={enabled:e.enabled,..."passthrough"===n||"reject"===n?{unknownModelPolicy:n}:{}}}else c=i&&"object"==typeof i&&!Array.isArray(i)?"enabled":"modelRelay";let l=!1;if(void 0!==s)if(s&&"object"==typeof s&&!Array.isArray(s)&&"boolean"==typeof s.enabled){const e=s,t=Object.keys(e).filter(e=>"enabled"!==e);t.length&&console.warn(JSON.stringify({message:"unknown stored node agent runtime setting fields were ignored",filePath:"runtime-settings.json",fields:t.map(e=>`wslRuntime.${e}`)})),d={enabled:e.enabled}}else l=!0;return(o.length||r.length)&&console.warn(JSON.stringify({message:"unknown stored node agent runtime setting fields were ignored",filePath:"runtime-settings.json",fields:[...o,...r.map(e=>`externalListener.${e}`)]})),l&&console.warn(JSON.stringify({message:"invalid stored node agent wsl runtime setting was normalized to disabled",filePath:"runtime-settings.json",field:"wslRuntime.enabled"})),c&&console.warn(JSON.stringify({message:"invalid stored node agent model relay setting was normalized to disabled",filePath:"runtime-settings.json",field:"modelRelay"===c?"modelRelay":"modelRelay.enabled"})),{version:t.version,externalListener:{bindScope:n.bindScope,port:n.port},...a?{modelRelay:a}:{},...d?{wslRuntime:d}:{}}}function Dg(e,t){return new pu(e.settingsPath,()=>({version:1,externalListener:t}),{schema:zg,sanitize:kg})}const Lg="runtime_local_host",Pg="runtime_wsl_host",Mg="task-handoff.node-agent.builtin";function jg(e){const t={...e};return delete t[Mg],t}function Ug(e){return"local-folder"===e.type?Po.parse({mode:"local-bind",path:"/workspace",readOnly:!1}):Po.parse({mode:"git-clone",path:"/workspace",readOnly:!1})}function Fg(e){const t=Lo.parse(e.source),n=e.projectId||("local-folder"===t.type?t.localFolderId:void 0)||("git-repository"===t.type?t.repositoryId:void 0)||("git-template"===t.type?t.templateId:void 0)||`project_${e.id}`;return qo.parse({id:n,name:"string"==typeof e.sourceSnapshot.name?e.sourceSnapshot.name:e.name,source:t,defaultImageSelection:e.imageSelection,defaultNodeId:e.nodeId,workspacePolicy:Ug(t),labels:{},createdAt:e.createdAt,updatedAt:e.updatedAt})}function $g(e,t){throw Object.assign(new Error(t),{statusCode:403,code:e})}function Hg(e,t){e!==Qi&&console.warn(JSON.stringify({message:"protocol version mismatch",peer:t,expectedProtocolVersion:Qi,actualProtocolVersion:e||"missing",errorCode:"PROTOCOL_VERSION_MISMATCH"}))}function qg(e={}){return Og("local",e)}class Bg{onStored;records;constructor(e){this.records=e}init(){}setOnStored(e){this.onStored=e}put(e){const t=this.records.put(Ia.parse(e));return this.onStored?.(t),t}putObservation(e){const t=this.records.putObservation(Ia.parse(e));return this.onStored?.(t),t}get(e){return this.records.get(e)}list(){return this.records.list()}delete(e){return this.records.delete(e)}}class Vg{nodeId;paths;persistence;localFolders;nodeRuntimes;controlledInstances;environmentTemplates;instancePrivateConfigs;modelRegistry;modelRelaySwitch;gitCredentials;updateJobs;node;listenerPort;platform;containerUrlOverride;builtinFolders;constructor(e,t,n,i,o,r,a){this.paths=e,this.nodeId=t,this.platform=r;const c=a||Wm(Jh(e));this.persistence=c,c.topology.nodeIdentity.ensure(t,de()),this.localFolders=c.topology.localFolders,this.nodeRuntimes=c.topology.runtimes,this.instancePrivateConfigs=new uc(e),this.controlledInstances=new Bg(c.topology.instances),this.environmentTemplates=new yg(e),this.gitCredentials=new _g(e,{repository:c.git}),this.modelRelaySwitch=new dg,this.modelRegistry=new sg(e,t,{has:e=>Boolean(this.controlledInstances.get(e)),list:()=>this.listInstances(),require:e=>this.requireInstance(e),put:e=>this.controlledInstances.put(e)},c.model,{enabled:()=>this.modelRelaySwitch.enabled(),unknownModelPolicy:()=>this.modelRelaySwitch.unknownModelPolicy(),originFor:e=>"docker"===e.runtime.kind?this.containerUrl:`http://127.0.0.1:${this.listenerPort}`}),this.updateJobs=new fg(e),this.listenerPort=o,this.containerUrlOverride=i;const d=de();this.node=Yr.parse({id:t,name:Yr.shape.name.safeParse(s.hostname()).data||t,connectionMode:"direct-http",endpoint:n,controlEndpoint:n,containerEndpoint:this.containerUrl,publicWebBase:n?n.replace(/:\d+$/,""):void 0,status:"online",health:"ok",capabilities:{},labels:{},createdAt:d,updatedAt:d})}init(){for(const e of this.localFolders.list())this.localFolders.put(e);if(this.instancePrivateConfigs.init(),this.controlledInstances.init(),this.environmentTemplates.init(),this.gitCredentials.init(),this.modelRegistry.init(),this.updateJobs.init(),this.updateJobs.reconcileServerUpdates(Tg(),{processStarted:!0}),!this.nodeRuntimes.get("runtime_local_docker")){const e=de();this.nodeRuntimes.put(Qr.parse({id:"runtime_local_docker",nodeId:this.nodeId,name:"Local Docker",type:"docker",status:"unknown",accessStrategy:"direct-port",capabilities:{},labels:{},createdAt:e,updatedAt:e}))}const e=this.nodeRuntimes.get(Lg),t=de();this.nodeRuntimes.put(Qr.parse({id:Lg,nodeId:this.nodeId,name:"Local Runtime",type:"local",status:e?.status||"unknown",accessStrategy:"node-proxy",capabilities:qg(e?.capabilities),labels:{...e?.labels,[Mg]:"true"},createdAt:e?.createdAt||t,updatedAt:e?.updatedAt||t}));const n=this.nodeRuntimes.get(Pg),i=Dg(this.paths,Cg("127.0.0.1",this.listenerPort)).get();if("win32"===this.platform&&function(e,t=process.env){const n=function(e){const t=String(e??"").trim().toLowerCase();if(t)return!!["1","true","yes","on"].includes(t)||!["0","false","no","off"].includes(t)&&void 0}(t.TASK_HANDOFF_WSL_RUNTIME_ENABLED);return void 0!==n?n:!0===e.wslRuntime?.enabled}(i)){const e=de();this.nodeRuntimes.put(Qr.parse({id:Pg,nodeId:this.nodeId,name:"WSL",type:"wsl",status:n?.status||"unknown",accessStrategy:"node-proxy",capabilities:na(n?.capabilities),labels:{...n?.labels,[Mg]:"true"},createdAt:n?.createdAt||e,updatedAt:e}))}for(const e of this.nodeRuntimes.list())e.nodeId!==this.nodeId&&this.nodeRuntimes.put(Qr.parse({...e,nodeId:this.nodeId,updatedAt:de()}));for(const e of this.localFolders.list())e.nodeId!==this.nodeId&&this.localFolders.put(Do.parse({...e,nodeId:this.nodeId,updatedAt:de()}));this.normalizeInstanceRuntimeVersions()}normalizeInstanceRuntimeVersions(){for(const e of this.controlledInstances.list()){const t=bg(e.build?.packageVersion||e.instanceVersion),n=Rg(this.requireRuntime(e.runtimeId)),i=["created","stopped","failed"].includes(e.status),s=n&&e.runtimeVersion?.desiredVersion===t.desiredVersion?e.runtimeVersion:void 0,o=n?"matched"===t.phase?i?t:{...t,phase:"verifying",matchedAt:void 0}:{...t,phase:"pending",attempt:s?.attempt||0,lastAttemptAt:s?.lastAttemptAt,error:s?.error||t.error}:t;this.controlledInstances.put(Ia.parse({...e,ready:!1,runtimeVersion:o,updatedAt:de()}))}}get localNodeAgentUrl(){return`http://127.0.0.1:${this.listenerPort}`}get currentListenerPort(){return this.listenerPort}get containerUrl(){return this.containerUrlOverride||`http://host.docker.internal:${this.listenerPort}`}setListenerPort(e){this.listenerPort=e,this.node.containerEndpoint=this.containerUrl,this.node.updatedAt=de()}runningInstanceCount(){const e=new Set(["created","stopped","failed"]);return this.listInstances().filter(t=>!e.has(t.status)).length}createLocalFolder(e){const t=de(),i=wl(e.path),s=Do.parse({...e,name:e.name.trim()||n.basename(i),path:i,id:e.id||du("folder"),nodeId:this.nodeId,labels:e.labels||{},createdAt:t,updatedAt:t});return this.localFolders.put(s)}attachBuiltinProjectFolders(e){this.builtinFolders=e}listLocalFolders(){return[...this.localFolders.list(),...this.builtinFolders?.list()||[]]}resolveLocalFolder(e){return this.localFolders.get(e)||this.builtinFolders?.get(e)}updateLocalFolder(e,t){const i=this.localFolders.get(e);if(!i)throw this.builtinFolderReadOnlyError(e,"renamed");return this.localFolders.put(Do.parse({...i,name:t.name.trim()||n.basename(i.path),updatedAt:de()}))}deleteLocalFolder(e){if(this.localFolders.get(e))return this.localFolders.delete(e);if(this.builtinFolders?.owns(e))throw this.builtinFolderReadOnlyError(e,"removed");return!1}builtinFolderReadOnlyError(e,t){return this.builtinFolders?.owns(e)?Object.assign(new Error(`Built-in project folder ${e} is owned by the node agent and cannot be ${t}.`),{statusCode:409,code:"NODE_LOCAL_FOLDER_BUILTIN_READONLY"}):Object.assign(new Error(`Local folder ${e} was not found.`),{statusCode:404,code:"NODE_LOCAL_FOLDER_NOT_FOUND"})}createRuntime(e){if("local"===e.type){const e=new Error("Local Runtime is built in and cannot be added manually.");throw Object.assign(e,{statusCode:409,code:"LOCAL_RUNTIME_BUILTIN"}),e}const t=de(),n=Qr.parse({...e,id:e.id||du("runtime"),nodeId:this.nodeId,accessStrategy:e.accessStrategy||(i=e.type,"docker"===i?"direct-port":"node-proxy"),capabilities:e.capabilities||{},labels:jg(e.labels),createdAt:t,updatedAt:t});var i;return this.nodeRuntimes.put(n)}updateRuntime(e,t){const n=this.requireRuntime(e);if("true"===n.labels[Mg]){const t=new Error(`Built-in runtime ${e} cannot be modified.`);throw Object.assign(t,{statusCode:400,code:"NODE_RUNTIME_BUILTIN"}),t}if("local"===n.type||"local"===t.type){const e=new Error("Local Runtime is built in and cannot be configured manually.");throw Object.assign(e,{statusCode:409,code:"LOCAL_RUNTIME_BUILTIN"}),e}const i=Qr.parse({...n,...t,id:n.id,nodeId:this.nodeId,accessStrategy:t.accessStrategy||n.accessStrategy,capabilities:t.capabilities||n.capabilities,labels:t.labels?jg(t.labels):n.labels,createdAt:n.createdAt,updatedAt:de()});return this.nodeRuntimes.put(i)}deleteRuntime(e){if("true"===this.requireRuntime(e).labels[Mg]){const t=new Error(`Built-in runtime ${e} cannot be deleted.`);throw Object.assign(t,{statusCode:400,code:"NODE_RUNTIME_BUILTIN"}),t}const t=this.listInstances().filter(t=>t.runtimeId===e);if(t.length){const n=new Error(`Runtime ${e} is used by ${t.length} instance${1===t.length?"":"s"}.`);throw Object.assign(n,{statusCode:409,code:"NODE_RUNTIME_IN_USE"}),n}return this.nodeRuntimes.delete(e)}recordRuntimeProbe(e,t){const n=this.requireRuntime(e),i=Qr.parse({...n,...t,id:n.id,nodeId:this.nodeId,accessStrategy:t.accessStrategy||n.accessStrategy,capabilities:t.capabilities||n.capabilities,labels:t.labels||n.labels,createdAt:n.createdAt,updatedAt:de()});return this.nodeRuntimes.put(i)}checkRuntime(e,t){if(!t.check)return this.recordRuntimeProbe(e,{status:"unknown"});const n=this.requireRuntime(e);return Promise.resolve(t.check(n)).then(t=>this.recordRuntimeProbe(e,t))}requireRuntime(e){const t=this.nodeRuntimes.get(e);if(!t){const t=new Error(`Node runtime ${e} was not found.`);throw Object.assign(t,{statusCode:404,code:"NODE_RUNTIME_NOT_FOUND"}),t}return t}requireInstance(e){const t=this.controlledInstances.get(e);if(!t){const t=new Error(`Instance ${e} was not found on node ${this.nodeId}.`);throw Object.assign(t,{statusCode:404,code:"NODE_INSTANCE_NOT_FOUND"}),t}const n=ba(t);if(!n.success)throw function(e,t){const n=t.map(e=>`${e.path.join(".")||"body"}: ${e.message}`).join("; ");return Object.assign(new Error(`Stored instance ${e} is not compatible with protocol ${Qi}: ${n}`),{statusCode:409,code:"NODE_INSTANCE_PAYLOAD_INVALID"})}(e,n.error.issues);return n.data}applyInstanceLifecycle(e,t){return this.controlledInstances.put(function(e,t,n=(new Date).toISOString()){switch(t.type){case"start-requested":return Ia.parse({...e,status:"starting",ready:!1,updatedAt:n});case"stop-requested":return Ia.parse({...e,status:"stopping",ready:!1,updatedAt:n});case"stop-failed":return"stopping"!==e.status?e:Ia.parse({...e,status:t.baseline.status,health:t.baseline.health,connectionStatus:t.baseline.connectionStatus,agentStatus:t.baseline.agentStatus,targetStatus:t.baseline.targetStatus,uiAccessStatus:t.baseline.uiAccessStatus,ready:t.baseline.ready,target:{...e.target,status:t.baseline.target.status},updatedAt:n});case"convergence-restart-requested":return Ia.parse({...e,build:void 0,instanceVersion:void 0,ready:!1,updatedAt:n});case"runtime-lifecycle-completed":return function(e,t,n,i){if(t.stateRevision>e.stateRevision&&["failed","stopping","stopped","deleting"].includes(t.status))return t;const s=t.stateRevision>e.stateRevision&&t.lastHeartbeatAt!==e.lastHeartbeatAt&&"online"===t.agentStatus;return Ia.parse({...t,...n,...s?{status:t.status,health:t.health,connectionStatus:t.connectionStatus,agentStatus:t.agentStatus,targetStatus:t.targetStatus,uiAccessStatus:t.uiAccessStatus}:{},ready:!!s&&t.ready,target:n.target?{...t.target,...n.target}:t.target,workspace:n.workspace?s?{...n.workspace,...t.workspace}:{...t.workspace,...n.workspace}:t.workspace,runtime:n.runtime?{...t.runtime,...n.runtime}:t.runtime,updatedAt:i})}(t.baseline,e,t.observation,n);case"stop-completed":return Ia.parse({...e,status:"stopped",health:"unknown",connectionStatus:"offline",ready:!1,agentStatus:"offline",targetStatus:"unknown",uiAccessStatus:"unknown",target:{...e.target,status:"unknown"},updatedAt:n});case"runtime-exited":case"start-failed":return Ia.parse({...e,status:"failed",ready:!1,health:"failed",connectionStatus:"offline",agentStatus:"offline",targetStatus:"unknown",uiAccessStatus:"unknown",workspace:{...e.workspace,error:(i=t.error,i instanceof Error?i.message:String(i))},updatedAt:n})}var i}(this.requireInstance(e),t))}listInstances(){return this.controlledInstances.list().flatMap(e=>{const t=ba(e);return t.success?[t.data]:[]})}resolvedAssignedModelEnvironment(e){return this.modelRegistry.resolvedEnvironment(e)}createInstance(e){const t=this.requireRuntime(e.runtimeId),i=de(),s=e.id||du("inst"),o=function(e){const t=Lo.parse(e);return"local-folder"===t.type?t:Lo.parse({...t,auth:{type:"none"}})}(e.source),r=e.environmentSource||(e.imageSelection?{type:"image",imageSelection:e.imageSelection}:void 0);if("template"===r?.type&&"docker"!==t.type){const e=new Error(`Runtime ${t.name} does not support environment templates.`);throw Object.assign(e,{statusCode:409,code:"ENVIRONMENT_TEMPLATE_RUNTIME_UNSUPPORTED"}),e}const a="template"===r?.type?this.environmentTemplates.get(r.environmentTemplateId):void 0;if("template"===r?.type&&(!a||"ready"!==a.status)){const e=new Error(`Environment template ${r.environmentTemplateId} is not ready on node ${this.nodeId}.`);throw Object.assign(e,{statusCode:a?409:404,code:a?"ENVIRONMENT_TEMPLATE_NOT_READY":"ENVIRONMENT_TEMPLATE_NOT_FOUND"}),e}if(a&&a.nodeId!==this.nodeId){const e=new Error(`Environment template ${a.id} belongs to node ${a.nodeId}, not ${this.nodeId}.`);throw Object.assign(e,{statusCode:409,code:"ENVIRONMENT_TEMPLATE_NODE_MISMATCH"}),e}if(function(e){return"boolean"==typeof e.capabilities.requiresImage?e.capabilities.requiresImage:"local"!==e.type}(t)&&(!r||"image"===r.type&&!e.image)){const e=new Error(`Runtime ${t.name} requires an image.`);throw Object.assign(e,{statusCode:400,code:"NODE_RUNTIME_IMAGE_REQUIRED"}),e}if("local"===t.type&&"local-folder"!==o.type){const e=new Error("Localhost runtime currently supports local folder sources only.");throw Object.assign(e,{statusCode:400,code:"LOCAL_RUNTIME_REQUIRES_LOCAL_FOLDER"}),e}if("local"===t.type&&this.listInstances().some(e=>"local"===this.requireRuntime(e.runtimeId).type)){const e=new Error("A localhost instance already exists on this node.");throw Object.assign(e,{statusCode:409,code:"LOCAL_RUNTIME_INSTANCE_EXISTS"}),e}const c=a?Cr.parse({id:a.id,origin:"custom",name:a.name,repository:"task-handoff/environment-template",tag:a.id.toLowerCase().replace(/[^a-z0-9_.-]/g,"-"),requestedReference:a.internalTag,resolvedDigest:a.imageId,resolvedReference:a.internalTag,downloadSizeBytes:a.sizeBytes||void 0,pullPolicy:"if-not-present",capabilities:[],optionalApps:[],defaultEnv:{},labels:{},createdAt:a.createdAt,updatedAt:a.updatedAt}):e.image?Cr.parse(e.image):void 0,d="local"===t.type&&"local-folder"===o.type?n.resolve(o.path):void 0,l=Ug(o),u=Ia.parse({id:s,name:e.name||`instance-${s.replace(/^inst_?/,"").slice(0,6)}`,source:o,sourceSnapshot:e.sourceSnapshot||{},modelSelection:e.modelSelection,projectId:e.projectId,nodeId:this.nodeId,runtimeId:t.id,imageSelection:"image"===r?.type?r.imageSelection:void 0,environmentSource:r,environmentTemplateOrigin:a?{templateId:a.id,nodeId:a.nodeId,imageId:a.imageId,name:a.name,platform:a.platform,architecture:a.architecture}:void 0,imageSnapshot:c,imageProvisioning:c&&"docker"===t.type&&"template"!==r?.type?{phase:"checking-image",requestedReference:c.requestedReference,generation:0,startedAt:i,updatedAt:i}:void 0,status:c&&"docker"===t.type&&"template"!==r?.type?"provisioning":"created",health:"unknown",connectionStatus:"unknown",agentStatus:"unknown",targetStatus:"unknown",uiAccessStatus:"unknown",controlMode:"controlled",ready:!1,runtimeVersion:bg(),capabilities:{},config:{autoImportAgentConfigs:e.config?.autoImportAgentConfigs??!0,codexConfigEnabled:e.config?.codexConfigEnabled??!0,codexHomeMode:e.config?.codexHomeMode??("local"===t.type?"taskhandoff":"default"),defaultCodexPermissionMode:e.config?.defaultCodexPermissionMode??("docker"===t.type?"full-access":"ask"),...e.config?.codexSettings?{codexSettings:e.config.codexSettings}:{},aiSessionHistoryLimit:e.config?.aiSessionHistoryLimit??50,aiSessionAttachmentRetentionDays:e.config?.aiSessionAttachmentRetentionDays??30,aiSessionMaxFileAttachmentBytes:e.config?.aiSessionMaxFileAttachmentBytes??ke},workspace:"local"===t.type?{mode:"local-bind",status:"unknown",path:d}:"local-folder"===o.type?{status:"unknown"}:{mode:"git-clone",status:"pending",path:l.path,gitProvisioning:{phase:"pending",remoteUrl:o.url,generation:0,startedAt:i,updatedAt:i}},target:{strategy:"node-proxy",status:"unknown"},runtime:"local"===t.type?{kind:"local",workspacePath:d,labels:{"task-handoff.runtime-kind":"local"}}:{labels:{}},registrationToken:lu(),createdAt:i,updatedAt:i}),p=this.persistence.transactionSync(()=>{let t=this.controlledInstances.put(u);const n=e.modelSelection;return n&&Object.values(n).some(e=>Array.isArray(e)?e.length>0:Boolean(e))&&(t=this.modelRegistry.assign(s,{modelSelection:n,modelEntityIds:n.modelEntityIds,codexModelHash:n.codexModelHash,claudeModelHash:n.claudeModelHash,opencodeModelHash:n.opencodeModelHash}).instance),e.gitWorkspaceProvisioning?.credentials.every(e=>"operation-only"===e.retention)&&this.gitCredentials.putWorkspaceProvisioning(e.gitWorkspaceProvisioning),t});return this.instancePrivateConfigs.materialize(p.id,p.registrationToken,this.resolvedAssignedModelEnvironment(p.id),this.modelRegistry.privateCatalog(p.id),p.config.codexSettings),p}takeGitWorkspaceProvisioning(e){const t=this.gitCredentials.getWorkspaceProvisioning(e);return this.gitCredentials.removeWorkspaceProvisioning(e),t}setGitWorkspaceProvisioning(e){const t=this.requireInstance(e.instanceId);if("local-folder"===t.source.type||t.source.url!==e.remoteUrl)throw Object.assign(new Error(`Git provisioning does not match instance ${t.id}.`),{code:"GIT_WORKSPACE_PROVISIONING_INSTANCE_MISMATCH",statusCode:409});this.gitCredentials.putWorkspaceProvisioning(e)}gitWorkspaceProvisioningFor(e){if("local-folder"===e.source.type)return;const t=this.gitCredentials.getWorkspaceProvisioning(e.id);if(t)return t;const n=this.gitCredentials.getAuthorizationSet(e.id).credentialIds.flatMap(e=>{const t=this.gitCredentials.getPayload(e);return t?[t]:[]}),i=n.map(e=>({id:e.credential.id,kind:e.credential.kind,scope:e.credential.scope,status:e.credential.status,pinnedKnownHosts:"ssh-key"===e.secret.kind&&Boolean(e.secret.pinnedKnownHosts.trim())})),s=zi(e.source.url,i);if("ambiguous"===s.status||"missing-host-key"===s.status)throw Object.assign(new Error(`Git credential resolution failed for instance ${e.id}: ${s.status}.`),{code:`GIT_CREDENTIAL_${s.status.replace(/-/g,"_").toUpperCase()}`,statusCode:409});return{operationId:`gitop_${e.id}_${e.stateRevision}`,instanceId:e.id,remoteUrl:e.source.url,ref:e.source.ref,clone:e.source.clone,credentials:n.map((t,n)=>({operationId:`gitcredop_${e.id}_${e.stateRevision}_${n}`,retention:"instance-retained",payload:t}))}}discardGitWorkspaceProvisioning(e){return this.gitCredentials.discardPendingWorkspaceProvisioning(e)}gitWorkspaceProvisioningStatus(e){return this.gitCredentials.workspaceProvisioningStatus(e)}registerInstance(e,t,n){const i=Ra.parse(t),s=de(),o=this.controlledInstances.get(e);if(!o){const t=new Error(`Instance ${e} was not found on node ${this.nodeId}.`);throw Object.assign(t,{statusCode:404,code:"NODE_INSTANCE_NOT_FOUND"}),t}if(this.validateInstanceReport(o,i,n),i.processIncarnationId&&i.processIncarnationId===o.processIncarnationId)return o;Hg(i.protocolVersion,`Instance ${e}`);const r=i.build?.packageVersion||i.instanceVersion,a=Rg(this.requireRuntime(o.runtimeId)),c=Ng(o,r,a),d=Ia.parse({...o,status:"registered",health:r===Tg()?"ok":"degraded",ready:!a&&r===Tg(),connectionStatus:"online",agentStatus:"online",targetStatus:o.targetStatus,uiAccessStatus:o.uiAccessStatus,controlMode:i.controlMode,protocolVersion:i.protocolVersion,instanceVersion:i.instanceVersion,build:i.build,runtimeVersion:c,processIncarnationId:i.processIncarnationId||o.processIncarnationId,capabilities:i.capabilities,appInventory:i.appInventory,workspace:{...i.workspace,...o.workspace.gitProvisioning?{gitProvisioning:o.workspace.gitProvisioning}:{}},target:o.target,registrationToken:o.registrationToken||i.registrationToken,lastHeartbeatAt:s,updatedAt:s});return this.controlledInstances.putObservation(d)}heartbeatInstance(e,t,n){const i=this.requireInstance(e);this.validateInstanceToken(i,n);const s=za.parse(t);i.processIncarnationId&&s.processIncarnationId&&s.processIncarnationId!==i.processIncarnationId&&function(e,t){throw Object.assign(new Error(t),{statusCode:409,code:"INSTANCE_PROCESS_INCARNATION_MISMATCH"})}(0,`Instance ${e} report belongs to an obsolete controlled-instance process.`),Hg(s.protocolVersion,`Instance ${e}`);const o=de(),r=i.target,a=i.targetStatus,c=Ng(i,s.build?.packageVersion||i.build?.packageVersion||i.instanceVersion,Rg(this.requireRuntime(i.runtimeId))),d=s.health||i.health,l="running"===(s.status||i.status)&&"failed"!==d,u=Ia.parse({...i,...s,...s.workspace&&i.workspace.gitProvisioning?{workspace:{...s.workspace,gitProvisioning:i.workspace.gitProvisioning}}:{},target:r,ready:l,health:d,runtimeVersion:c,processIncarnationId:s.processIncarnationId||i.processIncarnationId,agentStatus:"online",targetStatus:a,uiAccessStatus:a,connectionStatus:"online",build:s.build||i.build,lastHeartbeatAt:o,updatedAt:o});return this.controlledInstances.putObservation(u)}validateInstanceReport(e,t,n){this.validateInstanceToken(e,n||t.registrationToken),t.instanceId&&t.instanceId!==e.id&&$g("INSTANCE_ID_MISMATCH",`Instance ${t.instanceId} cannot register as ${e.id}.`),t.nodeId&&t.nodeId!==this.nodeId&&$g("INSTANCE_NODE_MISMATCH",`Instance ${e.id} belongs to node ${this.nodeId}.`),t.runtimeId&&t.runtimeId!==e.runtimeId&&$g("INSTANCE_RUNTIME_MISMATCH",`Instance ${e.id} belongs to runtime ${e.runtimeId}.`),t.imageSelection&&t.imageSelection.imageId!==e.imageSelection?.imageId&&$g("INSTANCE_IMAGE_MISMATCH",`Instance ${e.id} belongs to image ${e.imageSelection?.imageId}.`)}validateInstanceToken(e,t){e.registrationToken&&t===e.registrationToken||$g("INSTANCE_REGISTRATION_TOKEN_INVALID",`Invalid registration token for instance ${e.id}.`)}authenticateInstance(e,t){const n=this.requireInstance(e);return this.validateInstanceToken(n,t),n}context(e,t=this.resolvedAssignedModelEnvironment(e.id)){const n=t,i=e.imageSnapshot||Cr.parse({id:"img_localhost",origin:"custom",name:"Localhost",repository:"localhost",tag:"local",requestedReference:"localhost:local",pullPolicy:"if-not-present",capabilities:[],optionalApps:[],defaultEnv:{},labels:{},createdAt:e.createdAt,updatedAt:e.updatedAt}),s=this.instancePrivateConfigs.materialize(e.id,e.registrationToken,n,this.modelRegistry.privateCatalog(e.id),e.config.codexSettings),o=this.gitWorkspaceProvisioningFor(e);return{project:Fg(e),image:i,node:this.node,runtime:this.requireRuntime(e.runtimeId),instance:e,nodeAgentUrl:this.containerUrl,modelEnv:n,privateConfigPath:this.instancePrivateConfigs.filePath(s.instanceId),...o?{gitWorkspaceProvisioning:o,completeGitWorkspaceProvisioning:()=>this.gitCredentials.completeWorkspaceProvisioning(e.id,o.operationId)}:{}}}}async function Gg(e,t){const n=function(e){const t=Xg(e),n=[],i=t.pathname.split("/").filter(Boolean).at(-1)||"";return tf(n,Wg(t.toString(),/^v\d+$/.test(i)?"models":"v1/models")),tf(n,new URL("/v1/models",t.origin).toString()),tf(n,new URL("/models",t.origin).toString()),n}(t.endpoint),i=Date.now();let s;for(const o of n){const n=await Jg(e,o,{method:"GET",headers:{accept:"application/json",authorization:`Bearer ${t.key}`}});if(404===n.status||405===n.status){s=n.status;continue}if(!n.ok)throw Zg("MODEL_DISCOVERY_FAILED",n.status);const r=await Qg(n,"MODEL_DISCOVERY_RESPONSE_INVALID"),a=Array.isArray(r.data)?r.data:void 0;if(!a)throw ef("MODEL_DISCOVERY_RESPONSE_INVALID","The model endpoint returned an invalid model list.",502);const c=a.flatMap(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return[];const t=e,n="string"==typeof t.id?t.id.trim():"";if(!n)return[];const i="string"==typeof t.owned_by?t.owned_by.trim():"";return[{id:n,...i?{ownedBy:i}:{}}]}).sort((e,t)=>e.id.localeCompare(t.id));return{models:nf(c),latencyMs:Date.now()-i}}throw ef("MODEL_DISCOVERY_UNSUPPORTED","No compatible model-list endpoint was found for this endpoint.",502,s)}async function Kg(e,t){const n=Date.now(),i=t.protocol||("claude"===t.app?"anthropic-messages":"opencode"===t.app?"openai-chat-completions":"openai-responses"),s="openai-responses"===i?await Jg(e,Yg(t.endpoint,"responses"),{method:"POST",headers:{accept:"application/json",authorization:`Bearer ${t.key}`,"content-type":"application/json"},body:JSON.stringify({model:t.model,input:"Reply with OK.",max_output_tokens:32,stream:!1})}):"openai-chat-completions"===i?await Jg(e,Yg(t.endpoint,"chat/completions"),{method:"POST",headers:{accept:"application/json",authorization:`Bearer ${t.key}`,"content-type":"application/json"},body:JSON.stringify({model:t.model,messages:[{role:"user",content:"Reply with OK."}],max_tokens:32,stream:!1})}):await Jg(e,function(e){const t=Xg(e);if(/\/messages\/?$/.test(t.pathname))return t.toString();const n=t.pathname.split("/").filter(Boolean).at(-1)||"";return Wg(t.toString(),/^v\d+$/.test(n)?"messages":"v1/messages")}(t.endpoint),{method:"POST",headers:{accept:"application/json","anthropic-version":"2023-06-01","content-type":"application/json","x-api-key":t.key},body:JSON.stringify({model:t.model,max_tokens:8,messages:[{role:"user",content:"Reply with OK."}]})});if(!s.ok)throw Zg("MODEL_TEST_FAILED",s.status);if((await Qg(s,"MODEL_TEST_RESPONSE_INVALID")).error)throw ef("MODEL_TEST_RESPONSE_INVALID","The model endpoint returned an error payload.",502);return{success:!0,latencyMs:Date.now()-n}}function Wg(e,t){const n=Xg(e);return n.pathname=`${n.pathname.replace(/\/+$/,"")}/${t.replace(/^\/+/,"")}`,n.search="",n.hash="",n.toString()}function Yg(e,t){const n=Xg(e);return n.pathname.replace(/\/+$/,"").endsWith(`/${t}`)?n.toString():Wg(n.toString(),t)}function Xg(e){let t;try{t=new URL(e.trim())}catch{throw ef("MODEL_ENDPOINT_INVALID","The model endpoint must be a valid HTTP or HTTPS URL.",400)}if("http:"!==t.protocol&&"https:"!==t.protocol||t.username||t.password)throw ef("MODEL_ENDPOINT_INVALID","The model endpoint must be an HTTP or HTTPS URL without embedded credentials.",400);return t}async function Jg(e,t,n){try{return await e(t,{...n,redirect:"error",signal:AbortSignal.timeout(15e3)})}catch(e){const t=e&&"object"==typeof e&&"name"in e&&"TimeoutError"===e.name;throw ef(t?"MODEL_ENDPOINT_TIMEOUT":"MODEL_ENDPOINT_UNREACHABLE",t?"The model endpoint timed out.":"The model endpoint could not be reached.",t?504:502)}}async function Qg(e,t){const n=await e.text();if(n.length>1e6)throw ef(t,"The model endpoint response was too large.",502);try{const e=JSON.parse(n);if(!e||"object"!=typeof e||Array.isArray(e))throw new Error("not an object");return e}catch{throw ef(t,"The model endpoint returned invalid JSON.",502)}}function Zg(e,t){return ef(e,401===t||403===t?"The model endpoint rejected the API key.":"The model endpoint rejected the request.",502,t)}function ef(e,t,n,i){return Object.assign(new Error(t),{code:e,statusCode:n,...i?{details:{upstreamStatus:i}}:{}})}function tf(e,t){e.includes(t)||e.push(t)}function nf(e){const t=new Set;return e.filter(e=>!t.has(e.id)&&(t.add(e.id),!0))}const sf=c.z.object({endpoint:c.z.string().trim().url().max(2048),key:c.z.string().trim().min(1).max(4096).optional(),existingModelId:c.z.string().trim().min(1).max(120).optional()}).strict(),of=sf.extend({model:c.z.string().trim().min(1).max(240),app:c.z.enum(["codex","claude","opencode"]).optional(),protocol:c.z.enum(["openai-responses","openai-chat-completions","anthropic-messages"]).optional()}).strict().refine(e=>Boolean(e.protocol||e.app),{message:"A model protocol is required.",path:["protocol"]}),rf="MODEL_RELAY_UNAUTHORIZED",af="MODEL_RELAY_ROUTE_NOT_FOUND",cf="MODEL_RELAY_OPERATION_NOT_ALLOWED",df="MODEL_RELAY_INVALID_REQUEST_MODEL",lf="MODEL_RELAY_UPSTREAM_UNAVAILABLE";function uf(e,t,n,i){return Object.assign(new Error(n),{statusCode:e,code:t,...i?{details:i}:{}})}function pf(e){return 32===e||9===e||10===e||13===e}function mf(e){const t=[];return e<=127?t.push(e):e<=2047?t.push(192|e>>6,128|63&e):e<=65535?t.push(224|e>>12,128|e>>6&63,128|63&e):t.push(240|e>>18,128|e>>12&63,128|e>>6&63,128|63&e),Buffer.from(t)}function hf(e,t){if(t+4>e.length-1)return;const n=e.subarray(t,t+4).toString("ascii");return/^[0-9a-fA-F]{4}$/.test(n)?Number.parseInt(n,16):void 0}function gf(e){if(e.length<2||34!==e[0]||34!==e[e.length-1])return;const t=e.length-1,n=[];let i=1,s=1;for(;s<t;){if(92!==e[s]){s+=1;continue}if(s>i&&n.push(e.subarray(i,s)),s+=1,s>=t)return;const o=e[s],r={34:'"',92:"\\",47:"/",98:"\b",102:"\f",110:"\n",114:"\r",116:"\t"};if(void 0!==r[o]){n.push(r[o]),s+=1,i=s;continue}if(117!==o)return;const a=hf(e,s+1);if(void 0===a)return;if(s+=5,a>=55296&&a<=56319&&s+6<=t&&92===e[s]&&117===e[s+1]){const t=hf(e,s+2);if(void 0!==t&&t>=56320&&t<=57343){n.push(mf(65536+(a-55296<<10)+(t-56320))),s+=6,i=s;continue}}n.push(mf(a)),i=s}return s>i&&n.push(e.subarray(i,s)),Buffer.concat(n.map(e=>"string"==typeof e?Buffer.from(e,"utf8"):e)).toString("utf8")}class ff{paths;onModelValue;onInvalidModelValue;failOnOversizedValue;maxStringBytes;keys=[];containers=[];depth=0;slot="none";valuePath=[];inString=!1;stringRole="value";stringCandidate=!1;stringEscaped=!1;stringBytes=0;stringParts=[];stringStart=-1;stringDiscarded=!1;matchedValue=!1;constructor(e){this.paths=e.paths,this.onModelValue=e.onModelValue,this.onInvalidModelValue=e.onInvalidModelValue,this.failOnOversizedValue=e.failOnOversizedValue??!1,this.maxStringBytes=e.maxStringBytes??1024}get matched(){return this.matchedValue}push(e){return this.scan(e,!1).output}pushUntilMatch(e){return this.scan(e,!0)}scan(e,t){const n=[];let i=0;for(let s=0;s<e.length;s+=1){const o=e[s];if(this.inString){if(this.stringEscaped)this.stringEscaped=!1;else if(92===o)this.stringEscaped=!0;else if(34===o&&(this.finishString(e,s+1,n),i=s+1,t&&this.matchedValue))return{output:n,consumed:s+1}}else if(34!==o){if("value"===this.slot&&this.isModelPath()&&this.onInvalidModelValue&&!pf(o))throw this.onInvalidModelValue();if(123===o?(this.depth+=1,this.containers[this.depth-1]="object",this.keys.length=this.depth,this.keys[this.depth-1]=void 0,this.valuePath=[],this.slot="key"):91===o?(this.depth+=1,this.containers[this.depth-1]="array",this.keys.length=this.depth,this.keys[this.depth-1]=void 0,this.valuePath=[],this.slot="value"):125===o||93===o?(this.depth>0&&(this.depth-=1),this.containers.length=this.depth,this.keys.length=this.depth,this.valuePath=[],this.slot="none"):44===o?this.slot="object"===this.containers[this.depth-1]?"key":"value":58===o?(this.valuePath=[...this.keys.slice(0,this.depth-1),this.keys[this.depth-1]],this.slot="value"):pf(o)||"value"!==this.slot||(this.slot="none"),t&&this.matchedValue)return{output:n,consumed:s+1}}else s>i&&n.push(e.subarray(i,s)),this.startString(s),i=s}return this.inString&&(this.appendStringPart(e.subarray(this.stringStart>=0?this.stringStart:0),n),this.stringStart=-1,i=e.length),i<e.length&&n.push(e.subarray(i)),{output:n,consumed:e.length}}end(){const e=[...this.stringParts];return this.stringParts=[],e}isModelPath(){return this.paths.some(e=>function(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}(this.valuePath,e))}startString(e){this.inString=!0,this.stringEscaped=!1,this.stringBytes=0,this.stringParts=[],this.stringDiscarded=!1,this.stringRole="key"===this.slot&&"object"===this.containers[this.depth-1]?"key":"value",this.stringCandidate="value"===this.stringRole&&this.isModelPath(),this.stringStart=e}appendStringPart(e,t){if(!e.length)return;if(this.stringDiscarded||"key"!==this.stringRole&&!this.stringCandidate)return void t.push(e);this.stringParts.push(e),this.stringBytes+=e.length;const n="key"===this.stringRole?1024:this.maxStringBytes;if(!(this.stringBytes<=n)){if("value"===this.stringRole&&this.failOnOversizedValue&&this.onInvalidModelValue)throw this.onInvalidModelValue();this.stringDiscarded=!0,t.push(...this.stringParts),this.stringParts=[]}}finishString(e,t,n){this.appendStringPart(e.subarray(this.stringStart>=0?this.stringStart:0,t),n),this.stringStart=-1;const i=this.stringParts.length?Buffer.concat(this.stringParts):void 0;this.stringParts=[],this.inString=!1;const s=this.stringRole,o=this.stringCandidate;if(this.stringRole="value",this.stringCandidate=!1,"key"===s)return this.keys[this.depth-1]=i?gf(i):void 0,i&&n.push(i),void(this.slot="none");if(this.slot="none",!o||!i)return void(i&&n.push(i));const r=gf(i);if(void 0!==r)this.matchedValue=!0,n.push(this.onModelValue(r)??i);else{if(this.onInvalidModelValue)throw this.onInvalidModelValue();n.push(i)}}}function yf(e){let t=!1;return n=>{if(void 0!==e.expectedUpstreamName&&void 0!==e.externalName)return n===e.expectedUpstreamName?Buffer.from(JSON.stringify(e.externalName),"utf8"):void(t||(t=!0,e.onMismatch?.()))}}function If(e){return Buffer.isBuffer(e)?e:"string"==typeof e?Buffer.from(e,"utf8"):Buffer.from(e)}function _f(e,t,n){const i=e.subarray(t,n);let s=n;return i.length&&10===i[i.length-1]&&(s-=1),s>t&&13===e[s-1]&&(s-=1),{raw:Buffer.from(i),content:Buffer.from(e.subarray(t,s)),terminator:Buffer.from(e.subarray(s,n))}}function Ef(e,t,n){return f.Readable.from(async function*(){let i=[],s=0;const o=function*(){const e=[],n=[];i.forEach((t,i)=>{const s=function(e){if(e.length<5||"data:"!==e.subarray(0,5).toString("ascii"))return;let t=e.subarray(5);return t.length&&32===t[0]&&(t=t.subarray(1)),t}(t.content);void 0!==s&&(e.push(s),n.push(i))});const s=n.length?function(e,t){if(!e.length)return;const n=1===e.length?e[0]:Buffer.concat(e.flatMap((e,t)=>0===t?[e]:[Buffer.from("\n","utf8"),e]));if(!function(e){for(const t of e)if(32!==t&&9!==t)return 123===t;return!1}(n))return;const i=function(e,t){const n=new ff({paths:t.paths,onModelValue:yf(t)}),i=[...n.push(e),...n.end()];return 1===i.length?i[0]:Buffer.concat(i)}(n,t);if(i.equals(n))return;const s=function(e){const t=[];let n=0;for(let i=0;i<e.length;i+=1)10===e[i]&&(t.push(e.subarray(n,i)),n=i+1);return t.push(e.subarray(n)),t}(i);return s.length===e.length?s:void 0}(e,t):void 0,o=new Map;if(s)for(const[t,r]of n.entries()){const n=i[r],a=n.content.subarray(0,n.content.length-e[t].length);o.set(r,Buffer.concat([a,s[t],n.terminator]))}for(const[e,t]of i.entries())yield o.get(e)??t.raw};for await(const t of async function*(e){let t=Buffer.alloc(0);for await(const n of e){const e=Buffer.isBuffer(n)?n:Buffer.from(n,"utf8"),i=t.length?Buffer.concat([t,e]):e;let s=0,o=0;for(;o<i.length;){const e=i[o];if(10===e)yield _f(i,s,o+1),s=o+1;else if(13===e){if(o+1>=i.length)break;const e=10===i[o+1]?o+2:o+1;yield _f(i,s,e),s=e,o=e-1}o+=1}t=s<i.length?Buffer.from(i.subarray(s)):Buffer.alloc(0)}t.length&&(yield _f(t,0,t.length))}(e)){if(s+=t.raw.length,s>n.maxEventBytes)throw uf(502,"MODEL_RELAY_UPSTREAM_STREAM_ERROR","The upstream SSE event exceeded the relay frame limit.");0!==t.content.length?i.push(t):(yield*o(),i=[],s=0,yield t.raw)}yield*o()}(),{objectMode:!1})}function Af(e){return ar(e.modelNames,e.model).slice().sort((e,t)=>e.order-t.order||e.name.localeCompare(t.name)).map(e=>e.name)}function Tf(e,t,n){return`${e.replace(/\/+$/,"")}${t}${n}`}function wf(e){return{kind:"reject",name:"unknown",status:404,code:cf,message:`The node model relay does not allow this ${e} operation.`}}function bf(e){return JSON.stringify({object:"list",data:Af(e).map(e=>({id:e,object:"model",created:0,owned_by:"task-handoff"}))})}function Nf(e,t,n,i){return{kind:"upstream",name:e,method:t,url:n,responseMode:i}}function Sf(e,t){return{kind:"synthetic",name:e,status:200,headers:{"content-type":"application/json"},body:t}}function vf(e){return{protocol:e.protocol,planOperation:()=>wf(e.protocol),prepareRequest:async({body:e,plan:t,resolveUpstreamModelName:n,maxPrologueBytes:i})=>{if(!e||"GET"===t.method||"HEAD"===t.method)return{};const s=await async function(e){let t,n;const i=new ff({paths:e.paths??[["model"]],maxStringBytes:e.maxStringBytes,failOnOversizedValue:!0,onInvalidModelValue:()=>uf(400,df,"The relay request must contain exactly one top-level string model field."),onModelValue:i=>{if(void 0!==t)throw uf(400,"MODEL_RELAY_AMBIGUOUS_MODEL_NAME","The relay request contains more than one model field.");const s=e.resolveUpstreamModelName(i);return t=i,n=s,s===i?void 0:Buffer.from(JSON.stringify(s),"utf8")}}),s=[];let o=0;const r=t=>{for(const n of t){if(o+=n.length,o>e.maxPrologueBytes)throw uf(413,"MODEL_RELAY_REQUEST_PROLOGUE_TOO_LARGE","The relay request model field was not found within the configured limit.");s.push(n)}},a=async function*(e){for await(const t of e)yield If(t)}(e.body);let c;for(;void 0===t;){const e=await a.next();if(e.done)break;const n=i.pushUntilMatch(e.value);r(n.output),void 0!==t&&(c=e.value.subarray(n.consumed))}if(void 0===t||void 0===n)throw a.return?.(void 0),uf(400,df,"The relay request does not contain a top-level model field.");return{body:f.Readable.from(async function*(){let e=!1;try{for(const e of s)yield e;if(c?.length)for(const e of i.push(c))yield e;for(;;){const t=await a.next();if(t.done){e=!0;break}for(const e of i.push(t.value))yield e}for(const e of i.end())yield e}finally{e||await(a.return?.(void 0))}}(),{objectMode:!1}),externalModelName:t,upstreamModelName:n}}({body:e,resolveUpstreamModelName:n,maxPrologueBytes:i});return{body:s.body,externalModelName:s.externalModelName,upstreamModelName:s.upstreamModelName}},prepareResponse:({body:t,plan:n,externalModelName:i,upstreamModelName:s,maxResponseEventBytes:o,onDiagnostic:r})=>{if("raw"===n.responseMode)return t;const a=void 0!==i&&void 0!==s&&i!==s,c={paths:e.responsePaths,externalName:i,expectedUpstreamName:s,...a?{onMismatch:()=>r?.({code:"MODEL_RELAY_UPSTREAM_MODEL_MISMATCH"})}:{}};return"sse"===n.responseMode?Ef(t,c,{maxEventBytes:o}):function(e,t){const n=new ff({paths:t.paths,onModelValue:yf(t)});return f.Readable.from(async function*(){for await(const t of e)for(const e of n.push(If(t)))yield e;for(const e of n.end())yield e}(),{objectMode:!1})}(t,c)}}}const Of=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","content-length","expect","host","forwarded","x-forwarded-for","x-forwarded-host","x-forwarded-proto","x-forwarded-port","x-real-ip","via","authorization","x-api-key","cookie","x-provider","x-upstream","x-upstream-url","x-target-endpoint","x-api-base-url","x-model-endpoint","x-relay-target","x-original-url","accept-encoding"]),Rf=new Set(["connection","keep-alive","proxy-authenticate","trailer","transfer-encoding","upgrade","content-encoding","content-length","set-cookie","cookie","location","server","x-powered-by"]);function zf(e,t,n){if(void 0===n)return;const i=Array.isArray(n)?n.join(", "):n;i&&(e[t]=i)}function xf(e,t){const n={};for(const[t,i]of Object.entries(e))Of.has(t)||zf(n,t,i);return"anthropic-messages"===t.protocol?(n["x-api-key"]=t.credential,delete n.authorization):(n.authorization=`Bearer ${t.credential}`,delete n["x-api-key"]),n}function Cf(e,t){const n=Number(e);return Number.isFinite(n)&&n>0?Math.floor(n):t}function kf(e=process.env){return{responseHeadersTimeoutMs:Cf(e.TASK_HANDOFF_MODEL_RELAY_HEADER_TIMEOUT_MS,3e5),firstByteTimeoutMs:Cf(e.TASK_HANDOFF_MODEL_RELAY_FIRST_BYTE_TIMEOUT_MS,12e4),idleTimeoutMs:Cf(e.TASK_HANDOFF_MODEL_RELAY_IDLE_TIMEOUT_MS,3e5),maxRequestPrologueBytes:Cf(e.TASK_HANDOFF_MODEL_RELAY_MAX_PROLOGUE_BYTES,262144),maxRequestHeaderBytes:Cf(e.TASK_HANDOFF_MODEL_RELAY_MAX_HEADER_BYTES,16384),maxResponseEventBytes:Cf(e.TASK_HANDOFF_MODEL_RELAY_MAX_EVENT_BYTES,1048576),maxConcurrentRequests:Cf(e.TASK_HANDOFF_MODEL_RELAY_MAX_CONCURRENT,64),maxConcurrentRequestsPerInstance:Cf(e.TASK_HANDOFF_MODEL_RELAY_MAX_CONCURRENT_PER_INSTANCE,8),shutdownDrainMs:Cf(e.TASK_HANDOFF_MODEL_RELAY_SHUTDOWN_DRAIN_MS,5e3)}}class Df{adapters=new Map;constructor(e=[]){for(const t of e)this.register(t)}register(e){this.adapters.set(e.protocol,e)}get(e){return this.adapters.get(e)}protocols(){return[...this.adapters.keys()]}}const Lf="/api/node-agent/model-relay/instances/:instanceId/routes/:routeId/v1",Pf=["GET","POST","HEAD","PUT","PATCH","DELETE"];function Mf(e){return d.createHash("sha256").update(e).digest()}function jf(e){const t=e.authorization;if("string"!=typeof t)return;const n=/^Bearer\s+(.+)$/i.exec(t.trim());return n?.[1]?.trim()||void 0}function Uf(e){const t=e["x-api-key"];return"string"==typeof t&&t.trim()?t.trim():void 0}function Ff(e){const t=e=>{if(!e||"object"!=typeof e)return;const t=e,n="string"==typeof t.name&&/^[A-Za-z][A-Za-z0-9]{0,31}$/.test(t.name)?t.name:void 0,i="string"==typeof t.code&&/^[A-Za-z0-9_]{1,32}$/.test(t.code)?t.code:void 0;return n||i?{name:n,code:i}:void 0},n=t(e),i=t(e?.cause);return{...n?.name?{errorName:n.name}:{},...n?.code?{code:n.code}:{},...i?.name?{causeName:i.name}:{},...i?.code?{causeCode:i.code}:{}}}function $f(e){return new Promise(t=>{const n=()=>{e.off("drain",n),e.off("close",n),t()};e.once("drain",n),e.once("close",n)})}function Hf(e){return new Promise(t=>setTimeout(t,e))}class qf{resolver;adapters;limits;fetchImpl;log;closing=!1;activeTotal=0;activeByInstance=new Map;activeControllers=new Set;constructor(e){this.resolver=e.resolver,this.adapters=new Df(e.adapters),this.limits={...kf(),...e.limits},this.fetchImpl=e.fetchImpl||fetch,this.log=e.log}registerAdapter(e){this.adapters.register(e)}protocolCapabilities(){return this.adapters.protocols()}registerRoutes(e){const t=(e,t)=>this.handle(e,t);e.register(async e=>{e.removeAllContentTypeParsers(),e.addContentTypeParser(/^.*$/,(e,t,n)=>n(null,t));for(const n of[Lf,`${Lf}/*`])e.route({method:[...Pf],url:n,handler:t})}),e.addHook("preClose",async()=>{await this.shutdown()})}async shutdown(){this.closing=!0,await this.drainActive()}async drainActive(){const e=Date.now()+this.limits.shutdownDrainMs;for(;this.activeTotal>0&&Date.now()<e;)await Hf(20);for(const e of this.activeControllers)e.abort()}tryAcquire(e){if(this.closing)throw uf(503,"MODEL_RELAY_SHUTTING_DOWN","The node model relay is shutting down.");return!(this.activeTotal>=this.limits.maxConcurrentRequests||(this.activeByInstance.get(e)||0)>=this.limits.maxConcurrentRequestsPerInstance||(this.activeTotal+=1,this.activeByInstance.set(e,(this.activeByInstance.get(e)||0)+1),0))}release(e){this.activeTotal=Math.max(0,this.activeTotal-1);const t=this.activeByInstance.get(e)||0;t<=1?this.activeByInstance.delete(e):this.activeByInstance.set(e,t-1)}async handle(e,t){const n=Date.now(),i=e.url,s=i.indexOf("?"),o=-1===s?i:i.slice(0,s),r=-1===s?"":i.slice(s),a=tg(o);if(!a)throw uf(404,af,"The requested model relay route does not exist.");if(Object.entries(e.headers).reduce((e,[t,n])=>e+t.length+(Array.isArray(n)?n.join(", ").length:n?.length||0),0)>this.limits.maxRequestHeaderBytes)throw uf(431,"MODEL_RELAY_REQUEST_HEADERS_TOO_LARGE","The relay request headers are too large.");let c;try{c=this.resolver.instance(a.instanceId)}catch{throw uf(404,af,"The requested model relay route does not exist.")}const l=jf(e.headers)??Uf(e.headers);if(!l||(u=l,p=c.registrationToken,!d.timingSafeEqual(Mf(u),Mf(p))))throw uf(401,rf,"Model relay credentials are invalid for this instance.");var u,p;if(!this.tryAcquire(a.instanceId))throw uf(429,"MODEL_RELAY_BUSY","The node model relay is at capacity; retry later.",{retryable:!0});const m={instanceId:a.instanceId,routeId:a.routeId,operation:"unknown",protocol:void 0,modelEntityId:void 0};try{const i=this.resolver.resolveRoute(a.instanceId,a.routeId);if(m.protocol=i.protocol,m.modelEntityId=i.model.id,h=e.headers,!("anthropic-messages"===i.protocol?Uf(h):jf(h)))throw uf(401,rf,"Model relay credentials are invalid for this instance.");const s=this.adapters.get(i.protocol);if(!s)throw uf(404,cf,"The node does not relay this model protocol.");const o=s.planOperation({method:e.method,operationPath:a.operationPath,search:r,model:i.model});if(m.operation=o.name,"reject"===o.kind)throw uf(o.status,o.code,o.message);if("synthetic"===o.kind)return t.code(o.status).headers(o.headers||{}).send(o.body??""),void this.logCompleted(n,{...m,status:o.status,requestBytes:0,responseBytes:o.body?Buffer.byteLength(o.body):0});await this.proxyUpstream(e,t,i,s,o,m,n)}catch(e){const i=e&&"object"==typeof e&&"number"==typeof e.statusCode?e.statusCode:500,s=e&&"object"==typeof e&&"string"==typeof e.code?e.code:"MODEL_RELAY_ERROR";if(this.log?.warn({...m,status:i,code:s,...Ff(e),latencyMs:Date.now()-n,relayEnabled:this.resolver.relayEnabled()},"model relay request failed"),t.raw.headersSent||t.raw.writableEnded)return;throw e}finally{this.release(a.instanceId)}var h}logCompleted(e,t){this.log?.info({...t,latencyMs:Date.now()-e,relayEnabled:this.resolver.relayEnabled()},"model relay request completed")}async proxyUpstream(e,t,n,i,s,o,r){const a=n.model,c=this.allowedUpstreamUrl(s.url,a.endpoint),d="GET"!==e.method&&"HEAD"!==e.method;let l=0;const u=await i.prepareRequest({body:d?e.raw:void 0,plan:s,model:a,resolveUpstreamModelName:e=>this.resolver.resolveUpstreamModelName(a,e),maxPrologueBytes:this.limits.maxRequestPrologueBytes}),p=u.body?function(e){const t=new f.Transform({transform(e,t,n){var i;i=e.length,l+=i,n(null,e)}});return t.on("error",()=>{}),e.once("error",e=>t.destroy(e)),e.pipe(t)}(u.body):void 0,m=new AbortController;let h;this.activeControllers.add(m);const g=()=>{t.raw.writableEnded||(h="client",m.abort())};t.raw.once("close",g);const y=setTimeout(()=>{h="headers-timeout",m.abort()},this.limits.responseHeadersTimeoutMs);let I;try{I=await this.fetchImpl(c,{method:s.method,headers:xf(e.headers,{protocol:n.protocol,credential:a.key}),body:p,...p?{duplex:"half"}:{},redirect:"manual",signal:m.signal})}catch(e){if(clearTimeout(y),t.raw.off("close",g),this.activeControllers.delete(m),"client"===h)return void this.log?.debug({...o,status:499},"model relay client closed before upstream response");if("shutdown"===h||this.closing)return void this.log?.debug({...o,status:503},"model relay aborted for node-agent shutdown");if("headers-timeout"===h)throw uf(504,"MODEL_RELAY_UPSTREAM_TIMEOUT","The upstream model endpoint did not respond in time.",{phase:"headers"});if(e&&"object"==typeof e&&"number"==typeof e.statusCode)throw e;throw uf(502,lf,"The upstream model endpoint could not be reached.")}if(clearTimeout(y),I.status>=300&&I.status<400)throw await(I.body?.cancel().catch(()=>{})),t.raw.off("close",g),this.activeControllers.delete(m),uf(502,"MODEL_RELAY_UPSTREAM_REDIRECT","The upstream model endpoint attempted a redirect.");const _=function(e){const t={};for(const[n,i]of e.entries())Rf.has(n.toLowerCase())||(t[n]=i);return t}(I.headers),E=I.body,A="raw"!==s.responseMode&&/text\/event-stream/i.test(I.headers.get("content-type")||"")?"sse":s.responseMode,T=I.ok&&"raw"!==A&&E?i.prepareResponse({body:E,plan:{...s,responseMode:A},model:a,externalModelName:u.externalModelName,upstreamModelName:u.upstreamModelName,maxResponseEventBytes:this.limits.maxResponseEventBytes,onDiagnostic:e=>this.log?.warn({...o,code:e.code},"model relay response diagnostic")}):E;t.hijack(),t.raw.writeHead(I.status,_);let w,b=0,N=!0,S=0,v=0;const O=()=>{w&&clearTimeout(w),w=setTimeout(()=>{h=N?"first-byte-timeout":"idle-timeout",m.abort()},N?this.limits.firstByteTimeoutMs:this.limits.idleTimeoutMs)};T&&O();const R=()=>({...o,status:I.status,...S?{firstChunkMs:S-r}:{},...v?{lastChunkMs:v-r,msSinceLastChunk:Date.now()-v}:{},upstreamContentType:I.headers.get("content-type")||void 0,upstreamContentEncoding:I.headers.get("content-encoding")||void 0,requestBytes:l,responseBytes:b,relayEnabled:this.resolver.relayEnabled()});let z="completed";try{if(T)for await(const e of T){const n=Date.now();if(N?(N=!1,S=n,O()):O(),v=n,b+=e.length,"client"===h)break;t.raw.write(e)||await $f(t.raw)}z=h||"completed","completed"===z?t.raw.end():t.raw.destroy()}catch(e){return t.raw.destroy(),void this.log?.warn({...R(),reason:h||"upstream-stream-error",...Ff(e),latencyMs:Date.now()-r},"model relay stream interrupted")}finally{w&&clearTimeout(w),t.raw.off("close",g),this.activeControllers.delete(m)}"completed"===z?this.logCompleted(r,{...o,status:I.status,requestBytes:l,responseBytes:b}):this.log?.debug({...R(),reason:z,latencyMs:Date.now()-r},"model relay stream ended")}allowedUpstreamUrl(e,t){let n,i;try{n=new URL(t),i=new URL(e)}catch{throw uf(502,lf,"The assigned model endpoint is not a valid upstream URL.")}if(i.origin!==n.origin)throw uf(502,cf,"The relay operation resolved outside the assigned model endpoint.");return i.toString()}}function Bf(e,t){return Object.assign(new Error(t),{code:e})}function Vf(e,t=process.platform){return"win32"===t&&"host-ipc"===e?"named-pipe":"unix-socket"}function Gf(e){if("string"!=typeof e.scope||!e.scope.trim())throw Bf("LOCAL_IPC_SCOPE_INVALID","A local IPC endpoint requires a non-empty scope.");if("string"!=typeof e.key||!e.key.trim())throw Bf("LOCAL_IPC_KEY_INVALID","A local IPC endpoint requires a non-empty key.");if(void 0!==e.hashLength&&(!Number.isInteger(e.hashLength)||e.hashLength<1||e.hashLength>64))throw Bf("LOCAL_IPC_HASH_LENGTH_INVALID","hashLength must be an integer between 1 and 64.");if(void 0!==e.explicitPath&&(!e.explicitPath.trim()||e.explicitPath.includes("\0")))throw Bf("LOCAL_IPC_PATH_INVALID","explicitPath must be a non-empty path without NUL bytes.");if(void 0!==e.directoryName&&(!e.directoryName.trim()||/[\/\\\0]/.test(e.directoryName)))throw Bf("LOCAL_IPC_DIRECTORY_NAME_INVALID","directoryName must be a non-empty name without path separators or NUL bytes.")}function Kf(e=process.platform,n){if("darwin"===e)return"/private/tmp";if(n)return n;const i=s.tmpdir();try{return t.realpathSync(i)}catch{return i}}function Wf(e,t,n=16){return Gf({scope:e,key:t,hashLength:n}),`${e}-${function(e,t){return d.createHash("sha256").update(e).digest("hex").slice(0,t)}(t,n)}`}function Yf(e,n,i=process.platform){"win32"!==i&&t.chmodSync(e,n)}class Xf{invocations=new Map;store;idleTtlMs;maxTtlMs;cleanupTimer;constructor(e,t={}){this.store=e,this.idleTtlMs=t.idleTtlMs??6e4,this.maxTtlMs=t.maxTtlMs??3e5}resolveHttps(e,t){const{match:n,payload:i}=this.store.resolve(e,t);return"unique"!==n.status||"https-token"!==i?.secret.kind?{status:n.status}:{status:"ok",username:i.secret.username,password:i.secret.token}}async prepareSsh(e,i){this.cleanupExpired();const{match:s,payload:o}=this.store.resolve(e,i);if("unique"!==s.status||"ssh-key"!==o?.secret.kind)return{status:s.status};const r=`gitssh_${d.randomUUID()}`,a=t.mkdtempSync(n.join(Kf(),"task-handoff-node-git-ssh-"));Yf(a,448);const c=function(e,t){Gf({scope:t.scope,key:t.key});const i=t.platform??process.platform;if("named-pipe"===Vf("host-ipc",i))return{path:`\\\\.\\pipe\\${Wf(t.scope,t.key)}`,transport:"named-pipe",kind:"host-ipc",platform:i,filesystemBacked:!1};const s={path:n.join(e,t.fileName??"ipc.sock"),transport:"unix-socket",kind:"host-ipc",platform:i,filesystemBacked:!0};return function(e){if("unix-socket"!==e.transport)return;const t=function(e=process.platform){return"darwin"===e?103:107}(e.platform);if(Buffer.byteLength(e.path)>t)throw Bf("LOCAL_IPC_PATH_TOO_LONG",`Local IPC socket path exceeds the ${t}-byte limit on ${e.platform}: ${e.path}`)}(s),s}(a,{scope:"task-handoff-git-agent",key:r,fileName:"agent.sock"}),l={...process.env,SSH_AUTH_SOCK:c.path};let u;try{const s=await Qf("ssh-agent",["-s","-a",c.path]);if(u=Number(/SSH_AGENT_PID=(\d+)/.exec(s)?.[1]),!Number.isInteger(u)||u<=0)throw new Error("ssh-agent did not report a process id.");await async function(e,i,s,o){if("win32"!==process.platform){const r=n.join(e,"askpass.sh");t.writeFileSync(r,"#!/bin/sh\nprintf '%s' \"${TASK_HANDOFF_SSH_KEY_PASSPHRASE:-}\"\n",{mode:448});try{await Zf("ssh-add",["-"],i,{...o,SSH_ASKPASS:r,SSH_ASKPASS_REQUIRE:"force",DISPLAY:process.env.DISPLAY||":0",TASK_HANDOFF_SSH_KEY_PASSPHRASE:s||""})}finally{t.rmSync(r,{force:!0})}return}const r=n.join(e,"identity");t.writeFileSync(r,i,{mode:384});try{s&&await Qf("ssh-keygen",["-p","-P",s,"-N","","-f",r]),await Qf("ssh-add",[r],o)}finally{t.rmSync(r,{force:!0})}}(a,o.secret.privateKey,o.secret.passphrase,l);const d=await Qf("ssh-add",["-L"],l),p=Date.now();return this.invocations.set(r,{instanceId:e,remoteUrl:i,credentialId:o.credential.id,credentialRevision:o.credential.revision,socketPath:c.path,agentPid:u,directory:a,idleExpiresAt:p+this.idleTtlMs,absoluteExpiresAt:p+this.maxTtlMs}),this.scheduleCleanup(),{status:"ok",invocationId:r,publicIdentity:d,pinnedKnownHosts:o.secret.pinnedKnownHosts}}catch(e){if(u)try{process.kill(u,"SIGTERM")}catch{}throw t.rmSync(a,{recursive:!0,force:!0}),e}}async exchangeAgentFrame(e,t,n){this.cleanupExpired();const i=this.invocations.get(t);if(!i||i.instanceId!==e)throw Jf("GIT_CREDENTIAL_SSH_INVOCATION_INVALID",404);const{match:s,payload:o}=this.store.resolve(e,i.remoteUrl);if("unique"!==s.status||"ssh-key"!==o?.secret.kind||o.credential.id!==i.credentialId||o.credential.revision!==i.credentialRevision)throw this.release(t,e),Jf("GIT_CREDENTIAL_SSH_INVOCATION_REVOKED",403);const r=Buffer.from(n,"base64");if(r.length<5||r.length>1048576||r.readUInt32BE(0)!==r.length-4)throw Jf("GIT_CREDENTIAL_SSH_AGENT_FRAME_INVALID",400);i.idleExpiresAt=Math.min(i.absoluteExpiresAt,Date.now()+this.idleTtlMs),this.scheduleCleanup();const a=Math.max(1,Math.min(i.idleExpiresAt,i.absoluteExpiresAt)-Date.now());try{const e=await function(e,t,n){return new Promise((i,s)=>{const o=g.createConnection(e),r=[];let a=0,c=!1;const d=(e,t)=>{c||(c=!0,o.destroy(),e?s(e):i(t))};o.setTimeout(n),o.once("timeout",()=>d(new Error("Managed Git SSH agent exchange timed out."))),o.once("error",e=>d(e)),o.once("end",()=>d(new Error("Managed Git SSH agent closed before returning a complete frame."))),o.once("close",()=>d(new Error("Managed Git SSH agent closed before returning a complete frame."))),o.on("data",e=>{r.push(e);const t=Buffer.concat(r);!a&&t.length>=4&&(a=t.readUInt32BE(0)+4,a<5||a>1048576)?d(new Error("Managed Git SSH agent returned an invalid frame length.")):a&&t.length>=a&&d(void 0,t.subarray(0,a))}),o.once("connect",()=>o.write(t,e=>{e&&d(e)}))})}(i.socketPath,r,a);return{frame:e.toString("base64")}}catch{throw this.release(t,e),Jf("GIT_CREDENTIAL_SSH_AGENT_UNAVAILABLE",502)}}release(e,n){const i=this.invocations.get(e);if(!i||void 0!==n&&i.instanceId!==n)return!1;this.invocations.delete(e);try{process.kill(i.agentPid,"SIGTERM")}catch{}return t.rmSync(i.directory,{recursive:!0,force:!0}),this.scheduleCleanup(),!0}close(){this.cleanupTimer&&clearTimeout(this.cleanupTimer),this.cleanupTimer=void 0;for(const e of[...this.invocations.keys()])this.release(e)}cleanupExpired(){const e=Date.now();for(const[t,n]of this.invocations)(n.idleExpiresAt<=e||n.absoluteExpiresAt<=e)&&this.release(t)}scheduleCleanup(){this.cleanupTimer&&clearTimeout(this.cleanupTimer),this.cleanupTimer=void 0;const e=Math.min(...[...this.invocations.values()].map(e=>Math.min(e.idleExpiresAt,e.absoluteExpiresAt)));Number.isFinite(e)&&(this.cleanupTimer=setTimeout(()=>{this.cleanupTimer=void 0,this.cleanupExpired(),this.scheduleCleanup()},Math.max(0,e-Date.now())),this.cleanupTimer.unref?.())}}function Jf(e,t){return Object.assign(new Error("Managed Git broker request was rejected."),{code:e,statusCode:t})}function Qf(e,t,n=process.env){return Zf(e,t,void 0,n)}function Zf(e,t,n,i){return new Promise((s,o)=>{const r=l.spawn(e,t,{shell:!1,env:i,stdio:[void 0===n?"ignore":"pipe","pipe","pipe"]}),a=[];r.stdout.on("data",e=>a.push(e)),r.once("error",()=>o(new Error(`Managed Git SSH broker could not start ${e}.`))),r.once("close",t=>0===t?s(Buffer.concat(a).toString("utf8")):o(new Error(`Managed Git SSH broker command ${e} failed.`))),void 0!==n&&r.stdin.end(n)})}const ey=c.z.object({credentialId:c.z.string().trim().min(1).max(120)}).strict(),ty=c.z.object({id:c.z.string().trim().min(1).max(120)}).strict(),ny=ty.extend({invocationId:c.z.string().trim().min(1).max(120)}).strict();function iy(e){const t=e.authorization;return"string"==typeof t&&t.startsWith("Bearer ")?t.slice(7).trim():void 0}const sy=c.z.object({maxIdleAiSessions:c.z.number().int().min(1).max(50).default(5)}).strict(),oy=c.z.string().trim().min(1).max(1024).refine(e=>!e.startsWith("/")&&!e.includes("\\")&&e.split("/").every(e=>e.length>0&&"."!==e&&".."!==e),"Story paths must be normalized relative POSIX paths."),ry=c.z.string().regex(/^[a-f0-9]{64}$/),ay=c.z.object({title:c.z.string().trim().min(1).max(240),storyPath:oy,revision:ry}).strict(),cy=c.z.object({agent:qe.optional(),mode:At.optional(),permissionMode:Tt.optional(),modelSelection:Dt.optional(),reasoningEffort:Lt.optional(),cwdFolderId:c.z.string().trim().min(1).max(120).optional(),gitSelection:Mt.optional(),workspaceSelection:Pt.optional()}).strict().refine(e=>!(e.gitSelection&&e.workspaceSelection),{message:"gitSelection and workspaceSelection are mutually exclusive.",path:["workspaceSelection"]}),dy=c.z.object({id:c.z.string().trim().min(1).max(120),title:c.z.string().trim().min(1).max(120),promptTemplate:c.z.string().trim().min(1).max(32e3),targetInstanceId:c.z.string().trim().min(1).max(120).optional(),sessionPreset:cy.optional()}).strict(),ly=dy.omit({id:!0,targetInstanceId:!0}).extend({targetInstanceId:dy.shape.targetInstanceId.unwrap()}).strict(),uy=ly.extend({id:dy.shape.id.optional()}).strict(),py=c.z.object({targetInstanceId:c.z.string().trim().min(1).max(120),aiSessionId:c.z.string().trim().min(1).max(120)}).strict(),my=c.z.discriminatedUnion("scheduleKind",[c.z.object({scheduleKind:c.z.literal("interval"),intervalMs:c.z.number().int().min(6e4)}).strict(),c.z.object({scheduleKind:c.z.literal("daily"),timeOfDay:c.z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/),timezone:c.z.string().trim().min(1).max(120)}).strict(),c.z.object({scheduleKind:c.z.literal("weekly"),weekdays:c.z.array(c.z.number().int().min(0).max(6)).min(1).max(7).refine(e=>new Set(e).size===e.length,"Weekdays must be unique."),timeOfDay:c.z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/),timezone:c.z.string().trim().min(1).max(120)}).strict(),c.z.object({scheduleKind:c.z.literal("monthly"),dayOfMonth:c.z.number().int().min(-3).max(31).refine(e=>0!==e,"Day of month must not be zero."),timeOfDay:c.z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/),timezone:c.z.string().trim().min(1).max(120)}).strict()]),hy=c.z.object({cooldownMs:c.z.number().int().min(0).max(864e5).optional(),maxConcurrentRuns:c.z.number().int().min(1).max(20).default(1),whenBusy:c.z.enum(["skip","queue"]).default("skip")}).strict(),gy=c.z.object({id:c.z.string().trim().min(1).max(120),storyId:ze,actionId:dy.shape.id,schedule:my,enabled:c.z.boolean().default(!0),policy:hy.default({maxConcurrentRuns:1,whenBusy:"skip"}),createdAt:c.z.string().datetime(),updatedAt:c.z.string().datetime()}).strict(),fy=gy.omit({id:!0,createdAt:!0,updatedAt:!0}).strict(),yy=c.z.object({action:dy.extend({targetInstanceId:dy.shape.targetInstanceId.unwrap()}).strict(),automation:fy.omit({storyId:!0,actionId:!0}).strict()}).strict(),Iy=c.z.object({actionId:gy.shape.actionId.optional(),schedule:my.optional(),enabled:c.z.boolean().optional(),policy:hy.optional()}).strict().refine(e=>Object.keys(e).length>0,"At least one Automation field is required."),_y=c.z.object({code:c.z.string().trim().min(1).max(120),message:c.z.string().trim().min(1).max(2e3)}).strict(),Ey=c.z.enum(["queued","dispatching","running","completed","failed","skipped"]),Ay=c.z.object({id:c.z.string().trim().min(1).max(160),automationId:gy.shape.id,eventType:c.z.enum(["manual","schedule"]),status:Ey,scheduledFor:c.z.string().datetime(),targetInstanceId:c.z.string().trim().min(1).max(120),aiSessionId:c.z.string().trim().min(1).max(120).optional(),error:_y.optional(),queuedAt:c.z.string().datetime(),startedAt:c.z.string().datetime().optional(),completedAt:c.z.string().datetime().optional()}).strict(),Ty=c.z.enum(["disabled","blocked","scheduled","running","error"]),wy=c.z.object({automation:gy,effectiveStatus:Ty,blockedReason:_y.optional(),nextRunAt:c.z.string().datetime().optional(),currentRuns:c.z.array(Ay).max(20).default([]),lastRun:Ay.optional()}).strict(),by=c.z.object({automations:c.z.array(wy).default([])}).strict(),Ny=c.z.object({runs:c.z.array(Ay).max(120).default([])}).strict(),Sy=c.z.object({clientRequestId:Oe}).strict(),vy="story.automation.changed";c.z.object({storyId:ze,automationId:gy.shape.id,change:c.z.enum(["created","updated","deleted","status","run"]),status:wy.optional(),run:Ay.optional()}).strict();const Oy=c.z.enum(["pending","decided","cancelled","expired"]),Ry=c.z.object({id:c.z.string().trim().min(1).max(120),label:c.z.string().trim().min(1).max(240),description:c.z.string().trim().max(2e3).optional()}).strict(),zy=c.z.object({code:c.z.string().trim().min(1).max(120),message:c.z.string().trim().min(1).max(2e3)}).strict(),xy=c.z.object({id:c.z.string().trim().min(1).max(160),storyId:ze,sessionId:c.z.string().trim().min(1).max(120),turnId:c.z.string().trim().min(1).max(240).optional(),question:c.z.string().trim().min(1).max(32e3),options:c.z.array(Ry).max(20).default([]),allowFreeText:c.z.boolean().default(!0),context:c.z.string().trim().max(8e3).optional(),status:Oy,revision:c.z.number().int().min(1),response:c.z.string().trim().max(2e4).optional(),selectedOptionId:c.z.string().trim().min(1).max(120).optional(),decidedTurnId:c.z.string().trim().min(1).max(240).optional(),expiredReason:zy.optional(),createdAt:c.z.string().datetime(),updatedAt:c.z.string().datetime(),decidedAt:c.z.string().datetime().optional()}).strict(),Cy=c.z.object({question:c.z.string().trim().min(1).max(32e3),options:c.z.array(Ry).max(20).optional(),allowFreeText:c.z.boolean().optional(),context:c.z.string().trim().max(8e3).optional()}).strict().superRefine((e,t)=>{const n=e.options||[];new Set(n.map(e=>e.id)).size!==n.length&&t.addIssue({code:c.z.ZodIssueCode.custom,path:["options"],message:"Decision option ids must be unique."}),!1===e.allowFreeText&&0===n.length&&t.addIssue({code:c.z.ZodIssueCode.custom,path:["allowFreeText"],message:"A decision without free text requires at least one option."})}),ky=c.z.object({optionId:c.z.string().trim().min(1).max(120).optional(),response:c.z.string().trim().min(1).max(2e4).optional(),expectedRevision:c.z.number().int().min(1),retry:c.z.boolean().optional()}).strict().refine(e=>Boolean(e.optionId)||Boolean(e.response),{message:"A decision requires a selected option or a free-text response.",path:["response"]}),Dy=c.z.object({expectedRevision:c.z.number().int().min(1)}).strict(),Ly=c.z.object({decisions:c.z.array(xy).default([])}).strict();xy.strip(),c.z.object({decisions:c.z.array(c.z.unknown()).default([])}).strip(),c.z.object({storyId:ze,decisionId:xy.shape.id,revision:c.z.number().int().min(1),change:c.z.enum(["created","decided","cancelled","expired"]),decision:xy.optional()}).strict();const Py=c.z.object({id:ze,ownerNodeId:c.z.string().trim().min(1).max(120),title:c.z.string().trim().min(1).max(240),description:c.z.string().trim().max(4e3).optional(),documents:c.z.array(ay).max(500).default([]),actions:c.z.array(dy).max(50).default([]),createdAt:c.z.string().datetime(),updatedAt:c.z.string().datetime(),archivedAt:c.z.string().datetime().optional()}).strict();c.z.object({stories:c.z.array(Py).default([])}).strict();const My=c.z.object({title:Py.shape.title,description:Py.shape.description,actions:c.z.array(ly).max(50).optional(),maxIdleAiSessions:sy.shape.maxIdleAiSessions.optional()}).strict(),jy=c.z.object({title:Py.shape.title.optional(),description:Py.shape.description.nullable().optional(),actions:c.z.array(uy).max(50).optional(),maxIdleAiSessions:sy.shape.maxIdleAiSessions.optional()}).strict().refine(e=>Object.keys(e).length>0,"At least one Story field is required."),Uy=c.z.object({title:ay.shape.title.optional(),storyPath:oy.optional()}).strict().refine(e=>Object.keys(e).length>0,"At least one document field is required."),Fy=c.z.object({storyPaths:c.z.array(oy).max(500)}).strict();c.z.object({storyPath:oy,title:ay.shape.title.optional(),expectedRevision:ry.optional()}).strict();const $y=c.z.object({documents:c.z.array(ay).max(500)}).strict(),Hy=c.z.union([c.z.number(),c.z.string().regex(/^\d+$/).transform(Number)]),qy=c.z.object({page:Hy.pipe(c.z.number().int().min(1).max(500)).default(1),pageSize:Hy.pipe(c.z.number().int().min(1).max(100)).default(20)}).strict(),By=c.z.object({title:ay.shape.title,storyPath:oy}).strict(),Vy=c.z.object({page:c.z.number().int().min(1).max(500),pageSize:c.z.number().int().min(1).max(100),totalItems:c.z.number().int().nonnegative(),totalPages:c.z.number().int().nonnegative(),hasMore:c.z.boolean()}).strict(),Gy=c.z.object({storyCreatedAt:Py.shape.createdAt,documents:c.z.array(By).max(100),pagination:Vy}).strict();c.z.object({storyCreatedAt:Py.shape.createdAt,documents:c.z.array(By.strip()).max(100),pagination:Vy.strip()}).strip(),c.z.object({storyPath:oy,revision:ry,content:c.z.string(),size:c.z.number().int().nonnegative()}).strict();const Ky=c.z.object({storyPaths:c.z.array(oy).min(1).max(20),destinationPath:c.z.string().trim().min(1).max(4096)}).strict(),Wy=c.z.object({storyPath:oy,title:ay.shape.title.optional(),sourcePath:c.z.string().trim().min(1).max(4096),expectedRevision:ry.optional()}).strict(),Yy=c.z.object({storyPath:oy,path:c.z.string().trim().min(1).max(4096).optional(),revision:ry.optional(),error:c.z.object({code:c.z.string().trim().min(1).max(120),message:c.z.string().trim().min(1).max(2e3)}).strict().optional()}).strict();c.z.object({items:c.z.array(Yy).min(1).max(20)}).strict(),c.z.object({storyId:ze,nodeId:c.z.string().trim().min(1).max(120),change:c.z.enum(["created","updated","archived","restored","deleted","content.written","document.updated","document.reordered","document.deleted"]).optional(),storyPath:oy.optional()}).strict();const Xy=["agent_run"],Jy=c.z.enum(Xy),Qy=c.z.object({agentId:Bu,orchestrationId:gp}).strict(),Zy=c.z.object({enabledTools:c.z.array(Jy).max(Xy.length),allowedTargets:c.z.array(Qy).max(50)}).strict(),eI=c.z.object({agentId:Bu,orchestrationId:gp.optional(),prompt:c.z.string().trim().min(1).max(128e3),budget:Bp.optional()}).strict(),tI=c.z.object({clientRequestId:Oe,input:eI}).strict();function nI(e){const t=[...new Map(e.map(e=>[`${e.agentId}${e.orchestrationId}`,e])).values()].sort((e,t)=>e.agentId===t.agentId?e.orchestrationId.localeCompare(t.orchestrationId):e.agentId.localeCompare(t.agentId));return Zy.parse({enabledTools:t.length?Xy:[],allowedTargets:t})}function iI(e,t){const n=Zy.parse(t);return JSON.stringify(["2026-09-28",e,n.enabledTools,n.allowedTargets])}c.z.object({enabledTools:c.z.array(c.z.string()).max(100).optional(),allowedTargets:c.z.array(Qy).max(50).optional()}).strip(),c.z.enum(["content","actions","automations","aiSessions","decisions"]);const sI=c.z.object({content:c.z.boolean(),actions:c.z.boolean(),automations:c.z.boolean(),aiSessions:c.z.boolean(),decisions:c.z.boolean()}).strict(),oI=Object.freeze({content:!0,actions:!1,automations:!1,aiSessions:!1,decisions:!0}),rI=Object.freeze({content:!1,actions:!1,automations:!1,aiSessions:!1,decisions:!1}),aI=sI.strip().partial();function cI(e){const t=sI.parse(e);return`2026-09-28:${Number(t.content)}${Number(t.actions)}${Number(t.automations)}${Number(t.aiSessions)}${Number(t.decisions)}`}const dI=["story_list_content","story_get_content","story_set_content","story_list_actions","story_run_action","story_list_automations","story_create_automation","story_update_automation","story_delete_automation","story_run_automation","story_list_automation_runs","story_list_ai_sessions","story_get_ai_session","story_get_ai_session_turn","story_request_decision"],lI=c.z.enum(dI),uI=Object.freeze({content:["story_list_content","story_get_content","story_set_content"],actions:["story_list_actions","story_run_action"],automations:["story_list_automations","story_create_automation","story_update_automation","story_delete_automation","story_run_automation","story_list_automation_runs"],aiSessions:["story_list_ai_sessions","story_get_ai_session","story_get_ai_session_turn"],decisions:["story_request_decision"]}),pI=new Set(["story_list_content","story_get_content","story_list_actions","story_list_automations","story_list_automation_runs","story_list_ai_sessions","story_get_ai_session","story_get_ai_session_turn"]);function mI(e,t={}){const n=sI.parse(e),i=Object.keys(uI).filter(e=>n[e]).flatMap(e=>uI[e]);return t.archived?i.filter(e=>pI.has(e)):i}const hI=c.z.object({policy:sI,revision:c.z.string().regex(/^[a-f0-9]{64}$/)}).strict(),gI=c.z.object({policy:sI}).strict(),fI=hI.extend({storyId:ze,enabledTools:c.z.array(lI).max(dI.length),agentInvocation:Zy}).strict(),yI=c.z.object({storyId:ze,revision:hI.shape.revision}).strict();c.z.object({policy:sI.extend({decisions:c.z.boolean().default(!1)}).strip(),revision:hI.shape.revision}).strip().extend({storyId:ze,enabledTools:c.z.array(c.z.string()).max(100),agentInvocation:c.z.unknown().optional()}).strip();const II=c.z.object({page:c.z.number().int().min(1).max(500).default(1),pageSize:c.z.number().int().min(1).max(100).default(20)}).strict(),_I=c.z.object({totalItems:c.z.number().int().nonnegative(),nextPage:c.z.number().int().min(2).max(500).optional()}).strict();function EI(e,t,n){return _I.parse({totalItems:e,...t<500&&t*n<e?{nextPage:t+1}:{}})}const AI=II,TI=c.z.object({documents:c.z.array(c.z.object({title:ay.shape.title,storyPath:oy}).strict()).max(100),pagination:_I}).strict(),wI=c.z.object({items:c.z.array(c.z.object({storyPath:oy,path:c.z.string().trim().min(1).max(4096).optional(),revision:ry.optional(),error:c.z.object({code:c.z.string().trim().min(1).max(120),message:c.z.string().trim().min(1).max(2e3)}).strict().optional()}).strict()).min(1).max(20)}).strict(),bI=c.z.object({title:ay.shape.title,storyPath:oy,revision:ry,size:c.z.number().int().nonnegative()}).strict(),NI=c.z.enum(["STORY_ARCHIVED","STORY_ACTION_TARGET_REQUIRED","STORY_ACTION_TARGET_UNAVAILABLE"]),SI=II,vI=c.z.object({actions:c.z.array(c.z.object({id:dy.shape.id,title:dy.shape.title,promptPreview:c.z.string().max(500),promptTruncated:c.z.boolean(),executable:c.z.boolean(),unavailableReason:NI.optional()}).strict()).max(100),pagination:_I}).strict(),OI=c.z.object({actionId:dy.shape.id,clientRequestId:Oe}).strict(),RI=c.z.object({session:c.z.object({instanceId:c.z.string().trim().min(1).max(120),sessionId:c.z.string().trim().min(1).max(120)}).strict()}).strict(),zI=II,xI=c.z.object({actionId:dy.shape.id,schedule:my,enabled:c.z.boolean().default(!0),policy:hy.default({maxConcurrentRuns:1,whenBusy:"skip"})}).strict(),CI=c.z.object({automationId:c.z.string().trim().min(1).max(120),expectedUpdatedAt:c.z.string().datetime(),actionId:dy.shape.id.optional(),schedule:my.optional(),enabled:c.z.boolean().optional(),policy:hy.optional()}).strict().refine(e=>Object.keys(e).some(e=>!["automationId","expectedUpdatedAt"].includes(e)),"At least one Automation field is required."),kI=c.z.object({automationId:c.z.string().trim().min(1).max(120),expectedUpdatedAt:c.z.string().datetime()}).strict(),DI=c.z.object({automationId:c.z.string().trim().min(1).max(120),clientRequestId:Oe}).strict(),LI=c.z.object({automationId:c.z.string().trim().min(1).max(120),page:II.shape.page,pageSize:II.shape.pageSize}).strict(),PI=c.z.object({deleted:c.z.boolean()}).strict(),MI=c.z.object({id:c.z.string().trim().min(1).max(160),eventType:c.z.enum(["manual","schedule"]),status:Ey,scheduledFor:c.z.string().datetime(),session:c.z.object({instanceId:c.z.string().trim().min(1).max(120),sessionId:c.z.string().trim().min(1).max(120)}).strict().optional(),error:_y.optional(),startedAt:c.z.string().datetime().optional(),completedAt:c.z.string().datetime().optional()}).strict(),jI=c.z.object({id:c.z.string().trim().min(1).max(120),actionId:dy.shape.id,schedule:my,enabled:c.z.boolean(),policy:hy,updatedAt:c.z.string().datetime(),effectiveStatus:Ty,blockedReason:_y.optional(),nextRunAt:c.z.string().datetime().optional(),activeRunCount:c.z.number().int().nonnegative(),lastRun:MI.optional()}).strict(),UI=c.z.object({automations:c.z.array(jI).max(100),pagination:_I}).strict(),FI=c.z.object({runs:c.z.array(MI).max(100),pagination:_I}).strict(),$I=c.z.object({instanceId:c.z.string().trim().min(1).max(120),sessionId:c.z.string().trim().min(1).max(120)}).strict(),HI=II,qI=$I.extend({title:c.z.string().trim().max(240).optional(),agent:c.z.string().trim().min(1).max(120),status:c.z.enum(["running","waiting","idle"]),updatedAt:c.z.string().datetime()}).strict(),BI=c.z.object({sessions:c.z.array(qI).max(100),pagination:_I}).strict(),VI=$I.extend({page:II.shape.page,pageSize:c.z.number().int().min(1).max(50).default(10)}).strict(),GI=c.z.object({detail:Gt,turnIndex:Wt}).strict(),KI=c.z.object({cwd:Gt.shape.cwd,modelName:c.z.string().trim().min(1).max(240).optional(),reasoningEffort:Gt.shape.reasoningEffort,error:Gt.shape.error}).strict(),WI=Bt.pick({id:!0,status:!0,phase:!0,updatedAt:!0,completedAt:!0}).strict(),YI=Bt.pick({id:!0,status:!0,phase:!0,contextCompactions:!0,startedAt:!0,updatedAt:!0,completedAt:!0}).strict(),XI=c.z.object({ref:$I,session:KI,turns:c.z.array(WI).max(50),pagination:_I}).strict(),JI=$I.extend({turnId:c.z.string().trim().min(1).max(240),page:II.shape.page,pageSize:c.z.number().int().min(1).max(50).default(20),maxTextChars:c.z.number().int().min(256).max(32e3).default(8e3)}).strict(),QI=c.z.array(c.z.enum(["text","summary","input","output","paths"])).max(5).optional(),ZI=c.z.object({id:c.z.string().trim().min(1).max(240),truncatedFields:QI}).strict(),e_=ZI.extend({type:c.z.literal("user-message"),text:c.z.string().max(32e3),attachments:c.z.array(Xe).max(6).optional()}).strict(),t_=ZI.extend({type:c.z.literal("ai-message"),text:c.z.string().max(32e3)}).strict(),n_=ZI.extend({type:c.z.literal("activity"),activityKind:c.z.string().trim().min(1).max(120),title:c.z.string().trim().min(1).max(240),status:c.z.enum(["running","completed","failed","waiting"]).optional(),summary:c.z.string().max(32e3).optional(),input:c.z.string().max(32e3).optional(),output:c.z.string().max(32e3).optional(),paths:c.z.array(c.z.string().trim().min(1).max(4096)).max(100).optional(),exitCode:c.z.number().int().optional(),durationMs:c.z.number().int().nonnegative().optional()}).strict(),i_=c.z.discriminatedUnion("type",[e_,t_,n_]),s_=c.z.object({ref:$I,turn:YI,items:c.z.array(i_).max(50),pagination:_I}).strict(),o_=c.z.object({body:Yt,timeline:at}).strict(),r_=c.z.object({detail:Gt.strip(),turnIndex:Wt.strip()}).strip(),a_=c.z.object({body:Yt.strip(),timeline:at.strip()}).strip(),c_=Cy,d_=c.z.object({decisionId:c.z.string().trim().min(1).max(160),status:Oy}).strict(),l_={story_list_content:{input:AI,output:TI},story_get_content:{input:Ky,output:wI},story_set_content:{input:Wy,output:bI},story_list_actions:{input:SI,output:vI},story_run_action:{input:OI,output:RI},story_list_automations:{input:zI,output:UI},story_create_automation:{input:xI,output:jI},story_update_automation:{input:CI,output:jI},story_delete_automation:{input:kI,output:PI},story_run_automation:{input:DI,output:MI},story_list_automation_runs:{input:LI,output:FI},story_list_ai_sessions:{input:HI,output:BI},story_get_ai_session:{input:VI,output:XI},story_get_ai_session_turn:{input:JI,output:s_},story_request_decision:{input:c_,output:d_}},u_=c.z.object({storyId:ze}).strict(),p_=u_.extend({storyPath:c.z.string().min(1).max(2048)}).strict(),m_=u_.extend({automationId:c.z.string().trim().min(1).max(120)}).strict(),h_=c.z.object({id:c.z.string().trim().min(1).max(120),sessionId:c.z.string().trim().min(1).max(120)}).strict(),g_=h_.extend({tool:lI}).strict(),f_=u_.extend({actionId:c.z.string().trim().min(1).max(120)}).strict(),y_=u_.extend({decisionId:c.z.string().trim().min(1).max(160)}).strict(),I_=c.z.object({storyPath:oy}).strict(),__=I_.extend({title:c.z.string().trim().min(1).max(240).optional(),expectedRevision:c.z.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),E_=c.z.object({storyId:ze}).strict();function A_(e){const t=e.authorization;return"string"==typeof t&&t.startsWith("Bearer ")?t.slice(7).trim():void 0}function T_(e){return MI.parse({id:e.id,eventType:e.eventType,status:e.status,scheduledFor:e.scheduledFor,session:e.aiSessionId?{instanceId:e.targetInstanceId,sessionId:e.aiSessionId}:void 0,error:e.error,startedAt:e.startedAt,completedAt:e.completedAt})}function w_(e){return jI.parse({id:e.automation.id,actionId:e.automation.actionId,schedule:e.automation.schedule,enabled:e.automation.enabled,policy:e.automation.policy,updatedAt:e.automation.updatedAt,effectiveStatus:e.effectiveStatus,blockedReason:e.blockedReason,nextRunAt:e.nextRunAt,activeRunCount:e.currentRuns.length,lastRun:e.lastRun?T_(e.lastRun):void 0})}async function b_(e,t,n,i,s){const o=e.authenticateInstance(n,s).aiSessions.sessions.find(e=>e.id===i);if(!o)throw Object.assign(new Error("AI Session was not found in the authoritative instance snapshot."),{code:"AI_SESSION_NOT_FOUND",statusCode:404});if(!o.storyId)throw Object.assign(new Error("AI Session is not assigned to a Story."),{code:"STORY_CONTEXT_REQUIRED",statusCode:409});return await t.get(o.storyId)||(()=>{throw Object.assign(new Error("Story was not found."),{code:"STORY_NOT_FOUND",statusCode:404})})()}function N_(e,t,n,i){return e.header("content-type","application/octet-stream"),e.header("content-length",String(i)),e.header("x-story-revision",n),e.send(t)}function S_(){return Object.assign(new Error("Story Automation belongs to another Story."),{code:"STORY_AUTOMATION_STORY_MISMATCH",statusCode:409})}const v_=c.z.object({agentId:Bu,orchestrationId:gp,status:c.z.enum(["available","missing-reference"])}).strict(),O_=c.z.object({storyId:ze,revision:Vu,entries:c.z.array(v_)}).strict(),R_=c.z.object({expectedRevision:Vu,entries:c.z.array(c.z.object({agentId:Bu,orchestrationId:gp.optional()}).strict()).max(50)}).strict(),z_=["STORY_AGENT_ENTRY_STORY_NOT_FOUND","STORY_AGENT_ENTRY_AGENT_NOT_FOUND","STORY_AGENT_ENTRY_ORCHESTRATION_NOT_FOUND","STORY_AGENT_ENTRY_ORCHESTRATION_MISMATCH","STORY_AGENT_ENTRY_REVISION_CONFLICT"];c.z.enum(z_);const x_=v_.strip();O_.strip().extend({entries:c.z.array(x_)});const C_=c.z.object({agentId:Bu}).strict(),k_=c.z.object({referencingOrchestrations:c.z.enum(["keep","delete"]).optional()}).strict(),D_=c.z.object({orchestrationId:gp}).strict(),L_=c.z.object({runId:Dp}).strict(),P_=c.z.object({runId:Dp,memberId:Lp}).strict(),M_=P_.extend({sessionId:c.z.string().trim().min(1).max(120)}).strict(),j_=c.z.object({storyId:ze}).strict();function U_(e,t,i){const s=e.resolveLocalFolder(i);if(!s)return{status:"unknown-folder"};const o=t.runtime.workspacePath||t.workspace.path||"/workspace";if("local"===e.requireRuntime(t.runtimeId).type){const e=n.resolve(s.path);return{status:"resolved",folderId:s.id,folderPath:e,workspacePath:o,runtimePath:e}}if("local-folder"!==t.source.type)return{status:"unsupported-source"};const r=n.relative(n.resolve(t.source.path),n.resolve(s.path));return".."===r||r.startsWith(`..${n.sep}`)||n.isAbsolute(r)?{status:"outside-workspace"}:{status:"resolved",folderId:s.id,folderPath:n.resolve(s.path),workspacePath:o,runtimePath:r?n.posix.join(o,...r.split(n.sep)):o}}class F_{state;definitions;orchestrations;publish;constructor(e,t,n,i){this.state=e,this.definitions=t,this.orchestrations=n,this.publish=i}list(){return this.definitions.list()}get(e){const t=this.definitions.get(e);if(!t)throw $_("AGENT_DEFINITION_NOT_FOUND",`Agent definition ${e} was not found.`,404);return t}has(e){return Boolean(this.definitions.get(e))}resolveExecution(e){const t=this.get(e),n=this.requireTargetInstance(t.targetInstanceId);if(this.requireFolder(n,t.cwdFolderId),!Is(n.capabilities,t.providerId))throw $_("AGENT_DEFINITION_PROVIDER_UNSUPPORTED",`Instance ${n.id} does not support provider ${t.providerId}.`,409);if(!Xu(t.executionPolicy))throw $_("AGENT_DEFINITION_POLICY_UNSUPPORTED",`Execution policy ${t.executionPolicy.workspaceMaterializer}/${t.executionPolicy.processSandbox} is not published by this Node Agent.`,409);return{definition:t,runtimeType:this.state.requireRuntime(n.runtimeId).type}}create(e){const t=Zu.parse(e),n=du("agent"),i=(new Date).toISOString(),s=this.definitions.transaction(()=>{const e=function(e){return{name:e.name,description:e.description,appendedPrompt:e.appendedPrompt,targetInstanceId:e.targetInstanceId,cwdFolderId:e.cwdFolderId,providerId:e.providerId,modelEntityId:e.modelEntityId,modelName:e.modelName,modelUpstreamName:e.modelUpstreamName,reasoningEffort:e.reasoningEffort,permissionMode:e.permissionMode,executionPolicy:e.executionPolicy??{workspaceMaterializer:"overlay-copy-on-write",processSandbox:"instance"}}}(t);return this.validate(e),{definition:this.definitions.insert({id:n,...e},i),defaultOrchestration:this.orchestrations.insertDefaultForAgent(n,e.name,i)}});return this.definitions.afterCommit(()=>{this.emit("created",s.definition),this.orchestrations.publishChange("created",s.defaultOrchestration)}),s.definition}update(e,t){const n=ep.parse(t),i=(new Date).toISOString(),s=this.definitions.transaction(()=>{const t=this.definitions.get(e);if(!t)return{status:"missing"};const s=function(e,t){const n=(e,t)=>null===e?void 0:void 0===e?t:e;return{name:t.name??e.name,description:null===t.description?"":t.description??e.description,appendedPrompt:null===t.appendedPrompt?"":t.appendedPrompt??e.appendedPrompt,targetInstanceId:t.targetInstanceId??e.targetInstanceId,cwdFolderId:t.cwdFolderId??e.cwdFolderId,providerId:t.providerId??e.providerId,modelEntityId:n(t.modelEntityId,e.modelEntityId),modelName:n(t.modelName,e.modelName),modelUpstreamName:n(t.modelUpstreamName,e.modelUpstreamName),reasoningEffort:n(t.reasoningEffort,e.reasoningEffort),permissionMode:n(t.permissionMode,e.permissionMode),executionPolicy:t.executionPolicy??e.executionPolicy}}(t,n);return this.validate(s),this.definitions.update(e,n.expectedRevision,s,i)});if("missing"===s.status)throw $_("AGENT_DEFINITION_NOT_FOUND",`Agent definition ${e} was not found.`,404);if("revision-conflict"===s.status)throw Object.assign($_("AGENT_DEFINITION_REVISION_CONFLICT","Agent definition changed since it was read.",409),{details:{code:"AGENT_DEFINITION_REVISION_CONFLICT",expectedRevision:n.expectedRevision,actualRevision:s.definition.revision}});return this.definitions.afterCommit(()=>this.emit("updated",s.definition)),s.definition}delete(e,t={}){const n=this.get(e),i=this.definitions.transaction(()=>{const n=this.orchestrations.deleteForAgent(e,t.referencingOrchestrations??"keep");if(this.definitions.delete(e))return n});if(!i)throw $_("AGENT_DEFINITION_NOT_FOUND",`Agent definition ${e} was not found.`,404);return this.definitions.afterCommit(()=>{this.emit("deleted",n);for(const e of i)this.orchestrations.publishChange("deleted",e)}),{deletedOrchestrationIds:i.map(e=>e.id)}}emit(e,t){this.publish?.("agent.definition.changed",{agentId:t.id,change:e,revision:t.revision,definition:t},{})}validate(e){const t=this.requireTargetInstance(e.targetInstanceId);if(this.requireFolder(t,e.cwdFolderId),!Is(t.capabilities,e.providerId))throw $_("AGENT_DEFINITION_PROVIDER_UNSUPPORTED",`Instance ${t.id} does not support provider ${e.providerId}.`,409);if(!Xu(e.executionPolicy))throw $_("AGENT_DEFINITION_POLICY_UNSUPPORTED",`Execution policy ${e.executionPolicy.workspaceMaterializer}/${e.executionPolicy.processSandbox} is not published by this Node Agent.`,409)}requireTargetInstance(e){if(!this.state.controlledInstances.get(e))throw $_("AGENT_DEFINITION_TARGET_INSTANCE_UNKNOWN",`Instance ${e} does not belong to this Node Agent.`,404);return this.state.requireInstance(e)}requireFolder(e,t){const n=U_(this.state,e,t);if("unknown-folder"===n.status)throw $_("AGENT_DEFINITION_FOLDER_UNKNOWN",`Working folder ${t} was not found on this Node Agent.`,404);if("resolved"!==n.status)throw $_("AGENT_DEFINITION_FOLDER_UNKNOWN",`Working folder ${t} cannot be resolved on instance ${e.id}.`,409)}}function $_(e,t,n){if(!ip.includes(e))throw new Error(`Unknown Agent definition error code ${e}.`);return Object.assign(new Error(t),{code:e,statusCode:n})}class H_{orchestrations;definitions;publish;constructor(e,t,n){this.orchestrations=e,this.definitions=t,this.publish=n}list(){return this.orchestrations.list()}get(e){const t=this.orchestrations.get(e);if(!t)throw q_("AGENT_ORCHESTRATION_NOT_FOUND",`Agent orchestration ${e} was not found.`,404);return t}has(e){return Boolean(this.orchestrations.get(e))}find(e){return this.orchestrations.get(e)}containsAgent(e,t){const n=this.orchestrations.get(e);return!!n&&Rp(n,t)}create(e){const t=Ap.parse(e),n=du("orchestration"),i=(new Date).toISOString(),s=this.orchestrations.transaction(()=>(this.validateGraph(t,n),this.orchestrations.insert({id:n,...t},i)));return this.orchestrations.afterCommit(()=>this.publishChange("created",s)),s}update(e,t){const n=Tp.parse(t),i=(new Date).toISOString(),s=this.orchestrations.transaction(()=>{const t=this.orchestrations.get(e);if(!t)return{status:"missing"};const s={name:n.name??t.name,agentIds:n.agentIds??t.agentIds,edges:n.edges??t.edges};return this.validateGraph(s,e,t),this.orchestrations.update(e,n.expectedRevision,s,i)});if("missing"===s.status)throw q_("AGENT_ORCHESTRATION_NOT_FOUND",`Agent orchestration ${e} was not found.`,404);if("revision-conflict"===s.status)throw Object.assign(q_("AGENT_ORCHESTRATION_REVISION_CONFLICT","Agent orchestration changed since it was read.",409),{details:vp.parse({code:"AGENT_ORCHESTRATION_REVISION_CONFLICT",expectedRevision:n.expectedRevision,actualRevision:s.orchestration.revision})});return this.orchestrations.afterCommit(()=>this.publishChange("updated",s.orchestration)),s.orchestration}delete(e){const t=this.get(e);if(Ip(e))throw q_("AGENT_ORCHESTRATION_DEFAULT_PROTECTED","The default orchestration of an Agent cannot be deleted directly; delete the Agent instead.",409);return!!this.orchestrations.delete(e)&&(this.orchestrations.afterCommit(()=>this.publishChange("deleted",t)),!0)}insertDefaultForAgent(e,t,n){return this.orchestrations.insert({id:yp(e),name:t,agentIds:[e],edges:[]},n)}deleteForAgent(e,t){const n=yp(e),i=this.orchestrations.idsReferencingAgent(e),s="delete"===t?i.filter(e=>e===n||!Ip(e)):[],o=[...new Set([n,...s])].flatMap(e=>{const t=this.orchestrations.get(e);return t?[t]:[]});return this.orchestrations.deleteMany(o.map(e=>e.id)),o}publishChange(e,t){this.publish?.("agent.orchestration.changed",{orchestrationId:t.id,change:e,revision:t.revision,orchestration:t},{})}validateGraph(e,t,n){const i=zp(e),s=new Set(i.agentIds);for(const e of i.edges){if(e.fromAgentId===e.toAgentId)throw q_("AGENT_ORCHESTRATION_INVALID_GRAPH","An Agent cannot call itself.",409,{agentId:e.fromAgentId});if(!s.has(e.fromAgentId)||!s.has(e.toAgentId))throw q_("AGENT_ORCHESTRATION_INVALID_GRAPH","Every edge must connect Agents inside the orchestration graph.",409,{fromAgentId:e.fromAgentId,toAgentId:e.toAgentId})}const o=new Set(n?.agentIds??[]);for(const e of i.agentIds)if(!this.definitions.get(e)&&!o.has(e))throw q_("AGENT_ORCHESTRATION_AGENT_UNKNOWN",`Agent definition ${e} was not found on this Node Agent.`,409,{agentId:e});const r=function(e){const t=new Map;for(const n of e.agentIds)t.set(n,[]);for(const n of e.edges)t.get(n.fromAgentId)?.push(n.toAgentId);const n=new Map,i=[],s=e=>{n.set(e,"visiting"),i.push(e);for(const o of t.get(e)??[]){if("visiting"===n.get(o))return[...i.slice(i.indexOf(o)),o];if("visited"===n.get(o))continue;const e=s(o);if(e)return e}i.pop(),n.set(e,"visited")};for(const t of e.agentIds){if(n.has(t))continue;const e=s(t);if(e)return e;i.length=0}}(i);if(r)throw Object.assign(q_("AGENT_ORCHESTRATION_CYCLE",`The orchestration graph would form a cycle: ${r.join(" -> ")}.`,409),{details:{code:"AGENT_ORCHESTRATION_CYCLE",cycle:r}});const a=Ip(t);if(a){if(!this.definitions.get(a))throw q_("AGENT_ORCHESTRATION_DEFAULT_PROTECTED",`The owning Agent ${a} of this default orchestration was not found.`,409,{agentId:a});if(!s.has(a))throw q_("AGENT_ORCHESTRATION_DEFAULT_PROTECTED","A default orchestration must keep its owning Agent in the graph.",409,{agentId:a})}}}function q_(e,t,n,i){return Object.assign(new Error(t),{code:e,statusCode:n,...i?{details:i}:{}})}class B_{state;definitions;orchestrations;runs;supportsExecution;publish;resources;coordinator;constructor(e,t,n,i,s,o,r){this.state=e,this.definitions=t,this.orchestrations=n,this.runs=i,this.supportsExecution=s,this.publish=o,this.resources=r}setCoordinator(e){this.coordinator=e}list(){return this.runs.list().map(e=>this.withSharedSpace(e))}get(e){const t=this.runs.get(e);if(!t)throw G_("AGENT_RUN_NOT_FOUND",`Agent Run ${e} was not found.`,404,{runId:e});return this.withSharedSpace(t)}withSharedSpace(e){const t=this.resources?.getSharedSpace(e.runId);return t?{...e,sharedSpace:{runtimeId:t.runtimeId,state:t.state,usageBytes:t.usageBytes,quotaBytes:t.quotaBytes,...t.expiresAt?{expiresAt:t.expiresAt}:{}}}:e}getMember(e,t){this.get(e);const n=this.runs.getMember(e,t);if(!n)throw G_("AGENT_RUN_MEMBER_NOT_FOUND",`Agent Run member ${t} was not found.`,404,{runId:e,memberId:t});return n}transitionMember(e,t,n){const i=this.get(e),s=this.runs.transitionMember(e,t,n),o=this.get(e);return o.revision!==i.revision&&this.publishMember(o,s),s}resolveMemberInvocationTools(e,t){const n=this.get(e),i=this.requireOrchestrationForRun(n.orchestrationId);return nI(i.edges.filter(e=>e.fromAgentId===t).flatMap(e=>this.definitions.has(e.toAgentId)?[{agentId:e.toAgentId,orchestrationId:i.id}]:[]))}requireOrchestrationForRun(e){const t=this.orchestrations.find(e);if(!t)throw G_("AGENT_RUN_ORCHESTRATION_UNKNOWN",`Agent orchestration ${e} was not found on this Node Agent.`,409,{orchestrationId:e});return t}create(e){const t=nm.parse(e),n=this.runs.getByClientRequestId(t.clientRequestId);if(n){const e=n.members?.find(e=>e.memberId===n.rootMemberId);if(n.orchestrationId===t.orchestrationId&&(void 0===t.entryAgentId||e?.agentId===t.entryAgentId)&&w.isDeepStrictEqual(n.input,t.input)&&w.isDeepStrictEqual(n.provenance,t.provenance)&&w.isDeepStrictEqual(n.budget,V_(t.budget)))return this.withSharedSpace(n);throw G_("AGENT_RUN_IDEMPOTENCY_CONFLICT","The client request id is already associated with a different Agent Run request.",409,{clientRequestId:t.clientRequestId,runId:n.runId})}if("control-plane"!==t.provenance.source&&!this.state.controlledInstances.get(t.provenance.initiatingInstanceId))throw G_("AGENT_RUN_INITIATING_INSTANCE_UNKNOWN",`Initiating instance ${t.provenance.initiatingInstanceId} does not belong to this Node Agent.`,404,{initiatingInstanceId:t.provenance.initiatingInstanceId});const i=this.requireOrchestrationForRun(t.orchestrationId),s=function(e,t){if(t){if(!Rp(e,t))throw G_("AGENT_RUN_ENTRY_INVALID",`Agent ${t} is not part of orchestration ${e.id}.`,409,{orchestrationId:e.id,entryAgentId:t});return t}const n=function(e){const t=new Set(e.edges.map(e=>e.toAgentId));return e.agentIds.filter(e=>!t.has(e))}(e);if(1!==n.length)throw G_("AGENT_RUN_ENTRY_REQUIRED","The orchestration has multiple entry Agents; the request must name one.",409,{orchestrationId:e.id,entryAgentIds:n});return n[0]}(i,t.entryAgentId),{definition:o,runtimeType:r}=this.definitions.resolveExecution(s);if(!this.supportsExecution({targetInstanceId:o.targetInstanceId,runtimeType:r,providerId:o.providerId,permissionMode:o.permissionMode,executionPolicy:o.executionPolicy}))throw G_("AGENT_RUN_EXECUTION_UNSUPPORTED","The target runtime, workspace materializer, process sandbox, and provider combination is not supported.",409,{agentId:o.id,runtimeType:r,providerId:o.providerId,executionPolicy:o.executionPolicy});const a=this.runs.create({clientRequestId:t.clientRequestId,orchestrationId:i.id,input:t.input,provenance:t.provenance,budget:V_(t.budget),root:{agentId:o.id,instanceId:o.targetInstanceId,executionSnapshot:{agentRevision:o.revision,targetInstanceId:o.targetInstanceId,cwdFolderId:o.cwdFolderId,appendedPrompt:o.appendedPrompt,providerId:o.providerId,modelEntityId:o.modelEntityId,modelName:o.modelName,modelUpstreamName:o.modelUpstreamName,reasoningEffort:o.reasoningEffort,permissionMode:o.permissionMode,executionPolicy:o.executionPolicy},input:t.input}});this.publishRun(a);const c=a.members?.find(e=>e.memberId===a.rootMemberId);return c&&this.publishMember(a,c),c&&this.coordinator?.accept(a.runId,c.memberId),this.withSharedSpace(a)}addMember(e){const t=Vp.parse(e.input),n=this.get(e.runId);if("running"!==n.status)throw G_("AGENT_RUN_ALREADY_TERMINAL","Only a running Agent Run can accept another member.",409,{runId:e.runId,status:n.status});const i=this.getMember(e.runId,e.parentMemberId);if("running"!==i.status)throw G_("AGENT_RUN_ALREADY_TERMINAL","Only a running Agent Run member can invoke another Agent.",409,{runId:e.runId,memberId:e.parentMemberId,status:i.status});const s=this.requireOrchestrationForRun(n.orchestrationId);if(!function(e,t,n){return e.edges.some(e=>e.fromAgentId===t&&e.toAgentId===n)}(s,i.agentId,e.agentId))throw G_("AGENT_RUN_INVOCATION_FORBIDDEN","The caller Agent is not authorized to invoke the target Agent in this orchestration.",403,{runId:e.runId,memberId:e.parentMemberId,agentId:e.agentId,orchestrationId:s.id});const{definition:o,runtimeType:r}=this.definitions.resolveExecution(e.agentId);if(!this.supportsExecution({targetInstanceId:o.targetInstanceId,runtimeType:r,providerId:o.providerId,permissionMode:o.permissionMode,executionPolicy:o.executionPolicy}))throw G_("AGENT_RUN_EXECUTION_UNSUPPORTED","The callee execution combination has not passed behavior probing.",409,{agentId:o.id,runtimeType:r,providerId:o.providerId,executionPolicy:o.executionPolicy});const a=this.runs.addMember({runId:n.runId,parentMemberId:i.memberId,clientRequestId:e.clientRequestId,agentId:o.id,instanceId:o.targetInstanceId,input:t,executionSnapshot:{agentRevision:o.revision,targetInstanceId:o.targetInstanceId,cwdFolderId:o.cwdFolderId,appendedPrompt:o.appendedPrompt,providerId:o.providerId,modelEntityId:o.modelEntityId,modelName:o.modelName,modelUpstreamName:o.modelUpstreamName,reasoningEffort:o.reasoningEffort,permissionMode:o.permissionMode,executionPolicy:o.executionPolicy}}),c=this.get(n.runId),d={permissionModeChanged:i.executionSnapshot.permissionMode!==o.permissionMode,workspaceMaterializerChanged:i.executionSnapshot.executionPolicy.workspaceMaterializer!==o.executionPolicy.workspaceMaterializer,processSandboxChanged:i.executionSnapshot.executionPolicy.processSandbox!==o.executionPolicy.processSandbox,providerChanged:i.executionSnapshot.providerId!==o.providerId};return Object.values(d).some(Boolean)&&this.appendTimeline(n.runId,"member.policy-difference",{memberId:a.memberId,data:{parentMemberId:i.memberId,...d}}),this.publishMember(c,a),"queued"===a.status&&this.coordinator?.accept(n.runId,a.memberId),a}transitionRun(e,t){const n=this.runs.transitionRun(e,t);return this.publishRun(n),this.withSharedSpace(n)}appendTimeline(e,t,n={}){const i=this.runs.appendTimeline({runId:e,kind:t,...n});return this.publishRun(this.get(e)),i}toolResult(e){const t=this.get(e);if(mm.has(t.status)){if("completed"===t.status){const n=t.result?.text??"",i=n.slice(0,jp);return Xp.parse({runId:e,status:"completed",result:{text:i,truncated:Boolean(t.result?.truncated)||i.length<n.length}})}return Xp.parse({runId:e,status:t.status,error:t.error??{code:"cancelled"===t.status?"AGENT_RUN_CANCELLED":"AGENT_RUN_FAILED",message:"cancelled"===t.status?"The Agent Run was cancelled.":"The Agent Run failed.",retryable:!1}})}}async waitForToolResult(e,t,n=18e5){const i=Date.now();for(;;){const s=this.toolResult(e);if(s)return s;if(t?.aborted)throw G_("AGENT_RUN_ALREADY_TERMINAL","Waiting for the Agent Run result was aborted.",499,{runId:e});if(Date.now()-i>=n)return Xp.parse({runId:e,status:"failed",error:{code:"AGENT_RUN_RESULT_TIMEOUT",message:"The Agent Run did not reach a terminal state before the tool timeout.",retryable:!0}});await new Promise(e=>{const n=setTimeout(e,100);n.unref?.(),t?.addEventListener("abort",()=>{clearTimeout(n),e()},{once:!0})})}}async waitForMemberToolResult(e,t,n,i=18e5){const s=Date.now();for(;;){const o=this.getMember(e,t);if(mm.has(o.status)){if("completed"===o.status){const t=o.result?.text??"",n=t.slice(0,jp);return Xp.parse({runId:e,status:"completed",result:{text:n,truncated:Boolean(o.result?.truncated)||n.length<t.length}})}return Xp.parse({runId:e,status:o.status,error:o.error??{code:"cancelled"===o.status?"AGENT_RUN_MEMBER_CANCELLED":"AGENT_RUN_MEMBER_FAILED",message:"cancelled"===o.status?"The Agent Run member was cancelled.":"The Agent Run member failed.",retryable:!1}})}if(n?.aborted)throw G_("AGENT_RUN_ALREADY_TERMINAL","Waiting for the Agent Run member was aborted.",499,{runId:e,memberId:t});if(Date.now()-s>=i)return Xp.parse({runId:e,status:"failed",error:{code:"AGENT_RUN_MEMBER_RESULT_TIMEOUT",message:"The Agent Run member did not finish before the tool timeout.",retryable:!0}});await new Promise(e=>{const t=setTimeout(e,100);t.unref?.(),n?.addEventListener("abort",()=>{clearTimeout(t),e()},{once:!0})})}}cancel(e,t){const n=im.parse(t),i=this.get(e);if(void 0!==n.expectedRevision&&n.expectedRevision!==i.revision)throw G_("AGENT_RUN_REVISION_CONFLICT","Agent Run changed since it was read.",409,{runId:e,expectedRevision:n.expectedRevision,actualRevision:i.revision});if("finalizing"===i.status)return i;if(mm.has(i.status))throw G_("AGENT_RUN_ALREADY_TERMINAL","A terminal Agent Run cannot be cancelled.",409,{runId:e,status:i.status});const s=this.runs.transitionRun(e,{status:"finalizing"});return this.coordinator?.cancel?.(e),this.publishRun(s),this.withSharedSpace(s)}publishRun(e){e=this.withSharedSpace(e),this.publish?.("agent.run.changed",{runId:e.runId,revision:e.revision,run:e},{})}publishMember(e,t){this.publish?.("agent.run.member.changed",{runId:e.runId,memberId:t.memberId,revision:e.revision,member:t},{instanceId:t.instanceId})}}function V_(e){return e?{maxMembers:Math.min(e.maxMembers,Mp.maxMembers),maxDepth:Math.min(e.maxDepth,Mp.maxDepth),maxConcurrency:Math.min(e.maxConcurrency,Mp.maxConcurrency)}:{...Mp}}function G_(e,t,n,i){if(!om.includes(e))throw new Error(`Unknown Agent Run service error code ${e}.`);return Object.assign(new Error(t),{code:e,statusCode:n,...i?{details:i}:{}})}class K_{timers=new Map;running=new Map;queued=new Map;lastStartedAt=new Map;accepting=!0;adapter;maxQueuedPerJob;now;constructor(e,t=100,n=Date.now){this.adapter=e,this.maxQueuedPerJob=t,this.now=n}start(){this.accepting=!0}setTimer(e,t){const n=this.timers.get(e);n&&clearTimeout(n),this.timers.set(e,t)}clearTimer(e){const t=this.timers.get(e);t&&clearTimeout(t),this.timers.delete(e)}clearQueued(e,t="job-disabled"){const n=this.queued.get(e);if(n){for(const e of n)this.adapter.skipped(e.event,t);this.queued.delete(e)}}submit(e,t,n){if(!this.accepting)return this.adapter.skipped(t,"scheduler-stopped"),"skipped";const i=this.now(),s=this.lastStartedAt.get(e);if(n.cooldownMs&&void 0!==s&&i-s<n.cooldownMs)return this.adapter.skipped(t,"cooldown"),"skipped";if((this.running.get(e)??0)>=n.maxConcurrentRuns){if("skip"===n.whenBusy)return this.adapter.skipped(t,"busy"),"skipped";const i=this.queued.get(e)??[];return i.length>=this.maxQueuedPerJob?(this.adapter.skipped(t,"queue-full"),"skipped"):(i.push({event:t,policy:n}),this.queued.set(e,i),"queued")}return this.begin(e,t,n),"started"}stop(){this.accepting=!1;for(const e of this.timers.values())clearTimeout(e);this.timers.clear();for(const e of this.queued.values())for(const t of e)this.adapter.skipped(t.event,"scheduler-stopped");this.queued.clear()}begin(e,t,n){this.running.set(e,(this.running.get(e)??0)+1),this.lastStartedAt.set(e,this.now());const i=()=>{const t=(this.running.get(e)??1)-1;t>0?this.running.set(e,t):this.running.delete(e),this.drain(e)};this.adapter.execute(t).then(i,i)}drain(e){if(!this.accepting)return;const t=this.queued.get(e);if(!t?.length)return;const n=t[0];(this.running.get(e)??0)>=n.policy.maxConcurrentRuns||(t.shift(),t.length||this.queued.delete(e),this.begin(e,n.event,n.policy))}}function W_(e,t){return new Date(Date.UTC(e,t+1,0)).getUTCDate()}function Y_(e,t,n,i,s,o){return v.CronExpressionParser.parse(`0 ${i} ${n} ${e} ${t} *`,{currentDate:o,strict:!0,tz:s}).next().toDate()}function X_(e,t,n){return`sch_${d.createHash("sha256").update(`${e}\0${t}\0${n}`).digest("hex").slice(0,32)}`}const J_=/^[a-zA-Z0-9][a-zA-Z0-9_.:-]{0,119}$/;class Q_{entries=new Map;register(e,t){if(e.workspaceMaterializer!==t.kind)throw new Error(`Materializer ${t.kind} cannot be registered as ${e.workspaceMaterializer}.`);const n=this.key(e);if(this.entries.has(n))throw new Error(`Workspace materializer combination ${n} is already registered.`);this.entries.set(n,t)}require(e){const t=this.entries.get(this.key(e));if(t)return t;throw Object.assign(new Error("No workspace materializer is available for the requested execution combination."),{code:"AGENT_RUN_MATERIALIZER_UNAVAILABLE",statusCode:409,details:{...e}})}key(e){return`${e.runtimeType}\0${e.workspaceMaterializer}\0${e.processSandbox}`}}function Z_(e,t){if(!J_.test(e))throw Object.assign(new Error(`${t} is not a safe workspace path segment.`),{code:"AGENT_RUN_WORKSPACE_ID_INVALID",statusCode:400,details:{field:t}});return e}function eE(e,t,i="/run/task-handoff/agent-runs/workspaces"){const s=n.posix.resolve("/",i),o=n.posix.join(s,Z_(e,"runId")),r=n.posix.join(o,Z_(t,"memberId"));return{root:s,runRoot:o,memberRoot:r,cwd:n.posix.join(r,"merged"),markerPath:n.posix.join(r,".task-handoff-agent-run.json")}}function tE(e,t){const i=n.posix.resolve("/",e),s=n.posix.resolve("/",t);if(s===i||s.startsWith(`${i}/`))return s;throw Object.assign(new Error("Agent Run workspace path is outside its owned root."),{code:"AGENT_RUN_WORKSPACE_PATH_OUTSIDE_ROOT",statusCode:400})}function nE(e){return Z_(e.runId,"runId"),Z_(e.memberId,"memberId"),Z_(e.generationId,"generationId"),{version:1,runId:e.runId,memberId:e.memberId,generationId:e.generationId,createdAt:e.createdAt??(new Date).toISOString()}}function iE(e,t="AGENT_RUN_EXECUTION_FAILED"){const n=e&&"object"==typeof e?e:{};return{code:"string"==typeof n.code?n.code:t,message:e instanceof Error?e.message:String(e),retryable:!0===n.retryable}}class sE{runScheduler;memberScheduler;controllers=new Map;activeExecutions=new Set;completionWaiters=new Map;cleanupRetryTimers=new Map;managedRunIds=new Set;options;accepting=!0;constructor(e){this.options=e,this.memberScheduler=new K_({execute:e=>this.trackMemberExecution(e),skipped:(e,t)=>this.failQueued(e,t)}),this.runScheduler=new K_({execute:e=>this.submitRootMember(e),skipped:(e,t)=>this.failQueued(e,t)})}accept(e,t){if(!this.accepting)return this.failQueued(this.event(e,t),"scheduler-stopped");const n=this.event(e,t);if(n.root){if(this.managedRunIds.has(e))return;this.managedRunIds.add(e),this.runScheduler.submit(n.initiatorKey,n,{maxConcurrentRuns:2,whenBusy:"queue"})}else this.memberScheduler.submit(`run:${e}`,n,{maxConcurrentRuns:n.maxConcurrency,whenBusy:"queue"})}cancel(e){this.memberScheduler.clearQueued(`run:${e}`,"job-disabled");for(const[t,n]of this.controllers)t.startsWith(`${e}:`)&&n.abort()}async stop(){this.accepting=!1,this.runScheduler.stop(),this.memberScheduler.stop();for(const e of this.cleanupRetryTimers.values())clearTimeout(e);this.cleanupRetryTimers.clear();for(const e of this.controllers.values())e.abort();await Promise.allSettled([...this.activeExecutions])}async reconcile(){for(const e of this.options.runs.list()){if(mm.has(e.status)){this.managedRunIds.delete(e.runId);continue}if(this.managedRunIds.has(e.runId))continue;const t=this.options.resources.listForRun(e.runId);if("queued"===e.status&&0===t.length){const t=e.members?.find(t=>t.memberId===e.rootMemberId);"queued"===t?.status&&this.accept(e.runId,t.memberId);continue}await this.reconcileInterruptedRun(e.runId)}}async reconcileInterruptedRun(e){const t={code:"AGENT_RUN_NODE_RESTARTED",message:"The Node Agent restarted after this Agent Run began; started members are not executed again.",retryable:!1};let n=this.options.runs.get(e);"finalizing"!==n.status&&(n=this.options.runs.transitionRun(e,{status:"finalizing"}));for(const i of n.members??[])mm.has(i.status)||"finalizing"===i.status||this.options.runs.transitionMember(e,i.memberId,{status:"finalizing",error:t});const i=new Set;for(const t of this.options.resources.listForRun(e))if(t.instanceId&&i.add(t.instanceId),"provider-thread"===t.kind&&"deleted"!==t.phase&&"manual-intervention"!==t.phase)if(t.memberId&&t.instanceId)try{this.options.resources.transition(t.resourceId,"deleting"),await this.options.sessions.close(this.options.state.requireInstance(t.instanceId),e,t.memberId),this.options.resources.transition(t.resourceId,"deleted")}catch(e){this.options.resources.transition(t.resourceId,"delete-retrying",{incrementCleanupAttempts:!0,metadata:{code:"AGENT_RUN_PROVIDER_THREAD_CLOSE_FAILED",message:e instanceof Error?e.message:String(e)}})}else this.options.resources.transition(t.resourceId,"manual-intervention",{metadata:{code:"AGENT_RUN_RESOURCE_OWNERSHIP_UNPROVEN",message:"Provider thread ownership is incomplete."}});for(const e of i)await(this.options.reconcileInstanceResources?.(e).catch(()=>{}));const s=this.options.resources.listForRun(e).filter(e=>"provider-thread"===e.kind||"overlay-mount"===e.kind),o=s.some(e=>"manual-intervention"===e.phase),r=s.some(e=>"deleted"!==e.phase&&"manual-intervention"!==e.phase),a=Math.max(1,...s.map(e=>e.cleanupAttempts));if(r)this.options.runs.transitionRun(e,{status:"finalizing",error:t,cleanup:{status:"retrying",attempts:a,message:"Runtime cleanup will be retried.",updatedAt:(new Date).toISOString()}});else{for(const n of this.options.runs.get(e).members??[])mm.has(n.status)||this.options.runs.transitionMember(e,n.memberId,{status:"failed",error:t});this.options.runs.transitionRun(e,{status:"failed",error:t,cleanup:{status:o?"manual-intervention":"completed",attempts:a,...o?{message:"At least one runtime resource could not be proven to belong to this Agent Run."}:{},updatedAt:(new Date).toISOString()}})}}trackMemberExecution(e){const t=this.executeMember(e);return this.activeExecutions.add(t),t.finally(()=>this.activeExecutions.delete(t)),t}event(e,t){const n=this.options.runs.get(e);return this.options.runs.getMember(e,t),{runId:e,memberId:t,root:n.rootMemberId===t,initiatorKey:"control-plane"===n.provenance.source?`control-plane:${n.provenance.authorizationSubject?.subjectId??"system"}`:`story:${n.provenance.initiatingAiSessionId}`,maxConcurrency:n.budget.maxConcurrency}}async submitRootMember(e){await new Promise(t=>{this.completionWaiters.set(`${e.runId}:${e.memberId}`,t),this.memberScheduler.submit(`run:${e.runId}`,e,{maxConcurrentRuns:e.maxConcurrency,whenBusy:"queue"})})}async executeMember(e){const t=`${e.runId}:${e.memberId}`;if(this.controllers.has(t))return;const n=new AbortController;let i,s,o;this.controllers.set(t,n);let r,a,c,l=!1;try{let t=this.options.runs.get(e.runId),u=this.options.runs.getMember(e.runId,e.memberId);if("finalizing"===t.status)throw Object.assign(new Error("The Agent Run was cancelled before the member started."),{code:"AGENT_RUN_CANCELLED"});e.root&&this.options.runs.transitionRun(t.runId,{status:"preparing"}),u=this.options.runs.transitionMember(t.runId,u.memberId,{status:"preparing"}),this.options.runs.appendTimeline(t.runId,"member.preparing",{memberId:u.memberId}),o=this.options.state.requireInstance(u.instanceId);const p=this.options.state.requireRuntime(o.runtimeId);if("docker"!==p.type)throw Object.assign(new Error("Phase 1 Agent Run execution requires a Docker Runtime."),{code:"AGENT_RUN_RUNTIME_UNSUPPORTED"});const m=U_(this.options.state,o,u.executionSnapshot.cwdFolderId);if("resolved"!==m.status)throw Object.assign(new Error("The Agent working folder is no longer available in the target instance."),{code:"AGENT_RUN_FOLDER_UNAVAILABLE"});const h=`generation_${d.randomBytes(12).toString("hex")}`;e.root&&await this.options.sharedSpaces.ensure({runId:t.runId,runtimeId:p.id,instanceId:o.id,generationId:h}),this.options.sharedSpaces.bindingForMember(t.runId,p.id),s=this.options.materializers.require({runtimeType:p.type,workspaceMaterializer:u.executionSnapshot.executionPolicy.workspaceMaterializer,processSandbox:u.executionSnapshot.executionPolicy.processSandbox}),i=await s.prepare({runId:t.runId,memberId:u.memberId,generationId:h,runtimeId:p.id,instanceId:o.id,sourceRuntimePath:m.runtimePath,executionSnapshot:u.executionSnapshot});const g=this.options.sharedSpaces.pathPolicyForMember(t.runId,p.id,i.layout.cwd),f=this.options.runs.resolveMemberInvocationTools(t.runId,u.agentId),y=u.executionSnapshot.modelEntityId&&u.executionSnapshot.modelName?{modelEntityId:u.executionSnapshot.modelEntityId,modelName:u.executionSnapshot.modelName,modelUpstreamName:u.executionSnapshot.modelUpstreamName}:void 0;if(!u.input)throw Object.assign(new Error("The Agent Run member has no frozen input."),{code:"AGENT_RUN_MEMBER_INPUT_MISSING"});const I=await this.options.sessions.create(o,{runId:t.runId,memberId:u.memberId,clientRequestId:`agent_member_${u.memberId}`,providerId:u.executionSnapshot.providerId,cwd:{type:"runtime-path",path:g.cwd},writableRoots:{workspace:{type:"runtime-path",path:g.writableRoots[0]},shared:{type:"runtime-path",path:g.writableRoots[1]}},prompt:u.input.prompt,appendedPrompt:u.executionSnapshot.appendedPrompt,permissionMode:u.executionSnapshot.permissionMode||"auto-review",modelSelection:y,reasoningEffort:u.executionSnapshot.reasoningEffort,enabledTools:f.enabledTools});l=!0;const _=this.options.resources.register({runId:t.runId,memberId:u.memberId,instanceId:o.id,runtimeId:p.id,kind:"provider-thread",generationId:h,backendIdentity:I.providerSessionId,metadata:{aiSessionId:I.aiSessionId,providerId:u.executionSnapshot.providerId}});for(r=_.resourceId,this.options.resources.transition(_.resourceId,"ready"),this.options.runs.transitionMember(t.runId,u.memberId,{status:"running",aiSessionId:I.aiSessionId}),e.root&&this.options.runs.transitionRun(t.runId,{status:"running"}),this.options.runs.appendTimeline(t.runId,"member.running",{memberId:u.memberId});!n.signal.aborted&&(t=this.options.runs.get(t.runId),"finalizing"!==t.status);){const e=await this.options.sessions.status(o,t.runId,u.memberId);if(await this.options.sharedSpaces.refreshUsage(t.runId,o.id),"completed"===e.status){a=e.result;break}if("failed"===e.status){c=e.error;break}await new Promise(e=>setTimeout(e,this.options.pollIntervalMs??250))}a||c||(c={code:"AGENT_RUN_CANCELLED",message:"The Agent Run member was cancelled.",retryable:!1})}catch(e){c=iE(e)}finally{await this.finalizeMember(e,o,l,r,s,i,a,c),this.controllers.delete(t),this.complete(e)}}async finalizeMember(e,t,n,i,s,o,r,a){const c=`${e.runId}:${e.memberId}`;let d;this.cleanupRetryTimers.delete(c);const l=this.options.runs.getMember(e.runId,e.memberId),u=mm.has(l.status);try{if(u||"finalizing"===l.status||this.options.runs.transitionMember(e.runId,e.memberId,{status:"finalizing"}),!u&&n&&t){i&&this.options.resources.transition(i,"deleting");try{await this.options.sessions.close(t,e.runId,e.memberId),i&&this.options.resources.transition(i,"deleted")}catch(e){throw i&&this.options.resources.transition(i,"delete-retrying",{incrementCleanupAttempts:!0,metadata:{code:"AGENT_RUN_PROVIDER_THREAD_CLOSE_FAILED",message:e instanceof Error?e.message:String(e)}}),e}}!u&&o&&s&&await s.dispose(o,nE({runId:e.runId,memberId:e.memberId,generationId:o.generationId}))}catch(e){d=iE(e,"AGENT_RUN_CLEANUP_FAILED")}const p="finalizing"===this.options.runs.get(e.runId).status&&"AGENT_RUN_CANCELLED"===a?.code;if(d){if(u||this.options.runs.transitionMember(e.runId,e.memberId,{status:"finalizing",...r?{result:r}:{},...a?{error:a}:{}}),e.root){const t=this.options.runs.get(e.runId);"finalizing"!==t.status&&this.options.runs.transitionRun(e.runId,{status:"finalizing"});const n=(t.cleanup?.attempts??0)+1;this.options.runs.transitionRun(e.runId,{status:"finalizing",cleanup:{status:"retrying",attempts:n,message:d.message,updatedAt:(new Date).toISOString()}}),this.options.runs.appendTimeline(e.runId,"run.cleanup-retrying",{memberId:e.memberId,data:{code:d.code,attempts:n}})}return void this.scheduleCleanupRetry(e,t,n,i,s,o,r,a)}const m=a?p?"cancelled":"failed":"completed";if(u||(this.options.runs.transitionMember(e.runId,e.memberId,{status:m,..."completed"===m?{result:r}:{error:a}}),this.options.runs.appendTimeline(e.runId,`member.${m}`,{memberId:e.memberId})),!e.root)return;const h=this.options.runs.get(e.runId);"finalizing"!==h.status&&this.options.runs.transitionRun(e.runId,{status:"finalizing"});try{this.options.sharedSpaces.retain(e.runId)}catch(n){d=iE(n,"AGENT_RUN_SHARED_SPACE_RETAIN_FAILED");const i=(h.cleanup?.attempts??0)+1;return this.options.runs.transitionRun(e.runId,{status:"finalizing",cleanup:{status:"retrying",attempts:i,message:d.message,updatedAt:(new Date).toISOString()}}),void this.scheduleCleanupRetry(e,t,!1,void 0,void 0,void 0,r,a)}const g={status:"completed",attempts:(h.cleanup?.attempts??0)+1,updatedAt:(new Date).toISOString()},f=a?p?"cancelled":"failed":"completed";this.options.runs.transitionRun(e.runId,{status:f,..."completed"===f?{result:r}:{error:a},cleanup:g}),this.managedRunIds.delete(e.runId)}scheduleCleanupRetry(e,t,n,i,s,o,r,a){if(!this.accepting)return;const c=`${e.runId}:${e.memberId}`;if(this.cleanupRetryTimers.has(c))return;const d=this.options.runs.get(e.runId).cleanup?.attempts??1,l=Math.min((this.options.cleanupRetryBaseMs??1e3)*2**Math.min(d-1,6),6e4),u=setTimeout(()=>{this.cleanupRetryTimers.delete(c);const d=this.finalizeMember(e,t,n,i,s,o,r,a);this.activeExecutions.add(d),d.finally(()=>this.activeExecutions.delete(d))},l);u.unref?.(),this.cleanupRetryTimers.set(c,u)}failQueued(e,t){try{if("queued"!==this.options.runs.getMember(e.runId,e.memberId).status)return;this.options.runs.transitionMember(e.runId,e.memberId,{status:"finalizing"});const n={code:"AGENT_RUN_SCHEDULER_STOPPED",message:`Agent Run scheduling stopped: ${t}.`,retryable:"scheduler-stopped"===t};this.options.runs.transitionMember(e.runId,e.memberId,{status:"failed",error:n}),e.root&&("finalizing"!==this.options.runs.get(e.runId).status&&this.options.runs.transitionRun(e.runId,{status:"finalizing"}),this.options.runs.transitionRun(e.runId,{status:"failed",error:n,cleanup:{status:"completed",attempts:0,updatedAt:(new Date).toISOString()}}),this.managedRunIds.delete(e.runId))}catch{}finally{this.complete(e)}}complete(e){const t=`${e.runId}:${e.memberId}`,n=this.completionWaiters.get(t);n&&(this.completionWaiters.delete(t),n())}}const oE=c.z.union([lI,Jy]),rE=c.z.object({type:c.z.literal("runtime-path"),path:c.z.string().trim().min(1).max(4096).refine(e=>e.startsWith("/"),"Agent Run runtime paths must be absolute POSIX paths.")}).strict(),aE=c.z.object({runId:Dp,memberId:Lp,clientRequestId:Oe,providerId:qe,cwd:rE,writableRoots:c.z.object({workspace:rE,shared:rE}).strict(),prompt:c.z.string().trim().min(1).max(128e3),appendedPrompt:c.z.string().max(32e3),permissionMode:Tt.optional(),modelSelection:Dt.optional(),reasoningEffort:Lt.optional(),enabledTools:c.z.array(oE).max(100).default([])}).strict().superRefine((e,t)=>{e.cwd.path!==e.writableRoots.workspace.path&&t.addIssue({code:"custom",path:["writableRoots","workspace"],message:"The workspace writable root must be the member cwd."}),e.writableRoots.workspace.path===e.writableRoots.shared.path&&t.addIssue({code:"custom",path:["writableRoots"],message:"Workspace and shared roots must be distinct."})}),cE=c.z.object({disposition:c.z.enum(["created","already-created"]),aiSessionId:c.z.string().trim().min(1).max(120),providerSessionId:c.z.string().trim().min(1).max(240)}).strict(),dE=c.z.object({runId:Dp,memberId:Lp,aiSessionId:c.z.string().trim().min(1).max(120),status:c.z.enum(["running","completed","failed"]),result:Wp.optional(),error:Kp.optional()}).strict().superRefine((e,t)=>{"completed"!==e.status||e.result||t.addIssue({code:"custom",path:["result"],message:"Completed member status requires a result."}),"failed"!==e.status||e.error||t.addIssue({code:"custom",path:["error"],message:"Failed member status requires an error."})}),lE=c.z.object({runId:Dp,memberId:Lp,aiSessionId:c.z.string().trim().min(1).max(120),closed:c.z.boolean()}).strict(),uE=c.z.object({ordinaryAiSessionIds:c.z.array(c.z.string().trim().min(1).max(120)).max(1e4)}).strict();function pE(e,t,n,i){return Object.assign(new Error(t,void 0===i?void 0:{cause:i}),{code:e,statusCode:n})}class mE{fetchImpl;resolveInstanceWeb;constructor(e,t){this.fetchImpl=e,this.resolveInstanceWeb=t}async create(e,t){const n=aE.parse({...t,...t.modelSelection?{modelSelection:_s(e.capabilities,t.providerId,t.modelSelection)}:{}});return cE.parse(await this.request(e,"/api/internal/node-agent/agent-runs/members",{method:"POST",body:n}))}async status(e,t,n){return dE.parse(await this.request(e,`/api/internal/node-agent/agent-runs/${encodeURIComponent(t)}/members/${encodeURIComponent(n)}`,{method:"GET"}))}async close(e,t,n){return lE.parse(await this.request(e,`/api/internal/node-agent/agent-runs/${encodeURIComponent(t)}/members/${encodeURIComponent(n)}/close`,{method:"POST",body:{}}))}async probeState(e){return uE.parse(await this.request(e,"/api/internal/node-agent/agent-runs/probe-state",{method:"GET"}))}async request(e,t,n){if(!e.registrationToken)throw pE("AGENT_RUN_INSTANCE_CREDENTIAL_MISSING","Target instance has no registration credential.",503);let i;try{i=await this.fetchImpl(`${await this.resolveInstanceWeb(e)}${t}`,{method:n.method,headers:{authorization:`Bearer ${e.registrationToken}`,"content-type":"application/json"},...void 0===n.body?{}:{body:JSON.stringify(n.body)}})}catch(e){throw pE("AGENT_RUN_INSTANCE_UNAVAILABLE","Target instance is temporarily unavailable.",503,e)}const s=await i.json().catch(()=>({}));if(!i.ok)throw pE(s.error?.code||"AGENT_RUN_INSTANCE_REQUEST_FAILED",s.error?.message||`Target instance returned HTTP ${i.status}.`,i.status);return s.data}}const hE=10737418240;function gE(e,t,i){const s=Dp.parse(e),o=n.posix.resolve("/",i);return{runId:s,runtimeId:t,runtimePath:n.posix.join(o,s)}}class fE{repository;backend;root;constructor(e,t,n){this.repository=e,this.backend=t,this.root=n}async ensure(e){const t=this.repository.runtimeSharedSpaceUsage(e.runtimeId,e.runId);if(t>=hE)throw Object.assign(new Error("The Agent Run runtime shared-space quota is exhausted."),{code:"AGENT_RUN_SHARED_RUNTIME_QUOTA_EXCEEDED",statusCode:409,details:{runtimeId:e.runtimeId,usageBytes:t,quotaBytes:hE}});this.repository.ensureSharedSpace({...e,quotaBytes:1073741824});const n=gE(e.runId,e.runtimeId,this.root);try{const t=await this.backend.ensureRunDirectory({...e,runtimePath:n.runtimePath}),i=this.repository.updateSharedSpace(e.runId,{state:"active",diagnostics:t,timestamp:e.timestamp});return this.repository.register({runId:e.runId,instanceId:e.instanceId,runtimeId:e.runtimeId,kind:"shared-space-directory",generationId:e.generationId,backendIdentity:n.runtimePath,metadata:{runtimePath:n.runtimePath},timestamp:e.timestamp}),{space:i,binding:n}}catch(t){throw this.repository.updateSharedSpace(e.runId,{state:"delete-retrying",diagnostics:{code:"AGENT_RUN_SHARED_SPACE_PREPARE_FAILED",message:t instanceof Error?t.message:String(t)},timestamp:e.timestamp}),Object.assign(new Error("Could not prepare the Agent Run shared space.",{cause:t}),{code:"AGENT_RUN_SHARED_SPACE_PREPARE_FAILED",statusCode:409})}}bindingForMember(e,t){const n=this.repository.getSharedSpace(e);if(!n)throw Object.assign(new Error("The Agent Run shared space was not found."),{code:"AGENT_RUN_SHARED_SPACE_NOT_FOUND",statusCode:404});return function(e,t){if(e.runtimeId!==t)throw Object.assign(new Error("The member runtime cannot access this Agent Run shared space."),{code:"AGENT_RUN_SHARED_RUNTIME_MISMATCH",statusCode:409,details:{runId:e.runId,sharedRuntimeId:e.runtimeId,memberRuntimeId:t}})}(n,t),gE(e,t,this.root)}pathPolicyForMember(e,t,i){return function(e,t){if(!n.posix.isAbsolute(t))throw Object.assign(new Error("The Agent Run workspace cwd must be an absolute runtime path."),{code:"AGENT_RUN_WORKSPACE_PATH_INVALID",statusCode:400});return{cwd:n.posix.resolve(t),writableRoots:[n.posix.resolve(t),e.runtimePath]}}(this.bindingForMember(e,t),i)}retain(e,t=new Date){const n=new Date(t.getTime()+6048e5).toISOString();return this.repository.updateSharedSpace(e,{state:"retained",expiresAt:n,timestamp:t.toISOString()})}async refreshUsage(e,t,n=new Date){const i=this.repository.getSharedSpace(e);if(!i)throw Object.assign(new Error("The Agent Run shared space was not found."),{code:"AGENT_RUN_SHARED_SPACE_NOT_FOUND",statusCode:404});if(!this.backend.inspectRunDirectory)throw Object.assign(new Error("The shared-space backend cannot report usage."),{code:"AGENT_RUN_SHARED_USAGE_UNAVAILABLE",statusCode:409});const s=gE(e,i.runtimeId,this.root),o=await this.backend.inspectRunDirectory({runId:e,generationId:i.generationId,runtimeId:i.runtimeId,instanceId:t,runtimePath:s.runtimePath}),r=this.repository.runtimeSharedSpaceUsage(i.runtimeId,e)+o.usageBytes,a={...i.diagnostics,usageBytes:o.usageBytes,runQuotaBytes:i.quotaBytes,runtimeUsageBytes:r,runtimeQuotaBytes:hE,measuredAt:n.toISOString()};if(this.repository.updateSharedSpace(e,{usageBytes:o.usageBytes,diagnostics:a,timestamp:n.toISOString()}),o.usageBytes>i.quotaBytes)throw Object.assign(new Error("The Agent Run shared-space quota is exhausted."),{code:"AGENT_RUN_SHARED_RUN_QUOTA_EXCEEDED",statusCode:409,details:{runId:e,usageBytes:o.usageBytes,quotaBytes:i.quotaBytes}});if(r>hE)throw Object.assign(new Error("The Agent Run runtime shared-space quota is exhausted."),{code:"AGENT_RUN_SHARED_RUNTIME_QUOTA_EXCEEDED",statusCode:409,details:{runtimeId:i.runtimeId,usageBytes:r,quotaBytes:hE}});return this.repository.getSharedSpace(e)}async reconcileExpired(e=new Date){const t=this.repository.listSharedSpaces({expiredBefore:e.toISOString()}),n=[];for(const i of t){if("retained"!==i.state&&"delete-retrying"!==i.state)continue;const t=this.repository.listForRun(i.runId).find(e=>"shared-space-directory"===e.kind);if(t&&t.instanceId){this.repository.updateSharedSpace(i.runId,{state:"expiring",timestamp:e.toISOString()});try{if(!this.backend.removeRunDirectory)throw Object.assign(new Error("Shared-space backend does not support expiry cleanup."),{code:"AGENT_RUN_SHARED_SPACE_CLEANUP_UNSUPPORTED"});await this.backend.removeRunDirectory({runId:i.runId,generationId:t.generationId,runtimeId:i.runtimeId,instanceId:t.instanceId,runtimePath:String(t.metadata.runtimePath??t.backendIdentity)}),this.repository.updateSharedSpace(i.runId,{state:"expired",usageBytes:0,timestamp:e.toISOString()}),this.repository.transition(t.resourceId,"deleted",{timestamp:e.toISOString()}),n.push({runId:i.runId,status:"expired"})}catch(s){this.repository.updateSharedSpace(i.runId,{state:"delete-retrying",diagnostics:{code:"AGENT_RUN_SHARED_SPACE_CLEANUP_FAILED",message:s instanceof Error?s.message:String(s)},timestamp:e.toISOString()}),this.repository.transition(t.resourceId,"delete-retrying",{incrementCleanupAttempts:!0,timestamp:e.toISOString()}),n.push({runId:i.runId,status:"retrying"})}}else this.repository.updateSharedSpace(i.runId,{state:"manual-intervention",diagnostics:{code:"AGENT_RUN_SHARED_SPACE_OWNERSHIP_UNPROVEN"},timestamp:e.toISOString()}),n.push({runId:i.runId,status:"manual-intervention"})}return n}}const yE=["SYS_ADMIN","SYS_PTRACE","SYS_CHROOT","DAC_OVERRIDE","CHOWN"];function IE(e,t,n,i){return Object.assign(new Error(t,void 0===n?void 0:{cause:n}),{code:e,statusCode:409,...i?{details:i}:{}})}class _E{kind="overlay-copy-on-write";runCommand;resources;targetForInstance;terminateMemberThread;helperImage;constructor(e,t,n,i=async()=>{},s="ghcr.io/edgestorage/task-handoff-agent-run-overlay-helper:1"){this.runCommand=e,this.resources=t,this.targetForInstance=n,this.terminateMemberThread=i,this.helperImage=s}async prepare(e){if("overlay-copy-on-write"!==e.executionSnapshot.executionPolicy.workspaceMaterializer||"instance"!==e.executionSnapshot.executionPolicy.processSandbox)throw IE("AGENT_RUN_MATERIALIZER_UNAVAILABLE","The requested execution policy has no Docker instance materializer.");const t=this.targetForInstance(e.instanceId);if(t.runtimeId!==e.runtimeId)throw IE("AGENT_RUN_RUNTIME_MISMATCH","The target instance no longer belongs to the frozen runtime.");const i=await this.requireReadyContainer(t),s=eE(e.runId,e.memberId),o=n.posix.join(Ec,e.runId,e.memberId),r=n.posix.join(o,"upper"),a=n.posix.join(o,"work"),c=n.posix.join(Ac,e.runId);this.assertStorageBoundaries(e.sourceRuntimePath,{upperPath:r,workPath:a,sharedPath:c,mergedPath:s.cwd});const d=nE(e),l=`${String(i.Id)}:${s.cwd}`,u=this.resources.register({runId:e.runId,memberId:e.memberId,instanceId:e.instanceId,runtimeId:e.runtimeId,kind:"overlay-mount",generationId:e.generationId,backendIdentity:l,metadata:{containerId:i.Id,mergedPath:s.cwd,upperPath:r,workPath:a,sourceRuntimePath:e.sourceRuntimePath}}),p={materializer:this.kind,generationId:e.generationId,layout:s,backendIdentity:l,diagnostics:{isolation:"instance",sharesContainerUserNetworkAndCredentials:!0,sourceWritesDeniedBy:"provider-thread-write-roots",crossRunWritesDeniedBy:"provider-thread-write-roots-and-node-path-validation"},target:t,resourceId:u.resourceId,upperPath:r,workPath:a,sharedPath:c,marker:d};try{return this.appendInjectionAudit(u.resourceId,{requestedAt:(new Date).toISOString(),result:"pending",helperImage:this.helperImage,capabilities:[...yE],targetContainerId:String(i.Id)}),await this.runHelper(t,e.runId,e.memberId,e.generationId,["inject","--lower",e.sourceRuntimePath,"--upper",r,"--work",a,"--merged",s.cwd,"--shared",c,"--marker",JSON.stringify(d)]),this.finishInjectionAudit(u.resourceId,"completed"),this.resources.transition(u.resourceId,"ready"),p}catch(t){throw this.finishInjectionAudit(u.resourceId,"failed",t),await this.rollbackInjection(p,t),IE("AGENT_RUN_OVERLAY_INJECTION_FAILED","Could not inject the Agent Run overlay workspace.",t,{runId:e.runId,memberId:e.memberId})}}async ensureRunDirectory(e){const t=this.targetForInstance(e.instanceId);if(t.runtimeId!==e.runtimeId)throw IE("AGENT_RUN_SHARED_RUNTIME_MISMATCH","The target instance is outside the run runtime.");return await this.requireReadyContainer(t),await this.runHelper(t,e.runId,"shared_space",e.generationId,["shared-ensure","--path",e.runtimePath,"--generation",e.generationId]),{runtimePath:e.runtimePath,runtimeId:e.runtimeId,volumeRole:"agent-run"}}async prepareProbe(e){const t=this.targetForInstance(e.instanceId);if(t.runtimeId!==e.runtimeId)throw IE("AGENT_RUN_RUNTIME_MISMATCH","The probe target no longer belongs to the frozen runtime.");const i=await this.requireReadyContainer(t),s=eE(e.runId,e.memberId),o=n.posix.join(Ec,e.runId,e.memberId),r=n.posix.join(o,"upper"),a=n.posix.join(o,"work"),c=n.posix.join(Ac,e.runId);this.assertStorageBoundaries(e.sourceRuntimePath,{upperPath:r,workPath:a,sharedPath:c,mergedPath:s.cwd});const d=nE(e),l={materializer:this.kind,generationId:e.generationId,layout:s,backendIdentity:`${String(i.Id)}:${s.cwd}`,diagnostics:{probe:!0},target:t,resourceId:`probe:${e.generationId}`,upperPath:r,workPath:a,sharedPath:c,marker:d};return await this.runHelper(t,e.runId,e.memberId,e.generationId,["inject","--lower",e.sourceRuntimePath,"--upper",r,"--work",a,"--merged",s.cwd,"--shared",c,"--marker",JSON.stringify(d)]),l}async verifyProbe(e,t,n){const i=await this.runHelper(e.target,e.marker.runId,e.marker.memberId,e.marker.generationId,["probe-verify","--lower",t,"--merged",e.layout.cwd,"--shared",e.sharedPath,"--other-shared",n,"--generation",e.marker.generationId]),s=JSON.parse(i.stdout||"{}");if(!0!==s.workspaceWritable||!0!==s.sharedWritable||!0!==s.sourceWriteRejected||!0!==s.otherRunWriteRejected)throw IE("AGENT_RUN_BEHAVIOR_PROBE_FAILED","The Agent Run filesystem behavior probe did not prove every write boundary.",void 0,s);return s}async disposeProbe(e){await this.runHelper(e.target,e.marker.runId,e.marker.memberId,e.marker.generationId,["dispose","--merged",e.layout.cwd,"--upper",e.upperPath,"--work",e.workPath])}async removeRunDirectory(e){const t=this.targetForInstance(e.instanceId);if(t.runtimeId!==e.runtimeId)throw IE("AGENT_RUN_SHARED_RUNTIME_MISMATCH","The target instance is outside the run runtime.");return await this.requireReadyContainer(t),await this.runHelper(t,e.runId,"shared_space",e.generationId,["shared-expire","--path",e.runtimePath,"--generation",e.generationId]),{runtimePath:e.runtimePath,runtimeId:e.runtimeId,volumeRole:"agent-run"}}async inspectRunDirectory(e){const t=this.targetForInstance(e.instanceId);if(t.runtimeId!==e.runtimeId)throw IE("AGENT_RUN_SHARED_RUNTIME_MISMATCH","The target instance is outside the run runtime.");await this.requireReadyContainer(t);const n=await this.runHelper(t,e.runId,"shared_space",e.generationId,["shared-inspect","--path",e.runtimePath,"--generation",e.generationId]),i=JSON.parse(n.stdout||"{}");if(!Number.isSafeInteger(i.usageBytes)||Number(i.usageBytes)<0)throw IE("AGENT_RUN_SHARED_USAGE_INVALID","The shared-space helper returned an invalid usage measurement.");return{usageBytes:Number(i.usageBytes)}}async inspectOwnership(e,t){try{const n=await this.runCommand("docker",["inspect","--format","{{json .}}",e.target.containerName]),i=JSON.parse(n.stdout||"{}");if(!0!==i.State?.Running||e.target.expectedContainerId&&i.Id!==e.target.expectedContainerId)return"absent";const s=await this.runHelper(e.target,t.runId,t.memberId,t.generationId,["inspect","--merged",e.layout.cwd]),o=JSON.parse(s.stdout||"{}");return!0!==o.mounted?"absent":o.marker&&function(e,t){return 1===e.version&&e.runId===t.runId&&e.memberId===t.memberId&&e.generationId===t.generationId}(o.marker,t)?"owned":"foreign"}catch{return"foreign"}}async dispose(e,t){if("foreign"===await this.inspectOwnership(e,t))throw this.resources.transition(e.resourceId,"manual-intervention",{metadata:{ownership:"foreign",mergedPath:e.layout.cwd}}),IE("AGENT_RUN_RESOURCE_OWNERSHIP_UNPROVEN","Refusing to remove an Agent Run workspace with a foreign generation marker.");await this.terminateMemberThread(t.runId,t.memberId),this.resources.transition(e.resourceId,"deleting");try{await this.runHelper(e.target,t.runId,t.memberId,t.generationId,["dispose","--merged",e.layout.cwd,"--upper",e.upperPath,"--work",e.workPath]),this.resources.transition(e.resourceId,"deleted")}catch(t){throw this.resources.transition(e.resourceId,"delete-retrying",{incrementCleanupAttempts:!0,metadata:{code:"AGENT_RUN_OVERLAY_DISPOSE_FAILED",message:t instanceof Error?t.message:String(t)}}),IE("AGENT_RUN_OVERLAY_DISPOSE_FAILED","Could not dispose the Agent Run overlay workspace.",t)}}async reconcileInstance(e){const t=[];for(const n of this.resources.listActiveForInstance(e)){if("overlay-mount"!==n.kind||!n.memberId)continue;const e=this.workspaceFromResource(n),i=nE({runId:n.runId,memberId:n.memberId,generationId:n.generationId,createdAt:n.createdAt});try{await this.dispose(e,i),t.push({resourceId:n.resourceId,status:"deleted"})}catch{const e=this.resources.get(n.resourceId);t.push({resourceId:n.resourceId,status:"manual-intervention"===e?.phase?"manual-intervention":"retrying"})}}return t}async requireReadyContainer(e){let t;try{const n=await this.runCommand("docker",["inspect","--format","{{json .}}",e.containerName]);t=JSON.parse(n.stdout||"{}")}catch(e){throw IE("AGENT_RUN_INSTANCE_NOT_READY","The target Docker instance is not available.",e)}if("string"!=typeof t.Id||!0!==t.State?.Running||e.expectedContainerId&&t.Id!==e.expectedContainerId)throw IE("AGENT_RUN_INSTANCE_NOT_READY","The target Docker instance identity or running state is not ready.");if(!e.providerReady)throw IE("AGENT_RUN_PROVIDER_NOT_READY","The target instance shared provider is not ready.");const n=Array.isArray(t.Mounts)?t.Mounts:[],i=wc(e.nodeId,e.runtimeId),s=n.find(e=>e.Destination===i.mountPath);if(!s)throw IE("AGENT_RUN_RUNTIME_VOLUME_MISSING","The target instance does not have the Agent Run runtime volume.",void 0,{role:i.role});if("volume"!==s.Type||s.Name!==i.name)throw IE("AGENT_RUN_RUNTIME_VOLUME_IDENTITY_MISMATCH","The target instance has an unexpected Agent Run runtime volume.",void 0,{role:i.role});return t}assertStorageBoundaries(e,t){if(!n.posix.isAbsolute(e))throw IE("AGENT_RUN_SOURCE_PATH_INVALID","The workspace source must be an absolute runtime path.");const i=n.posix.resolve(e);for(const e of[t.upperPath,t.workPath])tE(Ec,e);if(tE(Ac,t.sharedPath),tE(n.posix.dirname(t.mergedPath),t.mergedPath),i===_c||i.startsWith(`${_c}/`)||t.upperPath===Ac||t.upperPath.startsWith(`${Ac}/`)||t.workPath===Ac||t.workPath.startsWith(`${Ac}/`)||t.sharedPath===Ec||t.sharedPath.startsWith(`${Ec}/`))throw IE("AGENT_RUN_OVERLAY_STORAGE_BOUNDARY_INVALID","The source, overlay backing subtree, and shared artifact subtree must remain disjoint.")}helperArgs(e,t,n,i,s){const o=["run","--rm","--name",`task-handoff-agent-helper-${t}-${n}`.replace(/[^a-zA-Z0-9_.-]/g,"-").slice(0,120),"--pid",`container:${e.expectedContainerId||e.containerName}`,"--network","none","--read-only","--tmpfs","/tmp:rw,nosuid,nodev,noexec,mode=1777","--cap-drop","ALL"];for(const e of yE)o.push("--cap-add",e);return o.push("--label","task-handoff.owner=task-handoff","--label","task-handoff.role=agent-run-overlay-helper","--label",`task-handoff.run-id=${t}`,"--label",`task-handoff.member-id=${n}`,"--label",`task-handoff.generation-id=${i}`,this.helperImage,...s),o}runHelper(e,t,n,i,s){return this.runCommand("docker",this.helperArgs(e,t,n,i,s),{timeoutMs:3e4})}async rollbackInjection(e,t){try{await this.runHelper(e.target,e.marker.runId,e.marker.memberId,e.marker.generationId,["rollback","--merged",e.layout.cwd,"--upper",e.upperPath,"--work",e.workPath]);const t=this.resources.get(e.resourceId);this.resources.transition(e.resourceId,"deleted",{metadata:{...t?.metadata,rolledBack:!0}})}catch(n){const i=this.resources.get(e.resourceId);this.resources.transition(e.resourceId,"delete-retrying",{incrementCleanupAttempts:!0,metadata:{...i?.metadata,code:"AGENT_RUN_OVERLAY_ROLLBACK_FAILED",prepareError:t instanceof Error?t.message:String(t),rollbackError:n instanceof Error?n.message:String(n)}})}}appendInjectionAudit(e,t){const n=this.resources.get(e);if(!n)return;const i=Array.isArray(n.metadata.injectionAttempts)?n.metadata.injectionAttempts:[];this.resources.transition(e,n.phase,{metadata:{...n.metadata,injectionAttempts:[...i,t]}})}finishInjectionAudit(e,t,n){const i=this.resources.get(e);if(!i)return;const s=Array.isArray(i.metadata.injectionAttempts)?[...i.metadata.injectionAttempts]:[],o=s.at(-1);o&&"object"==typeof o&&!Array.isArray(o)&&(s[s.length-1]={...o,result:t,finishedAt:(new Date).toISOString(),...void 0===n?{}:{error:n instanceof Error?n.message:String(n)}}),this.resources.transition(e,i.phase,{metadata:{...i.metadata,injectionAttempts:s}})}workspaceFromResource(e){if(!e.instanceId||!e.memberId)throw IE("AGENT_RUN_RESOURCE_INVALID","The overlay resource is missing instance or member ownership.");const t=eE(e.runId,e.memberId),i=n.posix.join(Ec,e.runId,e.memberId);return{materializer:this.kind,generationId:e.generationId,layout:t,backendIdentity:e.backendIdentity,diagnostics:e.metadata,target:this.targetForInstance(e.instanceId),resourceId:e.resourceId,upperPath:n.posix.join(i,"upper"),workPath:n.posix.join(i,"work"),sharedPath:n.posix.join(Ac,e.runId),marker:nE({runId:e.runId,memberId:e.memberId,generationId:e.generationId,createdAt:e.createdAt})}}}class EE{stories;definitions;orchestrations;entries;onUpdated;constructor(e,t,n,i,s){this.stories=e,this.definitions=t,this.orchestrations=n,this.entries=i,this.onUpdated=s}async get(e){if(!await this.stories.exists(e))throw TE("STORY_AGENT_ENTRY_STORY_NOT_FOUND",`Story ${e} was not found.`,404,{storyId:e});return this.project(this.entries.get(e))}async update(e,t){const n=R_.parse(t);if(!await this.stories.exists(e))throw TE("STORY_AGENT_ENTRY_STORY_NOT_FOUND",`Story ${e} was not found.`,404,{storyId:e});const i=this.entries.get(e);if(i.revision!==n.expectedRevision)throw TE("STORY_AGENT_ENTRY_REVISION_CONFLICT","Story Agent entries changed since they were read.",409,{storyId:e,expectedRevision:n.expectedRevision,actualRevision:i.revision});const s=new Set(i.entries.map(AE)),o=n.entries.map(e=>({agentId:e.agentId,orchestrationId:e.orchestrationId??yp(e.agentId)}));for(const t of o)if(!s.has(AE(t))){if(!this.definitions.has(t.agentId))throw TE("STORY_AGENT_ENTRY_AGENT_NOT_FOUND",`Agent definition ${t.agentId} was not found on this Node Agent.`,409,{storyId:e,agentId:t.agentId});if(!this.orchestrations.has(t.orchestrationId))throw TE("STORY_AGENT_ENTRY_ORCHESTRATION_NOT_FOUND",`Agent orchestration ${t.orchestrationId} was not found on this Node Agent.`,409,{storyId:e,orchestrationId:t.orchestrationId});if(!this.orchestrations.containsAgent(t.orchestrationId,t.agentId))throw TE("STORY_AGENT_ENTRY_ORCHESTRATION_MISMATCH",`Agent ${t.agentId} is not part of orchestration ${t.orchestrationId}.`,409,{storyId:e,agentId:t.agentId,orchestrationId:t.orchestrationId})}const r=this.project(this.entries.replace(e,o));return await(this.onUpdated?.(r)),r}project(e){return{storyId:e.storyId,revision:e.revision,entries:e.entries.map(e=>({agentId:e.agentId,orchestrationId:e.orchestrationId,status:this.referenceAvailable(e)?"available":"missing-reference"}))}}referenceAvailable(e){return this.definitions.has(e.agentId)&&this.orchestrations.containsAgent(e.orchestrationId,e.agentId)}}function AE(e){return`${e.agentId}${e.orchestrationId}`}function TE(e,t,n,i){if(!z_.includes(e))throw new Error(`Unknown Story Agent authorization error code ${e}.`);return Object.assign(new Error(t),{code:e,statusCode:n,...i?{details:i}:{}})}class wE{tails=new Map;accepting=!0;async acquire(e){if(!this.accepting)throw Object.assign(new Error("Story storage is shutting down."),{code:"STORY_STORAGE_QUIESCING",statusCode:503});const t=this.tails.get(e)??Promise.resolve();let n;const i=new Promise(e=>{n=e}),s=t.catch(()=>{}).then(()=>i);this.tails.set(e,s),await t.catch(()=>{});let o=!1;return()=>{o||(o=!0,n(),s.finally(()=>{this.tails.get(e)===s&&this.tails.delete(e)}))}}async run(e,t){const n=await this.acquire(e);try{return await t()}finally{n()}}stopAccepting(){this.accepting=!1}async drain(){await Promise.all([...this.tails.values()])}pendingStoryIds(){return[...this.tails.keys()]}}class bE{coordinator;paths;ownerNodeId;repository;maxFileBytes;onChange;constructor(e,t,n,i=33554432,s){this.paths=e,this.ownerNodeId=t,this.repository=n,this.maxFileBytes=i,this.onChange=s,this.coordinator=new wE}async init(){t.mkdirSync(this.paths.storyMutationsDir,{recursive:!0,mode:448}),t.mkdirSync(this.paths.storyTrashDir,{recursive:!0,mode:448}),t.chmodSync(this.paths.storyMutationsDir,448),t.chmodSync(this.paths.storyTrashDir,448),await this.recoverFileMutations()}setOnChange(e){this.onChange=e}async list(){const e=await this.repository.stories.list();return Promise.all(e.map(e=>this.project(e)))}async get(e){const t=await this.repository.stories.get(e);return t?this.project(t):void 0}async require(e){const t=await this.repository.stories.get(e);if(!t)throw NE("STORY_NOT_FOUND","Story was not found.",404);return t}async exists(e){return Boolean(await this.repository.stories.get(e))}async automationContext(e){const t=await this.repository.stories.get(e);if(!t)return;if(await this.repository.deletionIntents.get(e))throw NE("STORY_DELETING","Story is being deleted.",409);const n=(await this.repository.actions.list(e)).map(({storyId:e,displayOrder:t,sessionPreset:n,...i})=>dy.parse({...i,sessionPreset:n||void 0}));return{id:t.id,archivedAt:t.archivedAt||void 0,actions:n}}async create(e){const t=My.parse(e),n=(new Date).toISOString(),i=await this.repository.transaction(async e=>{const i=await e.stories.insert({id:du("story"),title:t.title,description:t.description,createdAt:n,updatedAt:n,maxIdleAiSessions:t.maxIdleAiSessions??5,nextDocumentSequence:1,agentToolsContent:oI.content,agentToolsActions:oI.actions,agentToolsAutomations:oI.automations,agentToolsAiSessions:oI.aiSessions,agentToolsDecisions:oI.decisions}),s=(t.actions||[]).map((e,t)=>({storyId:i.id,id:du("story_action"),title:e.title,promptTemplate:e.promptTemplate,targetInstanceId:e.targetInstanceId,sessionPreset:e.sessionPreset,displayOrder:t}));return await e.actions.replace(i.id,s),i}),s=await this.project(i);return this.onChange?.("created",s),s}async retentionSettings(e){return sy.parse({maxIdleAiSessions:(await this.require(e)).maxIdleAiSessions})}async update(e,t,n=!0){const i=jy.parse(t),s=(new Date).toISOString(),o=await this.repository.transaction(async t=>{if(!await t.stories.get(e))throw NE("STORY_NOT_FOUND","Story was not found.",404);if(await t.deletionIntents.get(e))throw NE("STORY_DELETING","Story is being deleted.",409);if(void 0!==i.actions){const n=await t.actions.list(e),s=new Set(i.actions.flatMap(e=>e.id?[e.id]:[])),o=n.map(e=>e.id).filter(e=>!s.has(e)),r=await t.automations.referencingActions(e,o);if(r.length)throw NE("STORY_ACTION_AUTOMATION_IN_USE","Story Action is referenced by an Automation.",409,{automationIds:r.map(e=>e.id)});await t.actions.replace(e,i.actions.map((t,n)=>({storyId:e,id:t.id||du("story_action"),title:t.title,promptTemplate:t.promptTemplate,targetInstanceId:t.targetInstanceId,sessionPreset:t.sessionPreset,displayOrder:n})))}return t.stories.update(e,{...void 0!==i.title?{title:i.title}:{},...void 0!==i.description?{description:i.description||null}:{},...void 0!==i.maxIdleAiSessions?{maxIdleAiSessions:i.maxIdleAiSessions}:{},updatedAt:s})}),r=await this.project(o);return n&&this.onChange?.("updated",r),r}async archive(e){return this.setArchived(e,!0)}async restore(e){return this.setArchived(e,!1)}async setArchived(e,t){await this.require(e);const n=(new Date).toISOString(),i=await this.repository.stories.update(e,{archivedAt:t?n:null,updatedAt:n}),s=await this.project(i);return this.onChange?.(t?"archived":"restored",s),s}async deleteRecord(e){const t=await this.get(e);if(!t)return!1;const n=await this.repository.stories.delete(e);return n&&this.onChange?.("deleted",t),n}notifyDeleted(e){this.onChange?.("deleted",e)}notifyUpdated(e){this.onChange?.("updated",e)}async listContent(e){const t=await this.require(e);return(await this.project(t)).documents}async pageContent(e,t,n){const i=await this.require(e),{items:s,totalItems:o}=await this.repository.documents.page(e,t,n),r=Math.ceil(o/n);return{storyCreatedAt:i.createdAt,documents:s,pagination:{page:t,pageSize:n,totalItems:o,totalPages:r,hasMore:t*n<o}}}async readContent(e,n){const i=await this.coordinator.acquire(e);try{await this.require(e);const s=oy.parse(n);if(!await this.repository.documents.get(e,s))throw NE("STORY_CONTENT_NOT_INDEXED","Story content is not indexed.",404);const o=this.openRegularFileWithinRoot(e,s),r=t.createReadStream("",{fd:o.fd,autoClose:!0});let a=!1;const c=()=>{a||(a=!0,i())};return r.once("close",c),r.once("error",c),{stream:r,size:o.size,revision:o.revision}}catch(t){if(i(),"ENOENT"===t.code)throw await this.removeMissingDocument(e,n),NE("STORY_CONTENT_NOT_FOUND","Story content file was not found.",404);throw t}}async writeContent(e,i){return this.coordinator.run(e,async()=>{if((await this.require(e)).archivedAt)throw NE("STORY_ARCHIVED","Archived Story content is read-only.",409);const s=oy.parse(i.storyPath),o=await this.repository.documents.get(e,s);if(o){if(!i.expectedRevision)throw NE("STORY_REVISION_REQUIRED","expectedRevision is required when replacing Story content.",409);const n=this.openRegularFileWithinRoot(e,s);if(t.closeSync(n.fd),n.revision!==i.expectedRevision)throw NE("STORY_REVISION_CONFLICT","Story content changed since it was read.",409)}else if(!i.title?.trim())throw NE("STORY_CONTENT_TITLE_REQUIRED","A title is required for new Story content.",400);this.ensureStoryParent(e,s);const r=du("story_file_mutation"),a=this.filePath(e,s),c=`${a}.${r}.tmp`,d=`${a}.${r}.bak`,l=(new Date).toISOString();if(!o&&t.existsSync(a))throw NE("STORY_PATH_CONFLICT","Story path already exists on disk.",409);await this.repository.fileMutations.insert({id:r,storyId:e,operation:"write",storyPath:s,title:i.title?.trim(),temporaryName:c,backupName:d,phase:"receiving",createdAt:l,updatedAt:l});let u=0,p=!1;try{const l=new f.Transform({transform:(e,t,n)=>{u+=e.byteLength,n(u>this.maxFileBytes?NE("STORY_FILE_TOO_LARGE","Story content exceeds the node limit.",413):null,e)}});await I.pipeline(i.stream,l,t.createWriteStream(c,{flags:"wx",mode:384})),this.fsyncFile(c),await this.repository.fileMutations.update(r,{phase:"prepared",updatedAt:(new Date).toISOString()}),o&&t.renameSync(a,d),t.renameSync(c,a),this.fsyncDirectory(n.dirname(a)),await this.repository.fileMutations.update(r,{phase:"files-staged",updatedAt:(new Date).toISOString()}),await this.repository.transaction(async t=>{const n=await t.stories.get(e);if(!n)throw NE("STORY_NOT_FOUND","Story was not found.",404);if(o)await t.documents.update(e,s,{title:i.title?.trim()||o.title});else{const o=await t.documents.list(e);await t.documents.insert({storyId:e,storyPath:s,title:i.title.trim(),indexedSequence:n.nextDocumentSequence,displayOrder:o.length}),await t.stories.update(e,{nextDocumentSequence:n.nextDocumentSequence+1,updatedAt:(new Date).toISOString()})}o&&await t.stories.update(e,{updatedAt:(new Date).toISOString()}),await t.fileMutations.update(r,{phase:"database-committed",updatedAt:(new Date).toISOString()})}),p=!0,t.rmSync(d,{force:!0}),await this.repository.fileMutations.update(r,{phase:"cleanup",updatedAt:(new Date).toISOString()}),await this.repository.fileMutations.delete(r);const m=this.openRegularFileWithinRoot(e,s);t.closeSync(m.fd);const h=await this.get(e);h&&this.onChange?.("content.written",h);const g=await this.repository.documents.get(e,s);if(!g)throw NE("STORY_CONTENT_NOT_INDEXED","Story content is not indexed.",500);return{title:g.title,storyPath:s,revision:m.revision,size:u}}catch(e){throw p||await this.rollbackFileMutation(r,a,c,d,Boolean(o)),e}})}async updateDocument(e,i,s){return this.coordinator.run(e,async()=>{if((await this.require(e)).archivedAt)throw NE("STORY_ARCHIVED","Archived Story content is read-only.",409);const o=oy.parse(i),r=await this.repository.documents.get(e,o);if(!r)throw NE("STORY_CONTENT_NOT_INDEXED","Story content is not indexed.",404);const a=s.storyPath?oy.parse(s.storyPath):o;if(a!==o&&await this.repository.documents.get(e,a))throw NE("STORY_PATH_CONFLICT","Story path is already indexed.",409);if(a===o)await this.repository.transaction(async t=>{await t.documents.update(e,o,{title:s.title?.trim()||r.title}),await t.stories.update(e,{updatedAt:(new Date).toISOString()})});else{this.openAndClose(e,o),this.ensureStoryParent(e,a);const i=this.filePath(e,o),c=this.filePath(e,a);if(t.existsSync(c))throw NE("STORY_PATH_CONFLICT","Story path already exists on disk.",409);const d=du("story_file_mutation"),l=(new Date).toISOString();await this.repository.fileMutations.insert({id:d,storyId:e,operation:"rename",storyPath:o,nextStoryPath:a,title:s.title?.trim(),temporaryName:i,backupName:c,phase:"prepared",createdAt:l,updatedAt:l});let u=!1;try{t.renameSync(i,c),this.fsyncDirectory(n.dirname(i)),n.dirname(i)!==n.dirname(c)&&this.fsyncDirectory(n.dirname(c)),await this.repository.fileMutations.update(d,{phase:"files-staged",updatedAt:(new Date).toISOString()}),await this.repository.transaction(async t=>{await t.documents.replacePath(e,o,{...r,storyPath:a,title:s.title?.trim()||r.title}),await t.stories.update(e,{updatedAt:(new Date).toISOString()}),await t.fileMutations.update(d,{phase:"database-committed",updatedAt:(new Date).toISOString()})}),u=!0,await this.repository.fileMutations.update(d,{phase:"cleanup",updatedAt:(new Date).toISOString()}),await this.repository.fileMutations.delete(d)}catch(e){throw u||(t.existsSync(c)&&!t.existsSync(i)&&t.renameSync(c,i),await this.repository.fileMutations.delete(d)),e}}const c=await this.get(e);return this.onChange?.("document.updated",c),c})}async reorderDocuments(e,t){const{storyPaths:n}=Fy.parse(t),i=(await this.repository.documents.list(e)).map(e=>e.storyPath);if(n.length!==i.length||new Set(n).size!==n.length||i.some(e=>!n.includes(e)))throw NE("STORY_DOCUMENT_ORDER_INVALID","Document order must contain every indexed storyPath exactly once.",400);await this.repository.transaction(async t=>{await t.documents.reorder(e,n),await t.stories.update(e,{updatedAt:(new Date).toISOString()})});const s=await this.get(e);return this.onChange?.("document.reordered",s),s}async deleteDocument(e,i){return this.coordinator.run(e,async()=>{if((await this.require(e)).archivedAt)throw NE("STORY_ARCHIVED","Archived Story content is read-only.",409);const s=oy.parse(i);if(!await this.repository.documents.get(e,s))return!1;const o=this.filePath(e,s),r=`${o}.${du("story_file_mutation")}.deleted`,a=du("story_file_mutation"),c=(new Date).toISOString();await this.repository.fileMutations.insert({id:a,storyId:e,operation:"delete",storyPath:s,backupName:r,phase:"prepared",createdAt:c,updatedAt:c});let d=!1;try{this.openAndClose(e,s),t.renameSync(o,r),this.fsyncDirectory(n.dirname(o)),await this.repository.fileMutations.update(a,{phase:"files-staged",updatedAt:(new Date).toISOString()}),await this.repository.transaction(async t=>{await t.documents.delete(e,s),await t.stories.update(e,{updatedAt:(new Date).toISOString()}),await t.fileMutations.update(a,{phase:"database-committed",updatedAt:(new Date).toISOString()})}),d=!0,t.rmSync(r,{force:!0}),await this.repository.fileMutations.update(a,{phase:"cleanup",updatedAt:(new Date).toISOString()}),await this.repository.fileMutations.delete(a)}catch(e){throw d||(t.existsSync(r)&&!t.existsSync(o)&&t.renameSync(r,o),await this.repository.fileMutations.delete(a)),e}const l=await this.get(e);return l&&this.onChange?.("document.deleted",l),!0})}stopAccepting(){this.coordinator.stopAccepting()}drain(){return this.coordinator.drain()}async project(e){const n=(await this.repository.actions.list(e.id)).map(({storyId:e,displayOrder:t,sessionPreset:n,...i})=>dy.parse({...i,sessionPreset:n||void 0})),i=await this.repository.documents.list(e.id),s=[];for(const n of i)try{const i=this.openRegularFileWithinRoot(e.id,n.storyPath);t.closeSync(i.fd),s.push({title:n.title,storyPath:n.storyPath,revision:i.revision})}catch(t){if("ENOENT"!==t.code)throw t;await this.removeMissingDocument(e.id,n.storyPath)}return Py.parse({id:e.id,ownerNodeId:this.ownerNodeId,title:e.title,description:e.description||void 0,actions:n,documents:s,createdAt:e.createdAt,updatedAt:e.updatedAt,archivedAt:e.archivedAt||void 0})}storyRoot(e){return n.resolve(this.paths.storyContentDir,Py.shape.id.parse(e))}filePath(e,t){const i=this.storyRoot(e),s=n.resolve(i,...oy.parse(t).split("/"));if(s===i||!s.startsWith(`${i}${n.sep}`))throw NE("STORY_PATH_OUTSIDE_ROOT","Story path is outside the Story directory.",400);return s}ensureStoryParent(e,i){const s=this.filePath(e,i);try{const e=t.lstatSync(this.paths.storyContentDir);if(e.isSymbolicLink()||!e.isDirectory())throw NE("STORY_PATH_UNSAFE","Story content root must be a real directory.",409)}catch(e){if("ENOENT"!==e.code)throw e;t.mkdirSync(this.paths.storyContentDir,{recursive:!0,mode:448})}t.chmodSync(this.paths.storyContentDir,448);let o=this.paths.storyContentDir;for(const e of n.relative(this.paths.storyContentDir,n.dirname(s)).split(n.sep).filter(Boolean)){o=n.join(o,e);try{const e=t.lstatSync(o);if(e.isSymbolicLink()||!e.isDirectory())throw NE("STORY_PATH_UNSAFE","Story path parent must be a real directory.",409)}catch(e){if("ENOENT"!==e.code)throw e;t.mkdirSync(o,{mode:448})}t.chmodSync(o,448)}}openRegularFileWithinRoot(e,i){const s=this.filePath(e,i);this.assertExistingParentsSafe(this.storyRoot(e),n.dirname(s));const o="number"==typeof t.constants.O_NOFOLLOW?t.constants.O_NOFOLLOW:0;if(!o)throw NE("STORY_NOFOLLOW_UNAVAILABLE","Safe no-follow file access is unavailable on this platform.",500);const r=t.openSync(s,t.constants.O_RDONLY|o);try{const e=t.fstatSync(r);if(!e.isFile())throw NE("STORY_CONTENT_NOT_FILE","Story content must be a regular file.",409);if(e.size>this.maxFileBytes)throw NE("STORY_FILE_TOO_LARGE","Story content exceeds the node limit.",413);const n=d.createHash("sha256"),i=Buffer.allocUnsafe(65536);let s=0;for(;s<e.size;){const o=t.readSync(r,i,0,Math.min(i.length,e.size-s),s);if(!o)break;n.update(i.subarray(0,o)),s+=o}return{fd:r,size:e.size,revision:n.digest("hex")}}catch(e){throw t.closeSync(r),e}}assertExistingParentsSafe(e,i){const s=n.relative(this.paths.storyContentDir,i);let o=this.paths.storyContentDir;for(const e of s.split(n.sep).filter(Boolean)){o=n.join(o,e);const i=t.lstatSync(o);if(i.isSymbolicLink()||!i.isDirectory())throw NE("STORY_PATH_UNSAFE","Story path parent must be a real directory.",409)}if(!i.startsWith(e))throw NE("STORY_PATH_OUTSIDE_ROOT","Story path is outside the Story directory.",400)}openAndClose(e,n){const i=this.openRegularFileWithinRoot(e,n);t.closeSync(i.fd)}fsyncFile(e){const n=t.openSync(e,"r");try{t.fsyncSync(n)}finally{t.closeSync(n)}}fsyncDirectory(e){if("win32"===process.platform)return;const n=t.openSync(e,"r");try{t.fsyncSync(n)}finally{t.closeSync(n)}}async removeMissingDocument(e,t){if(!await this.repository.documents.get(e,t))return;await this.repository.transaction(async n=>{await n.documents.delete(e,t),await n.stories.update(e,{updatedAt:(new Date).toISOString()})});const n=await this.get(e);n&&this.onChange?.("document.deleted",n)}async rollbackFileMutation(e,n,i,s,o){t.rmSync(i,{force:!0}),o&&t.existsSync(s)?(t.rmSync(n,{force:!0}),t.renameSync(s,n)):o||t.rmSync(n,{force:!0}),await this.repository.fileMutations.delete(e)}async recoverFileMutations(){for(const e of await this.repository.fileMutations.list())await this.coordinator.run(e.storyId,async()=>{const n=this.filePath(e.storyId,e.nextStoryPath||e.storyPath);if("database-committed"===e.phase||"cleanup"===e.phase)"write"===e.operation?(e.temporaryName&&t.rmSync(e.temporaryName,{force:!0}),e.backupName&&t.rmSync(e.backupName,{force:!0})):"delete"===e.operation&&e.backupName&&t.rmSync(e.backupName,{force:!0});else if("write"===e.operation){const i=Boolean(e.temporaryName&&t.existsSync(e.temporaryName)),s=Boolean(await this.repository.documents.get(e.storyId,e.storyPath));e.backupName&&t.existsSync(e.backupName)?(t.rmSync(n,{force:!0}),t.renameSync(e.backupName,n)):s||"files-staged"!==e.phase&&("prepared"!==e.phase||i)||t.rmSync(n,{force:!0}),e.temporaryName&&t.rmSync(e.temporaryName,{force:!0})}else"rename"===e.operation&&e.temporaryName&&t.existsSync(n)&&!t.existsSync(e.temporaryName)?t.renameSync(n,e.temporaryName):"delete"===e.operation&&e.backupName&&t.existsSync(e.backupName)&&!t.existsSync(n)&&t.renameSync(e.backupName,n);await this.repository.fileMutations.delete(e.id)})}}function NE(e,t,n,i){return Object.assign(new Error(t),{code:e,statusCode:n,...void 0===i?{}:{details:i}})}const SE=c.z.object({storyId:c.z.string().trim().min(1).max(120),actionId:c.z.string().trim().min(1).max(120),targetInstanceId:c.z.string().trim().min(1).max(120),prompt:c.z.string().trim().min(1).max(32e3),sessionPreset:cy.optional(),cwd:c.z.string().trim().min(1).max(4096)}).strict(),vE=my,OE=hy,RE=_y,zE=Ay.extend({executionKey:c.z.string().trim().min(1).max(160),requestFingerprint:c.z.string().regex(/^[a-f0-9]{64}$/),executionInput:SE}).strict(),xE=new Set(["completed","failed","skipped"]),CE={queued:["dispatching","skipped"],dispatching:["running","failed"],running:["completed","failed"],completed:[],failed:[],skipped:[]};class kE{repository;now;constructor(e,t=()=>new Date){this.repository=e,this.now=t}async init(){}async list(e){return(await this.repository.automations.list(e)).map(DE)}async stored(e){const t=await this.repository.automations.get(e);return t?function(e){return{...DE(e),scheduleAnchorAt:e.scheduleAnchorAt}}(t):void 0}async get(e){const t=await this.repository.automations.get(e);return t?DE(t):void 0}async create(e){const t=fy.parse(e),n=this.now().toISOString();return DE(await this.repository.automations.insert({id:du("story_automation"),storyId:t.storyId,actionId:t.actionId,schedule:vE.parse(t.schedule),enabled:t.enabled,policy:OE.parse(t.policy),scheduleAnchorAt:n,createdAt:n,updatedAt:n}))}async update(e,t,n){const i=Iy.parse(t);return this.repository.transaction(async t=>{const s=await t.automations.get(e);if(!s)return;jE(s.updatedAt,n);const o=function(e,t){return new Date(Math.max(e.getTime(),Date.parse(t)+1)).toISOString()}(this.now(),s.updatedAt),r=void 0!==i.schedule||!0===i.enabled&&!s.enabled,a=await t.automations.update(e,{...i,...r?{scheduleAnchorAt:o}:{},updatedAt:o});return a?DE(a):void 0})}referencingActions(e,t){return this.repository.automations.referencingActions(e,[...t])}async hasActiveRuns(e){return(await this.repository.runs.list(e)).some(e=>!xE.has(e.status))}activeRunsForStory(e){return this.repository.runs.activeForStory(e).then(e=>e.map(LE))}async delete(e,t){return this.repository.transaction(async n=>{const i=await n.automations.get(e);if(!i)return!1;if(jE(i.updatedAt,t),(await n.runs.list(e)).some(e=>!xE.has(e.status)))throw ME("STORY_AUTOMATION_RUN_ACTIVE","Automation has a non-terminal run.",409);return n.automations.delete(e)})}async deleteForStory(e){if((await this.activeRunsForStory(e)).length)throw ME("STORY_AUTOMATION_RUN_ACTIVE","Story has a non-terminal Automation run.",409);await this.repository.automations.deleteForStory(e)}async createRun(e){const t=SE.parse(e.executionInput);return this.repository.transaction(async n=>{const i=await n.runs.byExecutionKey(e.executionKey);if(i)return LE(i);const s=await n.runs.insert({...e,executionInput:t,id:du("story_automation_run"),status:"queued",targetInstanceId:t.targetInstanceId,queuedAt:this.now().toISOString()});return await n.runs.trimTerminal(e.automationId,100),LE(s)})}async transition(e,t,n={}){return this.repository.transaction(async i=>{const s=await i.runs.get(e);if(!s)throw ME("STORY_AUTOMATION_RUN_NOT_FOUND","Automation run was not found.",404);const o=LE(s);if(o.status===t)return o;if(!CE[o.status].includes(t))throw ME("STORY_AUTOMATION_RUN_TRANSITION_INVALID",`Cannot transition run from ${o.status} to ${t}.`,409);const r=this.now().toISOString(),a=await i.runs.update(e,{...n,status:t,..."dispatching"===t?{startedAt:r}:{},...xE.has(t)?{completedAt:r}:{}});return await i.runs.trimTerminal(o.automationId,100),LE(a)})}async runsFor(e){return(await this.repository.runs.list(e)).map(PE)}async run(e){const t=await this.repository.runs.get(e);return t?PE(t):void 0}async runByExecutionKey(e){const t=await this.repository.runs.byExecutionKey(e);return t?LE(t):void 0}async pendingRuns(){return(await this.repository.runs.pending()).map(LE)}}function DE(e){return gy.parse({id:e.id,storyId:e.storyId,actionId:e.actionId,schedule:vE.parse(e.schedule),enabled:e.enabled,policy:OE.parse(e.policy),createdAt:e.createdAt,updatedAt:e.updatedAt})}function LE(e){return zE.parse({...e,aiSessionId:e.aiSessionId||void 0,startedAt:e.startedAt||void 0,completedAt:e.completedAt||void 0,error:e.error?RE.parse(e.error):void 0,executionInput:SE.parse(e.executionInput)})}function PE(e){const{executionKey:t,requestFingerprint:n,executionInput:i,...s}=LE(e);return Ay.parse(s)}function ME(e,t,n){return Object.assign(new Error(t),{code:e,statusCode:n})}function jE(e,t){if(void 0!==t&&e!==t)throw ME("STORY_AUTOMATION_CONFLICT","Automation was changed by another request.",409)}class UE{state;stories;automations;scheduler;repository;aiSessionCloser;decisions;constructor(e,t,n,i,s,o,r){this.state=e,this.stories=t,this.automations=n,this.scheduler=i,this.repository=s,this.aiSessionCloser=o,this.decisions=r}async init(){t.mkdirSync(this.state.paths.storyTrashDir,{recursive:!0,mode:448});for(const e of await this.repository.deletionIntents.list()){const i=await this.repository.stories.get(e.storyId),s=this.storyRoot(e.storyId),o=e.trashName?n.join(this.state.paths.storyTrashDir,e.trashName):void 0;i?o&&t.existsSync(o)&&!t.existsSync(s)&&t.renameSync(o,s):o&&t.rmSync(o,{recursive:!0,force:!0}),await this.repository.deletionIntents.delete(e.storyId)}}async update(e,t){const n=jy.parse(t);n.actions&&this.assertActionTargets(n.actions);const i=await this.stories.update(e,n);return await this.scheduler.refresh(),i}async create(e){const t=My.parse(e);return this.assertActionTargets(t.actions||[]),this.stories.create(t)}async createAutomationWithAction(e,t){const n=yy.parse(t);this.assertActionTargets([n.action]);const i=await this.stories.automationContext(e);if(!i)throw FE("STORY_NOT_FOUND","Story was not found.",404);if(i.archivedAt)throw FE("STORY_ARCHIVED","Archived Story cannot create an Automation.",409);if(i.actions.some(e=>e.id===n.action.id))throw FE("STORY_ACTION_ID_CONFLICT","Story Action id already exists.",409);const s={storyId:e,actionId:n.action.id,...n.automation};await this.scheduler.validateCreate(s,{...i,actions:[...i.actions,n.action]});let o="";await this.repository.transaction(async t=>{await t.actions.replace(e,[...i.actions,n.action].map((t,n)=>({storyId:e,id:t.id,title:t.title,promptTemplate:t.promptTemplate,targetInstanceId:t.targetInstanceId,sessionPreset:t.sessionPreset,displayOrder:n}))),await t.stories.update(e,{updatedAt:(new Date).toISOString()}),o=(await this.automations.create(s)).id});const r=await this.stories.get(e);return r&&this.stories.notifyUpdated(r),this.scheduler.activateCreated(o)}async archive(e){const t=await this.stories.archive(e);return await this.scheduler.refresh(),t}async restore(e){const t=await this.stories.restore(e);return await this.scheduler.refresh(),t}async delete(e){return this.stories.coordinator.run(e,async()=>{const t=await this.stories.get(e);return!!t&&(await this.prepareStoryDeletion(e),this.deleteCoordinated(t))})}async prepareStoryDeletion(e){const t=await this.automations.activeRunsForStory(e);if(t.length)throw FE("STORY_AUTOMATION_RUN_ACTIVE","Story has a non-terminal Automation run.",409,{runIds:t.map(e=>e.id)});const n=this.state.listInstances().flatMap(t=>t.aiSessions.sessions.filter(t=>t.storyId===e).map(n=>({instance:t,sessionId:n.id,storyId:e})));if(!n.length)return;if(!this.aiSessionCloser)throw FE("STORY_AI_SESSION_CLOSE_UNAVAILABLE","AI Sessions cannot be closed for Story deletion.",503);const i=await Promise.allSettled(n.map(e=>this.aiSessionCloser.close(e))),s={code:"STORY_DELETED",message:"The Story owning the decision was deleted."};await Promise.all(i.flatMap((e,t)=>"fulfilled"===e.status?[this.decisions?.expireForSession(n[t].sessionId,s)]:[])),await(this.decisions?.expireForStory(e,s));const o=i.flatMap((e,t)=>"rejected"===e.status?[{instanceId:n[t].instance.id,aiSessionId:n[t].sessionId,message:e.reason instanceof Error?e.reason.message:String(e.reason)}]:[]);if(o.length)throw FE("STORY_AI_SESSION_CLOSE_FAILED","One or more AI Sessions could not be closed.",409,{sessions:o})}async deleteCoordinated(e){const i=e.id;await this.scheduler.clearStory(i);const s=this.storyRoot(i),o=`${i}-${Date.now()}-${Math.random().toString(16).slice(2)}`,r=n.join(this.state.paths.storyTrashDir,o),a=(new Date).toISOString();await this.repository.deletionIntents.put({storyId:i,phase:"prepared",trashName:null,createdAt:a,updatedAt:a});try{let c=!1;return t.existsSync(s)&&(t.renameSync(s,r),this.fsyncDirectory(n.dirname(s)),this.fsyncDirectory(n.dirname(r)),c=!0),await this.repository.deletionIntents.put({storyId:i,phase:"files-staged",trashName:c?o:null,createdAt:a,updatedAt:(new Date).toISOString()}),await this.repository.transaction(async e=>{const t=await e.runs.activeForStory(i);if(t.length)throw FE("STORY_AUTOMATION_RUN_ACTIVE","Story has a non-terminal Automation run.",409,{runIds:t.map(e=>e.id)});await e.automations.deleteForStory(i),await e.stories.delete(i),await e.deletionIntents.put({storyId:i,phase:"database-committed",trashName:c?o:null,createdAt:a,updatedAt:(new Date).toISOString()})}),c&&t.rmSync(r,{recursive:!0,force:!0}),await this.repository.deletionIntents.put({storyId:i,phase:"cleanup",trashName:c?o:null,createdAt:a,updatedAt:(new Date).toISOString()}),await this.repository.deletionIntents.delete(i),this.stories.notifyDeleted(e),!0}catch(e){throw await this.repository.stories.get(i)&&(t.existsSync(r)&&!t.existsSync(s)&&t.renameSync(r,s),await this.repository.deletionIntents.delete(i)),e}}storyRoot(e){return n.join(this.state.paths.storyContentDir,ze.parse(e))}assertActionTargets(e){for(const t of e)if(this.state.requireInstance(t.targetInstanceId).nodeId!==this.state.node.id)throw FE("STORY_NODE_MISMATCH","Story Action target belongs to another node.",409)}fsyncDirectory(e){if("win32"===process.platform)return;const n=t.openSync(e,"r");try{t.fsyncSync(n)}finally{t.closeSync(n)}}}function FE(e,t,n,i){return Object.assign(new Error(t),{code:e,statusCode:n,details:i})}const $E=c.z.object({agent:qe,cwd:kt,cwdFolderId:c.z.string().trim().min(1).max(120).optional(),gitSelection:Mt.optional(),workspaceSelection:Pt.optional(),message:c.z.string().trim().min(1).max(32e3),permissionMode:Tt.optional(),clientRequestId:Oe,modelSelection:Dt.optional(),reasoningEffort:Lt.optional(),storyId:ze}).strict().refine(e=>!(e.gitSelection&&e.workspaceSelection),{message:"gitSelection and workspaceSelection are mutually exclusive.",path:["workspaceSelection"]}),HE=c.z.object({disposition:c.z.enum(["created","already-created"]),aiSessionId:c.z.string().trim().min(1).max(120)}).strict();class qE{state;stories;fetchImpl;resolveInstanceWeb;constructor(e,t,n,i){this.state=e,this.stories=t,this.fetchImpl=n,this.resolveInstanceWeb=i}async resolve(e,t,n){const i=n?.id===e?n:await this.stories.automationContext(e);if(!i)throw BE("STORY_NOT_FOUND","Story was not found.",404);if(i.archivedAt)throw BE("STORY_ARCHIVED","Archived Story Action cannot run.",409);const s=i.actions.find(e=>e.id===t);if(!s)throw BE("STORY_ACTION_NOT_FOUND","Story Action was not found.",404);if(!s.targetInstanceId)throw BE("STORY_ACTION_TARGET_REQUIRED","Story Action requires a target instance.",409);const o=this.state.requireInstance(s.targetInstanceId);if(o.nodeId!==this.state.node.id)throw BE("STORY_NODE_MISMATCH","Story Action target belongs to another node.",409);return{storyId:i.id,actionId:s.id,targetInstanceId:o.id,prompt:s.promptTemplate,sessionPreset:s.sessionPreset,cwd:this.runtimeCwd(o,s.sessionPreset?.cwdFolderId)}}request(e,t){const n=e.sessionPreset;return $E.parse({agent:n?.agent||"codex",cwd:{type:"runtime-path",path:e.cwd},cwdFolderId:n?.cwdFolderId,gitSelection:n?.gitSelection,workspaceSelection:n?.workspaceSelection,message:e.prompt,permissionMode:n?.permissionMode||"ask",clientRequestId:t,modelSelection:n?.modelSelection,reasoningEffort:n?.reasoningEffort,storyId:e.storyId})}async dispatch(e,t){const n=this.state.requireInstance(e.targetInstanceId);if(!n.registrationToken)throw BE("STORY_ACTION_INSTANCE_CREDENTIAL_MISSING","Target instance has no registration credential.",503);const i=this.request(e,t),s=i.modelSelection?{...i,modelSelection:_s(n.capabilities,i.agent,i.modelSelection)}:i;let o;try{o=await this.fetchImpl(`${await this.resolveInstanceWeb(n)}/api/internal/node-agent/story-automation/ai-sessions`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${n.registrationToken}`},body:JSON.stringify(s)})}catch(e){throw BE("STORY_ACTION_DISPATCH_UNAVAILABLE","Target instance is temporarily unavailable.",503,e,!0)}const r=await o.json().catch(()=>({}));if(!o.ok)throw BE(r.error?.code||"STORY_ACTION_DISPATCH_FAILED",r.error?.message||`Target instance returned HTTP ${o.status}.`,o.status);return HE.parse(r.data)}async run(e,t,n){const i=await this.resolve(e,t),s=await this.dispatch(i,n);return{targetInstanceId:i.targetInstanceId,aiSessionId:s.aiSessionId}}runtimeCwd(e,t){if(!t)return e.runtime.workspacePath||e.workspace.path||"/workspace";const n=U_(this.state,e,t);if("unknown-folder"===n.status)throw BE("NODE_LOCAL_FOLDER_NOT_FOUND","Story Action working folder was not found.",404);if("unsupported-source"===n.status)throw BE("AI_SESSION_CWD_UNAVAILABLE","Working folder is unavailable for this instance source.",409);if("outside-workspace"===n.status)throw BE("AI_SESSION_CWD_OUTSIDE_WORKSPACE","Working folder is outside the instance workspace.",409);return n.runtimePath}}function BE(e,t,n,i,s=!1){return Object.assign(new Error(t),{code:e,statusCode:n,retryable:s,...void 0===i?{}:{cause:i}})}class VE{runtime;nextRunAt=new Map;completion=new Map;registeredAutomationIds=new Set;backgroundMutations=new Set;state;stories;automations;publish;now;actionExecution;constructor(e,t,n,i,s,o,r=()=>new Date,a){this.state=e,this.stories=t,this.automations=n,this.publish=o,this.now=r,this.actionExecution=a||new qE(e,t,i,s),this.runtime=new K_({execute:({runId:e})=>this.executeRun(e),skipped:({runId:e},t)=>this.trackMutation(this.skipRun(e,t))})}async start(){this.runtime.stop(),this.runtime.start(),this.nextRunAt.clear(),this.registeredAutomationIds.clear();for(const e of await this.automations.list())await this.register(e);for(const e of await this.automations.pendingRuns())await this.resume(e);await this.reconcileInstances()}async stop(){this.runtime.stop(),this.nextRunAt.clear(),await Promise.allSettled([...this.backgroundMutations])}async refresh(){for(const e of this.registeredAutomationIds)this.runtime.clearTimer(e);this.registeredAutomationIds.clear(),this.nextRunAt.clear();for(const e of await this.automations.list())e.enabled&&!await this.blockedReason(e)||this.runtime.clearQueued(e.id),await this.register(e)}async clearStory(e){for(const t of await this.automations.list(e))this.runtime.clearTimer(t.id),this.runtime.clearQueued(t.id),this.registeredAutomationIds.delete(t.id),this.nextRunAt.delete(t.id)}async status(e){const t=await this.requireAutomation(e),n=await this.automations.runsFor(e),i=n.filter(e=>!GE(e.status)),s=await this.blockedReason(t),o=n.find(e=>GE(e.status)),r=t.enabled?s?"blocked":i.length?"running":"failed"===o?.status?"error":"scheduled":"disabled";return wy.parse({automation:t,effectiveStatus:r,blockedReason:s,nextRunAt:this.nextRunAt.get(e),currentRuns:i.slice(0,20),lastRun:o})}async list(e){return Promise.all((await this.automations.list(e)).map(e=>this.status(e.id)))}async create(e){const t=await this.validateInput(e),n=await this.automations.create(t);return await this.register(n),await this.publishStatus(n.id,"created"),this.status(n.id)}async validateCreate(e,t){const n=fy.parse(e);return await this.validateReferences({...n,id:"validation",createdAt:this.now().toISOString(),updatedAt:this.now().toISOString()},t),n}async activateCreated(e){const t=await this.requireAutomation(e);return await this.register(t),await this.publishStatus(e,"created"),this.status(e)}async update(e,t,n){const i={...await this.requireAutomation(e),...t};if(await this.validateReferences(i),await this.automations.update(e,t,n))return await this.refresh(),await this.publishStatus(e,"updated"),this.status(e)}setEnabled(e,t){return this.update(e,{enabled:t})}async delete(e,t){const n=await this.requireAutomation(e),i=await this.automations.delete(e,t);return i&&(this.runtime.clearTimer(e),this.nextRunAt.delete(e),this.publish?.(vy,{storyId:n.storyId,automationId:e,change:"deleted"},{nodeId:this.state.node.id})),i}async manualRun(e,t){const n=await this.requireAutomation(e),i=this.now().toISOString(),s=X_(e,"manual",t.clientRequestId),o=await this.automations.runByExecutionKey(s);if(o)return this.automations.run(o.id);const r=await this.prepareRun(n,"manual",i,s);return this.runtime.submit(e,{runId:r.id},n.policy),this.automations.run(r.id)}async runs(e){return await this.requireAutomation(e),this.automations.runsFor(e)}async reconcileInstances(e){for(const t of(await this.automations.pendingRuns()).filter(e=>"running"===e.status&&e.aiSessionId)){if(e&&t.targetInstanceId!==e)continue;const n=this.state.listInstances().find(e=>e.id===t.targetInstanceId),i=n?.aiSessions.sessions.find(e=>e.id===t.aiSessionId);if(!i&&e!==t.targetInstanceId)continue;if(i&&"idle"!==i.status&&"failed"!==i.status)continue;const s="failed"===i?.status?"failed":"completed",o="failed"===s?{code:"AI_SESSION_FAILED",message:"The automated AI Session failed."}:void 0,r=await this.automations.transition(t.id,s,o?{error:o}:{});this.resolveCompletion(t.id),await this.publishRun(r),await this.publishStatus(t.automationId,"status")}}async register(e){if(!e.enabled||await this.blockedReason(e))return;const t=await this.automations.stored(e.id);if(!t)return;const n=function(e){const t=e.schedule;if("interval"===t.scheduleKind)return{type:"interval",intervalMs:t.intervalMs};if("daily"===t.scheduleKind)return{type:"daily",timeOfDay:t.timeOfDay,timezone:t.timezone};if("weekly"===t.scheduleKind)return{type:"weekly",weekdays:t.weekdays,timeOfDay:t.timeOfDay,timezone:t.timezone};if("monthly"===t.scheduleKind)return{type:"monthly",dayOfMonth:t.dayOfMonth,timeOfDay:t.timeOfDay,timezone:t.timezone};throw new Error(`Unsupported Story automation schedule kind: ${t.schedule.scheduleKind}`)}(e),i=function(e,t,n=t){if("interval"===e.type){const i=Math.max(0,t.getTime()-n.getTime()),s=Math.floor(i/e.intervalMs)+1;return new Date(n.getTime()+s*e.intervalMs)}const[i,s]=e.timeOfDay.split(":").map(Number);if("monthly"===e.type&&e.dayOfMonth<0)return function(e,t,n,i,s){const o=function(e,t){const n=new Intl.DateTimeFormat("en-US",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(e),i=e=>Number(n.find(t=>t.type===e)?.value);return{year:i("year"),month:i("month")-1,day:i("day")}}(s,i),r=[];for(let a=0;a<12;a+=1){const c=new Date(Date.UTC(o.year,o.month+a,1)),d=c.getUTCFullYear(),l=c.getUTCMonth(),u=W_(d,l)+e+1;r.push(Y_(u,l+1,t,n,i,s))}return r.sort((e,t)=>e.getTime()-t.getTime()),r[0]}(e.dayOfMonth,i,s,e.timezone,t);const o="weekly"===e.type?[...new Set(e.weekdays)].sort((e,t)=>e-t).join(","):"*",r="monthly"===e.type?String(e.dayOfMonth):"*";return v.CronExpressionParser.parse(`0 ${s} ${i} ${r} * ${o}`,{currentDate:t,strict:!0,tz:e.timezone}).next().toDate()}(n,this.now(),new Date(t.scheduleAnchorAt));this.nextRunAt.set(e.id,i.toISOString()),this.registeredAutomationIds.add(e.id);const s=setTimeout(()=>{this.trackMutation(this.handleTimer(e.id,i))},Math.max(1,i.getTime()-this.now().getTime()));s.unref?.(),this.runtime.setTimer(e.id,s)}async handleTimer(e,t){const n=await this.automations.get(e);if(!n?.enabled||await this.blockedReason(n))return;const i=t.toISOString();try{const e=await this.prepareRun(n,"schedule",i,X_(n.id,"schedule",i));this.runtime.submit(n.id,{runId:e.id},n.policy)}catch{await this.publishStatus(n.id,"status")}await this.register(n),await this.publishStatus(n.id,"status")}async prepareRun(e,t,n,i){const s=await this.executionInput(e),o=this.actionExecution.request(s,i);return this.automations.createRun({automationId:e.id,eventType:t,scheduledFor:n,executionKey:i,requestFingerprint:(r=o,d.createHash("sha256").update(JSON.stringify(r)).digest("hex")),executionInput:s});var r}async resume(e){const t=await this.automations.get(e.automationId);t&&(e.status,this.runtime.submit(t.id,{runId:e.id},t.policy))}async executeRun(e){let t=(await this.automations.pendingRuns()).find(t=>t.id===e);if(t){if("queued"===t.status&&(t=await this.automations.transition(t.id,"dispatching")),"dispatching"===t.status)try{try{const e=await this.actionExecution.dispatch(t.executionInput,t.executionKey);t=await this.automations.transition(t.id,"running",{aiSessionId:e.aiSessionId}),await this.publishRun(t)}catch(e){if(e&&"object"==typeof e&&"retryable"in e&&!0===e.retryable)return void await this.publishStatus(t.automationId,"status");throw e}}catch(e){const n=await this.automations.transition(t.id,"failed",{error:KE(e)});return await this.publishRun(n),void await this.publishStatus(t.automationId,"status")}await this.completionFor(t.id).promise}}async skipRun(e,t){const n=await this.automations.run(e);if(!n||"queued"!==n.status)return;const i=await this.automations.transition(e,"skipped",{error:{code:`STORY_AUTOMATION_${t.replaceAll("-","_").toUpperCase()}`,message:WE(t)}});await this.publishRun(i)}async executionInput(e,t){return this.actionExecution.resolve(e.storyId,e.actionId,t)}async validateInput(e){const t=fy.parse(e);return await this.validateReferences({...t,id:"validation",createdAt:this.now().toISOString(),updatedAt:this.now().toISOString()}),t}async validateReferences(e,t){await this.executionInput(e,t)}async blockedReason(e){try{return void await this.executionInput(e)}catch(e){const t=KE(e);return["STORY_ARCHIVED","STORY_DELETING","STORY_NOT_FOUND","STORY_ACTION_NOT_FOUND","STORY_ACTION_TARGET_REQUIRED","NODE_INSTANCE_NOT_FOUND","STORY_NODE_MISMATCH"].includes(t.code)?t:void 0}}async requireAutomation(e){const t=await this.automations.get(e);if(!t)throw Object.assign(new Error("Story Automation was not found."),{code:"STORY_AUTOMATION_NOT_FOUND",statusCode:404});return t}completionFor(e){const t=this.completion.get(e);if(t)return t;let n;const i={promise:new Promise(e=>{n=e}),resolve:n};return this.completion.set(e,i),i}resolveCompletion(e){this.completion.get(e)?.resolve(),this.completion.delete(e)}trackMutation(e){return this.backgroundMutations.add(e),e.finally(()=>this.backgroundMutations.delete(e)),e}async publishRun(e){const t=await this.automations.run(e.id),n=await this.automations.get(e.automationId);t&&n&&this.publish?.(vy,{storyId:n.storyId,automationId:n.id,change:"run",run:t},{nodeId:this.state.node.id,instanceId:e.targetInstanceId})}async publishStatus(e,t){const n=await this.status(e);this.publish?.(vy,{storyId:n.automation.storyId,automationId:e,change:t,status:n},{nodeId:this.state.node.id})}}function GE(e){return"completed"===e||"failed"===e||"skipped"===e}function KE(e){const t=e&&"object"==typeof e?e:void 0;return{code:"string"==typeof t?.code?t.code:"STORY_AUTOMATION_FAILED",message:"string"==typeof t?.message?t.message:String(e)}}function WE(e){return{cooldown:"Skipped by cooldown policy.",busy:"Skipped because the concurrency limit was reached.","queue-full":"Skipped because the queue is full.","scheduler-stopped":"Skipped because the scheduler stopped.","job-disabled":"Skipped because the Automation was disabled or blocked."}[e]}class YE{repository;constructor(e){this.repository=e}async settings(e){const t=await this.requireStory(e);return this.settingsFor(t)}async update(e,t){const n=sI.parse(t),i=await this.repository.transaction(async t=>{if(!await t.stories.get(e))throw XE("STORY_NOT_FOUND","Story was not found.",404);return t.stories.update(e,{agentToolsContent:n.content,agentToolsActions:n.actions,agentToolsAutomations:n.automations,agentToolsAiSessions:n.aiSessions,agentToolsDecisions:n.decisions,updatedAt:(new Date).toISOString()})});return this.settingsFor(i)}async resolve(e){const t=await this.requireStory(e),n=this.settingsFor(t),i=this.repository.agents.storyEntries.get(e),s=nI(t.archivedAt?[]:i.entries.filter(e=>{if(!this.repository.agents.definitions.get(e.agentId))return!1;const t=this.repository.agents.orchestrations.get(e.orchestrationId);return Boolean(t)&&Rp(t,e.agentId)})),o=d.createHash("sha256").update(JSON.stringify([cI(n.policy),Boolean(t.archivedAt),iI(i.revision,s)])).digest("hex");return fI.parse({storyId:e,policy:n.policy,revision:o,enabledTools:mI(n.policy,{archived:Boolean(t.archivedAt)}),agentInvocation:s})}async assertEnabled(e,t){const n=lI.safeParse(t),i=await this.resolve(e);if(!n.success||!i.enabledTools.includes(n.data))throw XE("STORY_AGENT_TOOL_DISABLED","The Story Agent tool is disabled.",403);return i}async assertAgentInvocation(e,t,n){const i=await this.resolve(e);if(!i.agentInvocation.enabledTools.includes("agent_run"))throw XE("STORY_AGENT_INVOCATION_FORBIDDEN","The Agent is not authorized as an entry Agent for this Story.",403);const s=i.agentInvocation.allowedTargets.filter(e=>e.agentId===t);if(n){const e=s.find(e=>e.orchestrationId===n);if(!e)throw XE("STORY_AGENT_INVOCATION_FORBIDDEN","The Agent is not authorized as an entry Agent for this Story.",403);return e}if(1===s.length)return s[0];if(!s.length)throw XE("STORY_AGENT_INVOCATION_FORBIDDEN","The Agent is not authorized as an entry Agent for this Story.",403);throw XE("STORY_AGENT_INVOCATION_AMBIGUOUS","The Agent is bound to multiple orchestrations in this Story; the call must name one.",409)}async requireStory(e){const t=await this.repository.stories.get(e);if(!t)throw XE("STORY_NOT_FOUND","Story was not found.",404);return t}settingsFor(e){const t=function(e){const t=aI.safeParse(e);return sI.parse({...rI,...t.success?t.data:{}})}({content:e.agentToolsContent,actions:e.agentToolsActions,automations:e.agentToolsAutomations,aiSessions:e.agentToolsAiSessions,decisions:e.agentToolsDecisions}),n=d.createHash("sha256").update(cI(t)).digest("hex");return hI.parse({policy:t,revision:n})}}function XE(e,t,n){return Object.assign(new Error(t),{code:e,statusCode:n})}class JE{state;fetchImpl;resolveInstanceWeb;warn;constructor(e,t,n,i){this.state=e,this.fetchImpl=t,this.resolveInstanceWeb=n,this.warn=i}async notify(e){const t=yI.parse(e),n=this.state.listInstances().filter(e=>e.registrationToken&&e.aiSessions.sessions.some(e=>e.storyId===t.storyId));await Promise.all(n.map(e=>this.notifyInstance(e,t)))}async notifyInstance(e,t){try{const n=await this.fetchImpl(`${await this.resolveInstanceWeb(e)}/api/internal/node-agent/story-agent-tools/invalidate`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.registrationToken}`},body:JSON.stringify(t)});if(!n.ok)throw new Error(`HTTP ${n.status}`)}catch(n){this.warn({storyId:t.storyId,revision:t.revision,instanceId:e.id,error:n instanceof Error?n.message:String(n)},"Story Agent Tool policy invalidation failed")}}}class QE{state;fetchImpl;resolveInstanceWeb;constructor(e,t,n){this.state=e,this.fetchImpl=t,this.resolveInstanceWeb=n}list(e,t,n){const i=this.candidates(e),s=(t-1)*n;return BI.parse({sessions:i.slice(s,s+n).map(({instance:e,session:t})=>({instanceId:e.id,sessionId:t.id,title:t.title,agent:t.agent,status:t.status,updatedAt:t.updatedAt})),pagination:EI(i.length,t,n)})}async get(e,t,n,i,s){const o=this.requireTarget(e,t,n),r=(a=await this.request(o.instance,`/api/internal/node-agent/story-ai-sessions/${encodeURIComponent(n)}`),GI.parse(r_.parse(a)));var a;const c=function(e){return e.map((e,t)=>({turn:e,index:t})).sort((e,t)=>{const n=[e.turn.startedAt,e.turn.updatedAt,e.turn.completedAt].filter(Boolean).sort().at(-1)||"";return([t.turn.startedAt,t.turn.updatedAt,t.turn.completedAt].filter(Boolean).sort().at(-1)||"").localeCompare(n)||t.index-e.index}).map(({turn:e})=>e)}(r.turnIndex.turns),d=(i-1)*s;return XI.parse({ref:{instanceId:t,sessionId:n},session:{cwd:r.detail.cwd,error:r.detail.error,modelName:r.detail.modelSelection?.modelName,reasoningEffort:r.detail.reasoningEffort},turns:c.slice(d,d+s).map(e=>({id:e.id,status:e.status,phase:e.phase,updatedAt:e.updatedAt,completedAt:e.completedAt})),pagination:EI(c.length,i,s)})}async turn(e,t,n,i,s,o,r){const a=this.requireTarget(e,t,n),c=(d=await this.request(a.instance,`/api/internal/node-agent/story-ai-sessions/${encodeURIComponent(n)}/turns/${encodeURIComponent(i)}`),o_.parse(a_.parse(d)));var d;const l=c.body.turn,u=(s-1)*o;return s_.parse({ref:{instanceId:t,sessionId:n},turn:{id:l.id,status:l.status,phase:l.phase,contextCompactions:l.contextCompactions,startedAt:l.startedAt,updatedAt:l.updatedAt,completedAt:l.completedAt},items:c.timeline.items.slice(u,u+o).map(e=>function(e,t){const n=[],i=(e,i)=>{if(void 0!==i)return i.length<=t?i:(n.push(e),i.slice(0,t))};if("user-message"===e.type)return{id:e.id,type:e.type,text:i("text",e.text),attachments:e.attachments,...n.length?{truncatedFields:n}:{}};if("ai-message"===e.type)return{id:e.id,type:e.type,text:i("text",e.text),...n.length?{truncatedFields:n}:{}};const s=e.paths?.slice(0,100);return e.paths&&e.paths.length>100&&n.push("paths"),{id:e.id,type:e.type,activityKind:e.activityKind,title:e.title,status:e.status,summary:i("summary",e.summary),input:i("input",e.input),output:i("output",e.output),paths:s,exitCode:e.exitCode,durationMs:e.durationMs,...n.length?{truncatedFields:n}:{}}}(e,r)),pagination:EI(c.timeline.items.length,s,o)})}candidates(e){return this.state.listInstances().flatMap(t=>t.aiSessions.sessions.flatMap(n=>this.inScope(e,t.id,n)?[{instance:t,session:n}]:[])).sort((e,t)=>t.session.updatedAt.localeCompare(e.session.updatedAt)||e.instance.id.localeCompare(t.instance.id)||e.session.id.localeCompare(t.session.id))}requireTarget(e,t,n){const i=this.candidates(e).find(({instance:e,session:i})=>e.id===t&&i.id===n);if(!i)throw ZE("AI_SESSION_NOT_FOUND","AI Session was not found.",404);return i}inScope(e,t,n){return n.storyId===e.storyId&&"subagent"!==n.lineage?.kind&&"failed"!==n.status&&(t!==e.instanceId||n.id!==e.sessionId)}async request(e,t){if(!e.registrationToken)throw ZE("AI_SESSION_UNAVAILABLE","AI Session instance is unavailable.",503);let n;try{n=await this.fetchImpl(`${await this.resolveInstanceWeb(e)}${t}`,{headers:{authorization:`Bearer ${e.registrationToken}`}})}catch(e){throw ZE("AI_SESSION_UNAVAILABLE","AI Session instance is unavailable.",503,e)}const i=await n.json().catch(()=>({}));if(!n.ok){if(404===n.status)throw ZE("AI_SESSION_NOT_FOUND","AI Session was not found.",404);throw ZE("AI_SESSION_READ_FAILED","AI Session could not be read.",n.status)}return i.data}}function ZE(e,t,n,i){return Object.assign(new Error(t),{code:e,statusCode:n,...void 0===i?{}:{cause:i}})}class eA{fetchImpl;resolveInstanceWeb;constructor(e,t){this.fetchImpl=e,this.resolveInstanceWeb=t}async close(e){if(!e.instance.registrationToken)throw new Error("AI Session instance is unavailable.");const t=await this.fetchImpl(`${await this.resolveInstanceWeb(e.instance)}/api/internal/node-agent/ai-sessions/${encodeURIComponent(e.sessionId)}/close-for-story-deletion`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.instance.registrationToken}`},body:JSON.stringify({clientRequestId:d.randomUUID(),storyId:e.storyId})});if(!t.ok)throw new Error(`AI Session close failed with HTTP ${t.status}.`)}}const tA=c.z.object({turnId:c.z.string().trim().min(1).max(240).optional()}).strip();class nA{state;repository;fetchImpl;resolveInstanceWeb;publish;constructor(e,t,n,i,s){this.state=e,this.repository=t,this.fetchImpl=n,this.resolveInstanceWeb=i,this.publish=s}async list(e){await this.requireStory(e);const t=await this.repository.decisions.list(e);return Ly.parse({decisions:t.map(iA)})}async get(e,t){return await this.requireStory(e),iA(await this.requireDecision(e,t))}async register(e,t){const n=Cy.parse(t);if((await this.requireStory(e.storyId)).archivedAt)throw sA("STORY_ARCHIVED","Archived Story cannot accept new decisions.",409);if(!this.findSessionInstance(e.storyId,e.sessionId))throw sA("STORY_DECISION_SESSION_SCOPE_MISMATCH","The AI Session does not belong to the requested Story.",409);if(!e.turnId)throw sA("STORY_DECISION_TURN_REQUIRED","The active AI Session turn could not be determined for the decision.",409);const i=await this.repository.decisions.bySessionTurn(e.storyId,e.sessionId,e.turnId);if(i){if("pending"===i.status)return iA(i);throw sA("STORY_DECISION_CONFLICT","A decision already exists for this AI Session turn.",409)}const s=(new Date).toISOString(),o=iA(await this.repository.decisions.insert({id:`story_decision_${d.randomUUID().replace(/-/g,"").slice(0,24)}`,storyId:e.storyId,sessionId:e.sessionId,turnId:e.turnId,question:n.question,options:n.options||[],allowFreeText:n.allowFreeText??!0,context:n.context,status:"pending",revision:1,createdAt:s,updatedAt:s}));return this.emit("created",o),o}async decide(e,t,n){const i=ky.parse(n);await this.assertStoryMutable(e);const s=await this.requireDecision(e,t),o=s.options||[];if("decided"===s.status&&function(e,t){return(e.selectedOptionId||void 0)===(t.optionId||void 0)&&(e.response||void 0)===(t.response||void 0)}(s,i))return iA(s);if("pending"!==s.status)throw sA("STORY_DECISION_TERMINAL","The decision is no longer pending.",409);if(s.revision!==i.expectedRevision)throw sA("STORY_DECISION_REVISION_CONFLICT","The decision was modified by another request.",409);if(i.optionId&&!o.some(e=>e.id===i.optionId))throw sA("STORY_DECISION_OPTION_UNKNOWN","The selected decision option does not exist.",400);if(!i.optionId&&i.response&&!1===s.allowFreeText)throw sA("STORY_DECISION_FREE_TEXT_FORBIDDEN","This decision does not accept a free-text response.",400);const r=this.findSessionInstance(s.storyId,s.sessionId);if(!r)throw sA("STORY_DECISION_SESSION_UNAVAILABLE","The AI Session that raised the decision is unavailable.",409);if(!r.registrationToken)throw sA("STORY_DECISION_SESSION_UNAVAILABLE","The AI Session instance is unavailable.",503);const a=function(e,t){const n=[];if(t.optionId){const i=(e.options||[]).find(e=>e.id===t.optionId);n.push(`Selected decision option: ${i?.label||t.optionId}`)}return t.response&&n.push(t.response),n.join("\n\n")}(s,i),c=hs(r.capabilities).features.aiSessionSendIdempotency?await this.dispatchResponse(r,s,a,s.id):await this.dispatchWithResumingLedger(r,s,a,!0===i.retry),d=(new Date).toISOString(),l=await this.repository.transaction(async e=>{const n=await e.decisions.get(t);if(!n||"pending"!==n.status||n.revision!==i.expectedRevision)throw sA("STORY_DECISION_REVISION_CONFLICT","The decision was modified by another request.",409);return e.decisions.updateIfRevision(t,i.expectedRevision,{status:"decided",revision:i.expectedRevision+1,response:i.response,selectedOptionId:i.optionId,decidedTurnId:c,decidedAt:d,updatedAt:d,resumeState:null,resumeAttemptedAt:null})});if(!l)throw sA("STORY_DECISION_REVISION_CONFLICT","The decision was modified by another request.",409);const u=iA(l);return this.emit("decided",u),u}async dispatchWithResumingLedger(e,t,n,i){if("resuming"===t.resumeState&&!i)throw Object.assign(sA("STORY_DECISION_RESUME_PENDING","A previous decision reply may already have reached the AI Session. Confirm an explicit retry to send it again.",409),{retryable:!0,details:{targetTag:"v0.0.33",reason:"TARGET_INSTANCE_WITHOUT_SEND_IDEMPOTENCY",resumeAttemptedAt:t.resumeAttemptedAt||void 0}});const s=(new Date).toISOString();await this.repository.decisions.update(t.id,{resumeState:"resuming",resumeAttemptedAt:s});try{return await this.dispatchResponse(e,t,n)}catch(e){throw"STORY_DECISION_DISPATCH_UNAVAILABLE"!==e.code&&await this.repository.decisions.update(t.id,{resumeState:null,resumeAttemptedAt:null}),e}}async cancel(e,t,n){const i=Dy.parse(n);if(await this.assertStoryMutable(e),"pending"!==(await this.requireDecision(e,t)).status)throw sA("STORY_DECISION_TERMINAL","The decision is no longer pending.",409);const s=(new Date).toISOString(),o=await this.repository.transaction(async e=>e.decisions.updateIfRevision(t,i.expectedRevision,{status:"cancelled",revision:i.expectedRevision+1,updatedAt:s}));if(!o)throw sA("STORY_DECISION_REVISION_CONFLICT","The decision was modified by another request.",409);const r=iA(o);return this.emit("cancelled",r),r}async expireForSession(e,t){const n=(new Date).toISOString(),i=(await this.repository.decisions.expirePendingForSession(e,t,n)).map(iA);for(const e of i)this.emit("expired",e);return i}async expireForStory(e,t){if(!await this.repository.stories.get(e))return[];const n=(await this.repository.decisions.list(e)).filter(e=>"pending"===e.status),i=[];for(const e of n){const n=await this.repository.decisions.updateIfRevision(e.id,e.revision,{status:"expired",revision:e.revision+1,expiredReason:t,updatedAt:(new Date).toISOString()});if(n){const e=iA(n);this.emit("expired",e),i.push(e)}}return i}async dispatchResponse(e,t,n,i){if(!e.registrationToken)throw sA("STORY_DECISION_SESSION_UNAVAILABLE","The AI Session instance is unavailable.",503);let s;try{s=await this.fetchImpl(`${await this.resolveInstanceWeb(e)}/api/internal/node-agent/ai-sessions/${encodeURIComponent(t.sessionId)}/messages`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.registrationToken}`},body:JSON.stringify(i?{message:n,clientRequestId:i}:{message:n})})}catch(e){throw sA("STORY_DECISION_DISPATCH_UNAVAILABLE","The AI Session instance is temporarily unavailable.",503,e)}const o=await s.json().catch(()=>({}));if(!s.ok)throw sA(o.error?.code||"STORY_DECISION_DISPATCH_FAILED",o.error?.message||`AI Session send failed with HTTP ${s.status}.`,s.status);return tA.parse(o.data||{}).turnId}findSessionInstance(e,t){return this.state.listInstances().find(n=>Boolean(n.registrationToken)&&n.aiSessions.sessions.some(n=>n.id===t&&n.storyId===e))}async requireStory(e){const t=await this.repository.stories.get(e);if(!t)throw sA("STORY_NOT_FOUND","Story was not found.",404);return t}async assertStoryMutable(e){const t=await this.requireStory(e);if(t.archivedAt)throw sA("STORY_DECISION_STORY_ARCHIVED","Archived Story decisions are read-only.",409);return t}async requireDecision(e,t){const n=await this.repository.decisions.get(t);if(!n||n.storyId!==e)throw sA("STORY_DECISION_NOT_FOUND","Story decision was not found.",404);return n}emit(e,t){this.publish?.({storyId:t.storyId,decisionId:t.id,revision:t.revision,change:e,decision:t})}}function iA(e){return xy.parse({id:e.id,storyId:e.storyId,sessionId:e.sessionId,turnId:e.turnId||void 0,question:e.question,options:e.options||[],allowFreeText:e.allowFreeText,context:e.context||void 0,status:e.status,revision:e.revision,response:e.response||void 0,selectedOptionId:e.selectedOptionId||void 0,decidedTurnId:e.decidedTurnId||void 0,expiredReason:e.expiredReason||void 0,createdAt:e.createdAt,updatedAt:e.updatedAt,decidedAt:e.decidedAt||void 0})}function sA(e,t,n,i){return Object.assign(new Error(t),{code:e,statusCode:n,...void 0===i?{}:{cause:i}})}class oA{closed=new Set;pending=new Set;reconciliation;state;stories;fetchImpl;resolveInstanceWeb;warn;onSessionClosed;constructor(e,t,n,i,s){this.state=e,this.stories=t,this.fetchImpl=n,this.resolveInstanceWeb=i,this.warn=s}setSessionClosedHandler(e){this.onSessionClosed=e}reconcile(){if(this.reconciliation)return this.reconciliation;const e=this.reconcileOnce().finally(()=>{this.reconciliation===e&&(this.reconciliation=void 0)});return this.reconciliation=e,e}async reconcileOnce(){const e=new Map,t=new Set,n=[];for(const n of this.state.listInstances()){if(!n.registrationToken)continue;let i;try{i=await this.fetchImpl(`${await this.resolveInstanceWeb(n)}/api/internal/node-agent/ai-sessions/idle-retention`,{headers:{authorization:`Bearer ${n.registrationToken}`}})}catch(e){this.warn({instanceId:n.id,error:e instanceof Error?e.message:String(e)},"could not inspect Story idle sessions");continue}if(!i.ok)continue;const s=await i.json().catch(()=>({}));if(Array.isArray(s.data))for(const i of s.data){if(!i||"object"!=typeof i)continue;const s=i;if("string"!=typeof s.sessionId||"string"!=typeof s.storyId||"idle"!==s.status)continue;if(void 0===aA(s))continue;if(!await this.stories.exists(s.storyId))continue;const o=`${n.id}:${s.sessionId}`;if(t.add(o),this.closed.has(o))continue;const r=e.get(s.storyId)||[];r.push({instance:n,sessionId:s.sessionId,storyId:s.storyId,status:"idle",completedAt:s.completedAt,updatedAt:s.updatedAt}),e.set(s.storyId,r)}}for(const[t,i]of e){const e=(await this.stories.retentionSettings(t)).maxIdleAiSessions;for(;i.length>e;){i.sort((e,t)=>aA(e)-aA(t)||`${e.instance.id}:${e.sessionId}`.localeCompare(`${t.instance.id}:${t.sessionId}`));const e=i.shift(),s=`${e.instance.id}:${e.sessionId}`;this.pending.has(s)||(this.pending.add(s),n.push(this.close(e,s).catch(n=>{this.warn({storyId:t,instanceId:e.instance.id,sessionId:e.sessionId,error:n instanceof Error?n.message:String(n)},"Story idle Session retention close failed"),setTimeout(()=>{this.reconcile()},5e3).unref?.()})))}}await Promise.all(n);for(const e of this.closed)t.has(e)||this.closed.delete(e)}async close(e,t){try{if(!await this.isUnchangedCandidate(e))return;const n=await this.fetchImpl(`${await this.resolveInstanceWeb(e.instance)}/api/internal/node-agent/ai-sessions/${encodeURIComponent(e.sessionId)}/close`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.instance.registrationToken}`},body:JSON.stringify({clientRequestId:d.randomUUID()})});if(204===n.status)return;if(!n.ok)throw new Error(`HTTP ${n.status}`);this.closed.add(t),await(this.onSessionClosed?.(e.sessionId))}finally{this.pending.delete(t)}}async isUnchangedCandidate(e){const t=await this.fetchImpl(`${await this.resolveInstanceWeb(e.instance)}/api/internal/node-agent/ai-sessions/idle-retention`,{headers:{authorization:`Bearer ${e.instance.registrationToken}`}});if(!t.ok)throw new Error(`HTTP ${t.status}`);const n=await t.json().catch(()=>({}));if(!Array.isArray(n.data))return!1;const i=n.data.find(t=>{if(!t||"object"!=typeof t)return!1;const n=t;return n.sessionId===e.sessionId&&n.storyId===e.storyId&&"idle"===n.status});return void 0!==i&&aA(i)===aA(e)}}class rA{closed=new Set;pending=new Set;reconciliation;state;fetchImpl;resolveInstanceWeb;warn;constructor(e,t,n,i){this.state=e,this.fetchImpl=t,this.resolveInstanceWeb=n,this.warn=i}reconcile(){if(this.reconciliation)return this.reconciliation;const e=this.reconcileOnce().finally(()=>{this.reconciliation===e&&(this.reconciliation=void 0)});return this.reconciliation=e,e}async reconcileOnce(){const e=new Map,t=new Set,n=[];for(const n of this.state.listInstances()){if(!n.registrationToken)continue;let i;try{i=await this.fetchImpl(`${await this.resolveInstanceWeb(n)}/api/internal/node-agent/ai-sessions/instance-idle-retention`,{headers:{authorization:`Bearer ${n.registrationToken}`}})}catch(e){this.warn({instanceId:n.id,error:e instanceof Error?e.message:String(e)},"could not inspect instance idle sessions");continue}if(!i.ok)continue;const s=await i.json().catch(()=>({}));if(Array.isArray(s.data))for(const i of s.data){if(!i||"object"!=typeof i)continue;const s=i;if("string"!=typeof s.sessionId||"idle"!==s.status)continue;if(void 0===aA(s))continue;const o=`${n.id}:${s.sessionId}`;if(t.add(o),this.closed.has(o))continue;const r=e.get(n.id)||[];r.push({instance:n,sessionId:s.sessionId,status:"idle",completedAt:s.completedAt,updatedAt:s.updatedAt}),e.set(n.id,r)}}for(const[t,i]of e)for(;i.length>100;){i.sort((e,t)=>aA(e)-aA(t)||`${e.instance.id}:${e.sessionId}`.localeCompare(`${t.instance.id}:${t.sessionId}`));const e=i.shift(),s=`${e.instance.id}:${e.sessionId}`;this.pending.has(s)||(this.pending.add(s),n.push(this.close(e,s).catch(n=>{this.warn({instanceId:t,sessionId:e.sessionId,error:n instanceof Error?n.message:String(n)},"Instance idle Session retention close failed"),setTimeout(()=>{this.reconcile()},5e3).unref?.()})))}await Promise.all(n);for(const e of this.closed)t.has(e)||this.closed.delete(e)}async close(e,t){try{const n=await this.fetchImpl(`${await this.resolveInstanceWeb(e.instance)}/api/internal/node-agent/ai-sessions/${encodeURIComponent(e.sessionId)}/close`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.instance.registrationToken}`},body:JSON.stringify({clientRequestId:d.randomUUID()})});if(204===n.status)return;if(!n.ok)throw new Error(`HTTP ${n.status}`);this.closed.add(t)}finally{this.pending.delete(t)}}}function aA(e){return cA(e.completedAt)??cA(e.updatedAt)}function cA(e){const t=e?Date.parse(e):Number.NEGATIVE_INFINITY;return Number.isFinite(t)?t:void 0}const dA=c.z.object({path:c.z.string().trim().min(1).max(2048),method:c.z.string().trim().min(1).max(20).default("GET"),headers:c.z.record(c.z.string(),c.z.string()).default({}),body:c.z.string().optional(),bodyBase64:c.z.string().optional()}).strict(),lA=c.z.object({id:c.z.string().trim().min(1).max(120).optional(),name:c.z.string().trim().max(160),path:c.z.string().trim().min(1).max(4096),defaultImageSelection:Ds.optional(),labels:c.z.record(c.z.string(),c.z.string()).default({})}).strict(),uA=c.z.object({name:c.z.string().trim().max(160)}).strict(),pA=c.z.object({path:c.z.string().trim().min(1).max(4096).optional(),depth:c.z.coerce.number().int().min(0).max(1).default(0)}).strict(),mA=c.z.object({id:c.z.string().trim().min(1).max(120).optional(),name:c.z.string().trim().min(1).max(160).optional(),runtimeId:c.z.string().trim().min(1).max(120),imageSelection:Ds.optional(),environmentSource:Ls.optional(),projectId:c.z.string().trim().min(1).max(120).optional(),image:Cr.optional(),source:Lo,sourceSnapshot:c.z.record(c.z.string(),c.z.unknown()).default({}),config:c.z.object({autoImportAgentConfigs:c.z.boolean().optional(),codexConfigEnabled:c.z.boolean().optional(),codexHomeMode:c.z.enum(["default","taskhandoff"]).optional(),defaultCodexPermissionMode:Tt.optional(),codexSettings:os.optional(),aiSessionHistoryLimit:c.z.number().int().min(1).max(en).optional(),aiSessionAttachmentRetentionDays:c.z.number().int().min(0).max(tn).optional(),aiSessionMaxFileAttachmentBytes:c.z.number().int().positive().max(De).optional()}).strict().optional(),modelSelection:Ia.shape.modelSelection,gitWorkspaceProvisioning:vi.optional()}).strict().superRefine((e,t)=>{e.environmentSource&&e.imageSelection&&t.addIssue({code:"custom",path:["environmentSource"],message:"environmentSource and imageSelection are mutually exclusive."}),"template"===e.environmentSource?.type&&e.image&&t.addIssue({code:"custom",path:["image"],message:"Template environment source is resolved by the node-agent and cannot include an image snapshot."}),e.gitWorkspaceProvisioning&&"local-folder"===e.source.type&&t.addIssue({code:"custom",path:["gitWorkspaceProvisioning"],message:"Git provisioning requires a Git source."})}),hA=c.z.object({name:c.z.string().trim().min(1).max(160).optional(),config:c.z.object({autoImportAgentConfigs:c.z.boolean().optional(),codexConfigEnabled:c.z.boolean().optional(),codexHomeMode:c.z.enum(["default","taskhandoff"]).optional(),defaultCodexPermissionMode:Tt.optional(),codexSettings:os.optional(),aiSessionHistoryLimit:c.z.number().int().min(1).max(en).optional(),aiSessionAttachmentRetentionDays:c.z.number().int().min(0).max(tn).optional(),aiSessionMaxFileAttachmentBytes:c.z.number().int().positive().max(De).optional()}).strict().optional(),modelSelection:Ia.shape.modelSelection.optional()}).strict(),gA=c.z.object({id:c.z.string().trim().min(1).max(120).optional(),name:c.z.string().trim().min(1).max(160),type:c.z.enum(["docker","kubernetes","local"]),status:c.z.enum(["unknown","online","offline","degraded"]).default("unknown"),accessStrategy:c.z.enum(["node-proxy","direct-port","kubernetes-ingress","kubernetes-port-forward"]).optional(),capabilities:c.z.record(c.z.string(),c.z.unknown()).default({}),labels:c.z.record(c.z.string(),c.z.string()).default({})}).strict(),fA=gA.omit({id:!0}).partial().strict();function yA(e){const t=e.authorization;return"string"==typeof t&&t.startsWith("Bearer ")?t.slice(7).trim():void 0}class IA{operations=new Map;intents=new Map;intent(e){const t=this.intents.get(e);if(t)return t;const n={controller:new AbortController};return this.intents.set(e,n),n}invalidate(e){this.intents.get(e)?.controller.abort();const t={controller:new AbortController};return this.intents.set(e,t),t}isIntentCurrent(e,t){return this.intents.get(e)===t}signal(e,t){const n=this.intents.get(e);return n===t?n.controller.signal:AbortSignal.abort()}clearIntent(e){this.intents.delete(e)}async run(e,t){const n=this.operations.get(e)||Promise.resolve();let i;const s=new Promise(e=>{i=e});this.operations.set(e,s),await n;try{return await t()}finally{i(),this.operations.get(e)===s&&this.operations.delete(e)}}}const _A=c.z.object({gitWorkspaceProvisioning:vi.optional()}).strict().default({});class EA{state;images;options;inFlight=new Map;abortController=new AbortController;stopped=!1;constructor(e,t,n){this.state=e,this.images=t,this.options=n}retry(e){const t=this.state.requireInstance(e);if("docker"!==this.state.requireRuntime(t.runtimeId).type||!t.imageSnapshot)throw Object.assign(new Error(`Instance ${e} does not use a Docker image.`),{statusCode:400,code:"INSTANCE_IMAGE_PROVISIONING_UNSUPPORTED"});if("failed"!==t.status||"failed"!==t.imageProvisioning?.phase)throw Object.assign(new Error(`Instance ${e} does not have failed image provisioning to retry.`),{statusCode:409,code:"INSTANCE_IMAGE_PROVISIONING_NOT_FAILED"});const n=de();return this.state.controlledInstances.put(Ia.parse({...t,status:"provisioning",health:"unknown",imageProvisioning:{phase:"checking-image",requestedReference:t.imageSnapshot.requestedReference,generation:(t.imageProvisioning?.generation||0)+1,startedAt:n,updatedAt:n},updatedAt:n}))}provision(e,t){if(this.stopped)return Promise.resolve();const n=e.imageProvisioning?.generation;if(void 0===n)return Promise.resolve();const i=`${e.id}:${n}`,s=this.inFlight.get(i);if(s)return s;const o=this.provisionGeneration(e,n,t).finally(()=>{this.inFlight.get(i)===o&&this.inFlight.delete(i)});return this.inFlight.set(i,o),o}async stop(){this.stopped=!0,this.abortController.abort(),await Promise.allSettled([...this.inFlight.values()])}async provisionGeneration(e,t,n){const i=this.currentGeneration(e.id,t,!0,e.createdAt);if(!i)return;let s,o=0,r=!1,a=Promise.resolve();try{const c=await this.images.ensure(i.imageSnapshot.requestedReference,n=>{a=a.then(async()=>{if(!s)try{await this.updatePhase(e.id,t,n,e.createdAt)}catch(e){s={error:e}}})},n=>{this.stopped||(r=!0,o=n.sequence,this.publishTerminalOutput(e,t,n))},this.abortController.signal);if(await a,s)throw s.error;if(this.stopped)return;r&&this.publishFinished(e,t,o+1,"succeeded");const d=async()=>{if(this.stopped)return;const i=this.currentGeneration(e.id,t,!0,e.createdAt);if(!i)return;const s=this.state.controlledInstances.put(Ia.parse({...i,status:"provisioning"===i.status?"created":i.status,health:"unknown",imageSnapshot:{...i.imageSnapshot,requestedReference:c.requestedReference,resolvedDigest:c.resolvedDigest,resolvedReference:c.resolvedReference},imageProvisioning:{...i.imageProvisioning,phase:"ready",error:void 0,updatedAt:de()},updatedAt:de()}));this.options.sync(),this.options.diagnostic({instanceId:e.id,action:"image.provision",reference:c.requestedReference,digest:c.resolvedDigest,pulled:c.pulled},"node instance image provisioning completed"),"starting"===s.status&&await(n?.())};await(this.options.runInstanceOperation?.(e.id,d)??d())}catch(n){if(await a,s&&(n=s.error),this.stopped)return;r&&this.publishFinished(e,t,o+1,"failed");const i=n instanceof Error?n.message:String(n),c=async()=>{if(this.stopped)return;const n=this.currentGeneration(e.id,t,!1,e.createdAt);n?.imageProvisioning&&["provisioning","starting"].includes(n.status)&&(this.state.controlledInstances.put(Ia.parse({...n,status:"failed",health:"failed",imageProvisioning:{...n.imageProvisioning,phase:"failed",error:i,updatedAt:de()},updatedAt:de()})),this.options.sync(),this.options.warn({instanceId:e.id,action:"image.provision",reference:n.imageProvisioning.requestedReference,error:i},"node instance image provisioning failed"))};await(this.options.runInstanceOperation?.(e.id,c)??c())}}currentGeneration(e,t,n=!0,i){const s=this.state.controlledInstances.get(e);if(!(!s||i&&s.createdAt!==i||s.imageProvisioning?.generation!==t||n&&!s.imageSnapshot))return s}async updatePhase(e,t,n,i){if(this.stopped)return;const s=async()=>{if(this.stopped)return;const s=this.currentGeneration(e,t,!0,i);s&&["provisioning","starting"].includes(s.status)&&(this.state.controlledInstances.put(Ia.parse({...s,status:"starting"===s.status?"starting":"provisioning",imageProvisioning:{...s.imageProvisioning,phase:n,error:void 0,updatedAt:de()},updatedAt:de()})),this.options.sync())};await(this.options.runInstanceOperation?.(e,s)??s())}eventBase(e,t){return{instanceId:e.id,generation:t,requestedReference:e.imageProvisioning.requestedReference,observedAt:de()}}publishTerminalOutput(e,t,n){for(const[i,s]of function(e,t=6e4){const n=[];for(let i=0;i<e.length;i+=t)n.push(e.slice(i,i+t));return n}(n.data).entries())this.options.publish(Dr,{...this.eventBase(e,t),sequence:1e3*n.sequence+i,data:s,...n.replay?{replay:!0}:{}},e.id)}publishFinished(e,t,n,i){this.options.publish(Lr,{...this.eventBase(e,t),sequence:1e3*n,outcome:i},e.id)}}const AA={GIT_WORKSPACE_PROVISIONING_TIMEOUT:"Git workspace provisioning timed out",GIT_WORKSPACE_PROVISIONING_CANCELLED:"Git workspace provisioning was cancelled",GIT_WORKSPACE_PROVISIONING_CLONE_FAILED:"Git clone failed",GIT_WORKSPACE_PROVISIONING_AUTHENTICATION_REJECTED:"Git authentication rejected",GIT_WORKSPACE_PROVISIONING_CREDENTIAL_AMBIGUOUS:"Git credential is ambiguous",GIT_WORKSPACE_PROVISIONING_CREDENTIAL_MISSING:"Git credential is missing",GIT_WORKSPACE_PROVISIONING_HOST_KEY_REQUIRED:"Git host key is not pinned",GIT_WORKSPACE_PROVISIONING_LFS_FAILED:"Git LFS pull failed",GIT_WORKSPACE_PROVISIONING_REF_NOT_FOUND:"Git ref was not found",GIT_WORKSPACE_PROVISIONING_REMOTE_UNSUPPORTED:"Git remote is not supported",GIT_WORKSPACE_PROVISIONING_SSH_AGENT_UNAVAILABLE:"Git SSH agent is unavailable",GIT_WORKSPACE_PROVISIONING_SUBDIRECTORY_NOT_FOUND:"Git subdirectory was not found",GIT_WORKSPACE_PROVISIONING_WORKSPACE_NOT_EMPTY:"Workspace is not empty",GIT_WORKSPACE_PROVISIONING_WORKSPACE_OWNERSHIP_MISMATCH:"Workspace belongs to another instance",GIT_CREDENTIAL_MISSING:"Git credential is missing",GIT_CREDENTIAL_AMBIGUOUS:"Git credential is ambiguous",GIT_CREDENTIAL_MISSING_HOST_KEY:"Git host key is not pinned"};class TA{state;options;inFlight=new Map;abortController=new AbortController;stopped=!1;constructor(e,t){this.state=e,this.options=t}provision(e,t){if(this.stopped)return Promise.resolve();const n=e.workspace.gitProvisioning?.generation;if(void 0===n)return Promise.resolve();const i=`${e.id}:${n}`,s=this.inFlight.get(i);if(s)return s;const o=this.provisionGeneration(e,n,t).finally(()=>{this.inFlight.get(i)===o&&this.inFlight.delete(i)});return this.inFlight.set(i,o),o}retry(e){const t=this.state.get(e);if(!t)throw Object.assign(new Error(`Instance ${e} was not found.`),{statusCode:404,code:"NODE_INSTANCE_NOT_FOUND"});const n=t.workspace.gitProvisioning;if(!n||"failed"!==n.phase)throw Object.assign(new Error(`Instance ${e} does not have failed Git provisioning to retry.`),{statusCode:409,code:"INSTANCE_GIT_PROVISIONING_NOT_FAILED"});const i=de();return this.state.put(Ia.parse({...t,status:"starting",health:"unknown",ready:!1,workspace:{...t.workspace,status:"pending",error:void 0,gitProvisioning:{...n,phase:"pending",error:void 0,generation:n.generation+1,updatedAt:i}},updatedAt:i}))}async stop(){this.stopped=!0,this.abortController.abort(),await Promise.allSettled([...this.inFlight.values()])}async provisionGeneration(e,t,n){const i=this.currentGeneration(e.id,t);if(!i)return;const s=new sc;let o,r=0,a=Promise.resolve();const c=e=>{a=a.then(()=>this.updatePhase(i.id,t,e))},d=e=>{if(e)for(const[n,s]of function(e,t=6e4){const n=[];for(let i=0;i<e.length;i+=t)n.push(e.slice(i,i+t));return n}(e).entries())this.options.publish($r,{...this.eventBase(i,t),sequence:1e3*(r+=1)+n,data:s},i.id)};try{await this.updatePhase(i.id,t,"cloning");const e=this.options.context(i);if(await this.options.run(e,{signal:this.abortController.signal,onOutput:e=>{const t=s.push(e);t.stage&&c(t.stage),t.commit&&(o=t.commit),d(e)}}),await a,this.stopped)return;this.publishFinished(i,t,++r,"succeeded"),await this.commitReady(i,t,o,n)}catch(e){if(s.flush(),await a,this.stopped)return;const n=function(e){const t=function(e){const t=e&&"object"==typeof e?e.code:void 0;return"string"==typeof t?t:void 0}(e);return t?.startsWith("GIT_WORKSPACE_PROVISIONING_")||t?.startsWith("GIT_CREDENTIAL_")?t:Uc(e)}(e),o=function(e,t){const n=AA[e]||"Git workspace provisioning failed",i=t?(s=t,s.replace(/(\b[a-z][a-z0-9+.-]*:\/\/)([^/@\s]+)@/gi,"$1***@")).slice(0,500):void 0;var s;return i?`${n}: ${i}`:n}(n,s.failureDetail()??(e instanceof Error?e.message:void 0));this.publishFinished(i,t,++r,"failed"),await this.commitFailure(i.id,t,o,n)}}currentGeneration(e,t){const n=this.state.get(e);if(n&&n.workspace.gitProvisioning?.generation===t)return n}async updatePhase(e,t,n){this.stopped||await this.runOperation(e,async()=>{if(this.stopped)return;const i=this.currentGeneration(e,t);if(!i||!["provisioning","starting"].includes(i.status))return;const s=i.workspace.gitProvisioning;s.phase!==n&&(this.state.put(Ia.parse({...i,workspace:{...i.workspace,gitProvisioning:{...s,phase:n,updatedAt:de()}},updatedAt:de()})),this.options.sync())})}async commitReady(e,t,n,i){const s=await this.runOperation(e.id,async()=>{if(this.stopped)return;const i=this.currentGeneration(e.id,t);if(!i)return;const s=i.workspace.gitProvisioning;return this.state.put(Ia.parse({...i,workspace:{...i.workspace,mode:"git-clone",status:"ready",error:void 0,resolvedCommit:n||i.workspace.resolvedCommit,gitProvisioning:{...s,phase:"ready",error:void 0,updatedAt:de()}},updatedAt:de()}))});s&&(this.options.sync(),this.options.diagnostic({instanceId:e.id,action:"git.provision",remoteUrl:s.workspace.gitProvisioning?.remoteUrl,resolvedCommit:s.workspace.resolvedCommit},"node instance git workspace provisioning completed"),"starting"===s.status&&await(i?.()))}async commitFailure(e,t,n,i){await this.runOperation(e,async()=>{if(this.stopped)return;const s=this.currentGeneration(e,t);if(!s||!["provisioning","starting"].includes(s.status))return;const o=s.workspace.gitProvisioning;this.state.put(Ia.parse({...s,status:"failed",health:"failed",ready:!1,workspace:{...s.workspace,status:"failed",error:n,gitProvisioning:{...o,phase:"failed",error:n,updatedAt:de()}},updatedAt:de()})),this.options.sync(),this.options.warn({instanceId:e,action:"git.provision",remoteUrl:o.remoteUrl,error:n,code:i},"node instance git workspace provisioning failed")})}runOperation(e,t){return this.options.runInstanceOperation?.(e,t)??t()}eventBase(e,t){return{instanceId:e.id,generation:t,remoteUrl:e.workspace.gitProvisioning.remoteUrl,observedAt:de()}}publishFinished(e,t,n,i){this.options.publish(Hr,{...this.eventBase(e,t),sequence:1e3*n,outcome:i},e.id)}}const wA=c.z.object({name:c.z.string().trim().min(1).max(160)}).strict();function bA(e,t,n){return{code:"object"==typeof e&&e&&"code"in e&&"string"==typeof e.code?e.code:t,message:e instanceof Error?e.message:String(e),phase:n}}class NA{templateOperations=new IA;store;docker;requireInstanceValue;requireRuntimeValue;runInstanceOperationValue;privateSecretValues;isImageReferencedValue;constructor(e,t,n,i,s,o,r=()=>!1){this.store=e,this.docker=t,this.requireInstanceValue=n,this.requireRuntimeValue=i,this.runInstanceOperationValue=s,this.privateSecretValues=o,this.isImageReferencedValue=r}list(){return this.store.list()}require(e){const t=this.store.get(e);if(!t)throw Object.assign(new Error(`Environment template ${e} was not found.`),{statusCode:404,code:"ENVIRONMENT_TEMPLATE_NOT_FOUND"});return t}runTemplateOperation(e,t){return this.templateOperations.run(e,async()=>t())}async create(e,t){const n=wA.parse(t),i=this.requireInstanceValue(e),s=this.requireRuntimeValue(i.runtimeId);if("docker"!==s.type)throw Object.assign(new Error(`Runtime ${s.name} does not support environment templates.`),{statusCode:409,code:"ENVIRONMENT_TEMPLATE_RUNTIME_UNSUPPORTED"});if(!i.runtime.containerName)throw Object.assign(new Error(`Instance ${i.id} does not have a Docker container.`),{statusCode:409,code:"ENVIRONMENT_TEMPLATE_CONTAINER_NOT_FOUND"});const o=de(),r=du("envtpl"),a=`task-handoff/environment-template:${r.toLowerCase().replace(/[^a-z0-9_.-]/g,"-")}`;return this.store.put(Js.parse({id:r,name:n.name,sourceInstanceId:i.id,nodeId:i.nodeId,internalTag:a,status:"creating",createdAt:o,updatedAt:o})),this.runInstanceOperationValue(i.id,async()=>{let e,t=!1;try{const n=this.requireInstanceValue(i.id);if("docker"!==this.requireRuntimeValue(n.runtimeId).type||!n.runtime.containerName)throw Object.assign(new Error(`Instance ${i.id} is no longer a valid Docker template source.`),{code:"ENVIRONMENT_TEMPLATE_SOURCE_CHANGED"});const s=this.privateSecretValues(n);await this.docker.inspectContainerConfigSecurity(n.runtime.containerName,s),e=await this.docker.commitEnvironmentTemplate(n.runtime.containerName,n.runtime.containerId,a),t=!0;const o=await this.docker.inspectEnvironmentTemplateImage(a);return await this.docker.inspectImageConfigSecurity(a,s),this.store.put(Js.parse({...this.require(r),...o,status:"ready",error:void 0,updatedAt:de()}))}catch(n){return t&&(await this.docker.untagEnvironmentTemplate(a,e).catch(()=>!1),e&&await this.docker.garbageCollectEnvironmentTemplateImage(e).catch(()=>!1)),this.store.put(Js.parse({...this.require(r),status:"failed",error:bA(n,"ENVIRONMENT_TEMPLATE_CREATE_FAILED","commit"),updatedAt:de()}))}})}async delete(e){return this.runTemplateOperation(e,async()=>{const t=this.require(e);this.store.put(Js.parse({...t,status:"deleting",error:void 0,updatedAt:de()}));try{const n=t.internalTag?await this.docker.untagEnvironmentTemplate(t.internalTag,t.imageId):void 0,i=t.imageId||n;return i&&!this.isImageReferencedValue(i)&&await this.docker.garbageCollectEnvironmentTemplateImage(i),this.store.delete(e),{deleted:!0,templateId:e}}catch(e){throw this.store.put(Js.parse({...t,status:"failed",error:bA(e,"ENVIRONMENT_TEMPLATE_DELETE_FAILED","delete"),updatedAt:de()})),e}})}async releaseUnusedImage(e){return!this.store.list().some(t=>t.imageId===e)&&!this.isImageReferencedValue(e)&&this.docker.garbageCollectEnvironmentTemplateImage(e)}}const SA=new Set(["content-encoding","content-length","transfer-encoding"]),vA=67108864;function OA(e){return Object.fromEntries([...e.entries()].filter(([e])=>!SA.has(e.toLowerCase())))}function RA(e){return e.bodyBase64?Buffer.from(e.bodyBase64,"base64"):e.body}function zA(){const e=Number(process.env.TASK_HANDOFF_INSTANCE_PROXY_MAX_RESPONSE_BYTES);return Number.isSafeInteger(e)&&e>0?e:67108864}const xA="x-task-handoff-trace-id";function CA(e){return e.startsWith("/")?e:`/${e}`}function kA(e,t){return e.code(502).send({error:{code:"INSTANCE_PROXY_RESPONSE_TOO_LARGE",message:`Instance response exceeds ${t} bytes.`}})}async function DA(e,t,n,i){try{return await e(t,n)}catch(e){if(n.signal?.aborted)throw e;throw i.diagnostic({instanceId:i.instanceId,action:"proxy.upstream.failed",method:i.method,path:i.path,error:e instanceof Error?e.message:String(e)},"node instance proxy upstream unavailable"),Object.assign(new Error(`Instance ${i.instanceId} web endpoint is not reachable.`),{statusCode:502,code:"INSTANCE_PROXY_UPSTREAM_UNREACHABLE",retryable:!0,cause:e})}}function LA(e,t){return Object.assign(new Error(`Instance ${e.id} has an invalid node-owned web endpoint: ${t}`),{statusCode:409,code:"NODE_INSTANCE_WEB_ENDPOINT_INVALID"})}function PA(e,t){return function(e,t={}){const n=t.fallbackWeb||(t.fallbackKind&&e.runtime?.kind===t.fallbackKind&&e.runtime.port?`http://127.0.0.1:${e.runtime.port}`:void 0),i=t.authoritativeWeb||n;if(!i){const t=new Error(`Instance ${e.id} does not have a web endpoint.`);throw Object.assign(t,{statusCode:409,code:"NODE_INSTANCE_WEB_ENDPOINT_MISSING"}),t}let s;try{s=new URL(i)}catch{throw LA(e,"endpoint is not a URL")}if("http:"!==s.protocol||"127.0.0.1"!==s.hostname||!s.port||s.username||s.password||"/"!==s.pathname&&""!==s.pathname||s.search||s.hash)throw LA(e,"endpoint must be an origin-only http://127.0.0.1:<port> URL");return s.origin}(e,{authoritativeWeb:t,fallbackKind:"local"})}async function MA(e){const t=xg(e.bindScope);return!await new Promise(t=>{const n=g.createConnection({host:"127.0.0.1",port:e.port}),i=e=>{n.removeAllListeners(),n.destroy(),t(e)};n.once("connect",()=>i(!0)),n.once("error",()=>i(!1)),n.setTimeout(250,()=>i(!1))})&&new Promise(n=>{const i=g.createServer();i.once("error",()=>n(!1)),i.listen({host:t,port:e.port,exclusive:!0},()=>i.close(()=>n(!0)))})}class jA{app;state;settings;sockets=new Set;config;source;status="error";error;onActiveListener;validateUpdate;synchronizeUpdate;updateQueue=Promise.resolve();constructor(e){this.app=e.app,this.state=e.state,this.settings=e.settings,this.config=e.config,this.source=e.source,this.onActiveListener=e.onActiveListener,this.validateUpdate=e.validateUpdate,this.synchronizeUpdate=e.synchronizeUpdate,this.app.server.on("connection",e=>{this.sockets.add(e),e.once("close",()=>this.sockets.delete(e))})}current(){return ra.parse({...this.config,host:xg(this.config.bindScope),status:this.status,source:this.source,...this.error?{error:this.error}:{}})}async start(){try{await this.listen(this.config),this.status="listening",this.error=void 0,this.state.setListenerPort(this.config.port)}catch(e){throw this.status="error",this.error=e instanceof Error?e.message:String(e),this.app.log.error({host:xg(this.config.bindScope),port:this.config.port,error:this.error},"node agent TCP listener failed to start"),Object.assign(new Error(`Failed to bind node agent TCP listener at ${xg(this.config.bindScope)}:${this.config.port}: ${this.error}`),{statusCode:409,code:"NODE_AGENT_LISTENER_BIND_FAILED"})}const e=this.current();return this.onActiveListener?.(e),e}update(e){const t=this.updateQueue.then(()=>this.updateOnce(e));return this.updateQueue=t.then(()=>{},()=>{}),t}async updateOnce(e){const t=aa.parse(e);if(t.bindScope===this.config.bindScope&&t.port===this.config.port)return this.current();if(t.port!==this.config.port){const e=this.state.runningInstanceCount();if(e>0&&!this.synchronizeUpdate)throw Object.assign(new Error(`Cannot change the node agent port while ${e} controlled instance(s) are running.`),{statusCode:409,code:"NODE_AGENT_LISTENER_PORT_IN_USE_BY_INSTANCES",blockingInstanceCount:e});await(this.validateUpdate?.(t))}const n=this.snapshot();await this.stop();try{await this.listen(t)}catch(e){throw await this.restore(n),Object.assign(new Error(`Failed to bind node agent TCP listener at ${xg(t.bindScope)}:${t.port}: ${e instanceof Error?e.message:String(e)}`),{statusCode:409,code:"NODE_AGENT_LISTENER_BIND_FAILED"})}this.state.setListenerPort(t.port);try{await(this.synchronizeUpdate?.(t))}catch(e){throw await this.stop(),await this.restore(n),await Promise.resolve(this.synchronizeUpdate?.(n.config)).catch(e=>{this.app.log.error({error:e instanceof Error?e.message:String(e)},"node agent listener instance endpoint rollback failed")}),Object.assign(new Error(`Failed to switch controlled instances to node agent port ${t.port}: ${e instanceof Error?e.message:String(e)}`),{statusCode:409,code:"NODE_AGENT_LISTENER_INSTANCE_SYNC_FAILED"})}try{this.settings.put({...this.settings.get(),version:1,externalListener:t})}catch(e){throw await this.stop(),await this.restore(n),await Promise.resolve(this.synchronizeUpdate?.(n.config)).catch(e=>{this.app.log.error({error:e instanceof Error?e.message:String(e)},"node agent listener persistence rollback failed")}),Object.assign(new Error(`Failed to persist node agent TCP listener: ${e instanceof Error?e.message:String(e)}`),{statusCode:500,code:"NODE_AGENT_LISTENER_PERSIST_FAILED"})}this.config=t,this.source="persisted",this.status="listening",this.error=void 0;const i=this.current();return this.onActiveListener?.(i),i}async shutdown(){await this.updateQueue,await this.stop()}snapshot(){return{config:this.config,source:this.source,status:this.status,error:this.error}}async restore(e){if(this.config=e.config,this.source=e.source,this.status=e.status,this.error=e.error,"listening"===e.status)try{await this.listen(e.config)}catch(e){this.status="error",this.error=`Failed to restore previous listener: ${e instanceof Error?e.message:String(e)}`,this.app.log.error({error:this.error},"node agent TCP listener rollback failed")}this.state.setListenerPort(e.config.port),"listening"===this.status&&this.onActiveListener?.(this.current())}async listen(e){await new Promise((t,n)=>{const i=e=>{this.app.server.off("listening",s),n(e)},s=()=>{this.app.server.off("error",i),t()};this.app.server.once("error",i),this.app.server.once("listening",s),this.app.server.listen({host:xg(e.bindScope),port:e.port})})}async stop(){this.app.server.listening&&await new Promise((e,t)=>{this.app.server.close(n=>n?t(n):e());for(const e of this.sockets)e.destroy()})}}const UA="TASK_HANDOFF_NODE_AGENT_V1",FA="/api/node-tunnel";function $A(e=""){return d.createHash("sha256").update(e).digest("hex")}function HA(e,t){return d.createHmac("sha256",e).update(function(e){return[UA,e.keyId,e.method.toUpperCase(),e.pathWithQuery,e.timestamp,e.nonce,e.bodySha256].join("\n")}(t)).digest("hex")}function qA(e){const t=e.timestamp||(new Date).toISOString(),n=e.nonce||d.randomBytes(18).toString("base64url"),i=$A(e.body||""),s=HA(e.secret,{keyId:e.keyId,method:e.method,pathWithQuery:e.pathWithQuery,timestamp:t,nonce:n,bodySha256:i});return{"x-taskhandoff-node-id":e.nodeId,"x-taskhandoff-key-id":e.keyId,"x-taskhandoff-timestamp":t,"x-taskhandoff-nonce":n,"x-taskhandoff-body-sha256":i,"x-taskhandoff-signature":s}}class BA{usedNonces=new Map;identity;nodeId;overrideSecret;overrideKeyId;nowMs;constructor(e,t,n,i,s=Date.now){this.identity=e,this.nodeId=t,this.overrideSecret=n,this.overrideKeyId=i,this.nowMs=s}hasRemoteSecrets(){return this.identity.remoteSecrets(this.overrideSecret,this.overrideKeyId).length>0}verify(e){const t=function(e){const t=new Map;for(const[n,i]of Object.entries(e)){const e=Array.isArray(i)?i.join(","):"string"==typeof i?i:void 0===i?"":String(i);t.set(n.toLowerCase(),e)}return{nodeId:t.get("x-taskhandoff-node-id")||"",keyId:t.get("x-taskhandoff-key-id")||"",timestamp:t.get("x-taskhandoff-timestamp")||"",nonce:t.get("x-taskhandoff-nonce")||"",bodySha256:t.get("x-taskhandoff-body-sha256")||"",signature:t.get("x-taskhandoff-signature")||""}}(e.headers);if(!t.nodeId&&!t.signature)return!1;const n="DELETE"===e.method&&"/api/node-agent/pairing/current"===e.url.split("?")[0],i=this.identity.remoteSecrets(this.overrideSecret,this.overrideKeyId,n);if(!i.length)return!1;if(t.nodeId!==this.nodeId)throw Object.assign(new Error("Invalid node agent HMAC node id."),{statusCode:401,code:"NODE_AGENT_HMAC_NODE_MISMATCH"});if(!t.keyId)throw Object.assign(new Error("Node agent HMAC key id is missing."),{statusCode:401,code:"NODE_AGENT_HMAC_KEY_MISSING"});const s=i.filter(e=>t.keyId===e.keyId);if(!s.length)throw Object.assign(new Error("Invalid node agent HMAC key id."),{statusCode:401,code:"NODE_AGENT_HMAC_KEY_INVALID"});const o=Date.parse(t.timestamp);if(!Number.isFinite(o)||Math.abs(this.nowMs()-o)>6e4)throw Object.assign(new Error("Node agent HMAC timestamp is outside the allowed window."),{statusCode:401,code:"NODE_AGENT_HMAC_TIMESTAMP_INVALID"});if(!t.nonce)throw Object.assign(new Error("Node agent HMAC nonce is missing."),{statusCode:401,code:"NODE_AGENT_HMAC_NONCE_MISSING"});this.pruneNonces();const r=`${t.nodeId}:${t.keyId}:${t.nonce}`;if(this.usedNonces.has(r))throw Object.assign(new Error("Node agent HMAC nonce was already used."),{statusCode:401,code:"NODE_AGENT_HMAC_NONCE_REPLAY"});const a=$A(null==(c=e.body)?"":"string"==typeof c||Buffer.isBuffer(c)?c:JSON.stringify(c));var c;if(t.bodySha256!==a)throw Object.assign(new Error("Node agent HMAC body hash mismatch."),{statusCode:401,code:"NODE_AGENT_HMAC_BODY_HASH_INVALID"});if(!s.some(n=>function(e,t){const n=Buffer.from(e,"hex"),i=Buffer.from(t,"hex");return n.length===i.length&&d.timingSafeEqual(n,i)}(t.signature,HA(n.secret,{keyId:t.keyId,method:e.method,pathWithQuery:e.url,timestamp:t.timestamp,nonce:t.nonce,bodySha256:a}))))throw Object.assign(new Error("Invalid node agent HMAC signature."),{statusCode:401,code:"NODE_AGENT_HMAC_SIGNATURE_INVALID"});return this.usedNonces.set(r,o+6e4+1),t.keyId}pruneNonces(){const e=this.nowMs();for(const[t,n]of this.usedNonces)n<=e&&this.usedNonces.delete(t)}}function VA(e,t){console.warn(JSON.stringify({message:e,...t}))}class GA{repository;logger;constructor(e,t,n={}){const i=t&&"readIdentity"in t?t:void 0,s=i?n:t||n;this.repository=i||Wm(Jh(e)).access,this.logger=s.logger||VA}read(){const e=this.repository.readIdentity();return e?wh(e,this.logger):void 0}init(){}write(e){const t=wh({...e,updatedAt:de()},this.logger);return this.repository.writeIdentity(t)}}class KA{values=new Map;put(e,t,n=Date.now()){this.prune(n),this.values.set(e,t)}take(e,t=Date.now()){this.prune(t);const n=this.values.get(e);return n&&this.values.delete(e),n}peek(e,t=Date.now()){return this.prune(t),this.values.get(e)}delete(e,t=Date.now()){this.prune(t);const n=this.values.get(e);return n&&this.values.delete(e),n}list(e=Date.now()){return this.prune(e),[...this.values.values()]}prune(e=Date.now()){for(const[t,n]of this.values)Date.parse(n.expiresAt)<=e&&this.values.delete(t)}}class WA{store;repository;pairingInvites=new KA;controlPlaneConnectionOperations=new Map;constructor(e,t){this.repository=t||Wm(Jh(e)).access,this.store=new GA(e,this.repository),this.store.init(),this.recoverControlPlaneConnectionOperations()}async runControlPlaneConnectionOperation(e,t){const n=e.replace(/\/$/,""),i=this.controlPlaneConnectionOperations.get(n)||Promise.resolve();let s;const o=new Promise(e=>{s=e});this.controlPlaneConnectionOperations.set(n,o),await i;try{return await t()}finally{s(),this.controlPlaneConnectionOperations.get(n)===o&&this.controlPlaneConnectionOperations.delete(n)}}resolveNodeId(e){if(e?.trim())return this.writeNodeId(e.trim()),e.trim();const t=this.store.read();if(t?.nodeId)return t.nodeId;const n=du("node");return this.writeNodeId(n),n}createPairingInvite(e){const t=de(),n=new Date(Date.now()+(e.expiresInMs||6e5)).toISOString(),i=lu(),s={tokenHash:$A(i),createdAt:t,expiresAt:n,...e.controlPlaneName?{controlPlaneName:e.controlPlaneName}:{}};return this.pairingInvites.put(s.tokenHash,s),{...s,token:i}}completePairingInvite(e){const t=this.store.read()||this.newIdentity(),n=$A(e.joinToken),i=this.pairingInvites.take(n);if(!i){const e=new Error("Node agent pairing invite is invalid or expired.");throw Object.assign(e,{statusCode:401,code:"NODE_AGENT_PAIRING_INVITE_INVALID"}),e}const s=de(),o={id:e.controlPlaneId||du("cp"),keyId:du("key"),...e.controlPlaneName||i.controlPlaneName?{name:e.controlPlaneName||i.controlPlaneName}:{},secret:lu(),pairedAt:s,updatedAt:s};return this.store.write({...t,controlPlanePairings:[...(t.controlPlanePairings||[]).filter(e=>e.id!==o.id),o]}),o}stageControlPlaneConnection(e){const{pairing:t,connection:n}=this.createControlPlaneConnection(e),i=this.store.read()||this.newIdentity(),s=n.url.replace(/\/$/,""),o=(i.controlPlaneConnections||[]).filter(e=>e.id===n.id||e.url.replace(/\/$/,"")===s),r={operationId:du("connection_operation"),pairing:t,connection:n,replacedConnections:o},a=de();return this.repository.transaction(()=>{this.store.write({...i,controlPlanePairings:[...(i.controlPlanePairings||[]).filter(e=>e.keyId!==t.keyId),t],controlPlaneConnections:[...(i.controlPlaneConnections||[]).filter(e=>e.id!==n.id&&e.url.replace(/\/$/,"")!==s),n]}),this.repository.putOperation({id:r.operationId,kind:"create-connection",phase:"prepared",requested:r,pairingKeyId:t.keyId,connectionId:n.id,replacedConnections:o,createdAt:a,updatedAt:a})}),r}markControlPlaneConnectionRemoteAccepted(e){const t=this.repository.listOperations().find(t=>t.id===e.operationId);if(!t)throw Object.assign(new Error("Control-plane connection operation was not found."),{code:"NODE_AGENT_CONNECTION_OPERATION_NOT_FOUND",statusCode:409});this.repository.putOperation({...t,phase:"remote-accepted",updatedAt:de()})}commitControlPlaneConnection(e,t={}){const n=this.store.read()||this.newIdentity(),i={...e.pairing,...t.name?{name:t.name}:{}},s={...e.connection,...t.name?{name:t.name}:{}},o=new Set((n.controlPlaneConnections||[]).map(e=>e.pairingKeyId)),r=new Set(e.replacedConnections.map(e=>e.pairingKeyId));return this.repository.transaction(()=>{this.store.write({...n,controlPlanePairings:[...(n.controlPlanePairings||[]).filter(e=>e.keyId!==i.keyId&&(!r.has(e.keyId)||o.has(e.keyId))),i],controlPlaneConnections:[...(n.controlPlaneConnections||[]).filter(e=>e.id!==s.id),s]});const t=this.repository.listOperations().find(t=>t.id===e.operationId);t&&this.repository.putOperation({...t,phase:"committed",updatedAt:de()}),this.repository.deleteOperation(e.operationId)}),{pairing:i,connection:s}}rollbackControlPlaneConnection(e){const t=this.store.read();if(!t)return;const n=new Set(e.replacedConnections.map(e=>e.id));this.repository.transaction(()=>{this.store.write({...t,controlPlanePairings:(t.controlPlanePairings||[]).filter(t=>t.keyId!==e.pairing.keyId),controlPlaneConnections:[...(t.controlPlaneConnections||[]).filter(t=>t.id!==e.connection.id&&!n.has(t.id)),...e.replacedConnections]}),this.repository.deleteOperation(e.operationId)})}recoverControlPlaneConnectionOperations(){for(const e of this.repository.listOperations(["prepared","remote-accepted"])){const t=e.requested;t?.pairing?.keyId&&t?.connection?.id?"remote-accepted"===e.phase?(this.repository.putOperation({...e,phase:"committed",updatedAt:de()}),this.repository.deleteOperation(e.id)):this.rollbackControlPlaneConnection(t):this.repository.putOperation({...e,phase:"failed",error:{code:"NODE_AGENT_CONNECTION_OPERATION_INVALID"},updatedAt:de()})}}createControlPlaneConnection(e){const t=de(),n={id:du("cp"),keyId:du("key"),...e.name?{name:e.name}:{},secret:lu(),pairedAt:t,updatedAt:t};return{pairing:n,connection:{id:du("connection"),pairingKeyId:n.keyId,...e.name?{name:e.name}:{},url:e.url,enabled:!1!==e.enabled,createdAt:t,updatedAt:t}}}resolvedControlPlaneAccess(){const e=this.store.read(),t=new Map((e?.controlPlanePairings||[]).filter(e=>!e.revokedAt).map(e=>[e.keyId,e])),n=e?.controlPlaneConnections||[];return{hasPersistedAccess:n.length>0||t.size>0,connections:n.map(e=>({connection:e,pairing:t.get(e.pairingKeyId)}))}}listControlPlanePairings(e=""){return(this.store.read()?.controlPlanePairings||[]).filter(e=>!e.revokedAt).map(({secret:t,...n})=>({...n,current:Boolean(e&&n.keyId===e)})).sort((e,t)=>Number(t.current)-Number(e.current)||t.updatedAt.localeCompare(e.updatedAt))}listControlPlaneConnections(){return[...this.store.read()?.controlPlaneConnections||[]].sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))}deleteControlPlanePairing(e,t=""){if(t&&e===t){const e=new Error("Cannot delete the pairing used to authenticate the current request.");throw Object.assign(e,{statusCode:409,code:"NODE_AGENT_PAIRING_CURRENT_REQUEST"}),e}const n=this.store.read();if(!n)return!1;if((n.controlPlaneConnections||[]).some(t=>t.pairingKeyId===e))throw Object.assign(new Error("Cannot delete a pairing used by a configured control-plane connection."),{statusCode:409,code:"NODE_AGENT_PAIRING_IN_USE"});const i=(n.controlPlanePairings||[]).filter(t=>t.keyId!==e);return i.length!==(n.controlPlanePairings||[]).length&&(this.store.write({...n,controlPlanePairings:i}),!0)}revokeCurrentControlPlanePairing(e){if(!e)throw Object.assign(new Error("Current paired-HMAC authentication is required to revoke this pairing."),{statusCode:403,code:"NODE_AGENT_PAIRING_SELF_REVOKE_HMAC_REQUIRED"});const t=this.store.read(),n=t?.controlPlanePairings?.find(t=>t.keyId===e);if(!t||!n)throw Object.assign(new Error("The current control-plane pairing no longer exists."),{statusCode:404,code:"NODE_AGENT_PAIRING_NOT_FOUND"});if(n.revokedAt)return{keyId:e,revoked:!0,revokedAt:n.revokedAt};if((t.controlPlaneConnections||[]).some(t=>t.pairingKeyId===e))throw Object.assign(new Error("Cannot revoke a pairing used by a configured control-plane connection."),{statusCode:409,code:"NODE_AGENT_PAIRING_IN_USE"});const i=de();return this.store.write({...t,controlPlanePairings:t.controlPlanePairings.map(t=>t.keyId===e?{...t,revokedAt:i,updatedAt:i}:t)}),{keyId:e,revoked:!0,revokedAt:i}}deleteControlPlaneConnection(e){const t=this.store.read();if(!t)return!1;const n=(t.controlPlaneConnections||[]).filter(t=>t.id!==e);return n.length!==(t.controlPlaneConnections||[]).length&&(this.store.write({...t,controlPlaneConnections:n}),!0)}remoteSecrets(e,t,n=!1){return[...(this.store.read()?.controlPlanePairings||[]).filter(e=>n||!e.revokedAt).map(e=>({keyId:e.keyId,secret:e.secret})),...e&&t?[{keyId:t,secret:e}]:[]]}isRevokedPairing(e){return Boolean(this.store.read()?.controlPlanePairings?.some(t=>t.keyId===e&&t.revokedAt))}reverseTunnelSecret(e,t,n){if(t&&n)return{keyId:n,secret:t};const i=this.store.read(),s=(i?.controlPlanePairings||[]).filter(e=>!e.revokedAt);if(!s.length)return;if(e){const t=e.replace(/\/$/,""),n=(i?.controlPlaneConnections||[]).find(e=>e.url.replace(/\/$/,"")===t),o=n&&s.find(e=>e.keyId===n.pairingKeyId);if(o)return{keyId:o.keyId,secret:o.secret}}const o=[...s].sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))[0];return o?{keyId:o.keyId,secret:o.secret}:void 0}newIdentity(){return{nodeId:this.resolveNodeId(),createdAt:de(),updatedAt:de(),controlPlanePairings:[],controlPlaneConnections:[]}}writeNodeId(e){const t=this.store.read();this.store.write({...t||{createdAt:de()},nodeId:e,updatedAt:de(),controlPlanePairings:t?.controlPlanePairings||[],controlPlaneConnections:t?.controlPlaneConnections||[]})}}const YA=c.z.string().trim().min(1).max(160);const XA=So.strict();function JA(e){const t=e.filter(e=>!["created","stopped","failed"].includes(e.status)),n=new Set(t.map(e=>e.id)),i=t.filter(e=>e.apps.runningCount>0||e.aiSessions.runningCount>0);return{runningInstanceCount:t.length,stoppedInstanceCount:e.length-t.length,activeInstanceCount:i.length,restartInstanceCount:t.length,runningInstanceIds:t.map(e=>e.id).sort(),stoppedInstanceIds:e.filter(e=>!n.has(e.id)).map(e=>e.id).sort(),activeInstanceIds:i.map(e=>e.id).sort()}}class QA{preflights=new Map;options;applying=!1;constructor(e){this.options=e}async check(e){const t=wo.parse(e),n=JA(this.options.listInstances()),i=await hg(this.options.runCommand,this.options.moduleDir),s=this.options.currentRuntimeVersion(),o=this.options.managedUpdateSupport?.(i)||{supported:!0};if(!o.supported)return bo.parse({source:"npm",channel:t.channel,currentVersion:i.currentVersion||s,availableVersion:i.currentVersion||s||"unavailable",impact:n,updateAvailable:!1,supported:!1,reason:o.reason||"Managed updates are unavailable on this node.",checkedAt:(new Date).toISOString()});const r="@task-handoff/server"===i.packageName?[...new Set([...i.relatedCurrentVersions,s])]:i.relatedCurrentVersions,a=await async function(e){const t=e.packageName||"@task-handoff/node-agent",n=await async function(e,t,n){const i=function(e){return"stable"===e?"latest":e}(n),s=await e(pg(),["view",`${t}@${i}`,"version","--json"]).catch(e=>{if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e,n=[t.message,t.details?.stdout,t.details?.stderr].filter(e=>"string"==typeof e).join("\n");return/\bE404\b/i.test(n)}(e))throw e});if(!s)return;const o=JSON.parse(s.stdout);if("string"!=typeof o)throw new Error(`npm did not resolve ${t}@${i} to one version.`);return o}(e.runCommand,t,e.channel);if(!n)return function(e){return bo.parse({source:"npm",channel:e.channel,currentVersion:e.currentVersion,availableVersion:e.currentVersion||"unavailable",impact:e.impact||{runningInstanceCount:0,stoppedInstanceCount:0,activeInstanceCount:0,restartInstanceCount:0,runningInstanceIds:[],stoppedInstanceIds:[],activeInstanceIds:[]},updateAvailable:!1,reason:`No ${e.channel} release is currently published.`,checkedAt:de()})}({channel:e.channel,currentVersion:e.currentVersion,impact:e.impact});const i=ug(e.currentVersion,n)||(e.relatedCurrentVersions||[]).some(e=>ug(e,n)),s=i?await async function(e,t,n){const i=await e(pg(),["view",`${t}@${n}`,"dist.integrity","--json"]),s=JSON.parse(i.stdout);if("string"!=typeof s||!/^sha(?:256|384|512)-[A-Za-z0-9+/=]+$/.test(s))throw Object.assign(new Error(`npm did not return immutable integrity metadata for ${t}@${n}.`),{statusCode:502,code:"NODE_UPDATE_PREFLIGHT_FAILED",retryable:!0});return s}(e.runCommand,t,n):void 0;return bo.parse({source:"npm",channel:e.channel,currentVersion:e.currentVersion,availableVersion:n,...s?{artifactRef:`npm:${t}@${n}#${s}`}:{},runtimeArtifacts:e.runtimeArtifacts||[],impact:e.impact||{runningInstanceCount:0,stoppedInstanceCount:0,activeInstanceCount:0,restartInstanceCount:0,runningInstanceIds:[],stoppedInstanceIds:[],activeInstanceIds:[]},updateAvailable:i,checkedAt:de()})}({channel:t.channel,currentVersion:i.currentVersion||s,runCommand:this.options.runCommand,packageName:i.packageName,relatedCurrentVersions:r,impact:n});if(!a.updateAvailable)return a;const c={...a,runtimeArtifacts:[],preflightToken:lu()};return this.preflights.set(c.preflightToken,{result:c,expiresAt:Date.now()+6e5}),c}async apply(e){const i=XA.parse(e),s=this.preflights.get(i.preflightToken);(!s||s.expiresAt<=Date.now())&&await this.consumePreflight(i),this.applying&&this.throwAlreadyRunning(),this.applying=!0;try{const{check:e,selection:s}=await this.consumePreflight(i);if(this.options.jobs.list().some(e=>!["succeeded","degraded","failed"].includes(e.status))&&this.throwAlreadyRunning(),!e.supported)throw Object.assign(new Error(e.reason||"The requested update is not supported."),{statusCode:400,code:"UPDATE_UNSUPPORTED"});if(!e.updateAvailable)throw Object.assign(new Error(e.reason||"No update is available for the selected channel."),{statusCode:409,code:"UPDATE_NOT_AVAILABLE"});const o=this.options.jobs.create(this.options.nodeId,e),{worker:r,packaged:a,expectedWorker:c}=function(e,i=t.existsSync){const s=[n.resolve(e,"..","bin","task-handoff-node-update-worker"),n.resolve(e,"..","..","bin","task-handoff-node-update-worker")],o=s.find(i),r=n.resolve(e,"..","..","..","..","scripts","node-update-worker.cts");return o?{worker:o,packaged:!0,expectedWorker:s[0]}:i(r)?{worker:r,packaged:!1,expectedWorker:s[0]}:{worker:void 0,packaged:!1,expectedWorker:s[0]}}(this.options.moduleDir);if(!r)throw this.options.jobs.patch(o.id,{status:"failed",rollout:{...o.rollout,phase:"failed"},error:{code:"NODE_UPDATE_FAILED",message:`Update worker was not found: ${c}`,retryable:!1},completedAt:(new Date).toISOString()}),Object.assign(new Error(`Node agent update worker was not found: ${c}`),{statusCode:500,code:"UPDATE_WORKER_NOT_FOUND"});const d=process.env.TASK_HANDOFF_CONTROL_PLANE_HEALTH_URL?.trim();try{await this.options.runCommand("systemd-run",["--unit",`task-handoff-update-${o.id}`,"--collect","--property=Type=exec",...a?[r]:[process.execPath,r],"--job-file",this.options.jobs.records.filePath(o.id),"--target-version",o.toVersion,"--npm-command",pg(),"--install-prefix",s.installPrefix,...process.env.TASK_HANDOFF_NODE_AGENT_IPC_PATH?.trim()?["--node-agent-ipc-path",process.env.TASK_HANDOFF_NODE_AGENT_IPC_PATH.trim()]:[],...d?["--control-plane-health-url",d]:[]])}catch(e){const t=e instanceof Error?e.message:String(e);throw this.options.jobs.patch(o.id,{status:"failed",rollout:{...o.rollout,phase:"failed"},error:{code:"NODE_UPDATE_FAILED",message:`Failed to launch the node update worker: ${t}`,retryable:!0},completedAt:(new Date).toISOString()}),Object.assign(new Error(`Failed to launch the node update worker: ${t}`),{statusCode:500,code:"NODE_UPDATE_WORKER_LAUNCH_FAILED",cause:e})}return await this.waitForWorkerClaim(o)}finally{this.applying=!1}}async consumePreflight(e){const t=this.preflights.get(e.preflightToken);if(this.preflights.delete(e.preflightToken),!t||t.expiresAt<=Date.now())throw Object.assign(new Error("The update preflight is missing or expired. Check for updates again."),{statusCode:409,code:"UPDATE_PREFLIGHT_EXPIRED"});const n=t.result,i=await hg(this.options.runCommand,this.options.moduleDir);return n.channel===e.channel&&n.availableVersion===e.targetVersion&&n.currentVersion===(i.currentVersion||this.options.currentRuntimeVersion())&&!0===n.artifactRef?.startsWith(`npm:${i.packageName}@`)&&JSON.stringify(n.impact)===JSON.stringify(JA(this.options.listInstances()))||this.throwStale(),{check:n,selection:i}}throwStale(){throw Object.assign(new Error("The update target or affected instances changed after preflight. Check for updates again."),{statusCode:409,code:"UPDATE_PREFLIGHT_STALE"})}throwAlreadyRunning(){throw Object.assign(new Error("Another server update is already running on this node."),{statusCode:409,code:"SERVER_UPDATE_ALREADY_RUNNING"})}async waitForWorkerClaim(e){const t=this.options.workerClaimTimeoutMs??5e3,n=this.options.workerClaimPollMs??50,i=Date.now()+t;for(;Date.now()<=i;){const t=this.options.jobs.records.get(e.id);if(!t)throw Object.assign(new Error(`Update job ${e.id} disappeared before the worker claimed it.`),{statusCode:500,code:"UPDATE_JOB_NOT_FOUND"});if("queued"!==t.status)return t;if(Date.now()>=i)break;await new Promise(e=>setTimeout(e,Math.max(1,Math.min(n,i-Date.now()))))}const s=this.options.jobs.records.get(e.id);if("queued"!==s?.status)return s||e;throw this.options.jobs.patch(e.id,{status:"failed",rollout:{...s.rollout,phase:"failed"},error:{code:"NODE_UPDATE_FAILED",message:"The node update worker did not claim the queued job after systemd accepted it.",retryable:!0},completedAt:(new Date).toISOString()}),Object.assign(new Error("The node update worker did not start after systemd accepted the update job."),{statusCode:500,code:"NODE_UPDATE_WORKER_START_TIMEOUT"})}}const ZA=new Set(["provisioning","starting","registering","registered","running"]);function eT(e,t){return"offline"!==t.status&&ZA.has(e.status)&&!Xl(e)&&!Jl(e)}function tT(e){return"offline"===e.status}function nT(e){return Ia.parse({...e,health:"unknown",connectionStatus:"offline",agentStatus:"offline",targetStatus:"unknown",uiAccessStatus:"unknown",target:{...e.target,status:"unknown"},updatedAt:de()})}class iT{options;restoredInstances=new Set;restoreErrors=new Map;unexpectedExitRetries=new Map;suppressedInstances=new Set;pendingUnexpectedExits=new Map;activeRestores=new Map;timer;activeCycle;cycleRequested=!1;cycleRequestDelayMs;started=!1;stopped=!1;constructor(e){this.options=e}markRestored(e){const t=this.options.state.requireInstance(e);return!(["failed","stopping","stopped"].includes(t.status)||Xl(t)||Jl(t)||(this.restoredInstances.add(e),this.restoreErrors.delete(e),0))}allowRecovery(e){this.suppressedInstances.delete(e);const t=this.pendingUnexpectedExits.get(e);void 0!==t&&(this.pendingUnexpectedExits.delete(e),this.applyUnexpectedLocalExit(e,t))}completeSuppressedOperation(e){this.pendingUnexpectedExits.delete(e),this.restoredInstances.delete(e),this.restoreErrors.delete(e),this.unexpectedExitRetries.delete(e)}forgetInstance(e){this.restoredInstances.delete(e),this.restoreErrors.delete(e),this.unexpectedExitRetries.delete(e),this.suppressedInstances.delete(e),this.activeRestores.delete(e),this.pendingUnexpectedExits.delete(e)}async suppressRecovery(e){this.suppressedInstances.add(e),await(this.activeRestores.get(e)?.catch(()=>{}))}handleUnexpectedLocalExit(e,t){this.stopped||(this.suppressedInstances.has(e)?this.pendingUnexpectedExits.set(e,t):this.applyUnexpectedLocalExit(e,t))}applyUnexpectedLocalExit(e,t){const n=this.options.state.requireInstance(e);if("local"!==this.options.state.requireRuntime(n.runtimeId).type)return;this.restoredInstances.delete(e);const i=this.options.nowMs?.()??Date.now(),s=this.unexpectedExitRetries.get(e),o=this.options.crashStableWindowMs??3e4,r=s&&i-s.lastExitAt<o?s.attempt+1:1;this.unexpectedExitRetries.set(e,{attempt:r,lastExitAt:i});const a=this.options.retryBaseDelayMs??1e3,c=1===r?0:Math.min(this.options.retryMaxDelayMs??3e4,a*2**Math.min(r-2,10)),d=t instanceof Error?t.message:String(t);this.restoreErrors.set(e,{message:d,attempt:r,nextAttemptAt:i+c}),this.options.state.applyInstanceLifecycle(e,{type:"runtime-exited",error:t}),this.requestCycle(c)}async restoreManagedInstances(){if(this.stopped)return;const{state:e}=this.options;for(const t of e.listInstances()){if(this.stopped)return;const n=e.requireRuntime(t.runtimeId);"docker"===n.type&&!tT(n)&&["provisioning","starting"].includes(t.status)&&"ready"!==t.imageProvisioning?.phase&&this.options.provisionImage(t),"docker"===n.type&&!tT(n)&&["provisioning","starting"].includes(t.status)&&Jl(t)&&!Xl(t)&&this.options.provisionGit?.(t)}const t=e.listInstances().filter(t=>{if(this.restoredInstances.has(t.id))return!1;if(this.suppressedInstances.has(t.id))return!1;const n=e.requireRuntime(t.runtimeId);if("local"===n.type){const e=this.restoreErrors.get(t.id);return(ZA.has(t.status)||"failed"===t.status)&&(!e||e.nextAttemptAt<=(this.options.nowMs?.()??Date.now()))}return("docker"===n.type||"wsl"===n.type)&&eT(t,n)});await Promise.all(t.map(async t=>{if(this.stopped)return;const n=async()=>{if(this.stopped)return;const n=e.listInstances().find(e=>e.id===t.id);if(!n)return;if(!this.isRestoreCandidate(n))return;const i=this.restoreErrors.get(n.id);try{const t=this.options.restoreInstance(n.id);this.activeRestores.set(n.id,t);try{await t}finally{this.activeRestores.get(n.id)===t&&this.activeRestores.delete(n.id)}if(this.stopped||this.suppressedInstances.has(n.id))return;if(await this.options.autoImport(e.requireInstance(n.id)),this.stopped||this.suppressedInstances.has(n.id))return;if(this.restoreErrors.get(n.id)!==i)return;if(!this.markRestored(n.id))throw new Error(`Restored instance ${n.id} did not reach a recoverable running state.`)}catch(t){if(this.stopped||this.suppressedInstances.has(n.id))return;"local"===e.requireRuntime(n.runtimeId).type&&e.applyInstanceLifecycle(n.id,{type:"start-failed",error:t});const i=t instanceof Error?t.message:String(t),s=this.restoreErrors.get(n.id),o=(s?.attempt??0)+1,r=this.options.retryBaseDelayMs??1e3,a=Math.min(this.options.retryMaxDelayMs??3e4,r*2**Math.min(o-1,10)),c=(this.options.nowMs?.()??Date.now())+a;this.restoreErrors.set(n.id,{message:i,attempt:o,nextAttemptAt:c}),s?.message===i&&s.attempt===o||this.options.warn({instanceId:n.id,action:"restore",runtimeId:n.runtimeId,error:i,attempt:o,nextAttemptAt:new Date(c).toISOString()},"node instance restore failed; recovery will retry")}};await(this.options.runInstanceOperation?.(t.id,n)??n())}))}isRestoreCandidate(e){if(this.restoredInstances.has(e.id)||this.suppressedInstances.has(e.id))return!1;const t=this.options.state.requireRuntime(e.runtimeId);if("local"===t.type){const t=this.restoreErrors.get(e.id);return(ZA.has(e.status)||"failed"===e.status)&&(!t||t.nextAttemptAt<=(this.options.nowMs?.()??Date.now()))}return("docker"===t.type||"wsl"===t.type)&&eT(e,t)}async recoverManagedInstances(){if(this.stopped)return;const{state:e,convergence:t}=this.options,n=e.listInstances().filter(n=>this.options.usesManagedArtifact(n)&&!t.isRunning(n.id)&&(this.restoredInstances.has(n.id)||"unknown"!==n.target.status)&&(!n.ready||"matched"!==n.runtimeVersion?.phase)&&!Xl(n)&&!tT(e.requireRuntime(n.runtimeId))&&!["created","stopped","failed","provisioning","stopping"].includes(n.status));await Promise.all(n.map(async e=>{if(!this.stopped)try{await t.schedule(e.id)}catch(t){this.options.error({instanceId:e.id,error:t},"runtime convergence recovery failed")}}))}start(){this.started||this.stopped||(this.started=!0,this.runAndContinue())}notifyRuntimeAvailable(){this.requestCycle(0)}async stop(){this.stopped=!0,this.timer&&clearTimeout(this.timer),this.timer=void 0;const e=this.options.stopImageProvisioning(),t=this.options.stopGitProvisioning?.()??Promise.resolve(),n=this.options.state.listInstances().map(e=>this.options.convergence.cancel(e.id));await Promise.all(n),await this.activeCycle,await e,await t,await this.options.runtimeAdapters.stopAll();for(const e of this.options.state.listInstances())"local"===this.options.state.requireRuntime(e.runtimeId).type&&this.options.state.controlledInstances.put(nT(e))}async runCycle(){await this.restoreManagedInstances(),this.stopped||await this.recoverManagedInstances()}runAndContinue(){if(this.stopped)return;const e=this.runCycle().catch(e=>this.options.error({error:e},"node agent startup recovery cycle failed"));this.activeCycle=e,e.finally(()=>{this.activeCycle===e&&(this.activeCycle=void 0),this.cycleRequested?(this.cycleRequested=!1,this.cycleRequestDelayMs=void 0,this.scheduleNext()):this.scheduleNext()})}scheduleNext(){if(this.stopped)return;const e=this.options.nowMs?.()??Date.now(),t=new Map(this.options.state.listInstances().map(e=>[e.id,e])),n=[...this.restoreErrors.entries()].reduce((e,[n,i])=>{const s=t.get(n);return!s||this.restoredInstances.has(n)||this.suppressedInstances.has(n)||"local"!==this.options.state.requireRuntime(s.runtimeId).type?e:ZA.has(s.status)||"failed"===s.status?Math.min(e,i.nextAttemptAt):e},Number.POSITIVE_INFINITY),i=Math.min(this.options.intervalMs??1e4,Math.max(0,n-e));this.timer=setTimeout(()=>{this.timer=void 0,this.runAndContinue()},i),this.timer.unref?.()}requestCycle(e=0){if(this.started&&!this.stopped){if(this.activeCycle)return this.cycleRequested=!0,void(this.cycleRequestDelayMs=void 0===this.cycleRequestDelayMs?e:Math.min(this.cycleRequestDelayMs,e));this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>{this.timer=void 0,this.runAndContinue()},e),this.timer.unref?.()}}}function sT(e){if(null==e||"string"==typeof e&&!e.trim())return 15e3;const t="number"==typeof e?e:Number(e);return!Number.isFinite(t)||t<=0?15e3:Math.max(1e3,Math.trunc(t))}function oT(e,t){return JSON.stringify({status:t.status??e.status,capabilities:t.capabilities??e.capabilities})}class rT{hooks;intervalMs;timer;probing=!1;stopped=!1;constructor(e,t={}){this.hooks=e,this.intervalMs=sT(t.intervalMs)}start(){this.stopped||this.timer||this.runCycle()}async checkNow(){this.stopped||(this.timer&&clearTimeout(this.timer),this.timer=void 0,await this.runCycle())}async checkRuntime(e){const t=this.hooks.listTargets().find(t=>t.runtime.id===e);return!!t&&(await this.probeTarget(t),!0)}stop(){this.stopped=!0,this.timer&&clearTimeout(this.timer),this.timer=void 0}async runCycle(){if(!this.stopped){try{await this.probeAll()}catch(e){this.hooks.onCycleError?.(e)}this.schedule(this.intervalMs)}}schedule(e){this.stopped||this.timer||(this.timer=setTimeout(()=>{this.timer=void 0,this.runCycle()},e),this.timer.unref?.())}async probeAll(){if(!this.stopped&&!this.probing){this.probing=!0;try{for(const e of this.hooks.listTargets()){if(this.stopped)return;await this.probeTarget(e)}}finally{this.probing=!1}}}async probeTarget(e){const t=e.runtime;let n;try{n=await e.probe()}catch(e){return void this.hooks.onProbeError?.(t,e)}if(!n)return;oT(t,n)!==oT(t,{})&&await this.hooks.apply(t,n);const i=n.status??t.status;if(i===t.status)return;const s={...t,...n,status:i};"online"===i?this.hooks.onAvailable?.(s,t):"offline"!==i&&"degraded"!==i||this.hooks.onUnavailable?.(s,t)}}const aT=new Set(["DELETE","GET","HEAD","PATCH","POST","PUT","OPTIONS"]);function cT(e){return"string"==typeof e&&aT.has(e.toUpperCase())?e.toUpperCase():"GET"}function dT(e){const t=function(e){if(null==e)return;const t=bs.parse(e);return"utf8"===t.encoding?t.data:Vi(t.data)}(e);return Buffer.isBuffer(t)?t:t instanceof Uint8Array?Buffer.from(t):t}function lT(e,t){const n=new URL(t.tunnelUrl);n.searchParams.set("nodeId",t.nodeId);const i=t.secret?qA({nodeId:t.nodeId,keyId:t.keyId,secret:t.secret,method:"GET",pathWithQuery:`${n.pathname}${n.search}`}):{},s=new h(n,{headers:i}),o=new Map,r=new Map,a=new Map;let c;s.on("error",i=>{e.log.warn({nodeId:t.nodeId,tunnelUrl:`${n.origin}${n.pathname}`,error:i instanceof Error?i.message:String(i)},"node agent reverse tunnel connection failed")});const d=e=>{const n=e.startsWith("/")?e:`/${e}`,i="function"==typeof t.port?t.port():t.port,s=new URL(`/api/node-agent${n}`,`http://127.0.0.1:${i}`);return s.protocol="ws:",s},l=(e,n,i,s={})=>{const o=e.startsWith("/")?e:`/${e}`;return{...s,...t.secret&&t.keyId?qA({nodeId:t.nodeId,keyId:t.keyId,secret:t.secret,method:n,pathWithQuery:`/api/node-agent${o}`,body:i}):t.token?{authorization:`Bearer ${t.token}`}:{}}},u=e=>t.secret?qA({nodeId:t.nodeId,keyId:t.keyId,secret:t.secret,method:"GET",pathWithQuery:`${e.pathname}${e.search}`}):{},p=(e,t,n)=>{const i=o.get(e);o.delete(e),i?.upstream&&j(i.upstream,t,n),i?.tunnel&&j(i.tunnel,t,n)},m=(e,t,n=!1)=>new Promise((i,s)=>{e.send(t,{binary:n,compress:!1},e=>e?s(e):i())});s.on("open",()=>{s.send(JSON.stringify({type:"node-agent.identify",nodeId:t.nodeId,serverTime:(new Date).toISOString()})),c=e.nodeAgentEventForwarder?.addOutput(s,{legacyFallbackMs:1e3})}),s.on("close",()=>{for(const e of o.keys())p(e,1001,"Reverse tunnel disconnected.");for(const[e,t]of r)r.delete(e),t.controller.abort(),j(t.tunnel,1001,"Reverse tunnel disconnected.");for(const[e,t]of a)a.delete(e),t.abort();c?.(),c=void 0});return s.on("message",i=>{(async i=>{let c;try{c=JSON.parse(String(i))}catch{return void s.send(JSON.stringify({type:"node-agent.error",code:"INVALID_JSON"}))}const g=c&&"object"==typeof c?c:{};if("control-plane.event-subscribe"!==g.type){if("control-plane.http.open"===g.type){const i="string"==typeof g.streamId?g.streamId:"",o="string"==typeof g.route&&g.route.startsWith("/")?g.route:"/health",a=g.init&&"object"==typeof g.init?g.init:{},c=a.headers&&"object"==typeof a.headers?a.headers:{},d=cT(a.method);let p;try{p=dT(a.body)}catch(n){return e.log.warn({nodeId:t.nodeId,messageType:g.type,streamId:i,error:n instanceof Error?n.message:String(n)},"node agent reverse tunnel request body rejected"),void s.send(JSON.stringify({type:"node-agent.error",code:"NODE_TUNNEL_REQUEST_BODY_INVALID",streamId:i}))}const f=new AbortController,y=(e=>{const t=new URL(n);return t.pathname=`${t.pathname.replace(/\/$/,"")}/http-streams/${encodeURIComponent(e)}`,t})(i),I=new h(y,{headers:u(y)});return r.set(i,{tunnel:I,controller:f}),I.on("open",async()=>{try{const e=await fetch((e=>{const n=e.startsWith("/")?e:`/${e}`,i="function"==typeof t.port?t.port():t.port;return new URL(`/api/node-agent${n}`,`http://127.0.0.1:${i}`)})(o),{method:d,headers:l(o,d,p,c),body:Buffer.isBuffer(p)?new Uint8Array(p):p,signal:f.signal});if(await m(I,JSON.stringify({type:"node-agent.http.head",streamId:i,status:e.status,headers:Object.fromEntries(e.headers.entries())})),e.body){const t=e.body.getReader();for(;;){const{done:e,value:n}=await t.read();if(e)break;await m(I,Buffer.from(n),!0)}}await m(I,JSON.stringify({type:"node-agent.http.end",streamId:i})),I.close(1e3,"HTTP stream completed.")}catch(e){I.readyState===h.OPEN&&(await m(I,JSON.stringify({type:"node-agent.http.error",streamId:i,message:e instanceof Error?e.message:String(e)})).catch(()=>{}),I.close(1011,"HTTP stream failed."))}finally{r.delete(i)}}),I.on("close",()=>{f.abort(),r.delete(i)}),void I.on("error",()=>f.abort())}if("control-plane.http.cancel"===g.type){const e="string"==typeof g.streamId?g.streamId:"",t=r.get(e);if(!t)return;return r.delete(e),t.controller.abort(),void j(t.tunnel,1e3,"string"==typeof g.reason?g.reason:"HTTP stream canceled.")}if("control-plane.websocket.open"===g.type){const e="string"==typeof g.streamId?g.streamId:"",t="string"==typeof g.route?g.route:"",i=Array.isArray(g.protocols)?g.protocols.filter(e=>"string"==typeof e):void 0;try{const r=l(t,"GET",void 0),a=i?.length?new h(d(t),i,{headers:r}):new h(d(t),{headers:r}),c=(e=>{const t=new URL(n);return t.pathname=`${t.pathname.replace(/\/$/,"")}/streams/${encodeURIComponent(e)}`,t})(e),p=new h(c,{headers:u(c)});o.set(e,{upstream:a,tunnel:p,close:(e=1e3,t="")=>{j(a,e,t),j(p,e,t)}}),a.on("open",()=>{s.send(JSON.stringify({type:"node-agent.websocket.open",streamId:e,protocol:a.protocol}))}),F(p,a,{pendingFrameLimit:256,upstreamOpenTimeoutMs:1e4,onClientClose:()=>{o.delete(e)},onClientError:t=>{o.delete(e),s.send(JSON.stringify({type:"node-agent.websocket.error",streamId:e,message:t instanceof Error?t.message:String(t)}))},onUpstreamClose:(t,n)=>{o.delete(e);const i=M(t),r=P(n);s.send(JSON.stringify({type:"node-agent.websocket.close",streamId:e,...void 0===i?{}:{code:i},...r?{reason:r}:{}}))},onUpstreamError:t=>{o.delete(e),s.send(JSON.stringify({type:"node-agent.websocket.error",streamId:e,message:t instanceof Error?t.message:String(t)}))}})}catch(t){s.send(JSON.stringify({type:"node-agent.websocket.error",streamId:e,message:t instanceof Error?t.message:String(t)}))}return}if("control-plane.websocket.close"===g.type){const e="string"==typeof g.streamId?g.streamId:"";return void p(e,"number"==typeof g.code?g.code:1e3,"string"==typeof g.reason?g.reason:"")}if("control-plane.request.cancel"===g.type){const e="string"==typeof g.requestId?g.requestId:"";return a.get(e)?.abort(),void a.delete(e)}if("control-plane.request"===g.type){const n="string"==typeof g.requestId?g.requestId:"",i=g.init&&"object"==typeof g.init?g.init:{},o="string"==typeof g.route&&g.route.startsWith("/")?g.route:"/health",r=i.headers&&"object"==typeof i.headers?i.headers:{},c=cT(i.method);let d;try{d=dT(i.body)}catch(i){return e.log.warn({nodeId:t.nodeId,messageType:g.type,requestId:n,error:i instanceof Error?i.message:String(i)},"node agent reverse tunnel request body rejected"),void s.send(JSON.stringify({type:"node-agent.response",requestId:n,status:400,error:{code:"NODE_TUNNEL_REQUEST_BODY_INVALID",message:"Reverse tunnel request body does not match the negotiated protocol."}}))}const u=new AbortController;a.set(n,u);try{const t=await e.inject({method:c,url:`/api/node-agent${o}`,headers:l(o,c,d,r),payload:d,signal:u.signal});if(u.signal.aborted)return;s.send(JSON.stringify({type:"node-agent.response",requestId:n,status:t.statusCode,headers:t.headers,body:t.body}))}catch(e){if(u.signal.aborted)return;s.send(JSON.stringify({type:"node-agent.response",requestId:n,status:502,error:{code:"NODE_AGENT_REVERSE_INJECT_FAILED",message:e instanceof Error?e.message:String(e)}}))}finally{a.delete(n)}}}else e.nodeAgentEventForwarder?.setOutputSubscription?.(s,g.aiSessionTransient,g.eventEnvelopeVersion,g.aiSessionHierarchy)})(i).catch(n=>{e.log.warn({nodeId:t.nodeId,error:n instanceof Error?n.message:String(n)},"node agent reverse tunnel message rejected");try{s.send(JSON.stringify({type:"node-agent.error",code:"INVALID_TUNNEL_MESSAGE"}))}catch{}})}),s}function uT(e,t){return Number.isFinite(e)&&Number(e)>0?Number(e):t}function pT(e){if(!e.length)return;const t=[...e].sort((e,t)=>e-t);return t[Math.ceil(.95*t.length)-1]}function mT(e){return e.unref?.(),e}class hT{connectTimeoutMs;handshakeTimeoutMs;heartbeatIntervalMs;heartbeatTimeoutMs;heartbeatMissThreshold;stableThresholdMs;now;setTimeoutFn;clearTimeoutFn;ping;onTimeout;onStable;onPhase;connectTimer;handshakeTimer;heartbeatTimer;stableTimer;awaitingPongSince;consecutiveHeartbeatMisses=0;stable=!1;stopped=!1;currentPhase="connecting";lastActivityAt;lastPongAt;pingRttMs;recentPingRttMs=[];constructor(e){this.connectTimeoutMs=uT(e.connectTimeoutMs,1e4),this.handshakeTimeoutMs=uT(e.handshakeTimeoutMs,1e4),this.heartbeatIntervalMs=uT(e.heartbeatIntervalMs,25e3),this.heartbeatTimeoutMs=uT(e.heartbeatTimeoutMs,15e3),this.heartbeatMissThreshold=Math.max(1,Math.floor(uT(e.heartbeatMissThreshold,2))),this.stableThresholdMs=uT(e.stableThresholdMs,6e4),this.now=e.now||Date.now,this.setTimeoutFn=e.setTimeoutFn||setTimeout,this.clearTimeoutFn=e.clearTimeoutFn||clearTimeout,this.ping=e.ping,this.onTimeout=e.onTimeout,this.onStable=e.onStable,this.onPhase=e.onPhase}get phase(){return this.currentPhase}start(){this.stopped=!1,this.setPhase("connecting"),this.clearTimer("connectTimer"),this.connectTimer=mT(this.setTimeoutFn(()=>this.timeout("connect"),this.connectTimeoutMs))}opened(){this.stopped||(this.clearTimer("connectTimer"),this.setPhase("handshaking"),this.handshakeTimer=mT(this.setTimeoutFn(()=>this.timeout("handshake"),this.handshakeTimeoutMs)),this.scheduleHeartbeat(this.heartbeatIntervalMs))}healthy(){this.stopped||(this.clearTimer("handshakeTimer"),this.activity(),this.setPhase("healthy"),this.stable||this.stableTimer||(this.stableTimer=mT(this.setTimeoutFn(()=>{this.stableTimer=void 0,this.stopped||"healthy"!==this.currentPhase||(this.stable=!0,this.onStable?.())},this.stableThresholdMs))))}activity(){this.stopped||(this.lastActivityAt=this.now(),this.awaitingPongSince=void 0,this.consecutiveHeartbeatMisses=0,"handshaking"!==this.currentPhase&&"healthy"!==this.currentPhase||this.scheduleHeartbeat(this.heartbeatIntervalMs))}pong(){if(this.stopped)return;const e=this.now();void 0!==this.awaitingPongSince&&(this.pingRttMs=Math.max(0,e-this.awaitingPongSince),this.recentPingRttMs.push(this.pingRttMs),this.recentPingRttMs.length>20&&this.recentPingRttMs.shift()),this.awaitingPongSince=void 0,this.consecutiveHeartbeatMisses=0,this.lastPongAt=e,this.lastActivityAt=e,this.scheduleHeartbeat(this.heartbeatIntervalMs)}close(){this.stopped||(this.stopped=!0,this.clearTimers(),this.awaitingPongSince=void 0,this.setPhase("closed"))}diagnostics(){return{phase:this.currentPhase,stable:this.stable,...void 0===this.pingRttMs?{}:{pingRttMs:this.pingRttMs},...this.recentPingRttMs.length?{pingRttP95Ms:pT(this.recentPingRttMs)}:{},...void 0===this.lastActivityAt?{}:{lastActivityAt:new Date(this.lastActivityAt).toISOString()},...void 0===this.lastPongAt?{}:{lastPongAt:new Date(this.lastPongAt).toISOString()},...this.consecutiveHeartbeatMisses?{consecutiveHeartbeatMisses:this.consecutiveHeartbeatMisses}:{}}}scheduleHeartbeat(e){this.stopped||(this.clearTimer("heartbeatTimer"),this.heartbeatTimer=mT(this.setTimeoutFn(()=>{if(this.heartbeatTimer=void 0,!this.stopped){if(void 0!==this.awaitingPongSince){const e=Math.max(0,this.now()-this.awaitingPongSince);return e>=this.heartbeatTimeoutMs?(this.consecutiveHeartbeatMisses+=1,this.awaitingPongSince=void 0,this.consecutiveHeartbeatMisses>=this.heartbeatMissThreshold?void this.timeout("heartbeat"):void this.sendHeartbeatProbe()):void this.scheduleHeartbeat(this.heartbeatTimeoutMs-e)}this.sendHeartbeatProbe()}},e)))}sendHeartbeatProbe(){this.awaitingPongSince=this.now();try{this.ping()}catch{if(this.consecutiveHeartbeatMisses+=1,this.awaitingPongSince=void 0,this.consecutiveHeartbeatMisses>=this.heartbeatMissThreshold)return void this.timeout("heartbeat")}this.scheduleHeartbeat(this.heartbeatTimeoutMs)}timeout(e){this.stopped||(this.clearTimers(),this.setPhase("failed"),this.onTimeout(e))}setPhase(e){this.currentPhase!==e&&(this.currentPhase=e,this.onPhase?.(e))}clearTimers(){this.clearTimer("connectTimer"),this.clearTimer("handshakeTimer"),this.clearTimer("heartbeatTimer"),this.clearTimer("stableTimer")}clearTimer(e){const t=this[e];t&&this.clearTimeoutFn(t),this[e]=void 0}}function gT(e){const t=new URL(FA,e);return t.protocol="https:"===t.protocol?"wss:":"ws:",t.toString()}const fT=new Set(["linux","darwin","win32","freebsd","openbsd","aix","sunos"]);function yT(e){return fT.has(e)?e:"unknown"}function IT(e){return!0===e.managedArtifacts}class _T{managedArtifacts=!0;executor;runCommand;platform;arch;constructor(e,t,n,i){this.executor=e,this.runCommand=t,this.platform=n,this.arch=i}artifactTarget(e){return this.executor.inspectRuntimeTarget(e?.instance.runtime.containerName)}resolveInstanceWeb(e){return this.executor.resolveInstanceWeb(e)}resolveNodeAgentUrl(e){return this.executor.resolveNodeAgentUrl(e)}runtimeState(e){const t=e.instance.runtime.containerName;return t?this.executor.runtimeState(t):Promise.resolve("absent")}async installRuntime(e,t){const n=e.instance.runtime.containerName;if(!n)throw Object.assign(new Error(`Instance ${e.instance.id} does not have a Docker container.`),{code:"INSTANCE_RUNTIME_INSTALL_FAILED"});await this.executor.installRuntimeReleaseWithRecovery({containerName:n,expectedContainerId:e.instance.runtime.containerId,artifactPath:t.archivePath,identity:t.identity})}async inspectRuntime(e,t){const n=e.instance.runtime.containerName;return!!n&&function(e,t){return e.packageName===t.packageName&&e.version===t.version&&e.platform===t.platform&&e.arch===t.arch&&e.formatVersion===t.formatVersion&&e.launcherAbi===t.launcherAbi&&e.entrypoint===t.entrypoint&&e.sha256===t.sha256}(await this.executor.inspectRuntimeVersion(n),t)}start(e){return this.executor.start(e)}stop(e){return this.executor.stop(e)}restart(e){return this.executor.restart(e,e.instance.runtime.containerId)}delete(e,t){return this.executor.delete(e,t)}async check(e){try{const t=(await this.runCommand("docker",["version","--format","{{.Server.Version}}"],{timeoutMs:5e3})).stdout.trim();return{status:"online",capabilities:{...Og("docker",e.capabilities),daemon:{status:"online",hostPlatform:yT(this.platform),...t?{serverVersion:t}:{}}}}}catch(t){return{status:"offline",capabilities:{...Og("docker",e.capabilities),daemon:{status:"offline",hostPlatform:yT(this.platform),error:t instanceof Error?t.message:String(t)}}}}}}class ET{members=new Map;constructor(e=[]){for(const t of e)this.register(t.type,t.adapter)}register(e,t){return this.members.set(e,t),this}has(e){return this.members.has(e)}types(){return[...this.members.keys()]}forRuntime(e){const t=this.members.get(e.type);if(!t)throw Object.assign(new Error(`Runtime type ${e.type} is not supported by this node agent.`),{statusCode:400,code:"NODE_RUNTIME_TYPE_UNSUPPORTED"});return t}managedAdapters(){return[...this.members.values()].filter(IT)}async stopAll(){for(const e of this.members.values())!0===e.stopOnShutdown&&await(e.stopAll?.())}}function AT(e,i,s){const o="win32"===i?[...new Set((s.PATHEXT||".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean).flatMap(e=>[e,e.toLowerCase()]))]:[""];for(const s of o){const o="win32"!==i||n.extname(e)?e:`${e}${s}`;try{if(t.accessSync(o,t.constants.X_OK),t.statSync(o).isFile())return o}catch{}}}function TT(e,t,i,s={}){const o=AT(n.join(t,i.command),i.platform,i.env);if(!o)return;const r=i.env.PATH||"";return{executable:o,resolver:e,env:{PATH:r?`${t}${n.delimiter}${r}`:t,...s}}}function wT(e,t){const n=e=>e.replace(/^v/,"").split(/[.-]/).map(e=>/^\d+$/.test(e)?Number(e):e),i=n(e),s=n(t);for(let e=0;e<Math.max(i.length,s.length);e+=1){const t=i[e]??0,n=s[e]??0;if(t!==n)return"number"==typeof t&&"number"==typeof n?n-t:String(n).localeCompare(String(t))}return 0}function bT(e,i){if(!i||n.isAbsolute(i)||i.split("/").some(e=>!e||"."===e||".."===e))return;const s=n.join(e,"alias",...i.split("/"));try{return t.readFileSync(s,"utf8").trim().split(/\s+/)[0]}catch{return}}const NT=[{id:"path",resolve(e){if(n.isAbsolute(e.command)){const t=AT(e.command,e.platform,e.env);return t?{executable:t,resolver:this.id}:void 0}if(e.explicitPath){const t=AT(n.resolve(e.cwd,e.command),e.platform,e.env);return t?{executable:t,resolver:this.id}:void 0}for(const t of(e.env.PATH||"").split(n.delimiter).filter(Boolean)){const i=AT(n.join(t,e.command),e.platform,e.env);if(i)return{executable:i,resolver:this.id}}}},{id:"nvm",resolve(e){if(e.explicitPath||"win32"===e.platform)return;const i=[];e.env.NVM_BIN&&i.push(e.env.NVM_BIN);const s=function(e){const i=n.join(e,"versions","node");try{return t.readdirSync(i,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name).sort(wT)}catch{return[]}}(e.nvmDir),o=function(e,t){let n="default";const i=new Set;for(let s=0;s<8&&n&&!i.has(n);s+=1){i.add(n);const s=bT(e,n);if(!s)break;const o=t.find(e=>e===s||e===`v${s}`);if(o)return o;if(/^(?:node|stable)$/.test(s))return t[0];if(/^v?\d+(?:\.\d+){0,2}$/.test(s)){const e=s.startsWith("v")?s:`v${s}`,n=t.find(t=>t===e||t.startsWith(`${e}.`));if(n)return n}n=s}}(e.nvmDir,s);o&&i.push(n.join(e.nvmDir,"versions","node",o,"bin"));for(const t of s)i.push(n.join(e.nvmDir,"versions","node",t,"bin"));for(const t of[...new Set(i)]){const n=TT(this.id,t,e,{NVM_BIN:t,NVM_DIR:e.nvmDir});if(n)return n}}},{id:"homebrew",resolve(e){if(!e.explicitPath&&"win32"!==e.platform)for(const t of e.homebrewBinDirectories){const n=TT(this.id,t,e);if(n)return n}}},{id:"npm-global",resolve(e){if(!e.explicitPath)for(const t of e.npmGlobalBinDirectories){const n=TT(this.id,t,e);if(n)return n}}}];function ST(e,t){const i=t.HOMEBREW_PREFIX?[n.join(t.HOMEBREW_PREFIX,"bin")]:[];return"darwin"===e&&i.push("/opt/homebrew/bin","/usr/local/bin"),"linux"===e&&i.push("/home/linuxbrew/.linuxbrew/bin"),[...new Set(i)]}function vT(e,t,i){const s=[],o=t.NPM_CONFIG_PREFIX||t.npm_config_prefix;if(o&&s.push("win32"===e?o:n.join(o,"bin")),"win32"===e){const e=t.APPDATA||(i?n.join(i,"AppData","Roaming"):void 0);e&&s.push(n.join(e,"npm"))}return[...new Set(s)]}function OT(e,t={}){const i=t.platform||process.platform;if("win32"!==i)return e;const o=e.PATHEXT?e:{...e,PATHEXT:".COM;.EXE;.BAT;.CMD"};if(function(e,t){for(const i of(e.PATH||"").split(n.delimiter).filter(Boolean))if(AT(n.join(i,"node"),t,e))return!0;return!1}(o,i))return o;const r=function(e,t={}){const i=t.platform||process.platform;if("win32"!==i)return;const o=t.homeDir||s.homedir(),r=t.nodeRuntimeDirectories||function(e,t,i){if("win32"!==e)return[];const s=t.LOCALAPPDATA||(i?n.join(i,"AppData","Local"):void 0),o=t.APPDATA||(i?n.join(i,"AppData","Roaming"):void 0),r="node.exe"===n.basename(process.execPath).toLowerCase()?n.dirname(process.execPath):void 0,a=[t.NVM_SYMLINK,t.NVM_HOME,t.TASK_HANDOFF_NODE?n.dirname(t.TASK_HANDOFF_NODE):void 0,r,t.ProgramFiles?n.join(t.ProgramFiles,"nodejs"):void 0,t["ProgramFiles(x86)"]?n.join(t["ProgramFiles(x86)"],"nodejs"):void 0,s?n.join(s,"Programs","nodejs"):void 0,s?n.join(s,"Volta","bin"):void 0,s?n.join(s,"Microsoft","WinGet","Links"):void 0,i?n.join(i,"scoop","shims"):void 0,o?n.join(o,"nvm"):void 0];return[...new Set(a.filter(e=>Boolean(e)))]}(i,e,o);for(const t of r)if(AT(n.join(t,"node"),i,e))return t}(o,{...t,platform:i});return r?{...o,PATH:o.PATH?`${r}${n.delimiter}${o.PATH}`:r}:o}function RT(e,t){return Object.assign(new Error(t),{code:e})}function zT(e,t=process.platform){return"win32"===t&&/\.(?:cmd|bat)$/i.test(e)}const xT=/[\s"&|<>^()[\]]/;const CT="task-handoff.local-process-nonce",kT=1e3,DT=1e4,LT=2e3;function PT(e,t){try{e?.(t)}catch{}}function MT(e){return e.runtime.port?`http://127.0.0.1:${e.runtime.port}`:void 0}async function jT(e,t){try{const n=await fetch(`${e}/api/internal/node-agent/process-identity`,{headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(kT)});if(!n.ok)return;const i=(await n.json()).data;if("string"!=typeof i?.instanceId||"number"!=typeof i.pid||"string"!=typeof i.processNonce)return;return{instanceId:i.instanceId,pid:i.pid,processNonce:i.processNonce,startIdentity:"string"==typeof i.startIdentity?i.startIdentity:void 0}}catch{return}}async function UT(e,t){if(q.processStartIdentity(e)!==t)return!1;try{process.kill(e,"SIGTERM")}catch{return!0}const n=Date.now()+DT;for(;Date.now()<n;){try{process.kill(e,0)}catch{return!0}await new Promise(e=>setTimeout(e,50))}try{process.kill(e,"SIGKILL")}catch{}const i=Date.now()+LT;for(;Date.now()<i;){try{process.kill(e,0)}catch{return!0}await new Promise(e=>setTimeout(e,50))}return!1}function FT(e,t){return Object.assign(new Error(t),{statusCode:503,code:"LOCAL_INSTANCE_STOP_UNCONFIRMED",instanceId:e.id})}async function $T(){const e=Number(process.env.TASK_HANDOFF_LOCAL_INSTANCE_PORT_START||19e3),t=Number.isInteger(e)&&e>0?e:19e3;for(let e=t;e<t+1e3&&e<=65535;e+=1)if(await qT(e))return e;throw Object.assign(new Error(`No free localhost port found in range ${t}-${Math.min(t+999,65535)}.`),{statusCode:503,code:"LOCAL_INSTANCE_PORT_UNAVAILABLE"})}async function HT(e){return!await function(e){return new Promise(t=>{const n=g.createConnection({host:"127.0.0.1",port:e}),i=e=>{n.removeAllListeners(),n.destroy(),t(e)};n.once("connect",()=>i(!0)),n.once("error",()=>i(!1)),n.setTimeout(250,()=>i(!1))})}(e)&&new Promise(t=>{const n=g.createServer();n.once("error",()=>t(!1)),n.listen({host:"127.0.0.1",port:e,exclusive:!0},()=>n.close(()=>t(!0)))})}const qT=HT;function BT(e,t){return null!==e.exitCode||null!==e.signalCode?Promise.resolve(!0):new Promise(n=>{const i=setTimeout(()=>{e.off("exit",s),n(null!==e.exitCode||null!==e.signalCode)},t);i.unref();const s=()=>{clearTimeout(i),n(!0)};e.once("exit",s)})}async function VT(e,t=1e4,n=2e3,i){if(await BT(e,t))return;PT(i,{stage:"graceful-timeout",pid:e.pid,timeoutMs:t});let s=!1;if(null===e.exitCode&&null===e.signalCode&&(e.kill("SIGKILL"),s=!0,PT(i,{stage:"force-signal-sent",pid:e.pid,signal:"SIGKILL"})),!await BT(e,n))throw PT(i,{stage:"force-exit-unconfirmed",pid:e.pid,signal:"SIGKILL",timeoutMs:n}),Object.assign(new Error(`Controlled instance process pid=${e.pid??"unknown"} did not exit after SIGKILL.`),{statusCode:503,code:"LOCAL_INSTANCE_PROCESS_EXIT_UNCONFIRMED",pid:e.pid});s&&PT(i,{stage:"force-exit-confirmed",pid:e.pid,signal:"SIGKILL"})}class GT{children=new Map;readyChildren=new WeakSet;expectedExits=new WeakSet;lifecycleReporters=new WeakMap;lockPath;onUnexpectedExit;onUnexpectedExitError;constructor(e,t,n){this.lockPath=e,this.onUnexpectedExit=t,this.onUnexpectedExitError=n}track(e,t,n){this.children.set(e,t),n&&this.lifecycleReporters.set(t,n),t.once("exit",(n,i)=>{if(this.release(e,t),this.readyChildren.has(t)&&!this.expectedExits.has(t)){const s={instanceId:e,pid:t.pid,code:n,signal:i},o=e=>{try{this.onUnexpectedExitError?.(e,s)}catch{}};try{Promise.resolve(this.onUnexpectedExit?.(s)).catch(o)}catch(e){o(e)}}}),t.unref()}markReady(e,t){return this.children.get(e)===t&&null===t.exitCode&&null===t.signalCode&&(this.readyChildren.add(t),!0)}release(e,t){this.children.get(e)===t&&this.children.delete(e)}async stop(e){const t=this.children.get(e.id);if(t){this.expectedExits.add(t);const n=this.lifecycleReporters.get(t);return t.killed||(t.kill("SIGTERM"),PT(n,{stage:"graceful-signal-sent",pid:t.pid,signal:"SIGTERM"})),this.children.delete(e.id),void await VT(t,DT,LT,n)}const i=await async function(e){const t=MT(e),n=e.runtime.labels?.[CT];if(!t||!n||!e.registrationToken)return;const i=await jT(t,e.registrationToken);if(i&&i.instanceId===e.id&&i.processNonce===n)try{return(await fetch(`${t}/api/internal/node-agent/shutdown`,{method:"POST",headers:{authorization:`Bearer ${e.registrationToken}`},signal:AbortSignal.timeout(kT)})).ok?i:void 0}catch{return}}(e);if(i){const t=MT(e),n=Date.now()+DT;for(;t&&Date.now()<n;){if(!await jT(t,e.registrationToken))return;await new Promise(e=>setTimeout(e,50))}const s=t?await jT(t,e.registrationToken):void 0;if(s&&s.instanceId===i.instanceId&&s.pid===i.pid&&s.processNonce===i.processNonce&&s.startIdentity===i.startIdentity&&s.startIdentity&&await UT(s.pid,s.startIdentity))return;throw FT(e,`Controlled instance ${e.id} accepted shutdown but its exit could not be confirmed.`)}const o=function(e=function(){const e="win32"===process.platform?s.tmpdir():"/tmp";return n.join(e,`task-handoff-local-controlled-instance-${function(){const e=process.getuid?.();return void 0!==e?String(e):s.userInfo().username.replace(/[^a-zA-Z0-9_.-]/g,"_")}()}.lock`)}()){return Y(e)}(this.lockPath),r=await async function(e){const t=MT(e);if(t)try{const[n,i]=await Promise.all([fetch(`${t}/api/instance/status`,{signal:AbortSignal.timeout(kT)}),fetch(`${t}/api/diagnostics`,{signal:AbortSignal.timeout(kT)})]);if(!n.ok||!i.ok)return;const s=await n.json(),o=await i.json(),r=o.data?.runtime?.pid;if(s.data?.id!==e.id||"controlled"!==s.data.controlMode||"number"!=typeof r||!Number.isInteger(r)||r<=0)return;const a=q.processStartIdentity(r);return a?{pid:r,startIdentity:a}:void 0}catch{return}}(e);if(r){if(await UT(r.pid,r.startIdentity))return;throw FT(e,`Legacy controlled instance ${e.id} did not exit after termination.`)}if(o?.instanceId===e.id&&Q(o))throw FT(e,`Local controlled instance ${e.id} is still owned by pid ${o.pid}, but its process identity could not be verified.`)}async waitUntilHealthy(e,t,n,i,s=function(e=process.env.TASK_HANDOFF_LOCAL_PROCESS_READY_TIMEOUT_MS){const t=Number(e);return Number.isFinite(t)&&t>0?t:3e4}()){const o=Date.now()+s;for(;Date.now()<o;){if(null!==n.exitCode||null!==n.signalCode)return!1;const s=await jT(e,i);if(s&&s.instanceId===t.instanceId&&s.pid===t.pid&&s.processNonce===t.processNonce&&s.startIdentity===t.startIdentity)return!0;await new Promise(e=>setTimeout(e,100))}return!1}async isRunning(e){const t=this.children.get(e.id);if(t&&null===t.exitCode&&null===t.signalCode)return!0;const n=MT(e);return!(!n||!e.registrationToken)&&Boolean(await jT(n,e.registrationToken))}async stopAll(){const e=Array.from(this.children.values());for(const t of e){this.expectedExits.add(t);const e=this.lifecycleReporters.get(t);t.killed||(t.kill("SIGTERM"),PT(e,{stage:"graceful-signal-sent",pid:t.pid,signal:"SIGTERM"}))}this.children.clear(),await Promise.all(e.map(e=>VT(e,DT,LT,this.lifecycleReporters.get(e))))}}function KT(){const e=process.env.TASK_HANDOFF_LOCAL_CONTROLLED_COMMAND_ARGV?.trim();if(!e){const e=process.env.TASK_HANDOFF_LOCAL_CONTROLLED_COMMAND?.trim();return e?e.split(/\s+/):void 0}let t;try{t=JSON.parse(e)}catch{throw Object.assign(new Error("TASK_HANDOFF_LOCAL_CONTROLLED_COMMAND_ARGV must be valid JSON."),{code:"LOCAL_CONTROLLED_COMMAND_INVALID"})}if(!Array.isArray(t)||!t.length||t.some(e=>"string"!=typeof e||!e))throw Object.assign(new Error("TASK_HANDOFF_LOCAL_CONTROLLED_COMMAND_ARGV must be a non-empty string array."),{code:"LOCAL_CONTROLLED_COMMAND_INVALID"});return t}async function WT(e,t){try{const i=function(e,t=[],i={}){const o=i.env||process.env,r=i.platform||process.platform,a=function(e,t={}){const i=t.env||process.env,o=t.platform||process.platform,r=t.homeDir||s.homedir(),a={command:e,env:i,cwd:t.cwd||process.cwd(),platform:o,homeDir:r,nvmDir:t.nvmDir||i.NVM_DIR||n.join(r,".nvm"),homebrewBinDirectories:t.homebrewBinDirectories||ST(o,i),npmGlobalBinDirectories:t.npmGlobalBinDirectories||vT(o,i,r),explicitPath:n.isAbsolute(e)||e.includes("/")||e.includes("\\")};for(const e of t.resolvers||NT){const t=e.resolve(a);if(t)return t}}(e,i),c=!a&&!0===i.win32ShimWhenUnresolved&&"win32"===r&&!zT(e,r)&&""===n.win32.extname(e),d=a?.executable||(c?`${e}.cmd`:e),l={...o,...a?.env||{}};if(!zT(d,r))return{executable:d,args:[...t],env:l,interpreterWrapped:!1};const u=OT(l,{...i,env:l,platform:r});return{executable:u.ComSpec||"cmd.exe",args:["/d","/s","/c","call",d,...t.map(e=>function(e){if(/[\0\r\n]/.test(e))throw RT("COMMAND_ARGUMENT_INVALID","Command arguments must not contain NUL or line breaks.");if(e.includes("%"))throw RT("COMMAND_ARGUMENT_UNSUPPORTED","cmd.exe expands '%' even inside quotes, so this argument cannot be passed through a .cmd/.bat shim safely.");return""===e?'""':xT.test(e)?`"${e.replace(/"/g,'\\"')}"`:e}(e))],env:u,interpreterWrapped:!0}}(t,["--version"]),o=i.interpreterWrapped?await e(i.executable,i.args,{env:i.env}):await e(t,["--version"]);return{available:!0,command:t,version:(o.stdout||o.stderr).split(/\r?\n/)[0]?.trim()||void 0}}catch{return{available:!1}}}class YT{stopOnShutdown=!0;runCommand;paths;nodeAgentUrl;processSupervisor;async resolveInstanceWeb(e){const t=e.instance.runtime.port;if(!t)throw Object.assign(new Error(`Instance ${e.instance.id} does not have a node-owned local runtime port.`),{statusCode:409,code:"INSTANCE_RUNTIME_ENDPOINT_UNAVAILABLE"});return`http://127.0.0.1:${t}`}async runtimeState(e){try{return await this.processSupervisor.isRunning(e.instance)?"running":"stopped"}catch{return"unknown"}}commandOverride;lockPath;constructor(e,t,n,i,s,o,r){this.runCommand=e,this.paths=t,this.nodeAgentUrl=n,this.commandOverride=i,this.lockPath=s,this.processSupervisor=new GT(s,o,r)}async start(e){await this.processSupervisor.stop(e.instance);const i=function(e){if("local-folder"!==e.source.type){const e=new Error("Localhost runtime currently supports local folder sources only.");throw Object.assign(e,{statusCode:400,code:"LOCAL_RUNTIME_REQUIRES_LOCAL_FOLDER"}),e}return n.resolve(e.source.path)}(e.instance),s=e.instance.runtime.port,o=!!s&&await HT(s),r="allocate"===process.env.TASK_HANDOFF_LOCAL_INSTANCE_PORT_CONFLICT;if(s&&!o&&!r)throw Object.assign(new Error(`Local controlled instance port 127.0.0.1:${s} is already in use.`),{statusCode:409,code:"LOCAL_INSTANCE_PORT_IN_USE"});const a=s&&o?s:await $T(),c=n.join(this.paths.dataDir,"local-instances",e.instance.id),u=n.join(c,"logs"),p=(e.instance.config?.codexConfigEnabled??1)&&"taskhandoff"===(e.instance.config?.codexHomeMode??"taskhandoff")?n.join(c,"configs","codex"):void 0;t.mkdirSync(u,{recursive:!0,mode:448}),p&&t.mkdirSync(p,{recursive:!0,mode:448}),Yf(c,448),Yf(u,448),p&&Yf(p,448);const[m,...h]=function(e){if(e)return e;const i=n.resolve(process.cwd(),"bin","task-handoff.js");if(t.existsSync(i))return[process.execPath,i,"web"];throw Object.assign(new Error("The bundled controlled-instance command is unavailable."),{statusCode:500,code:"LOCAL_CONTROLLED_COMMAND_MISSING"})}(this.commandOverride),g=[...h,"--host","127.0.0.1","--port",String(a)],f=d.randomUUID(),y=n.join(u,"controlled-instance.out.log"),I=n.join(u,"controlled-instance.err.log");Cl(y),Cl(I);const _=function(e){const i=e.platform??process.platform,s=e.kind??"host-ipc",o=e.directoryName??Wf(e.scope,e.key??d.randomUUID(),e.keyHashLength??12),r=Vf(s,i);if("named-pipe"===r)return{endpoint:{path:`\\\\.\\pipe\\${o}-${d.randomBytes(6).toString("hex")}`,transport:r,kind:s,platform:i,filesystemBacked:!1}};const a=e.rootDir||Kf(i,e.temporaryDirectory),c=t.mkdtempSync(n.join(a,`${o}-`));return{endpoint:{path:n.join(c,e.fileName??"ipc.sock"),transport:r,kind:s,platform:i,filesystemBacked:!0},directory:c}}({scope:"th-git",key:e.instance.id,keyHashLength:12,fileName:"broker.sock"});_.directory&&Yf(_.directory,448);const E=()=>{var e;(e=_.endpoint).filesystemBacked&&function(e){try{t.unlinkSync(e)}catch(e){if("ENOENT"!==e.code)throw e}}(e.path),_.directory&&t.rmSync(_.directory,{recursive:!0,force:!0})},A=t.openSync(y,"a",384),T=t.openSync(I,"a",384),w=l.spawn(m,g,{cwd:i,detached:!1,stdio:["ignore",A,T],env:{...process.env,TASK_HANDOFF_CONTROL_MODE:"controlled",TASK_HANDOFF_RUNTIME_KIND:"local",TASK_HANDOFF_CONTROLLED_INSTANCE_VERSION:Tg(),...this.lockPath?{TASK_HANDOFF_LOCAL_CONTROLLED_INSTANCE_LOCK_PATH:this.lockPath}:{},TASK_HANDOFF_NODE_AGENT_URL:this.nodeAgentUrl(),TASK_HANDOFF_INSTANCE_ID:e.instance.id,TASK_HANDOFF_INSTANCE_NAME:e.instance.name,TASK_HANDOFF_REGISTRATION_TOKEN:e.instance.registrationToken||"",TASK_HANDOFF_PROJECT_ID:e.project.id,TASK_HANDOFF_NODE_ID:e.node.id,TASK_HANDOFF_RUNTIME_ID:e.runtime.id,TASK_HANDOFF_LOCAL_PROCESS_NONCE:f,TASK_HANDOFF_WORKSPACE:i,TASK_HANDOFF_WORKSPACE_MODE:"local-bind",TASK_HANDOFF_DATA_DIR:c,TASK_HANDOFF_INSTANCE_PRIVATE_CONFIG_PATH:e.privateConfigPath||"",TASK_HANDOFF_LOG_DIR:u,TASK_HANDOFF_APP_SESSION_PERSIST:"1",TASK_HANDOFF_CODEX_APP_SERVER:process.env.TASK_HANDOFF_CODEX_APP_SERVER||"1",TASK_HANDOFF_WEB_PORT:String(a),TASK_HANDOFF_WEB_HOST:"127.0.0.1",TASK_HANDOFF_GIT_CREDENTIAL_SOCKET:_.endpoint.path,...e.modelEnv||{},CODEX_HOME:p}});t.closeSync(A),t.closeSync(T);try{await function(e){return new Promise((t,n)=>{const i=()=>{e.off("error",s),t()},s=t=>{e.off("spawn",i),n(t)};e.once("spawn",i),e.once("error",s)})}(w)}catch(e){E();const s=e instanceof Error?e.message:String(e);try{t.appendFileSync(n.join(u,"controlled-instance.lifecycle.log"),`[${(new Date).toISOString()}] spawn failed command=${m} cwd=${i} error=${s}\n`)}catch{}throw Object.assign(new Error(`Controlled instance process could not start with command ${m} in ${i}: ${s}`),{statusCode:500,code:"LOCAL_INSTANCE_PROCESS_SPAWN_FAILED"})}const b=n.join(u,"controlled-instance.lifecycle.log");this.processSupervisor.track(e.instance.id,w,e=>{t.appendFileSync(b,`[${(new Date).toISOString()}] shutdown stage=${e.stage} pid=${e.pid??""} signal=${e.signal??""} timeoutMs=${e.timeoutMs??""}\n`)}),w.on("error",e=>{try{t.appendFileSync(b,`[${(new Date).toISOString()}] process error pid=${w.pid??""} error=${e.message}\n`)}catch{}}),w.once("exit",(e,n)=>{E();try{t.appendFileSync(b,`[${(new Date).toISOString()}] exited pid=${w.pid??""} code=${e??""} signal=${n??""}\n`)}catch{}});const N=`http://127.0.0.1:${a}`,S=w.pid?q.processStartIdentity(w.pid):void 0;if(!(w.pid&&e.instance.registrationToken&&await this.processSupervisor.waitUntilHealthy(N,{instanceId:e.instance.id,pid:w.pid,processNonce:f,startIdentity:S},w,e.instance.registrationToken)&&this.processSupervisor.markReady(e.instance.id,w)))throw this.processSupervisor.release(e.instance.id,w),null===w.exitCode&&null===w.signalCode&&w.kill("SIGTERM"),await VT(w),Object.assign(new Error(`Controlled instance process did not become ready for instance ${e.instance.id} on ${N}.`),{statusCode:503,code:"LOCAL_INSTANCE_PROCESS_NOT_READY"});return{status:"registering",health:"unknown",connectionStatus:"online",agentStatus:"unknown",targetStatus:"unknown",uiAccessStatus:"unknown",target:{strategy:"direct-port",status:"unknown",web:N,api:`${N}/api`},workspace:{mode:"local-bind",status:"pending",path:i},runtime:{kind:"local",workspacePath:i,pid:w.pid,port:a,labels:{...e.instance.runtime.labels,"task-handoff.runtime-kind":"local",[CT]:f}}}}async stop(e){return await this.processSupervisor.stop(e.instance),{status:"stopped",health:"unknown",connectionStatus:"offline",agentStatus:"offline",targetStatus:"unknown",uiAccessStatus:"unknown",target:{...e.instance.target,status:"unknown"},runtime:e.instance.runtime}}async restart(e){return this.start(e)}async delete(e,t){return await this.stop(e),Bs.parse({instanceId:e.instance.id,containerDeleted:!0,completed:!0,deletedVolumes:[],retainedVolumes:[],volumeResults:[]})}async check(e){const[t,n]=await Promise.all([WT(this.runCommand,"codex"),WT(this.runCommand,"claude")]);return{status:"online",capabilities:qg({...e.capabilities,apps:{terminal:!0,codex:t,claude:n}})}}async stopAll(){await this.processSupervisor.stopAll()}}const XT="th-wsl-",JT=["sh","-c","while true; do sleep 30; done"],QT="WSL_COMMAND_FAILED",ZT="WSL_RUNTIME_UNSUPPORTED_PLATFORM";function ew(e,t,n){return Object.assign(new Error(t),{code:e,...n?{details:n}:{}})}function tw(e){return`'${e.replace(/'/g,"'\\''")}'`}function nw(e){const t=e.trim();if(!t)throw ew("WSL_INSTANCE_ID_INVALID","Instance id is required to derive a WSL distro name.");const n=d.createHash("sha256").update(t).digest("hex").slice(0,8),i=`-${n}`,s=function(e){return e.trim().toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}(t).slice(0,121-i.length);return`${XT}${s?`${s}${i}`:n}`}function iw(e,t){return"utf8"===t?e.toString("utf8"):"utf16le"===t?(e.length>=2&&255===e[0]&&254===e[1]?e.subarray(2):e).toString("utf16le"):function(e){if(e.length>=2&&255===e[0]&&254===e[1])return e.subarray(2).toString("utf16le");const t=e.subarray(0,Math.min(e.length,1024));let n=0,i=0;for(let e=0;e<t.length;e+=1)0===t[e]&&(e%2==1?n+=1:i+=1);return 0===n&&0===i?e.toString("utf8"):n>i?e.toString("utf16le"):e.toString("utf8")}(e)}class sw{wslPath;runner;spawnSession;platform;commandTimeoutMs;sessionCommand;sessions=new Map;constructor(e={}){this.wslPath=e.wslPath??function(e=process.env){const t=e.SystemRoot?.trim()||e.windir?.trim()||"C:\\Windows";return n.win32.join(t,"System32","wsl.exe")}(),this.runner=e.runner??function(e,n=l.spawn){return(i,s={})=>new Promise((o,r)=>{if(s.signal?.aborted)return void r(ew(QT,`${e} ${i.join(" ")} was aborted.`));const a=n(e,i,{stdio:[s.stdinFile?"pipe":"ignore","pipe","pipe"],windowsHide:!0}),c=[],d=[];let l=!1,u=!1;const p=s.timeoutMs??3e4,m=setTimeout(()=>{l=!0,a.kill("SIGKILL")},p),h=()=>{u=!0,a.kill("SIGKILL")};s.signal?.addEventListener("abort",h,{once:!0});const g=()=>{clearTimeout(m),s.signal?.removeEventListener("abort",h)};if(m.unref?.(),a.stdout?.on("data",e=>c.push(Buffer.from(e))),a.stderr?.on("data",e=>d.push(Buffer.from(e))),s.stdinFile&&a.stdin){const n=t.createReadStream(s.stdinFile);n.on("error",t=>{a.stdin?.destroy(),g(),r(ew(QT,`${e} could not read stdin file ${s.stdinFile}: ${t.message}`,{args:i}))}),n.pipe(a.stdin)}a.on("error",t=>{g(),r(ew(QT,`${e} could not be started: ${t.message}`,{args:i}))}),a.on("close",t=>{g();const n={stdout:iw(Buffer.concat(c),s.decode??"auto").trim(),stderr:iw(Buffer.concat(d),s.decode??"auto").trim(),exitCode:t??-1};l?r(ew(QT,`${e} ${i.join(" ")} timed out after ${p}ms`,{...n,args:i,timeoutMs:p})):u?r(ew(QT,`${e} ${i.join(" ")} was aborted.`,{...n,args:i})):o(n)})})}(this.wslPath),this.spawnSession=e.sessionSpawner??function(e,t=l.spawn){return(n,i)=>{const s=t(e,n,{stdio:["ignore","pipe","pipe"],windowsHide:!0});let o=!1;return s.stdout?.on("data",()=>{}),s.stderr?.on("data",()=>{}),s.on("error",()=>{o=!0}),s.unref?.(),{name:i,pid:s.pid,alive:()=>!o&&null===s.exitCode&&!s.killed,stop:()=>new Promise(e=>{if(o=!0,null!==s.exitCode)return void e();const t=()=>e();s.once("close",t),s.kill();const n=setTimeout(t,5e3);n.unref?.()})}}}(this.wslPath),this.platform=e.platform??process.platform,this.commandTimeoutMs=e.commandTimeoutMs??3e4,this.sessionCommand=e.sessionCommand??JT}get executablePath(){return this.wslPath}async run(e,t={}){if("win32"!==this.platform)throw ew(ZT,"The WSL runtime is available only on Windows nodes.",{platform:this.platform,args:e});return this.runner(e,{timeoutMs:this.commandTimeoutMs,...t})}async runOrThrow(e,t={},n){const i=await this.run(e,t);if(0!==i.exitCode)throw ew(QT,n??`wsl.exe ${e.join(" ")} failed with exit code ${i.exitCode}.`,{args:e,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr});return i}async version(){return(await this.runOrThrow(["--version"])).stdout}async available(){try{return await this.version(),!0}catch{return!1}}async listDistros(){return function(e){const t=[];for(const n of e.split(/\r?\n/)){const e=n.replace(/\0/g,"").trimEnd();if(!e.trim())continue;const i=/^(\*?)\s*(.+?)\s+(Running|Stopped|Installing|Uninstalling)\s+(\d+)\s*$/i.exec(e);i&&t.push({isDefault:"*"===i[1],name:i[2].trim(),state:`${i[3][0].toUpperCase()}${i[3].slice(1).toLowerCase()}`,version:Number(i[4])})}return t}((await this.runOrThrow(["--list","--verbose"],{decode:"auto"})).stdout)}async findDistro(e){return(await this.listDistros()).find(t=>t.name===e)}async distroState(e){const t=await this.findDistro(e);return t?"Running"===t.state?"running":"Stopped"===t.state?"stopped":"unknown":"absent"}async importDistro(e){return await this.runOrThrow(["--import",e.name,e.installDir,e.tarballPath,"--version",String(e.version??2)]),this.findDistro(e.name)}async terminate(e){await this.runOrThrow(["--terminate",e])}async unregister(e){await this.runOrThrow(["--unregister",e])}async exec(e,t,n={}){if(!t.length)throw ew(QT,"A command is required to exec inside a WSL distro.",{name:e});return this.run(["-d",e,"-u","root","--",...t],{decode:"utf8",...n})}async execOrThrow(e,t,n={}){const i=await this.exec(e,t,n);if(0!==i.exitCode)throw ew(QT,`wsl.exe -d ${e} -- ${t.join(" ")} failed with exit code ${i.exitCode}.`,{args:["-d",e,"-u","root","--",...t],exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr});return i}async execStream(e,t,n={}){if("win32"!==this.platform)throw ew(ZT,"The WSL runtime is available only on Windows nodes.",{platform:this.platform,args:t});if(!t.length)throw ew(QT,"A command is required to exec inside a WSL distro.",{name:e});const i=["-d",e,"-u","root","--",...t],s=l.spawn(this.wslPath,i,{stdio:["ignore","pipe","pipe"],windowsHide:!0}),o=[],r=[],a=n.timeoutMs??this.commandTimeoutMs;let c=!1;const d=setTimeout(()=>{c=!0,s.kill("SIGKILL")},a);d.unref?.();const u=()=>s.kill("SIGKILL");n.signal?.addEventListener("abort",u,{once:!0}),s.stdout?.on("data",e=>{o.push(Buffer.from(e)),n.onData?.(e.toString("utf8"))}),s.stderr?.on("data",e=>{r.push(Buffer.from(e)),n.onData?.(e.toString("utf8"))});const p=await new Promise((e,t)=>{s.on("error",e=>t(ew(QT,`${this.wslPath} could not be started: ${e.message}`,{args:i}))),s.on("close",t=>e(t??-1))}).finally(()=>{clearTimeout(d),n.signal?.removeEventListener("abort",u)}),m={stdout:Buffer.concat(o).toString("utf8").trim(),stderr:Buffer.concat(r).toString("utf8").trim(),exitCode:p};if(c)throw ew(QT,`${this.wslPath} ${i.join(" ")} timed out after ${a}ms`,{...m,args:i,timeoutMs:a});return m}async systemctl(e,t){return this.execOrThrow(e,["systemctl",...t])}static windowsPathToDrvfs(e){const t=/^([a-zA-Z]):[\\/](.*)$/.exec(e.trim());if(t)return`/mnt/${t[1].toLowerCase()}/${t[2].replace(/\\/g,"/")}`}async copyIntoDistro(e,t,i,s={}){const o=n.posix.dirname(i);await this.execOrThrow(e,["sh","-c",`mkdir -p ${tw(o)} && cat > ${tw(i)}`],{...s,stdinFile:t})}async defaultGateway(e){return(await this.exec(e,["sh","-c","ip -o -4 route show default 2>/dev/null | awk '{print $3; exit}'"])).stdout.trim().split(/\s+/)[0]||void 0}async unitActive(e,t){return(await this.exec(e,["systemctl","is-active",t])).stdout.split(/\s+/)[0]||"unknown"}async ensureDistroRunning(e,t={}){const n=Date.now()+(t.timeoutMs??6e4),i=await this.distroState(e);if("absent"===i)throw ew("WSL_DISTRO_MISSING",`WSL distro ${e} does not exist on this node.`,{name:e});if("running"===i)return"running";await this.exec(e,["true"]);const s=t.intervalMs??500;for(;Date.now()<n;){if("running"===await this.distroState(e))return"running";await new Promise(e=>setTimeout(e,s))}throw ew(QT,`WSL distro ${e} did not reach Running within the timeout.`,{name:e})}sessionAlive(e){const t=this.sessions.get(e);return!(!t||!t.alive()&&(this.sessions.delete(e),1))}async holdSession(e){if(this.sessionAlive(e))return this.sessions.get(e);const t=this.spawnSession(["-d",e,"-u","root","--",...this.sessionCommand],e);this.sessions.set(e,t);try{await this.ensureDistroRunning(e)}catch(t){throw await this.releaseSession(e).catch(()=>{}),ew("WSL_SESSION_FAILED",`Could not hold a keep-alive session for WSL distro ${e}.`,{name:e,cause:t instanceof Error?t.message:String(t)})}return t}async releaseSession(e){const t=this.sessions.get(e);this.sessions.delete(e),t&&await t.stop()}async releaseAllSessions(){const e=[...this.sessions.keys()];await Promise.all(e.map(e=>this.releaseSession(e).catch(()=>{})))}}const ow="/opt/task-handoff/instance-runtime",rw="/opt/task-handoff/bootstrap/runtime-installer.mjs",aw="/run/task-handoff/runtime-artifact.tar.gz";function cw(e){return`'${e.replace(/'/g,"'\\''")}'`}const dw="/opt/task-handoff/bootstrap",lw=`${dw}/entrypoint.sh`,uw="/run/task-handoff/private",pw=`${uw}/${dc}`,mw="task-handoff-instance.service",hw=`/etc/systemd/system/${mw}`,gw="/workspace",fw="/var/lib/task-handoff/bootstrap-revision",yw="WSL_LIFECYCLE_FAILED",Iw="WSL_WORKSPACE_UNSUPPORTED";function _w(e,t,n){return Object.assign(new Error(t),{code:e,...n?{details:n}:{}})}function Ew(e){return d.createHash("sha256").update(t.readFileSync(e)).digest("hex")}class Aw{provisioner;executor;options;constructor(e){this.options=e,this.provisioner=e.provisioner,this.executor=e.executor}distroNameFor(e){return this.provisioner.distroNameForInstance({id:e.id,containerName:e.runtime.containerName})}async provision(e){return this.provisioner.provision({id:e.id,runtimeId:e.runtimeId,containerName:e.runtime.containerName})}sessionAlive(e){const t=this.executor;return"function"==typeof t.sessionAlive&&t.sessionAlive(e)}async nodeAgentUrl(e,t){const n=this.options.hostAddress?.trim()||process.env.TASK_HANDOFF_WSL_NODE_AGENT_URL?.trim();if(n)return function(e,t){const n=e.trim();if(!n)throw new Error("A node agent URL is required.");if(/^https?:\/\//i.test(n))return new URL(n).origin;const i=/^([^:/]+)(?::(\d+))?$/.exec(n);if(!i)throw new Error(`Node agent address ${e} is not a valid host[:port] or URL.`);const s=i[2]?Number(i[2]):t;return`http://${i[1]}:${s}`}(n,this.options.listenerPort);const i=await this.executor.defaultGateway(t).catch(()=>{});if(i)return`http://${i}:${this.options.listenerPort}`;if(this.options.fallbackNodeAgentUrl)return this.options.fallbackNodeAgentUrl;throw _w(yw,`Could not resolve a node agent URL reachable from WSL distro ${t} for instance ${e.instance.id}.`,{distroName:t,instanceId:e.instance.id})}async syncBootstrapAssets(e){const i=this.options.bootstrapDir;if(!i||!t.existsSync(i))return;const s=function(e){const i=d.createHash("sha256"),s=t.existsSync(e)?t.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isFile()).sort((e,t)=>e.name.localeCompare(t.name)):[];for(const t of s){const s=n.join(e,t.name);i.update(t.name),i.update("\0"),i.update(Ew(s)),i.update("\0")}return i.digest("hex")}(i),o=await this.executor.exec(e,["cat",fw]);if(0!==o.exitCode||o.stdout.trim()!==s){await this.executor.execOrThrow(e,["sh","-c",`mkdir -p ${dw}`]);for(const s of t.readdirSync(i,{withFileTypes:!0}))s.isFile()&&await this.executor.copyIntoDistro(e,n.join(i,s.name),`${dw}/${s.name}`);await this.executor.execOrThrow(e,["sh","-c",`chmod 0755 ${dw}/*.sh ${dw}/*.mjs 2>/dev/null || true`]),await this.executor.execOrThrow(e,["sh","-c",`mkdir -p ${n.posix.dirname(fw)} && printf '%s' ${Tw(s)} > ${fw}`]),this.options.logger?.("wsl bootstrap assets synchronized",{distroName:e,revision:s,bootstrapDir:i})}}async syncPrivateConfig(e,n){e.privateConfigPath&&t.existsSync(e.privateConfigPath)&&(await this.executor.execOrThrow(n,["sh","-c",`mkdir -p ${uw} && chmod 0700 ${uw}`]),await this.executor.copyIntoDistro(n,e.privateConfigPath,pw),await this.executor.execOrThrow(n,["sh","-c",`chmod 0600 ${pw}`]))}async installRuntime(e,t){await async function(e,t,n){await e.copyIntoDistro(t,n.archivePath,aw),await e.execOrThrow(t,["sh","-c",`install -d -m 0755 ${ow} ${ow}/releases ${ow}/staging ${ow}/incoming && node ${rw} install --artifact ${aw} --version ${cw(n.identity.version)} --sha256 ${cw(n.identity.sha256)} --platform ${cw(n.identity.platform)} --arch ${cw(n.identity.arch)} --launcher-abi ${String(n.identity.launcherAbi)}`])}(this.executor,e,t)}async inspectRuntime(e,t){return async function(e,t,n){const i=await e.exec(t,["node",rw,"verify-active"]);if(0!==i.exitCode)return!1;let s;try{s=JSON.parse(i.stdout)}catch{return!1}return function(e,t){return e.packageName===t.packageName&&e.version===t.version&&e.platform===t.platform&&e.arch===t.arch&&e.formatVersion===t.formatVersion&&e.launcherAbi===t.launcherAbi&&e.entrypoint===t.entrypoint&&e.sha256===t.sha256}(s,n)}(this.executor,e,t)}artifactTarget(){return{platform:"linux",arch:this.options.hostArch??process.arch,launcherAbi:1}}async allocatePort(){return this.options.allocatePort?this.options.allocatePort():$T()}async writeUnit(e,t,n,i){const s=function(e,t){const n=Object.entries(e).filter(([,e])=>"string"==typeof e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`Environment="${e}=${function(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/%/g,"%%")}(t)}"`);return["[Unit]",`Description=${t.description}`,"After=network-online.target","Wants=network-online.target","","[Service]","Type=simple",`WorkingDirectory=${t.workspace}`,...n,`ExecStart=/bin/bash ${lw} task-handoff web`,"Restart=no","KillMode=mixed","TimeoutStopSec=20","","[Install]","WantedBy=multi-user.target",""].join("\n")}(t,{workspace:n,description:`Task Handoff controlled instance ${i}`}),o=Buffer.from(s,"utf8").toString("base64");await this.executor.execOrThrow(e,["sh","-c",`printf '%s' ${Tw(o)} | base64 -d > ${hw}`])}async waitForUnitActive(e){const t=Date.now()+(this.options.unitReadyTimeoutMs??3e4),n=this.options.pollIntervalMs??500;for(;Date.now()<t;){const t=await this.executor.unitActive(e,mw).catch(()=>"unknown");if("active"===t)return"active";if("failed"===t)throw _w(yw,`systemd unit ${mw} failed to start in WSL distro ${e}.`,{distroName:e});await new Promise(e=>setTimeout(e,n))}const i=await this.executor.unitActive(e,mw).catch(()=>"unknown");if("active"===i)return"active";throw _w(yw,`systemd unit ${mw} did not become active in WSL distro ${e} within the timeout.`,{distroName:e,state:i})}async start(e){const t=this.distroNameFor(e.instance),n=await this.provisioner.provision({id:e.instance.id,runtimeId:e.instance.runtimeId,containerName:e.instance.runtime.containerName}),i=await this.prepareWorkspace(e,t);await this.syncBootstrapAssets(t),await this.syncPrivateConfig(e,t),await this.executor.holdSession(t);const s=await this.nodeAgentUrl(e,t),o=function(e,t){const n={TASK_HANDOFF_CONTROL_MODE:"controlled",TASK_HANDOFF_NODE_AGENT_URL:t.nodeAgentUrl,TASK_HANDOFF_INSTANCE_ID:e.instance.id,TASK_HANDOFF_INSTANCE_NAME:e.instance.name,TASK_HANDOFF_PROJECT_ID:e.project.id,TASK_HANDOFF_NODE_ID:e.node?.id||"node_unset",TASK_HANDOFF_RUNTIME_ID:e.runtime?.id||"runtime_wsl_host",TASK_HANDOFF_RUNTIME_KIND:"wsl",TASK_HANDOFF_IMAGE_ID:e.image.id,TASK_HANDOFF_INSTANCE_LAUNCHER:`${dw}/instance-launcher.sh`,TASK_HANDOFF_CHAT_BRIDGES:"none",TASK_HANDOFF_WORKSPACE:t.workspace,TASK_HANDOFF_WORKSPACE_MODE:e.project.workspacePolicy.mode,TASK_HANDOFF_INSTANCE_PRIVATE_CONFIG_PATH:pw,...e.image.tag?{TASK_HANDOFF_IMAGE_TAG:e.image.tag}:{},..."local-folder"===e.project.source.type?{}:{TASK_HANDOFF_SKIP_WORKSPACE_BOOTSTRAP:"true"}};if("local-folder"!==e.project.source.type){n.TASK_HANDOFF_PROJECT_SOURCE=JSON.stringify(e.project.source),n.TASK_HANDOFF_WORKSPACE_POLICY=JSON.stringify(e.project.workspacePolicy);for(const[t,i]of Gc({url:e.project.source.url,ref:e.project.source.ref,clone:e.project.source.clone},{legacy:!0}))n[t]=i;e.project.source.clone?.subdirectory&&(n.TASK_HANDOFF_WORKSPACE_SUBDIRECTORY=e.project.source.clone.subdirectory)}return n}(e,{nodeAgentUrl:s,workspace:i});await this.writeUnit(t,o,i,e.instance.id);const r=e.instance.runtime.port??await this.allocatePort();await this.executor.systemctl(t,["daemon-reload"]),await this.executor.systemctl(t,["enable",mw]),await this.executor.systemctl(t,["restart",mw]);const a=await this.waitForUnitActive(t).catch(n=>(this.options.logger?.("wsl unit not active after start",{instanceId:e.instance.id,distroName:t,error:n instanceof Error?n.message:String(n)}),"unknown")),c=`http://127.0.0.1:${r}`;return this.options.logger?.("wsl instance started",{instanceId:e.instance.id,distroName:t,port:r,nodeAgentUrl:s,created:n.created,unitState:a}),{status:"registering",health:"unknown",connectionStatus:"online",agentStatus:"unknown",targetStatus:"unknown",uiAccessStatus:"unknown",target:{strategy:"node-proxy",status:"unknown",web:c,api:`${c}/api`},workspace:{mode:e.project.workspacePolicy.mode,status:"ready",path:i},runtime:{kind:"wsl",containerName:t,workspacePath:i,port:r,labels:{...e.instance.runtime.labels,...n.labels}}}}async stop(e){const t=this.distroNameFor(e.instance);return"absent"===await this.executor.distroState(t).catch(()=>"unknown")?(await this.executor.releaseSession(t).catch(()=>{}),this.stoppedResult(e)):(await this.executor.systemctl(t,["stop",mw]).catch(()=>{}),await this.executor.releaseSession(t).catch(()=>{}),await this.executor.terminate(t).catch(()=>{}),this.options.logger?.("wsl instance stopped",{instanceId:e.instance.id,distroName:t}),this.stoppedResult(e))}stoppedResult(e){return{status:"stopped",health:"unknown",connectionStatus:"offline",agentStatus:"offline",targetStatus:"unknown",uiAccessStatus:"unknown",target:{...e.instance.target,status:"unknown"},runtime:e.instance.runtime}}async restart(e){const t=this.distroNameFor(e.instance);return await this.executor.systemctl(t,["stop",mw]).catch(()=>{}),await this.executor.releaseSession(t).catch(()=>{}),this.start(e)}async delete(e,t){const n=this.distroNameFor(e.instance);if("absent"===await this.executor.distroState(n).catch(()=>"unknown"))return await this.executor.releaseSession(n).catch(()=>{}),this.provisioner.forgetDistro(n),Bs.parse({instanceId:e.instance.id,containerDeleted:!0,completed:!0,deletedVolumes:[],retainedVolumes:this.distroVolumeDispositions(n,"missing",t),volumeResults:this.distroVolumeDispositions(n,"missing",t)});let i,s=!1;try{await this.executor.systemctl(n,["stop",mw]).catch(()=>{}),await this.executor.releaseSession(n).catch(()=>{}),await this.executor.unregister(n),this.provisioner.forgetDistro(n),s=!0}catch(e){i={code:"object"==typeof e&&e&&"code"in e&&"string"==typeof e.code?String(e.code):yw,message:e instanceof Error?e.message:String(e)}}const o=s?"deleted":t.deleteVolumes?"failed":"retained",r=this.distroVolumeDispositions(n,o,t,i);return this.options.logger?.(s?"wsl instance deleted":"wsl instance delete incomplete",{instanceId:e.instance.id,distroName:n,status:o,...i?{error:i.message}:{}}),Bs.parse({instanceId:e.instance.id,containerDeleted:s,completed:s,deletedVolumes:r.filter(e=>"deleted"===e.status||"missing"===e.status),retainedVolumes:r.filter(e=>"retained"===e.status),volumeResults:r})}distroVolumeDispositions(e,t,n,i){const s="failed"!==t||n.deleteVolumes?t:"retained";return[{role:"data",mountPath:"/data"},{role:"agent-home",mountPath:"/home/agent"},{role:"workspace",mountPath:gw}].map(({role:t,mountPath:n})=>({role:t,name:`${e}:${t}`,mountPath:n,status:s,..."failed"===s?{error:i??{code:yw,message:`Could not remove WSL distro ${e}.`}}:{}}))}async prepareWorkspace(e,t){const n=e.project.workspacePolicy.path||gw;return"local-folder"===e.project.source.type?this.prepareLocalFolderWorkspace(e,t,n):(await this.executor.execOrThrow(t,["sh","-c",`mkdir -p ${Tw(n)}`]),n)}async prepareLocalFolderWorkspace(e,t,i){if("local-folder"!==e.project.source.type)throw _w(Iw,"Local folder workspace preparation requires a local-folder source.");const s=function(e){const t=/^([a-zA-Z]):[\\/](.*)$/.exec(e.trim());return t?`/mnt/${t[1].toLowerCase()}/${t[2].replace(/\\/g,"/")}`:void 0}(e.project.source.path);if(!s)throw _w(Iw,`Local folder ${e.project.source.path} is not a Windows absolute path mapable into WSL.`,{instanceId:e.instance.id,path:e.project.source.path});if(0!==(await this.executor.exec(t,["test","-d",s])).exitCode)throw _w("WSL_WORKSPACE_PREPARATION_FAILED",`Mapped local folder ${s} is not accessible inside WSL distro ${t}.`,{instanceId:e.instance.id,mapped:s});return await this.executor.execOrThrow(t,["sh","-c",`mkdir -p ${Tw(n.posix.dirname(i))} && ln -sfn ${Tw(s)} ${Tw(i)}`]),i}}function Tw(e){return`'${e.replace(/'/g,"'\\''")}'`}function ww(e){return e.runtime.containerName?.trim()||nw(e.id)}class bw{managedArtifacts=!0;executor;platform;lifecycle;constructor(e,t={}){this.executor=e,this.platform=t.platform??process.platform,this.lifecycle=t.lifecycle??(t.provisioner&&t.listenerPort?new Aw({provisioner:t.provisioner,executor:e,listenerPort:t.listenerPort,hostAddress:t.hostAddress,fallbackNodeAgentUrl:t.fallbackNodeAgentUrl,bootstrapDir:t.bootstrapDir,hostArch:t.hostArch??process.arch,allocatePort:t.allocatePort,logger:t.logger}):void 0)}requireLifecycle(e){if(this.lifecycle)return this.lifecycle;throw Object.assign(new Error(`The WSL runtime lifecycle is not configured; cannot ${e}.`),{statusCode:503,code:"WSL_RUNTIME_LIFECYCLE_UNAVAILABLE",details:{operation:e}})}async resolveInstanceWeb(e){const t=e.instance.runtime.port;if(!t)throw Object.assign(new Error(`Instance ${e.instance.id} does not have a node-owned WSL runtime port.`),{statusCode:409,code:"INSTANCE_RUNTIME_ENDPOINT_UNAVAILABLE"});return`http://127.0.0.1:${t}`}async resolveNodeAgentUrl(e){if(!this.lifecycle)return e.nodeAgentUrl||"";const t=ww(e.instance);return this.lifecycle.nodeAgentUrl(e,t)}async runtimeState(e){const t=ww(e.instance);if(!t)return"absent";try{return await this.executor.distroState(t)}catch{return"unknown"}}async start(e){return this.requireLifecycle("start").start(e)}async stop(e){return this.requireLifecycle("stop").stop(e)}async restart(e){return this.requireLifecycle("restart").restart(e)}async delete(e,t){return this.requireLifecycle("delete").delete(e,t)}async artifactTarget(e){return this.lifecycle?this.lifecycle.artifactTarget():{platform:"linux",arch:process.arch,launcherAbi:1}}async installRuntime(e,t){const n=this.requireLifecycle("installRuntime"),i=ww(e.instance);await n.installRuntime(i,t)}async inspectRuntime(e,t){if(!this.lifecycle)return!1;const n=ww(e.instance);return this.lifecycle.inspectRuntime(n,t)}async check(e){const t=function(e={}){return na(e)}(e.capabilities),n=yT(this.platform);try{const e=await this.executor.version();return{status:"online",capabilities:{...t,wsl:{status:"online",hostPlatform:n,executablePath:this.executor.executablePath,version:e}}}}catch(e){return{status:"offline",capabilities:{...t,wsl:{status:"offline",hostPlatform:n,executablePath:this.executor.executablePath,error:e instanceof Error?e.message:String(e)}}}}}}const Nw="WSL_BASE_TEMPLATE_MISSING",Sw="WSL_BASE_TEMPLATE_INVALID",vw="WSL_DISTRO_OWNERSHIP_CONFLICT",Ow="/var/lib/task-handoff/distro.json",Rw="wsl-base",zw="/var/lib/task-handoff/owner-baseline",xw=["/workspace","/data","/home/agent"],Cw="agent";function kw(){const e=xw.join(" "),t=`chown -R ${Cw}:${Cw}`;return`[ -f ${zw} ] || { mkdir -p ${e} && ${t} ${e} && { [ ! -d /app ] || ${t} /app; } && mkdir -p ${n.posix.dirname(zw)} && : > ${zw}; }`}const Dw="task-handoff.runtime-kind",Lw="wsl",Pw="task-handoff.instance-id",Mw="task-handoff.runtime-id",jw="task-handoff.owner-node-id",Uw="task-handoff.base-template";function Fw(e,t,n,i=500){return Object.assign(new Error(t),{statusCode:i,code:e,...n?{details:n}:{}})}const $w=c.z.object({id:c.z.string().min(1),version:c.z.string().min(1),platform:c.z.literal("linux"),arch:c.z.string().min(1),formatVersion:c.z.literal(1),sha256:c.z.string().regex(/^[a-f0-9]{64}$/),sizeBytes:c.z.number().int().nonnegative().optional(),createdAt:c.z.string().optional(),tools:c.z.record(c.z.string(),c.z.string()).optional()}).strict(),Hw=c.z.object({runtimeKind:c.z.literal(Lw),distroName:c.z.string().min(1),instanceId:c.z.string().min(1),runtimeId:c.z.string().min(1),nodeId:c.z.string().min(1),baseTemplateId:c.z.string().min(1),baseTemplateVersion:c.z.string().min(1),createdAt:c.z.string().min(1)}).strict(),qw=c.z.object({version:c.z.literal(1),distros:c.z.record(c.z.string(),Hw)}).strict();function Bw(e=process.env){const t=[],i=e.TASK_HANDOFF_WSL_BASE_TEMPLATE_DIR?.trim();i&&t.push(n.resolve(i));const s=e.TASK_HANDOFF_BUNDLED_RUNTIME_DIR?.trim(),o=s?n.resolve(s):n.resolve(n.dirname(process.argv[1]||process.cwd()),"..","runtime-artifacts");return t.push(n.join(o,"wsl-base"),o),t}function Vw(e,t){return`${Rw}-${e}-${t}`}async function Gw(e){let t;try{t=JSON.parse(await y.readFile(e,"utf8"))}catch(t){throw Fw(Sw,`WSL base template manifest ${e} could not be read.`,{manifestPath:e,cause:t instanceof Error?t.message:String(t)})}const n=$w.safeParse(t);if(!n.success)throw Fw(Sw,`WSL base template manifest ${e} is invalid.`,{manifestPath:e,issues:n.error.issues});return n.data}async function Kw(e,i){let s;try{s=await y.readdir(e)}catch{return}const o=[];for(const r of s){const s=n.join(e,r),a=n.join(s,"manifest.json"),c=n.join(s,".ready");if(!t.existsSync(c)||!t.existsSync(a))continue;const d=await Gw(a).catch(()=>{});if(!d)continue;if(i.expectedVersion&&d.version!==i.expectedVersion)continue;if(i.expectedArch&&d.arch!==i.expectedArch)continue;const l=n.join(s,`${Vw(d.version,d.arch)}.tar.gz`);t.existsSync(l)&&o.push({identity:d,archivePath:l,manifestPath:a,cacheHit:!0})}return o.sort((e,t)=>t.identity.version.localeCompare(e.identity.version)),o[0]}class Ww{filePath;constructor(e){this.filePath=e}file(){return new pu(this.filePath,()=>({version:1,distros:{}}),{schema:qw})}get(e){return this.file().get().distros[e]}list(){return this.file().get().distros}put(e){const t=this.file().get();return this.file().put({version:1,distros:{...t.distros,[e.distroName]:e}})}delete(e){const t=this.file().get(),{[e]:n,...i}=t.distros;return this.file().put({version:1,distros:i})}}class Yw{executor;nodeId;distroRoot;index;options;constructor(e){this.options=e,this.executor=e.executor,this.nodeId=e.nodeId,this.distroRoot=e.distroRoot,this.index=e.index}distroNameForInstance(e){const t=e.containerName?.trim();return t||nw(e.id)}forgetDistro(e){this.index.delete(e)}labelsFor(e,t){return n={instanceId:e.id,runtimeId:e.runtimeId,nodeId:this.nodeId,baseTemplateId:t.baseTemplateId},{[Dw]:Lw,[Pw]:n.instanceId,[Mw]:n.runtimeId,[jw]:n.nodeId,...n.baseTemplateId?{[Uw]:n.baseTemplateId}:{}};var n}async ensureBaseTemplate(){return async function(e){const i=await async function(e){if(e.archivePath){const i=n.resolve(e.archivePath),s=e.manifestPath?n.resolve(e.manifestPath):i.endsWith(".tar.gz")?`${i.slice(0,-7)}.manifest.json`:`${i}.manifest.json`;if(!t.existsSync(i))throw Fw(Nw,`WSL base template archive ${i} does not exist.`,{archivePath:i});if(!t.existsSync(s))throw Fw(Nw,`WSL base template manifest ${s} does not exist.`,{manifestPath:s});return{archivePath:i,manifestPath:s}}for(const i of e.sourceDirs??[]){let s;try{s=await y.readdir(i)}catch{continue}const o=s.filter(e=>e.startsWith(`${Rw}-`)&&e.endsWith(".manifest.json")).map(e=>n.join(i,e)).sort().reverse();for(const s of o){const o=await Gw(s).catch(()=>{});if(!o)continue;if(e.expectedVersion&&o.version!==e.expectedVersion)continue;if(e.expectedArch&&o.arch!==e.expectedArch)continue;const r=n.join(i,`${Vw(o.version,o.arch)}.tar.gz`);if(t.existsSync(r))return{archivePath:r,manifestPath:s}}}throw Fw(Nw,"No cached or bundled WSL base template was found. Build/package one or set TASK_HANDOFF_WSL_BASE_TEMPLATE.",{sourceDirs:e.sourceDirs??[]})}(e).catch(t=>{if(e.archivePath||t?.code!==Nw)throw t});if(!i){const t=await Kw(e.cacheDir,e);if(t)return t;throw Fw(Nw,"No cached or bundled WSL base template was found. Build/package one or set TASK_HANDOFF_WSL_BASE_TEMPLATE.",{sourceDirs:e.sourceDirs??[]})}const s=await Gw(i.manifestPath);!function(e,t){if(t.expectedVersion&&e.version!==t.expectedVersion)throw Fw(Sw,`WSL base template version ${e.version} does not match expected ${t.expectedVersion}.`,{actualVersion:e.version,expectedVersion:t.expectedVersion});if(t.expectedArch&&e.arch!==t.expectedArch)throw Fw(Sw,`WSL base template arch ${e.arch} does not match expected ${t.expectedArch}.`,{actualArch:e.arch,expectedArch:t.expectedArch})}(s,e);const o=await Kw(e.cacheDir,{...e,expectedVersion:s.version,expectedArch:s.arch});if(o)return o;const r=await async function(e){const n=d.createHash("sha256"),i=t.createReadStream(e);for await(const e of i)n.update(e);return n.digest("hex")}(i.archivePath);if(r!==s.sha256)throw Fw(Sw,`WSL base template ${s.id}@${s.version} failed SHA-256 verification.`,{archivePath:i.archivePath,expectedSha256:s.sha256,actualSha256:r});const a=n.join(e.cacheDir,Vw(s.version,s.arch));await y.mkdir(a,{recursive:!0});const c=n.join(a,`${Vw(s.version,s.arch)}.tar.gz`),l=n.join(a,"manifest.json"),u=`${c}.staging-${process.pid}`;return await y.copyFile(i.archivePath,u),await y.rename(u,c),m.sync(l,`${JSON.stringify(s,null,2)}\n`,{encoding:"utf8"}),m.sync(n.join(a,".ready"),"",{encoding:"utf8"}),e.logger?.("wsl base template cached",{version:s.version,arch:s.arch,sourceArchivePath:i.archivePath,cacheArchivePath:c,sizeBytes:s.sizeBytes}),{identity:s,archivePath:c,manifestPath:l,cacheHit:!1}}({cacheDir:this.options.baseTemplateCacheDir,sourceDirs:this.options.baseTemplateSourceDirs??Bw(),expectedVersion:this.options.expectedBaseTemplateVersion,expectedArch:this.options.expectedArch,logger:this.options.logger})}async provision(e){const t=this.distroNameForInstance(e),i=await this.executor.findDistro(t);if(i){const n=await this.assertOwnership(t,e);return await this.ensureMarker(t,n),await this.ensureAgentOwnershipBaseline(t),{distroName:t,created:!1,ownership:n,labels:this.labelsFor(e,n),state:i.state}}const s=await this.ensureBaseTemplate(),o=n.join(this.distroRoot,t);await y.mkdir(o,{recursive:!0});const r=await this.executor.importDistro({name:t,installDir:o,tarballPath:s.archivePath}),a={runtimeKind:Lw,distroName:t,instanceId:e.id,runtimeId:e.runtimeId,nodeId:this.nodeId,baseTemplateId:s.identity.id,baseTemplateVersion:s.identity.version,createdAt:(this.options.now?.()??new Date).toISOString()};return this.index.put(a),await this.writeMarker(t,a),await this.ensureAgentOwnershipBaseline(t),this.options.logger?.("wsl distro provisioned",{distroName:t,instanceId:e.id,installDir:o,baseTemplateVersion:s.identity.version,cacheHit:s.cacheHit}),{distroName:t,created:!0,ownership:a,labels:this.labelsFor(e,a),state:r?.state??"Stopped"}}async assertOwnership(e,t){const n=this.index.get(e);if(n)return this.assertOwnershipMatches(n,e,t),n;const i=await this.readMarker(e);if(i)return this.assertOwnershipMatches(i,e,t),this.index.put(i),i;throw Fw(vw,`WSL distro ${e} already exists but carries no ownership record for instance ${t.id}.`,{distroName:e,instanceId:t.id},409)}assertOwnershipMatches(e,t,n){if(e.nodeId!==this.nodeId||e.distroName!==t||e.instanceId!==n.id||e.runtimeId!==n.runtimeId)throw Fw(vw,`WSL distro ${t} is owned by node ${e.nodeId} instance ${e.instanceId}, not ${this.nodeId}/${n.id}.`,{distroName:t,ownerNodeId:e.nodeId,ownerInstanceId:e.instanceId,expectedNodeId:this.nodeId,expectedInstanceId:n.id},409)}async readMarker(e){const t=await this.executor.exec(e,["cat",Ow]);if(0===t.exitCode)try{const e=Hw.safeParse(JSON.parse(t.stdout));return e.success?e.data:void 0}catch{return}}async ensureAgentOwnershipBaseline(e){await this.executor.execOrThrow(e,["sh","-c",kw()])}async writeMarker(e,t){const i=Buffer.from(`${JSON.stringify(t,null,2)}\n`,"utf8").toString("base64"),s=n.posix.dirname(Ow);await this.executor.execOrThrow(e,["sh","-c",`mkdir -p ${s} && printf '%s' ${i} | base64 -d > ${Ow}`])}async ensureMarker(e,t){await this.readMarker(e)||await this.writeMarker(e,t)}async reconcileOrphans(e){const t=new Set(e.instanceIds),n=e.now?.()??Date.now(),i=e.retentionMs??6048e5,s={diagnostics:[],reclaimable:[],reclaimed:[]},o=(await this.executor.listDistros()).filter(e=>e.name.startsWith(XT));for(const r of o){let o=this.index.get(r.name);if(!o){if(!e.inspectUnindexedMarkers){s.diagnostics.push({code:"WSL_DISTRO_UNOWNED",distroName:r.name,action:"skipped",message:`WSL distro ${r.name} has no node-agent ownership record and was left untouched.`});continue}if(o=await this.readMarker(r.name).catch(()=>{}),!o){s.diagnostics.push({code:"WSL_DISTRO_UNOWNED",distroName:r.name,action:"skipped",message:`WSL distro ${r.name} has no readable ownership record and was left untouched.`});continue}this.index.put(o)}if(o.nodeId!==this.nodeId){s.diagnostics.push({code:"WSL_DISTRO_FOREIGN_NODE",distroName:r.name,instanceId:o.instanceId,action:"skipped",message:`WSL distro ${r.name} belongs to node ${o.nodeId} and was left untouched.`});continue}if(t.has(o.instanceId))continue;s.reclaimable.push(r.name);const a=Date.parse(o.createdAt),c=e.force||Number.isFinite(a)&&n-a>=i;e.reclaim&&c?(await this.executor.unregister(r.name),this.index.delete(r.name),s.reclaimed.push(r.name),s.diagnostics.push({code:"WSL_DISTRO_RECLAIMED",distroName:r.name,instanceId:o.instanceId,action:"reclaimed",message:`Reclaimed orphaned WSL distro ${r.name} for deleted instance ${o.instanceId}.`})):s.diagnostics.push({code:"WSL_DISTRO_ORPHANED",distroName:r.name,instanceId:o.instanceId,action:"retained",message:`WSL distro ${r.name} has no live instance record and is retained${c?" (eligible for reclaim)":""}.`})}return s}}const Xw="WSL_SESSION_RECOVERY_FAILED";class Jw{options;recovering=new Map;timer;active;started=!1;stopped=!1;constructor(e){this.options=e}start(){this.started||this.stopped||(this.started=!0,this.schedule(0))}notify(){this.started&&!this.stopped&&this.schedule(0)}async stop(){this.stopped=!0,this.timer&&clearTimeout(this.timer),this.timer=void 0,await this.active}schedule(e){this.stopped||(this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>{this.timer=void 0,this.runCycle()},e),this.timer.unref?.())}runCycle(){const e=this.checkOnce().catch(e=>this.options.onDiagnostic({code:Xw,instanceId:"node",distroName:"node",classification:"recovered",message:"WSL session supervision cycle failed.",error:e instanceof Error?e.message:String(e)})).finally(()=>{this.active===e&&(this.active=void 0),this.schedule(this.options.intervalMs??Math.max(1e3,Math.floor(5e3)))});this.active=e}async checkOnce(){let e=0;for(const t of this.options.listRunningInstances()){const{id:n,distroName:i}=t;this.options.sessionAlive(i)||(await this.recover(t),e+=1)}return e}recover(e){const t=this.recovering.get(e.id);if(t)return t;const n=this.recoverInstance(e).finally(()=>this.recovering.delete(e.id));return this.recovering.set(e.id,n),n}async recoverInstance(e){const{id:t,distroName:n}=e,i=this.options.recoveryBudgetMs??6e4,s=this.options.nowMs??(()=>Date.now()),o=this.options.delay??(e=>new Promise(t=>setTimeout(t,e))),r=s()+i;let a=await this.options.distroState(n).catch(()=>"unknown");const c="running"===a?"instance-crash":"session-lost";this.options.onDiagnostic({code:"WSL_SESSION_LOST",instanceId:t,distroName:n,classification:c,message:"session-lost"===c?`WSL keep-alive session for ${n} was lost and the distro may have been reclaimed; rebuilding.`:`WSL distro ${n} is running but its keep-alive session was lost; rebuilding without treating it as an instance crash.`}),await(this.options.onSessionLost?.(t,n));try{for("running"!==a&&(await this.options.ensureDistroRunning(n),a="running"),await this.options.holdSession(n);s()<r;){if("active"===await this.options.unitActive(n).catch(()=>"unknown")&&(!this.options.waitForEndpointHealthy||await this.options.waitForEndpointHealthy(t).catch(()=>!1)))return void this.options.onDiagnostic({code:"WSL_SESSION_RECOVERED",instanceId:t,distroName:n,classification:"recovered",message:`WSL keep-alive session for ${n} was rebuilt and the instance is healthy.`});await o(500)}throw new Error(`WSL distro ${n} did not reach unit ${mw} active with a healthy endpoint within ${i}ms.`)}catch(e){this.options.onDiagnostic({code:Xw,instanceId:t,distroName:n,classification:c,message:`WSL keep-alive session for ${n} could not be rebuilt.`,error:e instanceof Error?e.message:String(e)})}}async releaseFor(e,t){this.recovering.delete(e),await this.options.releaseSession(t).catch(()=>{})}}const Qw="/run/task-handoff/git-auth",Zw="/run/task-handoff/git-runtime",eb=`${dw}/git-wsl-provision.sh`,tb=`${dw}/git-wsl-credential-helper.mjs`,nb="TASK_HANDOFF_GIT_PROVISIONING_STAGE=",ib="TASK_HANDOFF_GIT_PROVISIONING_ERROR=",sb="TASK_HANDOFF_GIT_PROVISIONING_COMMIT=";function ob(e,t){return e.split(/\r?\n/).filter(e=>e.startsWith(t)).map(e=>e.slice(t.length).trim()).filter(Boolean).pop()}class rb{executor;logger;constructor(e){this.executor=e.executor,this.logger=e.logger}async ensureScripts(e){const i=t.mkdtempSync(n.join(s.tmpdir(),"task-handoff-wsl-git-"));try{const s=n.join(i,"git-wsl-provision.sh"),o=n.join(i,"git-wsl-credential-helper.mjs");t.writeFileSync(s,`#!/usr/bin/env bash\nset -euo pipefail\n\n# Cross-filesystem normalization (6.4): drvfs mounts and the distro ext4 root can disagree on\n# default modes, so pin the provisioning umask and hand the materialized workspace to the template's\n# \`agent\` user when it exists.\numask 022\n\nworkspace="\${TASK_HANDOFF_WORKSPACE:-${gw}}"\nstaging="\${workspace}/.task-handoff-git-provisioning"\ncheckout="\${staging}/checkout"\nruntime_dir="${Zw}"\n\nfail() {\n printf '${ib}%s\\n' "$1" >&2\n exit "\${2:-1}"\n}\nstage() {\n printf '${nb}%s\\n' "$1"\n}\n\nmkdir -p "\${workspace}" "\${staging}" "\${runtime_dir}"\nexisting="$(find "\${workspace}" -mindepth 1 -maxdepth 1 ! -name .task-handoff-git-provisioning -print -quit 2>/dev/null)"\nif [ -n "\${existing}" ]; then\n if [ -e "\${workspace}/.git" ]; then\n echo "Workspace is already materialized; skipping provisioning."\n exit 0\n fi\n fail WORKSPACE_NOT_EMPTY 73\nfi\nrm -rf -- "\${staging}"\nmkdir -p "\${staging}"\n\nif [ -d "${Qw}" ]; then\n cp -a "${Qw}/." "\${runtime_dir}/"\nfi\nchmod 0700 "\${runtime_dir}"\n\nexport TASK_HANDOFF_WSL_GIT_RUNTIME_DIR="\${runtime_dir}"\nexport GIT_TERMINAL_PROMPT=0\ngit_config=(-c credential.helper= -c credential.helper="!node ${tb} credential" -c credential.useHttpPath=true)\n\nssh_command=""\nfor credential_dir in "\${runtime_dir}"/credential-*; do\n [ -d "\${credential_dir}" ] || continue\n if [ -f "\${credential_dir}/private-key" ]; then\n chmod 0600 "\${credential_dir}/private-key"\n known_hosts="\${credential_dir}/known_hosts"\n [ -f "\${known_hosts}" ] || : > "\${known_hosts}"\n ssh_command="ssh -i \${credential_dir}/private-key -o IdentitiesOnly=yes -o UserKnownHostsFile=\${known_hosts} -o StrictHostKeyChecking=yes"\n fi\ndone\nexport GIT_SSH_COMMAND="\${ssh_command}"\n\nclone_args=(clone --progress)\nif [ -n "\${TASK_HANDOFF_WORKSPACE_GIT_DEPTH:-}" ] && [ -z "\${TASK_HANDOFF_WORKSPACE_GIT_COMMIT:-}" ]; then clone_args+=(--depth "\${TASK_HANDOFF_WORKSPACE_GIT_DEPTH}"); fi\nif [ -n "\${TASK_HANDOFF_WORKSPACE_GIT_REF:-}" ]; then clone_args+=(--branch "\${TASK_HANDOFF_WORKSPACE_GIT_REF}"); fi\nclone_args+=(-- "\${TASK_HANDOFF_WORKSPACE_GIT_URL}" "\${checkout}")\n\nstage cloning\nif ! git "\${git_config[@]}" "\${clone_args[@]}"; then fail CLONE_FAILED 74; fi\n\nif [ -n "\${TASK_HANDOFF_WORKSPACE_GIT_COMMIT:-}" ]; then\n stage checking-out\n if ! git -C "\${checkout}" checkout --detach "\${TASK_HANDOFF_WORKSPACE_GIT_COMMIT}"; then fail REF_NOT_FOUND 75; fi\nfi\nif [ "\${TASK_HANDOFF_WORKSPACE_GIT_SUBMODULES:-false}" = "true" ]; then\n stage submodules\n if ! git "\${git_config[@]}" -C "\${checkout}" submodule update --init --recursive --progress; then fail CLONE_FAILED 74; fi\nfi\nif [ "\${TASK_HANDOFF_WORKSPACE_GIT_LFS:-false}" = "true" ]; then\n stage lfs\n if ! git "\${git_config[@]}" -C "\${checkout}" lfs pull; then fail LFS_FAILED 76; fi\nfi\nif [ -n "\${TASK_HANDOFF_WORKSPACE_SUBDIRECTORY:-}" ] && [ ! -d "\${checkout}/\${TASK_HANDOFF_WORKSPACE_SUBDIRECTORY}" ]; then\n fail SUBDIRECTORY_NOT_FOUND 75\nfi\nstage finalizing\nprintf '${sb}%s\\n' "$(git -C "\${checkout}" rev-parse HEAD 2>/dev/null || true)"\nshopt -s dotglob nullglob\nmv -- "\${checkout}"/* "\${workspace}/"\nrm -rf -- "\${staging}"\nif id agent >/dev/null 2>&1; then chown -R agent:agent "\${workspace}" 2>/dev/null || true; fi\n`,{mode:493}),t.writeFileSync(o,`#!/usr/bin/env node\n// Generated by the Task Handoff node agent. Reads bridged managed credentials and\n// implements the git credential helper contract for HTTPS remotes only. SSH is\n// handled by GIT_SSH_COMMAND with the bridged private key, so this helper never\n// emits secrets on stdout except the username/password git itself requires.\nimport fs from "node:fs";\nimport path from "node:path";\nconst runtimeDir = process.env.TASK_HANDOFF_WSL_GIT_RUNTIME_DIR || ${JSON.stringify(Zw)};\nconst mode = process.argv[2];\nif (mode !== "credential") process.exit(0);\nlet input = "";\nprocess.stdin.setEncoding("utf8");\nprocess.stdin.on("data", (chunk) => { input += chunk; });\nprocess.stdin.on("end", () => {\n const fields = {};\n for (const line of input.split(/\\r?\\n/)) {\n const index = line.indexOf("=");\n if (index > 0) fields[line.slice(0, index)] = line.slice(index + 1);\n }\n if (fields.protocol && fields.protocol !== "https") process.exit(0);\n let entries = [];\n try { entries = fs.readdirSync(runtimeDir).filter((name) => name.startsWith("credential-")); } catch { process.exit(0); }\n for (const name of entries.sort()) {\n const dir = path.join(runtimeDir, name);\n let scope = {};\n try { scope = JSON.parse(fs.readFileSync(path.join(dir, "scope.json"), "utf8")); } catch {}\n if (scope.scheme && scope.scheme !== "https") continue;\n if (fields.host && scope.host && scope.host !== fields.host) continue;\n let username = "";\n let token = "";\n try { username = fs.readFileSync(path.join(dir, "username"), "utf8").trim(); } catch {}\n try { token = fs.readFileSync(path.join(dir, "token"), "utf8").trim(); } catch {}\n if (!token) continue;\n process.stdout.write("username=" + username + "\\npassword=" + token + "\\n");\n process.exit(0);\n }\n process.exit(1);\n});\n`,{mode:384}),await this.executor.execOrThrow(e,["sh","-c",`mkdir -p ${dw}`]),await this.executor.copyIntoDistro(e,s,eb),await this.executor.copyIntoDistro(e,o,tb),await this.executor.execOrThrow(e,["sh","-c",`chmod 0755 ${eb} && chmod 0600 ${tb}`])}finally{t.rmSync(i,{recursive:!0,force:!0})}}async provision(e,i,o={}){const r=e.gitWorkspaceProvisioning;if(!r||"local-folder"===e.project.source.type)throw Object.assign(new Error("Git provisioning requires a Git source and operation input."),{code:"GIT_WORKSPACE_PROVISIONING_INVALID",statusCode:400});await this.ensureScripts(i);const a=t.mkdtempSync(n.join(s.tmpdir(),"task-handoff-wsl-git-auth-"));t.chmodSync(a,448);try{this.materializeGitProvisioningAuth(a,r),await this.bridgeAuth(i,a);const t=this.gitEnvironment(e),n=[...Object.entries(t).map(([e,t])=>`${e}=${function(e){return`'${e.replace(/'/g,"'\\''")}'`}(t)}`),`bash ${eb}`].join(" "),s=await this.executor.execStream(i,["sh","-c",n],{onData:o.onOutput,signal:o.signal,timeoutMs:o.timeoutMs??9e5});if(0!==s.exitCode){const t=ob(s.stdout+"\n"+s.stderr,ib)??"CLONE_FAILED";throw Object.assign(new Error(`WSL Git workspace provisioning failed for ${e.instance.id}: ${t}.`),{code:"GIT_WORKSPACE_PROVISIONING_FAILED",statusCode:502,details:{code:t,distroName:i,instanceId:e.instance.id}})}e.completeGitWorkspaceProvisioning?.();const c=`${s.stdout}\n${s.stderr}`,d=c.split(/\r?\n/).filter(e=>e.startsWith(nb)).map(e=>e.slice(36).trim()),l=ob(c,sb);return this.logger?.("wsl git workspace provisioned",{instanceId:e.instance.id,distroName:i,stages:d,...l?{commit:l}:{}}),{...l?{commit:l}:{},stages:d}}finally{await this.executor.execOrThrow(i,["sh","-c",`rm -rf ${Qw}`]).catch(()=>{}),t.rmSync(a,{recursive:!0,force:!0})}}gitEnvironment(e){const t=e.gitWorkspaceProvisioning,n={TASK_HANDOFF_INSTANCE_ID:e.instance.id,TASK_HANDOFF_WORKSPACE:e.project.workspacePolicy.path||gw};for(const[e,i]of Gc({url:t.remoteUrl,ref:t.ref,clone:t.clone},{legacy:!1}))n[e]=i;return t.clone.subdirectory&&(n.TASK_HANDOFF_WORKSPACE_SUBDIRECTORY=t.clone.subdirectory),n}materializeGitProvisioningAuth(e,i){const s=(e,i,s)=>{const o=n.join(e,i);t.writeFileSync(o,s,{encoding:"utf8",mode:384}),t.chmodSync(o,384)};i.credentials.forEach((i,o)=>{const r=n.join(e,`credential-${o}`);if(t.mkdirSync(r,{recursive:!0,mode:448}),t.chmodSync(r,448),s(r,"scope.json",JSON.stringify(i.payload.credential.scope)),"https-token"===i.payload.secret.kind)return s(r,"username",i.payload.secret.username),void s(r,"token",i.payload.secret.token);s(r,"private-key",i.payload.secret.privateKey),s(r,"known_hosts",i.payload.secret.pinnedKnownHosts),i.payload.secret.passphrase&&s(r,"passphrase",i.payload.secret.passphrase)})}async bridgeAuth(e,i){await this.executor.execOrThrow(e,["sh","-c",`rm -rf ${Qw} && mkdir -p ${Qw} && chmod 0700 ${Qw}`]);for(const s of t.readdirSync(i,{withFileTypes:!0}))if(s.isDirectory()){await this.executor.execOrThrow(e,["sh","-c",`mkdir -p ${Qw}/${s.name} && chmod 0700 ${Qw}/${s.name}`]);for(const o of t.readdirSync(n.join(i,s.name)))await this.executor.copyIntoDistro(e,n.join(i,s.name,o),`${Qw}/${s.name}/${o}`)}else await this.executor.copyIntoDistro(e,n.join(i,s.name),`${Qw}/${s.name}`);await this.executor.execOrThrow(e,["sh","-c",`find ${Qw} -type f -exec chmod 0600 {} +`])}}const ab=["codex","claude"],cb=5e3,db=q.processStartIdentity(process.pid),lb=new WeakSet;function ub(e){const t=process.env[e]?.trim();return t||void 0}function pb(e){const t=e.authorization;return"string"==typeof t&&t.startsWith("Bearer ")?t.slice(7).trim():void 0}function mb(e){if("string"!=typeof e)return!1;const t=e.trim().toLowerCase();return"localhost"===t||"127.0.0.1"===t||"::1"===t||"::ffff:127.0.0.1"===t}function hb(e){return!e.ip&&!e.socket.remoteAddress&&!e.socket.remoteFamily}function gb(e){const t=e.split("?")[0];return/^\/api\/node-agent\/instances\/[^/]+\/(register|heartbeat)$/.test(t)||/^\/api\/node-agent\/instances\/[^/]+\/git-credentials\//.test(t)||/^\/api\/node-agent\/instances\/[^/]+\/story-agent-tools$/.test(t)||/^\/api\/node-agent\/instances\/[^/]+\/ai-sessions\/[^/]+\/story-agent-tools$/.test(t)||/^\/api\/node-agent\/instances\/[^/]+\/ai-sessions\/[^/]+\/story-agent-tools\/[^/]+$/.test(t)||/^\/api\/node-agent\/instances\/[^/]+\/ai-sessions\/[^/]+\/story-content(?:\/|$)/.test(t)}function fb(e){const t=e.capabilities;for(const e of["daemon","wsl"]){const n=t?.[e];if(!n||"object"!=typeof n)continue;const i=n.error;if("string"==typeof i&&i.trim())return i}}async function yb(e,t,n){const i=new AbortController,s=setTimeout(()=>i.abort(),2e3);try{return(await e(`${await n(t)}/api/health`,{signal:i.signal})).ok?"reachable":"endpoint-unreachable"}catch{return"endpoint-unreachable"}finally{clearTimeout(s)}}async function Ib(e,t,n,i){const s=new AbortController,o=setTimeout(()=>s.abort(),i);try{return await e(t,{...n,signal:s.signal})}finally{clearTimeout(o)}}async function _b(e,t,n,i=async e=>PA(e)){if(!t.registrationToken)return"unavailable";const s=ms.parse({nodeAgentUrl:n}),o=await Ib(e,`${await i(t)}/api/internal/node-agent-connection`,{method:"PUT",headers:{"content-type":"application/json",authorization:`Bearer ${t.registrationToken}`},body:JSON.stringify(s)},5e3);if(404===o.status)return"unsupported";if(!o.ok)throw Object.assign(new Error(`Controlled instance rejected the node-agent connection update (HTTP ${o.status}).`),{code:"NODE_AGENT_CONNECTION_UPDATE_FAILED",statusCode:o.status});return"applied"}async function Eb(e,t,n,i,s){if(!t.config.autoImportAgentConfigs)return void i.diagnostic({instanceId:t.id,action:n},"node instance config auto-import skipped");if("reachable"!==t.targetStatus)return;const o=await s(t),r=Number(process.env.TASK_HANDOFF_CONFIG_AUTO_IMPORT_TIMEOUT_MS||cb);for(const s of ab)try{const a=await Ib(e,`${o}/api/config-sync/import/${encodeURIComponent(s)}`,{method:"POST"},Number.isFinite(r)&&r>0?r:cb);if(!a.ok){i.warn({instanceId:t.id,action:n,preset:s,statusCode:a.status},"node instance config auto-import failed");continue}i.diagnostic({instanceId:t.id,action:n,preset:s},"node instance config auto-import completed")}catch(e){i.warn({instanceId:t.id,action:n,preset:s,error:e instanceof Error?e.message:String(e)},"node instance config auto-import failed")}}async function Ab(e,t,n,i,s=async e=>PA(e)){const o=t.requireInstance(n),r=t.resolvedAssignedModelEnvironment(n),a=t.modelRegistry.privateCatalog(n);t.instancePrivateConfigs.materialize(o.id,o.registrationToken,r,a,o.config.codexSettings);const c=o.aiSessions?.sessions?.length??0,d=o.aiSessions?.runningCount??0;if(c>0||d>0)return i?.({instanceId:n,reason:"sessions-bound",boundSessionCount:c,runningSessionCount:d},"node instance model environment live sync deferred"),!1;let l,u;try{l=await s(o)}catch(e){return i?.({instanceId:n,error:e instanceof Error?e.message:String(e)},"node instance model environment live sync deferred"),!1}try{u=await Ib(e,`${l}/api/internal/model-environment`,{method:"PUT",headers:{"content-type":"application/json",authorization:`Bearer ${o.registrationToken}`},body:JSON.stringify(r)},cb)}catch(e){return i?.({instanceId:n,targetWeb:o.target.web,error:e instanceof Error?e.message:String(e)},"node instance model environment live sync deferred"),!1}return u.ok?await async function(e,t,n,i,s){let o;try{o=await Ib(e,`${t}/api/internal/model-catalog`,{method:"PUT",headers:{"content-type":"application/json",authorization:`Bearer ${n.registrationToken}`},body:JSON.stringify(i)},cb)}catch(e){return s?.({instanceId:n.id,error:e instanceof Error?e.message:String(e)},"node instance model catalog live sync deferred"),!1}if(o.ok)return!0;const r=await async function(e,t,n){try{const i=await Ib(e,`${t}/api/internal/model-catalog`,{headers:{authorization:`Bearer ${n}`}},cb);if(!i.ok)return;const s=await i.json(),o=s.data?.catalog?.entities;return{source:"string"==typeof s.data?.source?s.data.source:void 0,loadedAt:"string"==typeof s.data?.loadedAt?s.data.loadedAt:void 0,modelEntityIds:Array.isArray(o)?o.map(e=>"string"==typeof e?.id?e.id:"unknown"):void 0}}catch{return}}(e,t,n.registrationToken);return s?.({instanceId:n.id,statusCode:o.status,assignedModelEntityIds:i.entities.map(e=>e.id),instanceModelEntityIds:r?.modelEntityIds,instanceModelCatalogSource:r?.source,instanceModelCatalogLoadedAt:r?.loadedAt},"node instance model catalog live sync deferred"),!1}(e,l,o,a,i):(i?.({instanceId:n,targetWeb:o.target.web,statusCode:u.status},"node instance model environment live sync deferred"),!1)}async function Tb(e,t,n,i,s,o,r="request",a){const c=e.requireInstance(i);if(c.imageProvisioning&&"ready"!==c.imageProvisioning.phase&&"docker"===e.requireRuntime(c.runtimeId).type)return s.diagnostic({instanceId:i,action:"start",reason:r,runtimeId:c.runtimeId,imageId:c.imageSelection?.imageId,imagePhase:c.imageProvisioning.phase},"node instance start queued until image provisioning completes"),e.controlledInstances.put(Ia.parse({...c,status:"starting",updatedAt:de()}));if("local-folder"!==c.source.type&&Jl(c)&&"docker"===e.requireRuntime(c.runtimeId).type)return s.diagnostic({instanceId:i,action:"start",reason:r,runtimeId:c.runtimeId,gitPhase:c.workspace.gitProvisioning?.phase},"node instance start queued until git workspace provisioning completes"),e.controlledInstances.put(Ia.parse({...c,status:"starting",updatedAt:de()}));s.diagnostic({instanceId:i,action:"start",reason:r,runtimeId:c.runtimeId,imageId:c.imageSelection?.imageId},"node instance start requested");const d=e.applyInstanceLifecycle(i,{type:"start-requested"}),l=t.forRuntime(e.requireRuntime(d.runtimeId)),u=await l.start({...e.context(d),signal:a}),p=Ia.parse({...d,...u,target:{...d.target,...u.target},workspace:u.workspace?{...d.workspace,error:void 0,...u.workspace}:d.workspace,runtime:u.runtime?{...d.runtime,...u.runtime}:d.runtime,updatedAt:de()}),m=u.target?.web?await yb(n,p,o):"unknown";if("docker"===e.requireRuntime(d.runtimeId).type&&"reachable"===m){const t=await(l.resolveNodeAgentUrl?.(e.context(p)))||e.containerUrl;_b(n,p,t,o).then(e=>{s.diagnostic({instanceId:i,action:"node-agent-connection.sync",reason:r,syncStatus:e,nodeAgentUrl:t},"node instance connection endpoint synchronized")}).catch(e=>{s.warn({instanceId:i,action:"node-agent-connection.sync",reason:r,error:e instanceof Error?e.message:String(e)},"node instance connection endpoint sync deferred")})}const h=e.applyInstanceLifecycle(i,{type:"runtime-lifecycle-completed",baseline:d,observation:{...u,target:u.target?{...u.target,status:m}:void 0,workspace:u.workspace?{error:void 0,...u.workspace}:void 0,targetStatus:m,uiAccessStatus:m}});return s.diagnostic({instanceId:i,action:"start",reason:r,status:h.status,connectionStatus:h.connectionStatus,targetStatus:h.targetStatus,targetWeb:h.target.web,containerName:h.runtime.containerName},"node instance start completed"),h}async function wb(e={}){const i=e.token||process.env.TASK_HANDOFF_NODE_AGENT_TOKEN,d=Number(e.port||process.env.TASK_HANDOFF_NODE_AGENT_PORT||"8091"),l=`http://127.0.0.1:${d}`,u=e.containerUrl||process.env.TASK_HANDOFF_NODE_AGENT_CONTAINER_URL,p=zl(e.dataDir),g=await async function(e){return Jh(e)}(p);try{const I=Wm(g),_=e.remoteSecret||process.env.TASK_HANDOFF_NODE_AGENT_REMOTE_SECRET,E=e.remoteKeyId||process.env.TASK_HANDOFF_NODE_AGENT_REMOTE_KEY_ID,A=new WA(p,I.access),T=A.resolveNodeId(e.nodeId||process.env.TASK_HANDOFF_NODE_ID),w=e.connectionMode||("local-ipc"===process.env.TASK_HANDOFF_NODE_AGENT_CONNECTION_MODE?"local-ipc":"local-loopback"),b=e.ipcPath||process.env.TASK_HANDOFF_NODE_AGENT_IPC_PATH||Dl(p.dataDir),N="local-ipc"===w?`ipc://${encodeURIComponent(b)}`:l,S=e.platform||process.platform,v=e.arch||process.arch,O=new Vg(p,T,l,u,d,S,I);O.node.connectionMode=w,O.node.controlEndpoint=N,O.node.endpoint=N,O.init();const R=new bE(p,T,I);await R.init();const x=new YE(I),C=new kE(I);await C.init();const k=e.dockerCommandRunner||qa,L=new Ya(k,e.dockerTerminalCommandRunner),P=function(e,i=rc()){const s=t.readdirSync(i,{withFileTypes:!0}),o=new Map(s.flatMap(e=>{if(!e.isFile())return[];const s=n.join(i,e.name);return[[e.name,{source:s,mode:511&t.statSync(s).mode}]]})),r=[...oc].filter(e=>!o.has(e));if(r.length)throw new Error(`Node agent bootstrap assets are incomplete: missing ${r.sort().join(", ")} in ${i}.`);t.mkdirSync(e,{recursive:!0,mode:493}),t.chmodSync(e,493);for(const[i,s]of o){const o=n.join(e,i);m.sync(o,t.readFileSync(s.source),{mode:s.mode}),t.chmodSync(o,s.mode)}for(const i of t.readdirSync(e,{withFileTypes:!0}))o.has(i.name)||t.rmSync(n.join(e,i.name),{recursive:!0,force:!0});return n.resolve(e)}(p.dockerBootstrapDir),M=new Rc(k,{publishHost:"127.0.0.1",imageService:L,terminalCommandRunner:e.dockerTerminalCommandRunner,launcherAssetsDir:P,nodeAgentContainerIpcPath:e.containerIpcPath});let j;const U=new ET([{type:"docker",adapter:new _T(M,k,S,v)},{type:"local",adapter:new YT(e.dockerCommandRunner||qa,p,()=>O.localNodeAgentUrl,KT(),e.localControlledInstanceLockPath||process.env.TASK_HANDOFF_LOCAL_CONTROLLED_INSTANCE_LOCK_PATH,e=>j.handleUnexpectedLocalExit(e.instanceId,new Error(`Local controlled instance exited unexpectedly (pid=${e.pid??"unknown"}, code=${e.code??"none"}, signal=${e.signal??"none"}).`)),(e,t)=>pe.log.error({error:e,instanceId:t.instanceId,pid:t.pid},"local controlled instance exit recovery failed"))}]),$=O.nodeRuntimes.get("runtime_wsl_host")?new sw({platform:S}):void 0,H=new Ww(p.wslDistroIndexPath),q=$?new Yw({executor:$,nodeId:T,distroRoot:p.wslDistrosDir,baseTemplateCacheDir:p.wslBaseTemplateCacheDir,index:H,baseTemplateSourceDirs:Bw(),expectedArch:v,logger:(e,t)=>pe.log.info(t,e)}):void 0;$&&q&&U.register("wsl",new bw($,{platform:S,hostArch:v,provisioner:q,listenerPort:d,bootstrapDir:P,fallbackNodeAgentUrl:O.containerUrl,logger:(e,t)=>pe.log.info(t,e)}));const B=async e=>PA(e,await U.forRuntime(O.requireRuntime(e.runtimeId)).resolveInstanceWeb(O.context(e))),V=e.updateCommandRunner||e.dockerCommandRunner||qa,G=e.fetchImpl||fetch,K=new oA(O,R,G,B,(e,t)=>pe.log.warn(e,t)),W=new rA(O,G,B,(e,t)=>pe.log.warn(e,t)),Y=new JE(O,G,B,(e,t)=>pe.log.warn(e,t)),X=new Map,J=new Map,Q=e=>{if("endpoint-unreachable"!==e.targetStatus||"online"!==e.connectionStatus||"online"!==e.agentStatus||!e.target.web||J.has(e.id))return;const t=e.processIncarnationId,n=(async()=>{if("reachable"!==await yb(G,e,B))return;const n=O.requireInstance(e.id);n.processIncarnationId===t&&"online"===n.connectionStatus&&"online"===n.agentStatus&&(O.controlledInstances.put(Ia.parse({...n,target:{...n.target,status:"reachable"},targetStatus:"reachable",uiAccessStatus:"reachable",updatedAt:de()})),Ee.syncNow())})().catch(t=>{pe.log.debug({instanceId:e.id,error:t},"node instance endpoint reconciliation probe failed")}).finally(()=>{J.delete(e.id)});J.set(e.id,n)},Z=async e=>{const t=O.requireInstance(e);if("reachable"!==t.targetStatus||!t.registrationToken)return!1;const n=`${t.processIncarnationId||"unknown"}:${t.config.aiSessionHistoryLimit}:${t.config.aiSessionAttachmentRetentionDays}:${t.config.aiSessionMaxFileAttachmentBytes}`;if(X.get(e)===n)return!0;let i;try{i=await Ib(G,`${await B(t)}/api/internal/ai-session-persistence-settings`,{method:"PUT",headers:{"content-type":"application/json",authorization:`Bearer ${t.registrationToken}`},body:JSON.stringify({historyLimit:t.config.aiSessionHistoryLimit,attachmentRetentionDays:t.config.aiSessionAttachmentRetentionDays,maxFileAttachmentBytes:t.config.aiSessionMaxFileAttachmentBytes})},cb)}catch(t){return Ve.warn({instanceId:e,error:t instanceof Error?t.message:String(t)},"node instance AI session persistence settings live sync deferred"),!1}return i.ok?(X.set(e,n),!0):(Ve.warn({instanceId:e,statusCode:i.status},"node instance AI session persistence settings live sync deferred"),!1)},ee=async e=>{const t=O.requireInstance(e);if(O.instancePrivateConfigs.materialize(t.id,t.registrationToken,O.resolvedAssignedModelEnvironment(e),O.modelRegistry.privateCatalog(e),t.config.codexSettings),!t.config.codexSettings)return!0;if("reachable"!==t.targetStatus||!t.registrationToken)return!1;try{const n=await Ib(G,`${await B(t)}/api/internal/codex-settings`,{method:"PUT",headers:{"content-type":"application/json",authorization:`Bearer ${t.registrationToken}`},body:JSON.stringify(t.config.codexSettings||{})},cb);return!!n.ok||(Ve.warn({instanceId:e,statusCode:n.status},"node instance Codex settings live sync deferred"),!1)}catch(t){return Ve.warn({instanceId:e,error:t instanceof Error?t.message:String(t)},"node instance Codex settings live sync deferred"),!1}},te=function(e,t){const n=new Map,i=e=>e.aiSessions?.sessions?.length??0,s=e=>e.aiSessions?.runningCount??0;return{arm(e){n.set(e.id,e.processIncarnationId||"")},async converge(o,r){const a=n.get(o.id);if(void 0!==a)if((o.processIncarnationId||"")!==a){if("heartbeat"===r){if(i(o)>0||s(o)>0)return n.delete(o.id),void t({instanceId:o.id,reason:"sessions-bound",boundSessionCount:i(o),runningSessionCount:s(o)},"node instance model environment convergence abandoned");try{await e(o.id)&&n.delete(o.id)}catch(e){t({instanceId:o.id,error:e instanceof Error?e.message:String(e)},"node instance model environment convergence deferred")}}}else n.delete(o.id)}}}(e=>Ab(G,O,e,Ve.warn,B),(e,t)=>Ve.warn(e,t)),ne=new Bl({cacheDir:n.join(p.dataDir,"runtime-artifacts"),fetchImpl:G}),ie=e.resolveRuntimeArtifactRelease||((e,t,n)=>Vl(e,t,n,G)),se=async(t,n,i)=>{const s=await n.artifactTarget(i);if(e.resolveRuntimeArtifact)return e.resolveRuntimeArtifact(t,s.platform,s.arch);const o=await ie(t,s.platform,s.arch);if(o.identity.launcherAbi>s.launcherAbi)throw Object.assign(new Error(`Runtime requires launcher ABI ${o.identity.launcherAbi}, but ${s.platform}-${s.arch} provides ABI ${s.launcherAbi}.`),{code:"INSTANCE_BASE_RUNTIME_INCOMPATIBLE",retryable:!1});return ne.resolve(o.identity,o.source)},oe=e=>U.forRuntime(O.requireRuntime(e.runtimeId)),re=async e=>{const t=oe(e),n=await(t.resolveNodeAgentUrl?.(O.context(e)));return n||("docker"===O.requireRuntime(e.runtimeId).type?O.containerUrl:O.localNodeAgentUrl)},ae=e=>{const t=oe(e);return IT(t)?t:void 0},ce=e=>{const t=ae(e);if(t)return t;throw Object.assign(new Error(`Runtime for instance ${e.id} does not use managed artifacts.`),{code:"INSTANCE_RUNTIME_ARTIFACT_UNMANAGED",retryable:!1})},le=e=>Boolean(ae(e)),ue=(e,t)=>{const n=O.context(e);return se(t,ce(e),n)},pe=r({logger:e.logger??!0});I.agents.definitions.setDiagnostic((e,t)=>pe.log.warn(t,e)),I.agents.storyEntries.setDiagnostic((e,t)=>pe.log.warn(t,e)),I.agents.orchestrations.setDiagnostic((e,t)=>pe.log.warn(t,e));const me=new kl(p,{logger:(e,t)=>pe.log.warn(t,e)}),he=()=>O.listInstances().map(e=>e.id),ge=()=>{try{me.run(he())}catch(e){pe.log.warn({error:e},"node-agent persistence maintenance failed")}},fe=()=>{try{me.capNodeAgentLogs(),me.capActiveInstanceLogs(he())}catch(e){pe.log.warn({error:e},"node-agent open log maintenance failed")}};ge();const ye=setInterval(()=>{ge()},216e5);ye.unref();const Ie=setInterval(()=>{fe()},6e4);Ie.unref();const _e={requests:0,active:0,completed:0,aborted:0,limitRejected:0,responseBytes:0,totalDurationMs:0,maxResponseBytes:zA()};pe.decorate("nodeAgentState",O),pe.decorate("nodeAgentIdentityService",A),pe.decorate("nodeAgentResolveInstanceNodeAgentUrl",re),await pe.register(a,{options:D});const Ee=new sl(O,i,{logger:pe.log,safetyIntervalMs:Number(process.env.TASK_HANDOFF_EVENT_CONNECTION_SAFETY_INTERVAL_MS)||void 0}),Ae=new Gl(O.controlledInstances,Tg,{isInstalled:async(e,t)=>{const n=await ue(e,t);return await ce(e).inspectRuntime(O.context(e),n.identity)},isRuntimeRunning:async e=>{const t=oe(e);if(!t.runtimeState)return!0;const n=await t.runtimeState(O.context(e));return"stopped"!==n&&"absent"!==n},onDrainSkipped:e=>pe.log.warn({instanceId:e.id},"runtime is not running; skipping app session drain before runtime convergence"),beginDrain:async e=>{try{const t=await async function(e,t,n=async e=>PA(e)){const i=await n(t);if(t.registrationToken&&(await Ib(e,`${i}/api/internal/node-agent/drain`,{method:"POST",headers:{authorization:`Bearer ${t.registrationToken}`}},1e4)).ok)return{requested:t.apps.runningCount,failures:[]};const s=await Ib(e,`${i}/api/apps/sessions`,{method:"GET",headers:{"cache-control":"no-cache"}},5e3);if(!s.ok)throw new Error(`Could not list app sessions for runtime drain (HTTP ${s.status}).`);const o=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return[];const t=e.data;if(Array.isArray(t))return t;if(!t||"object"!=typeof t||Array.isArray(t))return[];const n=t.snapshot,i=(n&&"object"==typeof n&&!Array.isArray(n)?n:t).sessions;return Array.isArray(i)?i:[]}(await s.json()).flatMap(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return[];const t=e;return"running"===t.status&&"string"==typeof t.id&&t.id?[t.id]:[]}),r=await Promise.all(o.map(async t=>{try{const n=await Ib(e,`${i}/api/apps/sessions/${encodeURIComponent(t)}/stop`,{method:"POST"},5e3);return n.ok?void 0:{sessionId:t,error:`HTTP ${n.status}`}}catch(e){return{sessionId:t,error:e instanceof Error?e.message:String(e)}}}));return{requested:o.length,failures:r.filter(e=>Boolean(e))}}(G,e,B);return t.failures.length?pe.log.warn({instanceId:e.id,requested:t.requested,failures:t.failures},"runtime convergence could not stop every app session"):pe.log.info({instanceId:e.id,requested:t.requested},"runtime convergence requested app session drain"),!0}catch(t){return pe.log.warn({instanceId:e.id,error:t instanceof Error?t.message:String(t)},"runtime convergence could not request app session drain"),!1}},endDrain:async e=>{try{await async function(e,t,n=async e=>PA(e)){return!!t.registrationToken&&(await Ib(e,`${await n(t)}/api/internal/node-agent/resume`,{method:"POST",headers:{authorization:`Bearer ${t.registrationToken}`}},5e3)).ok}(G,e,B)&&pe.log.info({instanceId:e.id},"runtime convergence released app session drain")}catch(t){pe.log.warn({instanceId:e.id,error:t instanceof Error?t.message:String(t)},"runtime convergence could not release app session drain")}},install:async(e,t)=>{const n=ce(e);await n.installRuntime(O.context(e),await ue(e,t))},restart:async e=>{const t=oe(e),n=O.applyInstanceLifecycle(e.id,{type:"convergence-restart-requested"}),i=await t.restart(O.context(n)),s=Ia.parse({...n,...i,target:i.target?{...n.target,...i.target}:n.target,runtime:i.runtime?{...n.runtime,...i.runtime}:n.runtime,updatedAt:de()}),o=await yb(G,s,B);O.applyInstanceLifecycle(e.id,{type:"runtime-lifecycle-completed",baseline:n,observation:{...i,target:i.target?{...i.target,status:o}:void 0,targetStatus:o,uiAccessStatus:o}})},onForcedDrain:e=>pe.log.warn({instanceId:e.id},"runtime convergence drain deadline reached; restarting instance")},{drainTimeoutMs:Number(process.env.TASK_HANDOFF_RUNTIME_DRAIN_TIMEOUT_MS)||void 0,verificationTimeoutMs:Number(process.env.TASK_HANDOFF_RUNTIME_VERIFY_TIMEOUT_MS)||void 0,maxAttempts:Number(process.env.TASK_HANDOFF_RUNTIME_MAX_ATTEMPTS)||void 0});O.controlledInstances.setOnStored(e=>{Ee.publishInstanceLifecycle(e)}),Ee.start(),pe.decorate("nodeAgentEventForwarder",Ee);const Te=new H_(I.agents.orchestrations,I.agents.definitions,(e,t,n)=>Ee.publish(e,t,n)),we=new F_(O,I.agents.definitions,Te,(e,t,n)=>Ee.publish(e,t,n)),be={runtime:"docker",workspaceMaterializer:"overlay-copy-on-write",processSandbox:"instance",providerId:"codex"},Se=new B_(O,we,Te,I.agents.runs,e=>e.runtimeType===be.runtime&&e.providerId===be.providerId&&e.executionPolicy.workspaceMaterializer===be.workspaceMaterializer&&e.executionPolicy.processSandbox===be.processSandbox&&"full-access"!==e.permissionMode,(e,t,n)=>Ee.publish(e,t,n),I.agents.resources),ve=new mE(G,B),Oe=new _E(k,I.agents.resources,e=>{const t=O.requireInstance(e);return{nodeId:O.node.id,runtimeId:t.runtimeId,instanceId:e,containerName:t.runtime.containerName||Bc(e),expectedContainerId:t.runtime.containerId,providerReady:t.ready&&"running"===t.status&&"online"===t.connectionStatus&&"online"===t.agentStatus&&"reachable"===t.targetStatus}},async(e,t)=>{const n=Se.getMember(e,t);await ve.close(O.requireInstance(n.instanceId),e,t)}),Re=new Q_;Re.register({runtimeType:"docker",workspaceMaterializer:"overlay-copy-on-write",processSandbox:"instance"},Oe);const xe=new fE(I.agents.resources,Oe,Ac),Ce=new sE({state:O,runs:Se,materializers:Re,sharedSpaces:xe,resources:I.agents.resources,sessions:ve,reconcileInstanceResources:e=>Oe.reconcileInstance(e)});Se.setCoordinator(Ce),Ce.reconcile().catch(e=>pe.log.warn({error:e},"Agent Run startup reconciliation failed")),xe.reconcileExpired().catch(e=>pe.log.warn({error:e},"Agent Run startup shared-space expiry reconciliation failed"));const ke=setInterval(()=>{Ce.reconcile().catch(e=>pe.log.warn({error:e},"Agent Run reconciliation retry failed")),xe.reconcileExpired().catch(e=>pe.log.warn({error:e},"Agent Run shared-space expiry reconciliation failed"))},5e3);ke.unref();const De=new EE(R,we,Te,I.agents.storyEntries,async({storyId:e})=>{const t=await x.resolve(e);await Y.notify({storyId:e,revision:t.revision})}),Le=new qE(O,R,G,B),Pe=new QE(O,G,B),Me=new eA(G,B),je=new nA(O,I,G,B,e=>Ee.publish("story.decision.changed",e,{nodeId:O.node.id}));K.setSessionClosedHandler(async e=>{await je.expireForSession(e,{code:"AI_SESSION_CLOSED",message:"The AI Session that raised the decision was closed."})});const Ue=new VE(O,R,C,G,B,(e,t,n)=>Ee.publish(e,t,n),void 0,Le),Fe=new UE(O,R,C,Ue,I,Me,je);await Fe.init(),await Ue.start(),R.setOnChange((e,t)=>{Ee.publish("story.changed",{storyId:t.id,nodeId:t.ownerNodeId,change:e},{nodeId:t.ownerNodeId}),K.reconcile()});const $e=new ml(k,()=>O.listInstances().filter(e=>"docker"===O.requireRuntime(e.runtimeId).type),e=>Ee.publish("instance.metrics.snapshot",e,{instanceId:e.instanceId}));$e.start(),pe.decorate("nodeAgentRuntimeMetrics",$e);const He=(y=process.env.TASK_HANDOFF_DIAGNOSTIC_LOGS,["1","true","yes","on"].includes(String(y||"").trim().toLowerCase())),qe=new BA(A,T,_,E),Be=(e,t)=>{He&&pe.log.info(e,t)},Ve={diagnostic:Be,warn:(e,t)=>pe.log.warn(e,t)},Ge=new IA,Ke=new NA(O.environmentTemplates,M,e=>O.requireInstance(e),e=>O.requireRuntime(e),(e,t)=>Ge.run(e,t),e=>[e.registrationToken,...O.modelRegistry.privateSecretValues(e.id)].filter(e=>Boolean(e)),e=>O.listInstances().some(t=>t.environmentTemplateOrigin?.imageId===e)),We=(e,t,n)=>{const i=n&&"object"==typeof n&&!Array.isArray(n)?n.protocolVersion:void 0;if("string"!=typeof i||i===Qi)return n;const s=({field:n,action:s})=>pe.log.warn({instanceId:e,report:t,protocolVersion:i,expectedProtocolVersion:Qi,field:n,action:s},"cross-version controlled instance report sanitized");return"register"===t?function(e,t){if(!e||"object"!=typeof e||Array.isArray(e))return e;const n=e,i=["instanceId","projectId","source","nodeId","runtimeId","imageSelection","instanceVersion","protocolVersion","build","controlMode","capabilities","appInventory","target","workspace","registrationToken","processIncarnationId"],s=new Set([...i,"imageId"]);for(const e of Object.keys(n))s.has(e)||t?.({field:e,action:"ignored"});return Object.prototype.hasOwnProperty.call(n,"imageId")&&t?.({field:"imageId",action:"migrated"}),{...Oa(n,i),imageSelection:Gs(n.imageSelection,n.imageId)}}(n,s):function(e,t){if(!e||"object"!=typeof e||Array.isArray(e))return e;const n=["status","health","protocolVersion","build","capabilities","appInventory","apps","aiSessions","triggers","workspace","target","processIncarnationId"],i=new Set(n);for(const n of Object.keys(e))i.has(n)||t?.({field:n,action:"ignored"});return Oa(e,n)}(n,s)},Ye=e=>"local-folder"!==e.source.type&&Jl(e),Xe=async(e,t,n=()=>!0,i)=>{try{if(!n())return O.requireInstance(e);let s=O.requireInstance(e);te.arm(s),"failed"===s.runtimeVersion?.phase&&le(s)&&(s=O.controlledInstances.put(Ia.parse({...s,ready:!1,runtimeVersion:bg(Kl(s)),updatedAt:de()})));const o=O.requireRuntime(s.runtimeId);Ye(s)&&"docker"===o.type&&!Xl(s)&&tt(s),await Tb(O,U,G,e,Ve,B,t,i);const r=O.requireInstance(e);if("docker"===o.type&&r.imageProvisioning&&"ready"!==r.imageProvisioning.phase)return Ee.syncNow(),r;if("docker"===o.type&&Ye(r))return Ee.syncNow(),r;if(!n())return O.requireInstance(e);j.markRestored(e);let a=O.requireInstance(e);if(le(a)){try{a=await Ae.schedule(e,{startRequested:!0})}catch(n){a=O.requireInstance(e),Ve.warn({instanceId:e,action:"runtime.converge",reason:t,error:n instanceof Error?n.message:String(n)},"node instance runtime convergence failed after start")}"matched"!==a.runtimeVersion?.phase&&a.runtimeVersion?.error&&Ve.warn({instanceId:e,action:"runtime.converge",reason:t,error:a.runtimeVersion.error},"node instance started with pending runtime convergence")}if("docker"===o.type&&"reachable"===a.targetStatus){const n=await(U.forRuntime(o).resolveNodeAgentUrl?.(O.context(a)))||O.containerUrl;_b(G,a,n,B).then(i=>{Ve.diagnostic({instanceId:e,action:"node-agent-connection.sync",reason:t,syncStatus:i,nodeAgentUrl:n},"node instance connection endpoint synchronized after runtime convergence")}).catch(n=>{Ve.warn({instanceId:e,action:"node-agent-connection.sync",reason:t,error:n instanceof Error?n.message:String(n)},"node instance connection endpoint sync after runtime convergence deferred")})}return n()?(await Eb(G,a,"start",Ve,B),Ee.syncNow(),a):O.requireInstance(e)}catch(n){throw O.applyInstanceLifecycle(e,{type:"start-failed",error:n}),Ee.syncNow(),Ve.warn({instanceId:e,action:"start",reason:t,error:n instanceof Error?n.message:String(n)},"node instance start failed"),n}},Je=new EA(O,L,{sync:()=>Ee.syncNow(),diagnostic:Ve.diagnostic,warn:Ve.warn,publish:(e,t,n)=>Ee.publish(e,t,{instanceId:n}),runInstanceOperation:(e,t)=>Ge.run(e,t)}),Qe=e=>{const t=Ge.intent(e.id);Je.provision(e,async()=>{await Xe(e.id,"image-ready",()=>Ge.isIntentCurrent(e.id,t),Ge.signal(e.id,t)).catch(()=>{})})},Ze=$?new rb({executor:$,logger:(e,t)=>pe.log.debug(t,e)}):void 0,et=new TA(O.controlledInstances,{context:e=>O.context(e),run:(e,t)=>{if("wsl"===O.requireRuntime(e.instance.runtimeId).type){if(!Ze||!q)throw Object.assign(new Error(`The WSL runtime is not configured on this node; cannot provision the Git workspace for ${e.instance.id}.`),{statusCode:503,code:"GIT_WORKSPACE_PROVISIONING_UNSUPPORTED"});const n=q.distroNameForInstance({id:e.instance.id,containerName:e.instance.runtime.containerName});return Ze.provision(e,n,{onOutput:t.onOutput,signal:t.signal})}return M.provisionGitWorkspaceStreaming(e,{onOutput:t.onOutput,signal:t.signal})},sync:()=>Ee.syncNow(),diagnostic:Ve.diagnostic,warn:Ve.warn,publish:(e,t,n)=>Ee.publish(e,t,{instanceId:n}),runInstanceOperation:(e,t)=>Ge.run(e,t)}),tt=e=>{const t=Ge.intent(e.id);et.provision(e,async()=>{await Xe(e.id,"git-ready",()=>Ge.isIntentCurrent(e.id,t),Ge.signal(e.id,t)).catch(()=>{})})},nt=function(e,i){const s=i??id();try{const i=function(e=id()){if(!t.existsSync(e))return[];const i=[];for(const s of t.readdirSync(e,{withFileTypes:!0}).sort((e,t)=>e.name.localeCompare(t.name))){if(!s.isDirectory())continue;const o=n.join(e,s.name);if(!t.existsSync(n.join(o,Wc)))continue;const r=ad(o),a=n.join(o,"content");if(!t.existsSync(a))throw nd("BUILTIN_PROJECT_CONTENT_INVALID",`Built-in project ${r.id} has no content directory.`,{root:o});const c=od(a),d=rd(c);if(d!==r.contentDigest)throw nd("BUILTIN_PROJECT_CONTENT_INVALID",`Built-in project ${r.id} content does not match its manifest digest.`,{root:o,expected:r.contentDigest,actual:d});i.push({id:r.id,name:r.name,...r.localizedNames?{localizedNames:r.localizedNames}:{},runtimes:r.runtimes,contentDigest:r.contentDigest,root:o,contentDir:a,files:c})}return i}(s);if(i.length)return i;e.diagnostic({sourceDir:s},"node agent built-in project catalog is empty")}catch(t){e.diagnostic({sourceDir:s,error:t instanceof Error?t.message:String(t)},"node agent built-in project catalog unavailable")}}(Ve,e.builtinProjectsDir);if(nt){const e=gd({definitions:nt,targetsDir:p.builtinProjectTargetsDir,nodeId:T});if(O.attachBuiltinProjectFolders(e),O.nodeRuntimes.list().some(e=>"local"===e.type))for(const t of e.prepare())"failed"!==t.status?pe.log.info({projectId:t.projectId,status:t.status},"builtin project ready"):Ve.diagnostic({projectId:t.projectId,targetDir:t.targetDir,errorCode:t.code,error:t.message},"builtin project initialization failed")}j=new iT({state:O,runtimeAdapters:U,convergence:Ae,restoreInstance:e=>Tb(O,U,G,e,Ve,B,"restore"),autoImport:e=>Eb(G,e,"start",Ve,B),provisionImage:Qe,provisionGit:tt,stopImageProvisioning:()=>Je.stop(),stopGitProvisioning:()=>et.stop(),usesManagedArtifact:le,warn:Ve.warn,error:(e,t)=>pe.log.error(e,t),runInstanceOperation:(e,t)=>Ge.run(e,t)});const it=$&&q&&U.has("wsl")?new Jw({listRunningInstances:()=>O.listInstances().filter(e=>"wsl"===O.requireRuntime(e.runtimeId).type).filter(e=>["registering","registered","running","unhealthy"].includes(e.status)).map(e=>({id:e.id,distroName:q.distroNameForInstance({id:e.id,containerName:e.runtime.containerName})})),holdSession:e=>$.holdSession(e),sessionAlive:e=>$.sessionAlive(e),releaseSession:e=>$.releaseSession(e),distroState:e=>$.distroState(e),ensureDistroRunning:async e=>{await $.ensureDistroRunning(e)},unitActive:e=>$.unitActive(e,mw),waitForEndpointHealthy:async e=>"reachable"===await yb(G,O.requireInstance(e),B),onDiagnostic:e=>{"WSL_SESSION_RECOVERED"===e.code?pe.log.info(e,e.message):pe.log.warn(e,e.message),Ee.syncNow()},onSessionLost:(e,t)=>{j.allowRecovery(e),Ve.warn({instanceId:e,distroName:t},"wsl keep-alive session lost; the supervisor will rebuild it"),Ee.syncNow()}}):void 0,st=new rT({listTargets:()=>O.nodeRuntimes.list().flatMap(e=>{let t;try{const n=U.forRuntime(e);t=n.check?.bind(n)}catch{return[]}return t?[{runtime:e,probe:()=>t(O.requireRuntime(e.id))}]:[]}),apply:(e,t)=>{O.recordRuntimeProbe(e.id,t)},onAvailable:(e,t)=>{pe.log.info({runtimeId:e.id,runtimeType:e.type,previousStatus:t.status},"node runtime became available; resuming instance recovery"),j.notifyRuntimeAvailable()},onUnavailable:(e,t)=>{pe.log.warn({runtimeId:e.id,runtimeType:e.type,previousStatus:t.status,error:fb(e)},"node runtime is unavailable; instance recovery is paused until it returns")},onProbeError:(e,t)=>{pe.log.warn({runtimeId:e.id,runtimeType:e.type,error:t},"node runtime availability probe failed")},onCycleError:e=>{pe.log.warn({error:e},"node runtime availability cycle failed")}},{intervalMs:sT(process.env.TASK_HANDOFF_RUNTIME_AVAILABILITY_INTERVAL_MS)}),ot=new QA({nodeId:T,jobs:O.updateJobs,runCommand:V,currentRuntimeVersion:Tg,listInstances:()=>O.listInstances(),moduleDir:("undefined"==typeof document?require("url").pathToFileURL(__filename).href:z&&"SCRIPT"===z.tagName.toUpperCase()&&z.src||new URL("cli.js",document.baseURI).href)?n.dirname(o.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(__filename).href:z&&"SCRIPT"===z.tagName.toUpperCase()&&z.src||new URL("cli.js",document.baseURI).href)):__dirname,managedUpdateSupport:e.managedUpdateSupport||(n=>"linux"!==(e.platform||process.platform)?{supported:!1,reason:"Managed server updates require Linux and systemd."}:"function"==typeof process.getuid&&0!==process.getuid()?{supported:!1,reason:"Managed server updates require the node agent to run as root."}:t.existsSync("/run/systemd/system")?"@task-handoff/server"!==n.packageName||process.env.TASK_HANDOFF_CONTROL_PLANE_HEALTH_URL?.trim()?process.env.TASK_HANDOFF_NODE_AGENT_IPC_PATH?.trim()?{supported:!0}:{supported:!1,reason:"Managed server updates require the node-agent IPC readiness endpoint."}:{supported:!1,reason:"Managed server updates require a local control-plane health URL."}:{supported:!1,reason:"Managed server updates require an active systemd host."})});pe.setErrorHandler((e,t,n)=>{const i=function(e){if(e instanceof c.z.ZodError)return{statusCode:400,code:"VALIDATION_ERROR",message:e.issues.map(e=>`${e.path.join(".")||"body"}: ${e.message}`).join("; "),details:{issues:e.issues.map(e=>({path:e.path.map(String),code:e.code,message:e.message}))}};const t=e&&"object"==typeof e?e:{};return{statusCode:"number"==typeof t.statusCode?t.statusCode:500,code:"string"==typeof t.code?t.code:"NODE_AGENT_ERROR",message:e instanceof Error?e.message:String(e),...t.details&&"object"==typeof t.details&&!Array.isArray(t.details)?{details:t.details}:{},..."boolean"==typeof t.retryable?{retryable:t.retryable}:{}}}(e);(He||i.statusCode>=500)&&(i.statusCode>=500?pe.log.error.bind(pe.log):pe.log.warn.bind(pe.log))({method:t.method,url:t.url,statusCode:i.statusCode,errorCode:i.code,error:i.message},"node agent request failed"),n.code(i.statusCode).send({error:{code:i.code,message:i.message,...i.details?{details:i.details}:{},...e&&"object"==typeof e&&"string"==typeof e.expectedVersion?{expectedVersion:e.expectedVersion}:{},...e&&"object"==typeof e&&"string"==typeof e.actualVersion?{actualVersion:e.actualVersion}:{},...e&&"object"==typeof e&&"string"==typeof e.phase?{phase:e.phase}:{},...e&&"object"==typeof e&&"boolean"==typeof e.retryable?{retryable:e.retryable}:{},...e&&"object"==typeof e&&"number"==typeof e.blockingInstanceCount?{blockingInstanceCount:e.blockingInstanceCount}:{}}})}),pe.addHook("preHandler",async e=>{if(lb.has(e.raw)){if(gb(e.url))return;const t=new Error("Container IPC only accepts instance-scoped node agent requests.");throw Object.assign(t,{statusCode:401,code:"NODE_AGENT_CONTAINER_IPC_ROUTE_FORBIDDEN"}),t}if(tg(e.url.split("?")[0]))return;const t=qe.verify(e);if(t){if(A.isRevokedPairing(t)&&"/api/node-agent/pairing/current"!==e.url.split("?")[0]){const e=new Error("The node agent pairing used for this request has been revoked.");throw Object.assign(e,{statusCode:401,code:"NODE_AGENT_HMAC_KEY_REVOKED"}),e}e.nodeAgentAuthKeyId=t}else if(hb(e)){if(i&&pb(e.headers)!==i){const e=new Error("Invalid node agent token.");throw Object.assign(e,{statusCode:401,code:"NODE_AGENT_UNAUTHORIZED"}),e}}else if("/api/node-agent/pairing/complete"!==e.url.split("?")[0]&&!gb(e.url)){if(qe.hasRemoteSecrets()){const e=new Error("Node agent HMAC signature is required.");throw Object.assign(e,{statusCode:401,code:"NODE_AGENT_HMAC_SIGNATURE_REQUIRED"}),e}if(!function(e){return mb(e.ip)||mb(e.socket.remoteAddress)||!e.ip&&!e.socket.remoteAddress&&!e.socket.remoteFamily}(e)){const e=new Error("Local node agent access is only accepted from loopback or local IPC connections.");throw Object.assign(e,{statusCode:401,code:"NODE_AGENT_LOCAL_TOKEN_REQUIRES_LOOPBACK"}),e}if(i&&pb(e.headers)!==i){const e=new Error("Invalid node agent token.");throw Object.assign(e,{statusCode:401,code:"NODE_AGENT_UNAUTHORIZED"}),e}}}),pe.addHook("onClose",async()=>{R.stopAccepting(),I.stopAccepting();const e=Number(process.env.TASK_HANDOFF_STORY_DRAIN_DIAGNOSTIC_MS)||3e4,t=setTimeout(()=>{pe.log.warn({pendingStoryIds:R.coordinator.pendingStoryIds()},"Story storage drain deadline reached; waiting for accepted operations and preserving recovery intents")},e);t.unref();try{clearInterval(ke),await Ce.stop(),await Ue.stop(),clearInterval(ye),clearInterval(Ie),$e.stop(),st.stop(),Ee.stop(),await(it?.stop()),await j.stop(),await R.drain(),await I.close()}finally{clearTimeout(t)}}),pe.decorate("nodeAgentRestoreManagedInstances",()=>j.restoreManagedInstances()),pe.decorate("nodeAgentRecoverManagedInstances",()=>j.recoverManagedInstances()),pe.decorate("nodeAgentStartRecoverySupervisor",()=>j.start()),pe.decorate("nodeAgentStartRuntimeAvailabilityMonitor",()=>st.start()),pe.decorate("nodeAgentStartWslSessionSupervisor",()=>it?.start()),pe.get("/api/node-agent/health",async()=>{const e=s.hostname().trim();return{data:{ok:!0,role:"node-agent",...e?{hostname:e}:{},process:{pid:process.pid,...db?{startIdentity:db}:{}},listener:{host:"127.0.0.1",port:O.currentListenerPort},nodeId:T,platform:yT(S),arch:process.arch,protocolVersion:Qi,capabilities:{modelEndpointProbe:!0,managedModels:{multiEntityAssignment:!0,privateModelCatalog:!0,stableModelIdentity:!0,requestMappings:!0,modelRelay:(()=>{const e=rt.protocolCapabilities();return{protocols:e,streaming:e.length>0,unknownModelPolicy:!0}})()},aiSessionHistoryLimit:!0,aiSessionAttachmentRetention:!0,aiSessionFileAttachmentLimit:!0,codexManagedSettings:!0,folderPlaces:!0,localFolderNameUpdate:!0,managedGitCredentials:{registry:!0,runtimeBroker:!0,workspaceProvisioning:{docker:!0,kubernetes:!1,local:!1,wsl:U.has("wsl")}},stories:{enabled:!0,agentTools:!0,agentToolCapabilities:{policy:!0,actions:!0,automations:!0,aiSessionRead:!0,decisions:!0},sessionRetention:!0,maxFileBytes:33554432,maxBatchPaths:20},agentExecution:{definitions:!0,runs:!0,orchestration:{storyEntryAuthorization:!0,orchestrations:!0,runMembers:!0,manualRuns:!0},sharedSpace:{enabled:!0,runtimes:["docker"]},combinations:[be]}},build:(t="node-agent",{component:t,packageName:"@task-handoff/node-agent",packageVersion:Tg(),protocolVersion:Qi,buildId:ub("TASK_HANDOFF_BUILD_ID"),builtAt:ub("TASK_HANDOFF_BUILT_AT"),gitCommit:ub("TASK_HANDOFF_GIT_COMMIT"),imageRef:ub("TASK_HANDOFF_IMAGE_REF"),imageDigest:ub("TASK_HANDOFF_IMAGE_DIGEST")}),instanceProxy:{..._e},eventTransport:Ee.eventTransportHealth(),serverTime:(new Date).toISOString()}};var t}),!function(e,t){e.get("/api/node-agent/settings/external-listener",async e=>({data:t(e).current()})),e.patch("/api/node-agent/settings/external-listener",async e=>({data:await t(e).update(e.body)}))}(pe,e=>{if(!hb(e)){const e=new Error("Node agent TCP listener settings are available only over local Unix IPC.");throw Object.assign(e,{statusCode:403,code:"NODE_AGENT_LISTENER_LOCAL_IPC_ONLY"}),e}if(!pe.nodeAgentListenerManager){const e=new Error("Node agent TCP listener manager is not initialized.");throw Object.assign(e,{statusCode:503,code:"NODE_AGENT_LISTENER_UNAVAILABLE"}),e}return pe.nodeAgentListenerManager}),function(e,t,n){e.get("/api/node-agent/updates/jobs",async()=>({data:n.list()})),e.post("/api/node-agent/updates/check",async e=>({data:await t.check(e.body)})),e.post("/api/node-agent/updates/apply",async(e,n)=>n.code(202).send({data:await t.apply(e.body)}))}(pe,ot,O.updateJobs),function(e,t){const{identity:n,nodeId:i,fetchImpl:s}=t;e.post("/api/node-agent/pairing/invites",async(e,t)=>{const s=n.createPairingInvite(ph.parse(e.body||{}));return t.code(201).send({data:{nodeId:i,joinToken:s.token,expiresAt:s.expiresAt}})}),e.post("/api/node-agent/pairing/complete",async(e,t)=>{const s=n.completePairingInvite(mh.parse(e.body));return t.code(201).send({data:{nodeId:i,keyId:s.keyId,secret:s.secret,pairedAt:s.pairedAt}})}),e.get("/api/node-agent/control-plane-pairings",async e=>({data:n.listControlPlanePairings(e.nodeAgentAuthKeyId)})),e.delete("/api/node-agent/control-plane-pairings/:keyId",async e=>{const t=YA.parse(e.params.keyId);return{data:{deleted:n.deleteControlPlanePairing(t,e.nodeAgentAuthKeyId)}}}),e.delete("/api/node-agent/pairing/current",async e=>({data:n.revokeCurrentControlPlanePairing(e.nodeAgentAuthKeyId||"")})),e.get("/api/node-agent/control-plane-connections",async()=>({data:n.listControlPlaneConnections().map(e=>({...e,...t.reverseTunnels()?.state(e.id)||{status:e.enabled?"connecting":"disabled"}}))})),e.delete("/api/node-agent/control-plane-connections/:connectionId",async e=>{const i=YA.parse(e.params.connectionId),s=n.deleteControlPlaneConnection(i);return s&&t.reverseTunnels()?.connectConfigured(),{data:{deleted:s}}}),e.post("/api/node-agent/control-plane-connections",async(e,o)=>{const r=hh.parse(e.body),a=function(e){const t=new URL(e);if("http:"!==t.protocol&&"https:"!==t.protocol){const e=new Error("Control-plane URL must use http or https.");throw Object.assign(e,{statusCode:400,code:"NODE_AGENT_REMOTE_CONTROL_PLANE_URL_INVALID"}),e}return t.toString().replace(/\/$/,"")}(r.controlPlaneUrl);return n.runControlPlaneConnectionOperation(a,async()=>{const e=n.stageControlPlaneConnection({url:a,...r.controlPlaneName?{name:r.controlPlaneName}:{},enabled:!1!==r.activate});let c;try{c=await async function(e,t,n){const i=await e(new URL("/api/node-join/complete",t).toString(),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n)}),s=await i.json().catch(()=>({}));if(!i.ok){const e=new Error(s.error?.message||`Control-plane node join failed with HTTP ${i.status}.`);throw Object.assign(e,{statusCode:i.status,code:s.error?.code||"NODE_AGENT_REMOTE_JOIN_FAILED"}),e}return s.data||{}}(s,a,{joinToken:r.joinToken,nodeId:i,nodeName:t.nodeName(),keyId:e.pairing.keyId,secret:e.pairing.secret,pairedAt:e.pairing.pairedAt})}catch(t){throw n.rollbackControlPlaneConnection(e),t}n.markControlPlaneConnectionRemoteAccepted(e);const d=n.commitControlPlaneConnection(e,{name:r.controlPlaneName||("string"==typeof c.name&&c.name?c.name:void 0)});let l,u=d.connection.enabled?"saved":"disabled";const p=t.reverseTunnels();if(p)try{p.connectConfigured(),d.connection.enabled&&(u="connecting")}catch(e){u="failed",l=e instanceof Error?e.message:String(e)}return o.code(201).send({data:{pairing:n.listControlPlanePairings().find(e=>e.keyId===d.pairing.keyId),connection:d.connection,tunnel:{status:u,...l?{error:l}:{}}}})})})}(pe,{identity:A,nodeId:T,nodeName:()=>O.node.name,fetchImpl:G,reverseTunnels:()=>pe.nodeAgentReverseTunnels}),function(e,t){e.get("/api/node-agent/runtimes",async()=>({data:t.listRuntimes()})),e.post("/api/node-agent/runtimes",async(e,n)=>n.code(201).send({data:t.createRuntime(gA.parse(e.body))})),e.patch("/api/node-agent/runtimes/:id",async e=>({data:t.updateRuntime(e.params.id,fA.parse(e.body))})),e.delete("/api/node-agent/runtimes/:id",async e=>({data:{deleted:t.deleteRuntime(e.params.id)}})),e.post("/api/node-agent/runtimes/:id/check",async e=>({data:await t.checkRuntime(e.params.id)})),e.get("/api/node-agent/local-folders",async()=>({data:t.listLocalFolders()})),e.get("/api/node-agent/folders/places",async()=>({data:t.listFolderPlaces()})),e.get("/api/node-agent/folders/tree",async e=>({data:t.listFolderTree(pA.parse(e.query))})),e.post("/api/node-agent/local-folders",async(e,n)=>n.code(201).send({data:t.createLocalFolder(lA.parse(e.body))})),e.patch("/api/node-agent/local-folders/:id",async e=>({data:t.updateLocalFolder(e.params.id,uA.parse(e.body))})),e.delete("/api/node-agent/local-folders/:id",async e=>({data:{deleted:t.deleteLocalFolder(e.params.id)}}))}(pe,{listRuntimes:()=>O.nodeRuntimes.list(),createRuntime:e=>O.createRuntime(e),updateRuntime:(e,t)=>O.updateRuntime(e,t),deleteRuntime:e=>O.deleteRuntime(e),checkRuntime:async e=>{if(await st.checkRuntime(e))return O.requireRuntime(e);const t=O.requireRuntime(e);return O.checkRuntime(e,U.forRuntime(t))},listLocalFolders:()=>O.listLocalFolders(),listFolderPlaces:Sl,listFolderTree:Ol,createLocalFolder:e=>O.createLocalFolder(e),updateLocalFolder:(e,t)=>O.updateLocalFolder(e,t),deleteLocalFolder:e=>O.deleteLocalFolder(e)}),function(e,t,n,i){const s=async e=>{for(const i of t.referencingInstanceIds(e))await n(i)};e.get("/api/node-agent/models",async()=>({data:t.list()})),e.post("/api/node-agent/models",async(e,n)=>n.code(201).send({data:t.create(Qo.parse(e.body))})),e.post("/api/node-agent/models/discover",async e=>{const n=sf.parse(e.body);return{data:await Gg(i,{...n,key:t.resolveProbeKey(n.existingModelId,n.key)})}}),e.post("/api/node-agent/models/test",async e=>{const n=of.parse(e.body);return{data:await Kg(i,{...n,key:t.resolveProbeKey(n.existingModelId,n.key)})}}),e.put("/api/node-agent/models/:id/deploy",async e=>{const n=e.params.id,i=er.parse(e.body);if(i.id!==n)throw Object.assign(new Error(`Model payload id ${i.id} does not match route id ${n}.`),{statusCode:400,code:"NODE_MODEL_ID_MISMATCH"});const o=t.deploy(i);return await s(o.id),{data:o}}),e.patch("/api/node-agent/models/:id",async e=>{const n=t.update(e.params.id,Zo.parse(e.body));return await s(n.id),{data:n}}),e.post("/api/node-agent/models/:id/merge",async e=>{const i=e.params.id,{targetModelId:s}=ir.parse(e.body),o=t.merge(i,s);for(const e of o.reassignedInstances)await n(e);return{data:o}}),e.delete("/api/node-agent/models/:id",async e=>({data:{deleted:t.delete(e.params.id)}})),e.put("/api/node-agent/instances/:id/model-assignment",async e=>{const i=e.params.id,s=e.body&&"object"==typeof e.body&&!Array.isArray(e.body)&&Object.prototype.hasOwnProperty.call(e.body,"modelEntityIds"),o=t.assign(i,or.parse(e.body));if(await n(i),s)return{data:o};const{modelEntityIds:r,...a}=o.assignment;return{data:{...o,assignment:a}}}),e.post("/api/node-agent/instances/:id/sync-models",async e=>{const t=e.params.id;return{data:{synced:!0===await n(t)}}})}(pe,O.modelRegistry,e=>Ab(G,O,e,Ve.warn,B),G);const rt=new qf({resolver:new ig(O.modelRegistry),adapters:[{...vf({protocol:"openai-responses",responsePaths:[["model"],["response","model"]]}),planOperation:({method:e,operationPath:t,search:n,model:i})=>"GET"===e&&"/models"===t?Sf("models.list",bf(i)):"POST"===e&&"/responses"===t?Nf("responses.create","POST",Tf(i.endpoint,"/responses",n),"json"):wf("openai-responses")},{...vf({protocol:"openai-chat-completions",responsePaths:[["model"]]}),planOperation:({method:e,operationPath:t,search:n,model:i})=>"GET"===e&&"/models"===t?Sf("models.list",bf(i)):"POST"===e&&"/chat/completions"===t?Nf("chat.completions.create","POST",Tf(i.endpoint,"/chat/completions",n),"json"):wf("openai-chat-completions")},{...vf({protocol:"anthropic-messages",responsePaths:[["model"],["message","model"]]}),planOperation:({method:e,operationPath:t,search:n,model:i})=>{const s=function(e){return e.startsWith("/v1/")?e.slice(3):e}(t);return"GET"===e&&"/models"===s?Sf("models.list",function(e){const t=Af(e);return JSON.stringify({data:t.map(e=>({id:e,type:"model",display_name:e,created_at:"2026-01-01T00:00:00Z"})),has_more:!1,first_id:t[0]??null,last_id:t[t.length-1]??null})}(i)):"POST"===e&&"/messages"===s?Nf("messages.create","POST",Tf(i.endpoint,"/v1/messages",n),"json"):"POST"===e&&"/messages/count_tokens"===s?Nf("messages.count_tokens","POST",Tf(i.endpoint,"/v1/messages/count_tokens",n),"json"):"HEAD"===e&&"/api/hello"===s?{kind:"reject",name:"gateway.probe",status:404,code:cf,message:"The node model relay does not proxy gateway probes."}:wf("anthropic-messages")}}],log:pe.log,fetchImpl:G});pe.decorate("nodeAgentModelRelay",rt),rt.registerRoutes(pe);const at=new lg({settings:Dg(p,Cg("127.0.0.1",d)),registry:O.modelRegistry,relaySwitch:O.modelRelaySwitch});return at.restore(),function(e,t){e.get("/api/node-agent/settings/model-relay",async()=>({data:t.effective()})),e.patch("/api/node-agent/settings/model-relay",async e=>{const n=t.enabled(),i=t.update(e.body);return n!==i.enabled&&await(async e=>{for(const e of O.modelRegistry.assignedInstanceIds())await Ab(G,O,e,Ve.warn,B);e.enabled||await rt.drainActive()})(i),{data:i}})}(pe,at),function(e,t){const n=new Xf(t.gitCredentials);e.addHook("onClose",async()=>n.close()),e.put("/api/node-agent/git-credentials/:credentialId",async e=>{const n=ey.parse(e.params),i=Ii.parse(e.body);if(i.credential.id!==n.credentialId)throw Object.assign(new Error("Credential payload identity mismatch."),{code:"GIT_CREDENTIAL_IDENTITY_MISMATCH",statusCode:409});return{data:t.gitCredentials.putPayload(i).credential}}),e.delete("/api/node-agent/git-credentials/:credentialId",async e=>({data:{deleted:t.gitCredentials.removePayload(ey.parse(e.params).credentialId)}})),e.get("/api/node-agent/instances/:id/git-credential-authorizations",async e=>{const{id:n}=ty.parse(e.params);return t.requireInstance(n),{data:t.gitCredentials.getAuthorizationSet(n)}}),e.put("/api/node-agent/instances/:id/git-credential-authorizations",async e=>{const{id:n}=ty.parse(e.params);t.requireInstance(n);const i=_i.parse(e.body);if(i.instanceId!==n)throw Object.assign(new Error("Git credential authorization identity mismatch."),{code:"GIT_CREDENTIAL_AUTHORIZATION_IDENTITY_MISMATCH",statusCode:409});return{data:t.gitCredentials.putAuthorizationSet(i)}}),e.post("/api/node-agent/instances/:id/git-credentials/https",async e=>{const{id:i}=ty.parse(e.params);t.authenticateInstance(i,iy(e.headers));const s=Ei.parse(e.body);return{data:Ai.parse(n.resolveHttps(i,s.remoteUrl))}}),e.post("/api/node-agent/instances/:id/git-credentials/ssh/prepare",async e=>{const{id:i}=ty.parse(e.params);t.authenticateInstance(i,iy(e.headers));const s=Ti.parse(e.body);return{data:wi.parse(await n.prepareSsh(i,s.remoteUrl))}}),e.post("/api/node-agent/instances/:id/git-credentials/ssh/agent",async e=>{const{id:i}=ty.parse(e.params);t.authenticateInstance(i,iy(e.headers));const s=bi.parse(e.body);return{data:Ni.parse(await n.exchangeAgentFrame(i,s.invocationId,s.frame))}}),e.delete("/api/node-agent/instances/:id/git-credentials/ssh/:invocationId",async e=>{const{id:i,invocationId:s}=ny.parse(e.params);return t.authenticateInstance(i,iy(e.headers)),{data:{deleted:n.release(s,i)}}})}(pe,O),function(e,t){e.get("/api/node-agent/agents",async()=>({data:tp.parse({agents:t.list()})})),e.post("/api/node-agent/agents",async(e,n)=>{const i=Zu.parse(e.body);return n.code(201).send({data:Ju.parse(t.create(i))})}),e.get("/api/node-agent/agents/:agentId",async e=>{const{agentId:n}=C_.parse(e.params);return{data:Ju.parse(t.get(n))}}),e.patch("/api/node-agent/agents/:agentId",async e=>{const{agentId:n}=C_.parse(e.params),i=ep.parse(e.body);return{data:Ju.parse(t.update(n,i))}}),e.delete("/api/node-agent/agents/:agentId",async e=>{const{agentId:n}=C_.parse(e.params),{referencingOrchestrations:i}=k_.parse(e.query??{}),s=t.delete(n,{referencingOrchestrations:i});return{data:np.parse({id:n,deleted:!0,...s})}})}(pe,we),function(e,t){e.get("/api/node-agent/agent-orchestrations",async()=>({data:wp.parse({orchestrations:t.list()})})),e.post("/api/node-agent/agent-orchestrations",async(e,n)=>{const i=Ap.parse(e.body);return n.code(201).send({data:Ep.parse(t.create(i))})}),e.get("/api/node-agent/agent-orchestrations/:orchestrationId",async e=>{const{orchestrationId:n}=D_.parse(e.params);return{data:Ep.parse(t.get(n))}}),e.patch("/api/node-agent/agent-orchestrations/:orchestrationId",async e=>{const{orchestrationId:n}=D_.parse(e.params),i=Tp.parse(e.body);return{data:Ep.parse(t.update(n,i))}}),e.delete("/api/node-agent/agent-orchestrations/:orchestrationId",async e=>{const{orchestrationId:n}=D_.parse(e.params);return{data:bp.parse({id:n,deleted:t.delete(n)})}})}(pe,Te),function(e,t,n){e.get("/api/node-agent/agent-runs",async()=>({data:sm.parse({runs:t.list()})})),e.post("/api/node-agent/agent-runs",async(e,n)=>{const i=nm.parse(e.body);return n.code(201).send({data:tm.parse(t.create(i))})}),e.get("/api/node-agent/agent-runs/:runId",async e=>{const{runId:n}=L_.parse(e.params);return{data:tm.parse(t.get(n))}}),e.get("/api/node-agent/agent-runs/:runId/members/:memberId",async e=>{const{runId:n,memberId:i}=P_.parse(e.params);return{data:Zp.parse(t.getMember(n,i))}}),e.post("/api/node-agent/agent-runs/:runId/cancel",async e=>{const{runId:n}=L_.parse(e.params),i=im.parse(e.body??{});return{data:tm.parse(t.cancel(n,i))}}),e.post("/api/node-agent/agent-runs/:runId/members/:memberId/ai-sessions/:sessionId/agent-runs",async e=>{if(!n)throw Object.assign(new Error("Agent Run member invocation is unavailable."),{code:"AGENT_RUN_MEMBER_INVOCATION_UNAVAILABLE",statusCode:503});const{runId:i,memberId:s,sessionId:o}=M_.parse(e.params),r=t.getMember(i,s);if(!r.aiSessionId||r.aiSessionId!==o)throw Object.assign(new Error("The provider session does not own this Agent Run member."),{code:"AGENT_RUN_MEMBER_SESSION_MISMATCH",statusCode:403});const a=e.headers.authorization,c="string"==typeof a&&a.startsWith("Bearer ")?a.slice(7).trim():void 0;n.authenticateInstance(r.instanceId,c);const d=tI.parse(e.body),l=t.addMember({runId:i,parentMemberId:s,clientRequestId:d.clientRequestId,agentId:d.input.agentId,input:{prompt:d.input.prompt}});return{data:await t.waitForMemberToolResult(i,l.memberId,e.signal)}})}(pe,Se,O),function(e,t){e.get("/api/node-agent/stories/:storyId/agent-entries",async e=>{const{storyId:n}=j_.parse(e.params);return{data:O_.parse(await t.get(n))}}),e.put("/api/node-agent/stories/:storyId/agent-entries",async e=>{const{storyId:n}=j_.parse(e.params),i=R_.parse(e.body);return{data:O_.parse(await t.update(n,i))}})}(pe,De),function(e,t,n,i={}){if(e.hasContentTypeParser("application/octet-stream")||e.addContentTypeParser("application/octet-stream",(e,t,n)=>n(null,t)),e.get("/api/node-agent/stories",async()=>({data:{stories:await n.list()}})),e.post("/api/node-agent/stories",async(e,t)=>{const s=My.parse(e.body),o=i.commands?await i.commands.create(s):await n.create(s);return i.onRetentionSettingsChanged?.(),t.code(201).send({data:o})}),e.get("/api/node-agent/stories/:storyId",async e=>{const{storyId:t}=u_.parse(e.params);return{data:await n.get(t)||(()=>{throw Object.assign(new Error("Story was not found."),{code:"STORY_NOT_FOUND",statusCode:404})})()}}),e.patch("/api/node-agent/stories/:storyId",async e=>{const{storyId:t}=u_.parse(e.params),s=jy.parse(e.body),o=i.commands?await i.commands.update(t,s):await n.update(t,s);return void 0!==s.maxIdleAiSessions&&i.onRetentionSettingsChanged?.(),{data:o}}),e.get("/api/node-agent/stories/:storyId/settings",async e=>{const{storyId:t}=u_.parse(e.params);return{data:await n.retentionSettings(t)}}),e.get("/api/node-agent/stories/:storyId/settings/agent-tools",async e=>{const{storyId:t}=u_.parse(e.params);if(!i.toolPolicy)throw Object.assign(new Error("Story Agent Tool policy is unavailable."),{code:"STORY_AGENT_TOOL_POLICY_UNAVAILABLE",statusCode:503});return{data:await i.toolPolicy.settings(t)}}),e.post("/api/node-agent/stories/:storyId/actions/:actionId/run",async e=>{const{storyId:t,actionId:n}=f_.parse(e.params);if(!i.actionExecution)throw Object.assign(new Error("Story Action execution is unavailable."),{code:"STORY_ACTION_EXECUTION_UNAVAILABLE",statusCode:503});const s=OI.omit({actionId:!0}).parse(e.body||{});return{data:py.parse(await i.actionExecution.run(t,n,s.clientRequestId))}}),e.put("/api/node-agent/stories/:storyId/settings/agent-tools",async e=>{const{storyId:t}=u_.parse(e.params);if(!i.toolPolicy)throw Object.assign(new Error("Story Agent Tool policy is unavailable."),{code:"STORY_AGENT_TOOL_POLICY_UNAVAILABLE",statusCode:503});const{policy:s}=gI.parse(e.body),o=await i.toolPolicy.update(t,s),r=await n.get(t);r&&n.notifyUpdated(r);const a=await i.toolPolicy.resolve(t);return await(i.onToolPolicyInvalidated?.({storyId:t,revision:a.revision})),{data:o}}),e.get("/api/node-agent/stories/:storyId/decisions",async e=>{const{storyId:t}=u_.parse(e.params);if(!i.decisions)throw Object.assign(new Error("Story decisions are unavailable."),{code:"STORY_DECISION_UNAVAILABLE",statusCode:503});return{data:Ly.parse(await i.decisions.list(t))}}),e.get("/api/node-agent/stories/:storyId/decisions/:decisionId",async e=>{const{storyId:t,decisionId:n}=y_.parse(e.params);if(!i.decisions)throw Object.assign(new Error("Story decisions are unavailable."),{code:"STORY_DECISION_UNAVAILABLE",statusCode:503});return{data:xy.parse(await i.decisions.get(t,n))}}),e.post("/api/node-agent/stories/:storyId/decisions/:decisionId/decide",async e=>{const{storyId:t,decisionId:n}=y_.parse(e.params);if(!i.decisions)throw Object.assign(new Error("Story decisions are unavailable."),{code:"STORY_DECISION_UNAVAILABLE",statusCode:503});const s=ky.parse(e.body||{});return{data:xy.parse(await i.decisions.decide(t,n,s))}}),e.post("/api/node-agent/stories/:storyId/decisions/:decisionId/cancel",async e=>{const{storyId:t,decisionId:n}=y_.parse(e.params);if(!i.decisions)throw Object.assign(new Error("Story decisions are unavailable."),{code:"STORY_DECISION_UNAVAILABLE",statusCode:503});const s=Dy.parse(e.body||{});return{data:xy.parse(await i.decisions.cancel(t,n,s))}}),e.post("/api/node-agent/stories/:storyId/archive",async e=>({data:i.commands?await i.commands.archive(u_.parse(e.params).storyId):await n.archive(u_.parse(e.params).storyId)})),e.post("/api/node-agent/stories/:storyId/restore",async e=>({data:i.commands?await i.commands.restore(u_.parse(e.params).storyId):await n.restore(u_.parse(e.params).storyId)})),e.delete("/api/node-agent/stories/:storyId",async e=>{const{storyId:t}=u_.parse(e.params);if(!i.commands)throw Object.assign(new Error("Story command service is unavailable."),{code:"STORY_COMMAND_UNAVAILABLE",statusCode:503});return{data:{deleted:await i.commands.delete(t)}}}),i.scheduler){const t=i.scheduler,s=async(e,n)=>{const i=await t.status(n);if(i.automation.storyId!==e)throw Object.assign(new Error("Story Automation belongs to another Story."),{code:"STORY_AUTOMATION_STORY_MISMATCH",statusCode:409});return i};e.get("/api/node-agent/stories/:storyId/automations",async e=>{const{storyId:i}=u_.parse(e.params);return await n.require(i),{data:by.parse({automations:await t.list(i)})}}),e.post("/api/node-agent/stories/:storyId/automations",async(e,n)=>{const{storyId:i}=u_.parse(e.params),s=fy.parse(e.body);if(s.storyId!==i)throw Object.assign(new Error("Automation storyId does not match the route."),{code:"STORY_AUTOMATION_STORY_MISMATCH",statusCode:409});return n.code(201).send({data:wy.parse(await t.create(s))})}),e.post("/api/node-agent/stories/:storyId/automations/with-action",async(e,t)=>{const{storyId:n}=u_.parse(e.params);if(!i.commands)throw Object.assign(new Error("Story command service is unavailable."),{code:"STORY_COMMAND_UNAVAILABLE",statusCode:503});const s=yy.parse(e.body);return t.code(201).send({data:wy.parse(await i.commands.createAutomationWithAction(n,s))})}),e.get("/api/node-agent/stories/:storyId/automations/:automationId",async e=>{const{storyId:t,automationId:n}=m_.parse(e.params);return{data:wy.parse(await s(t,n))}}),e.patch("/api/node-agent/stories/:storyId/automations/:automationId",async e=>{const{storyId:n,automationId:i}=m_.parse(e.params);return await s(n,i),{data:wy.parse(await t.update(i,Iy.parse(e.body)))}}),e.delete("/api/node-agent/stories/:storyId/automations/:automationId",async e=>{const{storyId:n,automationId:i}=m_.parse(e.params);return await s(n,i),{data:{deleted:await t.delete(i)}}});for(const n of["enable","disable"])e.post(`/api/node-agent/stories/:storyId/automations/:automationId/${n}`,async e=>{const{storyId:i,automationId:o}=m_.parse(e.params);return await s(i,o),{data:wy.parse(await t.setEnabled(o,"enable"===n))}});e.post("/api/node-agent/stories/:storyId/automations/:automationId/run",async e=>{const{storyId:n,automationId:i}=m_.parse(e.params);return await s(n,i),{data:await t.manualRun(i,Sy.parse(e.body))}}),e.get("/api/node-agent/stories/:storyId/automations/:automationId/runs",async e=>{const{storyId:n,automationId:i}=m_.parse(e.params);return await s(n,i),{data:Ny.parse({runs:await t.runs(i)})}})}e.get("/api/node-agent/stories/:storyId/content",async e=>{const{storyId:t}=u_.parse(e.params);return{data:$y.parse({documents:await n.listContent(t)})}}),e.get("/api/node-agent/stories/:storyId/content/file",async(e,t)=>{const{storyId:i}=u_.parse(e.params),{storyPath:s}=I_.parse(e.query),o=await n.readContent(i,s);return N_(t,o.stream,o.revision,o.size)}),e.put("/api/node-agent/stories/:storyId/content/file",{bodyLimit:33555456},async e=>{const{storyId:t}=u_.parse(e.params),i=__.parse(e.query),{storyPath:s,revision:o,size:r}=await n.writeContent(t,{...i,stream:e.body});return{data:{storyPath:s,revision:o,size:r}}}),e.patch("/api/node-agent/stories/:storyId/documents/:storyPath",async e=>{const t=p_.parse(e.params),i=oy.parse(decodeURIComponent(t.storyPath));return{data:await n.updateDocument(t.storyId,i,Uy.parse(e.body))}}),e.delete("/api/node-agent/stories/:storyId/documents/:storyPath",async e=>{const t=p_.parse(e.params);return{data:{deleted:await n.deleteDocument(t.storyId,oy.parse(decodeURIComponent(t.storyPath)))}}}),e.post("/api/node-agent/stories/:storyId/documents/order",async e=>{const{storyId:t}=u_.parse(e.params);return{data:await n.reorderDocuments(t,e.body)}}),e.get("/api/node-agent/instances/:id/ai-sessions/:sessionId/story-content",async e=>{const{id:s,sessionId:o}=h_.parse(e.params),r=await b_(t,n,s,o,A_(e.headers));await(i.toolPolicy?.assertEnabled(r.id,"story_list_content"));const{page:a,pageSize:c}=qy.parse(e.query||{});return{data:Gy.parse(await n.pageContent(r.id,a,c))}}),e.get("/api/node-agent/instances/:id/story-agent-tools",async e=>{const{id:n}=c.z.object({id:c.z.string().trim().min(1).max(120)}).strict().parse(e.params),{storyId:s}=E_.parse(e.query);if(t.authenticateInstance(n,A_(e.headers)),!i.toolPolicy)throw Object.assign(new Error("Story Agent Tool policy is unavailable."),{code:"STORY_AGENT_TOOL_POLICY_UNAVAILABLE",statusCode:503});return{data:fI.parse(await i.toolPolicy.resolve(s))}}),e.get("/api/node-agent/instances/:id/ai-sessions/:sessionId/story-agent-tools",async e=>{const{id:s,sessionId:o}=h_.parse(e.params),r=await b_(t,n,s,o,A_(e.headers));if(!i.toolPolicy)throw Object.assign(new Error("Story Agent Tool policy is unavailable."),{code:"STORY_AGENT_TOOL_POLICY_UNAVAILABLE",statusCode:503});return{data:fI.parse(await i.toolPolicy.resolve(r.id))}}),e.post("/api/node-agent/instances/:id/ai-sessions/:sessionId/agent-runs",async e=>{const{id:s,sessionId:o}=h_.parse(e.params),r=await b_(t,n,s,o,A_(e.headers));if(!i.toolPolicy||!i.agentRuns)throw Object.assign(new Error("Story Agent invocation is unavailable."),{code:"STORY_AGENT_INVOCATION_UNAVAILABLE",statusCode:503});const a=tI.parse(e.body),c=await i.toolPolicy.assertAgentInvocation(r.id,a.input.agentId,a.input.orchestrationId),d=i.agentRuns.create({clientRequestId:a.clientRequestId,orchestrationId:c.orchestrationId,entryAgentId:c.agentId,input:{prompt:a.input.prompt},provenance:{initiatingInstanceId:s,initiatingAiSessionId:o,storyId:r.id},budget:a.input.budget});return{data:Xp.parse(await i.agentRuns.waitForToolResult(d.runId,e.signal))}}),e.post("/api/node-agent/instances/:id/ai-sessions/:sessionId/story-agent-tools/:tool",async e=>{const{id:s,sessionId:o,tool:r}=g_.parse(e.params),a=await b_(t,n,s,o,A_(e.headers));await(i.toolPolicy?.assertEnabled(a.id,r));const d=c.z.object({input:c.z.unknown()}).strict().parse(e.body||{}),l=l_[r].input.parse(d.input??{});if("story_list_actions"===r){const{page:e,pageSize:n}=SI.parse(l),i=(e-1)*n,s=new Set(t.listInstances().filter(e=>e.nodeId===t.node.id).map(e=>e.id)),o=a.actions.slice(i,i+n).map(e=>{const t=a.archivedAt?"STORY_ARCHIVED":e.targetInstanceId?s.has(e.targetInstanceId)?void 0:"STORY_ACTION_TARGET_UNAVAILABLE":"STORY_ACTION_TARGET_REQUIRED";return{id:e.id,title:e.title,promptPreview:e.promptTemplate.slice(0,500),promptTruncated:e.promptTemplate.length>500,executable:!t,unavailableReason:t}}),r=a.actions.length;return{data:vI.parse({actions:o,pagination:EI(r,e,n)})}}if("story_run_action"===r){if(!i.actionExecution)throw Object.assign(new Error("Story Action execution is unavailable."),{code:"STORY_ACTION_EXECUTION_UNAVAILABLE",statusCode:503});const e=OI.parse(l),t=await i.actionExecution.run(a.id,e.actionId,e.clientRequestId);return{data:RI.parse({session:{instanceId:t.targetInstanceId,sessionId:t.aiSessionId}})}}if("story_list_automations"===r){const{page:e,pageSize:t}=zI.parse(l);if(!i.scheduler)throw Object.assign(new Error("Story Automation scheduler is unavailable."),{code:"STORY_AUTOMATION_UNAVAILABLE",statusCode:503});const n=await i.scheduler.list(a.id),s=(e-1)*t;return{data:l_[r].output.parse({automations:n.slice(s,s+t).map(w_),pagination:EI(n.length,e,t)})}}if("story_create_automation"===r){if(!i.scheduler)throw Object.assign(new Error("Story Automation scheduler is unavailable."),{code:"STORY_AUTOMATION_UNAVAILABLE",statusCode:503});const e=xI.parse(l);return{data:l_[r].output.parse(w_(await i.scheduler.create({storyId:a.id,...e})))}}if("story_update_automation"===r){if(!i.scheduler)throw Object.assign(new Error("Story Automation scheduler is unavailable."),{code:"STORY_AUTOMATION_UNAVAILABLE",statusCode:503});const{automationId:e,expectedUpdatedAt:t,...n}=CI.parse(l);if((await i.scheduler.status(e)).automation.storyId!==a.id)throw S_();return{data:l_[r].output.parse(w_(await i.scheduler.update(e,n,t)))}}if("story_delete_automation"===r){if(!i.scheduler)throw Object.assign(new Error("Story Automation scheduler is unavailable."),{code:"STORY_AUTOMATION_UNAVAILABLE",statusCode:503});const{automationId:e,expectedUpdatedAt:t}=kI.parse(l);if((await i.scheduler.status(e)).automation.storyId!==a.id)throw S_();return{data:PI.parse({deleted:await i.scheduler.delete(e,t)})}}if("story_run_automation"===r){if(!i.scheduler)throw Object.assign(new Error("Story Automation scheduler is unavailable."),{code:"STORY_AUTOMATION_UNAVAILABLE",statusCode:503});const{automationId:e,clientRequestId:t}=DI.parse(l);if((await i.scheduler.status(e)).automation.storyId!==a.id)throw S_();return{data:l_[r].output.parse(T_(await i.scheduler.manualRun(e,{clientRequestId:t})))}}if("story_list_automation_runs"===r){if(!i.scheduler)throw Object.assign(new Error("Story Automation scheduler is unavailable."),{code:"STORY_AUTOMATION_UNAVAILABLE",statusCode:503});const{automationId:e,page:t,pageSize:n}=LI.parse(l);if((await i.scheduler.status(e)).automation.storyId!==a.id)throw S_();const s=await i.scheduler.runs(e),o=(t-1)*n;return{data:l_[r].output.parse({runs:s.slice(o,o+n).map(T_),pagination:EI(s.length,t,n)})}}const u={instanceId:s,sessionId:o,storyId:a.id};if("story_request_decision"===r){if(!i.decisions)throw Object.assign(new Error("Story decisions are unavailable."),{code:"STORY_DECISION_UNAVAILABLE",statusCode:503});const{session:c}=await async function(e,t,n,i,s){const o=e.authenticateInstance(n,s).aiSessions.sessions.find(e=>e.id===i);if(!o)throw Object.assign(new Error("AI Session was not found in the authoritative instance snapshot."),{code:"AI_SESSION_NOT_FOUND",statusCode:404});if(!o.storyId)throw Object.assign(new Error("AI Session is not assigned to a Story."),{code:"STORY_CONTEXT_REQUIRED",statusCode:409});const r=await t.get(o.storyId);if(!r)throw Object.assign(new Error("Story was not found."),{code:"STORY_NOT_FOUND",statusCode:404});return{session:o,story:r}}(t,n,s,o,A_(e.headers)),d=await i.decisions.register({storyId:a.id,sessionId:o,turnId:c.activeTurnId},l_[r].input.parse(l));return{data:d_.parse({decisionId:d.id,status:d.status})}}if("story_list_ai_sessions"===r){if(!i.aiSessionRead)throw Object.assign(new Error("Story AI Session read is unavailable."),{code:"STORY_AI_SESSION_READ_UNAVAILABLE",statusCode:503});const{page:e,pageSize:t}=HI.parse(l);return{data:BI.parse(i.aiSessionRead.list(u,e,t))}}if("story_get_ai_session"===r){if(!i.aiSessionRead)throw Object.assign(new Error("Story AI Session read is unavailable."),{code:"STORY_AI_SESSION_READ_UNAVAILABLE",statusCode:503});const e=VI.parse(l);return{data:XI.parse(await i.aiSessionRead.get(u,e.instanceId,e.sessionId,e.page,e.pageSize))}}if("story_get_ai_session_turn"===r){if(!i.aiSessionRead)throw Object.assign(new Error("Story AI Session read is unavailable."),{code:"STORY_AI_SESSION_READ_UNAVAILABLE",statusCode:503});const e=JI.parse(l);return{data:s_.parse(await i.aiSessionRead.turn(u,e.instanceId,e.sessionId,e.turnId,e.page,e.pageSize,e.maxTextChars))}}throw Object.assign(new Error("Story Agent Tool is not implemented."),{code:"STORY_AGENT_TOOL_NOT_IMPLEMENTED",statusCode:501})}),e.get("/api/node-agent/instances/:id/ai-sessions/:sessionId/story-content/file",async(e,s)=>{const{id:o,sessionId:r}=h_.parse(e.params),a=await b_(t,n,o,r,A_(e.headers));await(i.toolPolicy?.assertEnabled(a.id,"story_get_content"));const{storyPath:c}=I_.parse(e.query),d=await n.readContent(a.id,c);return N_(s,d.stream,d.revision,d.size)}),e.put("/api/node-agent/instances/:id/ai-sessions/:sessionId/story-content/file",{bodyLimit:33555456},async e=>{const{id:s,sessionId:o}=h_.parse(e.params),r=await b_(t,n,s,o,A_(e.headers));await(i.toolPolicy?.assertEnabled(r.id,"story_set_content"));const a=__.parse(e.query);return{data:await n.writeContent(r.id,{...a,stream:e.body})}}),e.put("/api/node-agent/instances/:id/ai-sessions/:sessionId/story",async e=>{const{id:s,sessionId:o}=h_.parse(e.params),r=t.requireInstance(s),a=c.z.object({storyId:ze.nullable()}).strict().parse(e.body||{});if(a.storyId){const e=await n.get(a.storyId);if(!e)throw Object.assign(new Error("Story belongs to another node or was not found."),{code:"STORY_NODE_MISMATCH",statusCode:409});if(e.archivedAt)throw Object.assign(new Error("Archived Story cannot receive new Session associations."),{code:"STORY_ARCHIVED",statusCode:409})}if(!i.fetchImpl||!i.resolveInstanceWeb||!r.registrationToken)throw Object.assign(new Error("Managed instance Session association is unavailable."),{code:"STORY_SESSION_ASSOCIATION_UNAVAILABLE",statusCode:503});const d=await i.resolveInstanceWeb(r),l=await i.fetchImpl(`${d}/api/ai-sessions/${encodeURIComponent(o)}/story`,{method:"PUT",headers:{"content-type":"application/json",authorization:`Bearer ${r.registrationToken}`},body:JSON.stringify(a)}),u=await l.json().catch(()=>({}));if(!l.ok)throw Object.assign(new Error(u.error?.message||"Controlled instance rejected Story association."),{code:u.error?.code||"STORY_SESSION_ASSOCIATION_FAILED",statusCode:l.status});return u})}(pe,O,R,{fetchImpl:G,resolveInstanceWeb:B,onRetentionSettingsChanged:()=>K.reconcile(),commands:Fe,scheduler:Ue,toolPolicy:x,actionExecution:Le,aiSessionRead:Pe,decisions:je,agentRuns:Se,onToolPolicyInvalidated:e=>Y.notify(e)}),function(e,t){e.get("/api/node-agent/environment-templates",async()=>({data:t.list()})),e.get("/api/node-agent/environment-templates/:id",async e=>({data:Js.parse(t.require(e.params.id))})),e.post("/api/node-agent/instances/:id/environment-templates",async(e,n)=>{const i=await t.create(e.params.id,e.body);return n.code(201).send({data:i})}),e.delete("/api/node-agent/environment-templates/:id",async e=>({data:await t.delete(e.params.id)}))}(pe,Ke),function(e,t){e.get("/api/node-agent/instances",async()=>({data:t.list()})),e.post("/api/node-agent/instances",async(e,n)=>{const i=await t.create(mA.parse(e.body));return t.afterCreate(i),n.code(201).send({data:i})}),e.post("/api/node-agent/instances/:id/image-provisioning/retry",async e=>{const n=t.retryImageProvisioning(e.params.id);return t.afterImageRetry(n),{data:n}}),e.post("/api/node-agent/instances/:id/git-provisioning/retry",async e=>{const n=t.retryGitProvisioning(e.params.id);return t.afterGitRetry(n),{data:n}}),e.patch("/api/node-agent/instances/:id",async e=>{const n=t.update(e.params.id,hA.parse(e.body));return await t.afterUpdate(n),{data:n}}),e.post("/api/node-agent/instances/:id/register",async(e,n)=>{const i=e.params.id,s=t.sanitizeReport(i,"register",e.body),o=t.register(i,Ra.parse(s),yA(e.headers));return t.afterReport(o,"register"),n.header("x-task-handoff-node-agent-protocol-version",Qi).code(201).send({data:o})}),e.post("/api/node-agent/instances/:id/heartbeat",async e=>{const n=e.params.id,i=t.sanitizeReport(n,"heartbeat",e.body),s=t.heartbeat(n,za.parse(i),yA(e.headers));return t.afterReport(s,"heartbeat"),{data:s}})}(pe,{list:()=>O.listInstances(),create:e=>"template"===e.environmentSource?.type?Ke.runTemplateOperation(e.environmentSource.environmentTemplateId,()=>O.createInstance(e)):O.createInstance(e),retryImageProvisioning:e=>Je.retry(e),retryGitProvisioning:e=>et.retry(e),update:(e,t)=>{const n=O.requireInstance(e),i=t.config?.codexSettings?.multiAgent.defaultModel;if(i){const t=O.modelRegistry.privateCatalog(e).entities.find(e=>e.id===i.modelEntityId&&e.protocols.includes("openai-responses"));if(!t||!(Ne(t.modelNames,i.modelUpstreamName??i.modelName)??Ne(t.modelNames,i.modelName)))throw Object.assign(new Error("The Codex subagent model must be assigned to this instance."),{statusCode:400,code:"CODEX_SUBAGENT_MODEL_UNAVAILABLE"})}return O.controlledInstances.put(Ia.parse({...n,...t,...t.config?{config:{...n.config,...t.config}}:{},updatedAt:de()}))},register:(e,t,n)=>O.registerInstance(e,t,n),heartbeat:(e,t,n)=>O.heartbeatInstance(e,t,n),sanitizeReport:We,afterCreate:e=>{Ee.syncNow(),e.imageProvisioning&&Qe(e)},afterImageRetry:e=>{Ee.syncNow(),Qe(e)},afterGitRetry:e=>{Ee.syncNow(),tt(e)},afterUpdate:async e=>{Ee.syncNow(),await Promise.all([Z(e.id),ee(e.id)])},afterReport:(e,t)=>{Ee.syncNow(),Ue.reconcileInstances("heartbeat"===t?e.id:void 0).catch(t=>pe.log.warn({error:t,instanceId:e.id},"Story scheduler reconciliation failed")),Q(e),Z(e.id),ee(e.id),te.converge(e,t),K.reconcile(),W.reconcile(),"register"===t?Be({instanceId:e.id,action:t,protocolVersion:e.protocolVersion,build:e.build,targetStatus:e.targetStatus,targetStrategy:e.target.strategy},"node instance registered"):Be({instanceId:e.id,action:t,status:e.status,health:e.health,protocolVersion:e.protocolVersion,build:e.build,targetStatus:e.targetStatus,apps:e.apps.runningCount},"node instance heartbeat accepted"),!le(e)||e.ready&&"matched"===e.runtimeVersion?.phase||Ae.schedule(e.id).catch(n=>pe.log.error({instanceId:e.id,error:n},`runtime convergence after ${t} failed`))}}),pe.get("/api/node-agent/events",{websocket:!0},(e,t)=>{const n=e;n.send(JSON.stringify({type:"node-agent.events.connected",nodeId:T,serverTime:(new Date).toISOString()}));const i=t.query,s=Ee.addOutput(n,{expectsTransientSubscription:"1"===i.aiSessionTransient});n.on("message",e=>{try{const t=JSON.parse(String(e));"subscribe"===t.type&&void 0!==t.aiSessionTransient&&Ee.setOutputSubscription(n,t.aiSessionTransient,t.eventEnvelopeVersion,t.aiSessionHierarchy)}catch{}}),n.on("close",s),n.on("error",s)}),pe.get("/api/node-agent/docker/images",async()=>({data:await qc(e.dockerCommandRunner)})),pe.get("/api/node-agent/instances/:id/metrics",async e=>{const t=e.params.id,n=O.requireInstance(t);if("docker"!==O.requireRuntime(n.runtimeId).type){const e=new Error(`Runtime type ${O.requireRuntime(n.runtimeId).type} does not provide resource metrics.`);throw Object.assign(e,{statusCode:409,code:"INSTANCE_METRICS_UNSUPPORTED"}),e}return{data:await $e.snapshot(t)}}),function(e,t,n,i,s,o=new IA){const r=e=>o.intent(e),a=e=>Promise.resolve(i.cancel(e)).then(()=>({ok:!0}),e=>({ok:!1,error:e})),c=(e,t)=>{if(!o.isIntentCurrent(e,t))throw Object.assign(new Error(`Instance operation for ${e} was superseded by stop or delete.`),{statusCode:409,code:"INSTANCE_OPERATION_SUPERSEDED"})},d=(e,t)=>{const n=o.signal;return"function"==typeof n?n.call(o,e,t):void 0},l=(e,n)=>{if(n){if(n.instanceId!==e)throw Object.assign(new Error(`Git provisioning belongs to ${n.instanceId}, not ${e}.`),{code:"GIT_WORKSPACE_PROVISIONING_INSTANCE_MISMATCH",statusCode:409});t.setGitWorkspaceProvisioning(n)}},u=(e,n)=>{if(!n)return e;const i=t.gitWorkspaceProvisioningStatus(e.id);return"consumed"===i?.status&&i.operationId===n.operationId?{instance:e,gitWorkspaceProvisioningOperationId:n.operationId}:e};e.post("/api/node-agent/instances/:id/start",async e=>{const t=_A.parse(e.body),n=e.params.id,i=r(n);return o.run(n,async()=>(c(n,i),l(n,t.gitWorkspaceProvisioning),s.allowRecovery(n),{data:u(await s.start(n,()=>o.isIntentCurrent(n,i),d(n,i)),t.gitWorkspaceProvisioning)}))}),e.post("/api/node-agent/instances/:id/runtime/reconcile",async e=>{const n=e.params.id;_A.parse(e.body);const a=r(n);return o.run(n,async()=>{c(n,a);const e=t.requireInstance(n);t.putInstance(Ia.parse({...e,ready:!1,runtimeVersion:bg(Kl(e)),updatedAt:de()})),c(n,a);const o=await i.schedule(n,{startRequested:!["created","stopped"].includes(e.status),resumeCancelled:!0});return c(n,a),s.sync(),{data:o}})}),e.post("/api/node-agent/instances/:id/stop",async e=>{const i=e.params.id;t.requireInstance(i),t.discardGitWorkspaceProvisioning(i),o.invalidate(i);const r=a(i);return o.run(i,async()=>{const e=t.requireInstance(i);t.applyLifecycle(i,{type:"stop-requested"});try{await s.suppressRecovery(i);const e=await r;if("error"in e)throw e.error;const o=t.requireInstance(i);s.diagnostic({instanceId:i,action:"stop",runtimeId:o.runtimeId,containerName:o.runtime.containerName},"node instance stop requested"),await n.forRuntime(t.requireRuntime(o.runtimeId)).stop(t.context(o))}catch(n){try{t.applyLifecycle(i,{type:"stop-failed",baseline:e}),s.sync()}finally{s.allowRecovery(i)}throw n}const o=t.applyLifecycle(i,{type:"stop-completed"});return s.completeSuppressedRecovery(i),s.sync(),s.diagnostic({instanceId:i,action:"stop",status:o.status,connectionStatus:o.connectionStatus,containerName:o.runtime.containerName},"node instance stop completed"),{data:o}})}),e.post("/api/node-agent/instances/:id/restart",async e=>{const a=e.params.id,d=_A.parse(e.body),p=r(a);return o.run(a,async()=>{c(a,p),l(a,d.gitWorkspaceProvisioning),s.allowRecovery(a);let e=t.requireInstance(a);if(s.isManaged(e)&&(!e.ready||"matched"!==e.runtimeVersion?.phase)){"failed"===e.runtimeVersion?.phase&&(e=t.putInstance(Ia.parse({...e,runtimeVersion:bg(Kl(e)),updatedAt:de()}))),c(a,p);const n=await i.schedule(a,{startRequested:!0});return c(a,p),s.sync(),{data:u(n,d.gitWorkspaceProvisioning)}}s.diagnostic({instanceId:a,action:"restart",runtimeId:e.runtimeId,imageId:e.imageSelection?.imageId,containerName:e.runtime.containerName},"node instance restart requested");const o=await n.forRuntime(t.requireRuntime(e.runtimeId)).restart(t.context(e));let r=t.applyLifecycle(a,{type:"runtime-lifecycle-completed",baseline:e,observation:{...o,target:o.target?{...e.target,...o.target}:void 0}});s.markRestarted(a),c(a,p);const m=Ia.parse({...r,updatedAt:de()}),h=await s.probe(m);return c(a,p),r=t.applyLifecycle(a,{type:"runtime-lifecycle-completed",baseline:r,observation:{target:{...r.target,status:h},targetStatus:h,uiAccessStatus:h}}),await s.autoImport(r),s.sync(),s.diagnostic({instanceId:a,action:"restart",status:r.status,connectionStatus:r.connectionStatus,targetStatus:r.targetStatus,targetWeb:r.target.web,containerName:r.runtime.containerName},"node instance restart completed"),{data:u(r,d.gitWorkspaceProvisioning)}})}),e.post("/api/node-agent/instances/:id/delete",async e=>{const i=e.params.id,r=Hs.parse(e.body);t.requireInstance(i),o.invalidate(i);const c=a(i);return o.run(i,async()=>{const e=t.requireInstance(i);"deleting"!==e.status&&t.applyLifecycle(i,{type:"stop-requested"});try{await s.suppressRecovery(i);const e=await c;if("error"in e)throw e.error;const a=t.requireInstance(i);t.putInstance(Ia.parse({...a,status:"deleting",ready:!1,updatedAt:de()})),s.diagnostic({instanceId:i,action:"delete",runtimeId:a.runtimeId,containerName:a.runtime.containerName},"node instance delete requested");const d=await n.forRuntime(t.requireRuntime(a.runtimeId)).delete(t.context(a,{}),r);if(!d.completed)return s.diagnostic({instanceId:i,action:"delete",volumeResults:d.volumeResults},"node instance delete requires retry"),s.sync(),{data:d};s.diagnostic({instanceId:i,action:"delete"},"node instance delete completed");const l=t.deleteInstance(i);return l&&(s.forgetRecovery(i),o.clearIntent(i)),s.deleteMetadata(i),l&&s.retireInstanceData(i),l&&a.environmentTemplateOrigin?.imageId&&s.releaseEnvironmentImage&&await s.releaseEnvironmentImage(a.environmentTemplateOrigin.imageId).catch(e=>{s.diagnostic({instanceId:i,action:"release-environment-image",error:e instanceof Error?e.message:String(e)},"environment image cleanup deferred after instance deletion")}),s.sync(),{data:d}}catch(n){try{t.putInstance(Ia.parse({...e,updatedAt:de()})),s.sync()}finally{s.allowRecovery(i)}throw n}})})}(pe,{requireInstance:e=>O.requireInstance(e),requireRuntime:e=>O.requireRuntime(e),putInstance:e=>O.controlledInstances.put(e),deleteInstance:e=>O.controlledInstances.delete(e),applyLifecycle:(e,t)=>O.applyInstanceLifecycle(e,t),context:(e,t)=>O.context(e,t),setGitWorkspaceProvisioning:e=>O.setGitWorkspaceProvisioning(e),discardGitWorkspaceProvisioning:e=>O.discardGitWorkspaceProvisioning(e),gitWorkspaceProvisioningStatus:e=>O.gitWorkspaceProvisioningStatus(e)},U,Ae,{start:(e,t,n)=>Xe(e,"request",t,n),sync:()=>Ee.syncNow(),isManaged:le,probe:e=>yb(G,e,B),autoImport:e=>Eb(G,e,"restart",Ve,B),markRestarted:e=>j.markRestored(e),allowRecovery:e=>j.allowRecovery(e),suppressRecovery:e=>j.suppressRecovery(e),forgetRecovery:e=>j.forgetInstance(e),completeSuppressedRecovery:e=>j.completeSuppressedOperation(e),deleteMetadata:e=>{X.delete(e),O.modelRegistry.deleteInstanceMetadata(e),O.gitCredentials.removeInstance(e),O.gitCredentials.collectUnreferencedPayloads(),O.discardGitWorkspaceProvisioning(e),O.instancePrivateConfigs.delete(e)},retireInstanceData:e=>{me.retire(e)},releaseEnvironmentImage:e=>Ke.releaseUnusedImage(e),diagnostic:Be},Ge),function(e,t){const{fetchImpl:n,metrics:i,diagnostic:s}=t;e.post("/api/node-agent/instances/:id/proxy",async(e,i)=>{const o=performance.now(),r=e.params.id,a=dA.parse(e.body),c=await t.instanceBase(r),d=CA(a.path);"POST"===a.method&&"/api/apps/sessions"===d&&await t.syncModelEnvironment(r),s({instanceId:r,action:"proxy",method:a.method,path:d,instanceBase:c},"node instance proxy requested");const l=await DA(n,`${c}${d}`,{method:a.method,headers:{...a.headers},body:RA(a)},{instanceId:r,method:a.method,path:d,diagnostic:s}),u=l.headers.get("content-type")||"application/octet-stream",p=await l.text(),m=performance.now()-o,h=l.headers.get(xA)||a.headers[xA],g=function(...e){return e.map(e=>String(e||"").trim()).filter(Boolean).join(", ")}(l.headers.get("server-timing"),function(e,t){return`node_proxy;dur=${(Number.isFinite(t)?Math.max(0,t):0).toFixed(1)}`}(0,m));i.header("server-timing",g),h&&i.header(xA,h),s({instanceId:r,action:"proxy",method:a.method,path:d,statusCode:l.status,contentType:u,durationMs:m,traceId:h},"node instance proxy completed"),i.code(l.status).type(u).send(p)}),e.post("/api/node-agent/instances/:id/proxy/stream",{bodyLimit:vA},async(e,o)=>{const r=Date.now();i.requests+=1,i.active+=1;const a=new AbortController;let c=0,d=!1,l=!1;const u=e=>{l||(l=!0,i.active-=1,i.totalDurationMs+=Date.now()-r,i.responseBytes+=c,i[e]+=1)},p=()=>{a.abort(),d&&u("aborted")};e.raw.once("aborted",p),o.raw.once("close",p);try{const r=e.params.id,l=dA.parse(e.body),p=await t.instanceBase(r),m=CA(l.path);s({instanceId:r,action:"proxy.stream",method:l.method,path:m,instanceBase:p},"node instance streaming proxy requested");const h=await DA(n,`${p}${m}`,{method:l.method,headers:{...l.headers},body:RA(l),signal:a.signal},{instanceId:r,method:l.method,path:m,diagnostic:s}),g=Number(h.headers.get("content-length"));if(Number.isFinite(g)&&g>i.maxResponseBytes)return i.limitRejected+=1,a.abort(),kA(o,i.maxResponseBytes);o.code(h.status);for(const[e,t]of Object.entries(OA(h.headers)))o.header(e,t);if(!h.body||"HEAD"===l.method)return u("completed"),o.send();const y=new f.Transform({transform(e,t,n){if(c+=e.length,c>i.maxResponseBytes)return i.limitRejected+=1,a.abort(),void n(Object.assign(new Error("Instance proxy response limit exceeded."),{code:"INSTANCE_PROXY_RESPONSE_TOO_LARGE"}));n(null,e)}});return d=!0,y.once("end",()=>u("completed")),y.once("error",()=>u("aborted")),o.send(f.Readable.fromWeb(h.body).pipe(y))}catch(e){throw u("aborted"),e}finally{e.raw.off("aborted",p),d||u("completed")}}),e.post("/api/node-agent/instances/:id/proxy/raw",{bodyLimit:vA},async(e,o)=>{const r=e.params.id,a=dA.parse(e.body),c=await t.instanceBase(r),d=CA(a.path);s({instanceId:r,action:"proxy.raw",method:a.method,path:d,instanceBase:c},"node instance raw proxy requested");const l=await DA(n,`${c}${d}`,{method:a.method,headers:{...a.headers},body:RA(a)},{instanceId:r,method:a.method,path:d,diagnostic:s}),u=Number(l.headers.get("content-length"));if(Number.isFinite(u)&&u>i.maxResponseBytes)return i.limitRejected+=1,await(l.body?.cancel("Instance proxy response limit exceeded.").catch(()=>{})),kA(o,i.maxResponseBytes);let p;try{p=await async function(e,t){if(!e.body)return Buffer.alloc(0);const n=[];let i=0;const s=e.body.getReader();for(;;){const{done:e,value:o}=await s.read();if(e)break;if(i+=o.byteLength,i>t)throw await s.cancel("Instance proxy response limit exceeded.").catch(()=>{}),Object.assign(new Error("Instance proxy response limit exceeded."),{code:"INSTANCE_PROXY_RESPONSE_TOO_LARGE"});n.push(Buffer.from(o))}return Buffer.concat(n,i)}(l,i.maxResponseBytes)}catch(e){if(!(e instanceof Error)||"INSTANCE_PROXY_RESPONSE_TOO_LARGE"!==e.code)throw e;return i.limitRejected+=1,kA(o,i.maxResponseBytes)}return s({instanceId:r,action:"proxy.raw",method:a.method,path:d,statusCode:l.status,byteLength:p.length},"node instance raw proxy completed"),{data:{status:l.status,headers:OA(l.headers),bodyBase64:p.toString("base64")}}}),e.get("/api/node-agent/instances/:id/proxy/ws/*",{websocket:!0},async(e,n)=>{const i=n.params.id,o=n.params["*"]||"",r=n.url.indexOf("?"),a=r>=0?n.url.slice(r):"";let c;try{const r=await t.instanceBase(i),d=new URL(`/${o}${a}`,`${r}/`);d.protocol="https:"===d.protocol?"wss:":"ws:";const l=function(e){const t=Object.entries(e).find(([e])=>"sec-websocket-protocol"===e.toLowerCase()),n=t?.[1],i=(Array.isArray(n)?n.join(","):"string"==typeof n?n:"").split(",").map(e=>e.trim()).filter(Boolean);return i.length?i:void 0}(n.headers);s({instanceId:i,action:"proxy.ws",path:`/${o}${a}`,upstreamUrl:d.toString(),protocols:l||[]},"node instance websocket proxy opening"),c=l?new h(d,l,{perMessageDeflate:!1}):new h(d,{perMessageDeflate:!1}),c.on("open",()=>{s({instanceId:i,action:"proxy.ws",path:`/${o}${a}`},"node instance websocket proxy opened")}),c.on("close",()=>{s({instanceId:i,action:"proxy.ws",path:`/${o}${a}`},"node instance websocket proxy closed")}),c.on("error",e=>{s({instanceId:i,action:"proxy.ws",path:`/${o}${a}`,error:e instanceof Error?e.message:String(e)},"node instance websocket proxy failed")}),F(e,c,{upstreamOpenTimeoutMs:1e4})}catch(t){s({instanceId:i,action:"proxy.ws",path:`/${o}${a}`,error:t instanceof Error?t.message:String(t)},"node instance websocket endpoint unavailable"),c?.close(),e.close(1011,"Instance websocket endpoint is not reachable.")}})}(pe,{fetchImpl:G,metrics:_e,instanceBase:e=>B(O.requireInstance(e)),syncModelEnvironment:e=>Ab(G,O,e,Ve.warn,B),diagnostic:Be}),pe}catch(e){throw await g.close(),e}var y}async function bb(e){const o=function(e=Date.now()){return(t,n={})=>{try{process.stdout.write(`${JSON.stringify({level:30,time:Date.now(),pid:process.pid,hostname:s.hostname(),...n,elapsedMs:Date.now()-e,msg:`node agent ${t}`})}\n`)}catch{}}}();o("starting",{dataDir:e.dataDir||process.env.TASK_HANDOFF_NODE_AGENT_DATA_DIR||"",version:process.env.TASK_HANDOFF_VERSION||""});const r=zl(e.dataDir);let a;try{a=function(e,i={}){return function(e,i={}){t.mkdirSync(n.dirname(e),{recursive:!0});const o=q.processStartIdentity(process.pid),r={pid:process.pid,hostname:s.hostname(),command:process.argv.join(" "),acquiredAt:(new Date).toISOString(),token:d.randomUUID(),...void 0!==i.component?{component:i.component}:{},...o?{startIdentity:o}:{},...void 0!==i.dataDir?{dataDir:i.dataDir}:{},...void 0!==i.host?{host:i.host}:{},...void 0!==i.port?{port:i.port}:{},...void 0!==i.instanceId?{instanceId:i.instanceId}:{}};for(let n=0;n<5;n+=1)try{return t.mkdirSync(e),t.writeFileSync(G(e),`${JSON.stringify({token:r.token,pid:r.pid,startIdentity:r.startIdentity,startedAt:(new Date).toISOString()})}\n`,{encoding:"utf8",mode:384,flag:"wx"}),Z(e,r),{lockPath:e,owner:r,updateDetails:t=>ee(e,r,t),release(){const n=X(e);n?.token===r.token&&t.rmSync(e,{recursive:!0,force:!0})}}}catch(s){if("EEXIST"!==s.code)throw s;const o=X(e);if(Q(o))throw new B(e,o,i.error);if(!o&&(ne(e)||oe(e)<(i.incompleteLockStaleMs??2e3))){if(n+1<5){se();continue}throw new B(e,void 0,i.error)}const r=d.randomUUID();if(!re(e,r)){if(n+1<5){se();continue}throw new B(e,X(e),i.error)}const a=X(e);if(Q(a))throw ie(K(e)),new B(e,a,i.error);if(o?.token&&a?.token!==o.token){ie(K(e));continue}if(!ce(e,r))continue;t.rmSync(e,{recursive:!0,force:!0})}const a=X(e);throw new B(e,a,i.error)}(e,{...i,component:"node-agent",error:{label:"Node agent",code:"NODE_AGENT_ALREADY_RUNNING"}})}(function(){const e=process.env.TASK_HANDOFF_NODE_AGENT_LOCK_PATH?.trim();return e?n.resolve(e):n.join(s.tmpdir(),`task-handoff-node-agent-${process.getuid?.()??"user"}.lock`)}(),{dataDir:r.dataDir})}catch(e){throw o("startup failed",{error:e instanceof Error?e.message:String(e)}),e}o("singleton lease acquired",{lockPath:a.lockPath});try{const s=Cg(e.host,e.port),d=t.existsSync(r.settingsPath),l=Dg(r,s);let u=l.get().externalListener;"allocate"===process.env.TASK_HANDOFF_NODE_AGENT_PORT_CONFLICT&&(u=await async function(e,t=20){for(let n=0;n<t&&e.port+n<=65535;n+=1){const t={...e,port:e.port+n};if(await MA(t))return t}throw Object.assign(new Error(`No available node-agent port found starting at ${e.port}.`),{statusCode:503,code:"NODE_AGENT_LISTENER_PORT_UNAVAILABLE"})}(u));const p=e=>{if(!a.updateDetails({dataDir:r.dataDir,host:e.host,port:e.port,instanceId:void 0}))throw new Error("Node agent singleton ownership changed while publishing listener state.")},m=e.ipcPath||process.env.TASK_HANDOFF_NODE_AGENT_IPC_PATH||Dl(r.dataDir),h="linux"===(e.platform||process.platform)?e.containerIpcPath||process.env.TASK_HANDOFF_NODE_AGENT_CONTAINER_IPC_PATH||(c=r.dataDir,n.join(n.resolve(c),"container-ipc","node-agent.sock")):void 0,g={...e,port:u.port,ipcPath:m,containerIpcPath:h},f=await wb(g);o("application initialized",{ipcPath:m});const y=f.nodeAgentState;if(!y)throw new Error("Node agent state was not initialized.");const I=f.nodeAgentIdentityService;if(!I)throw new Error("Node agent identity service was not initialized.");const _=f.nodeAgentResolveInstanceNodeAgentUrl;if(!_)throw new Error("Node agent runtime transport resolver was not initialized.");const E=I.resolveNodeId(e.nodeId||process.env.TASK_HANDOFF_NODE_ID),A=function(e,t,n,i,s){const o=t.token||process.env.TASK_HANDOFF_NODE_AGENT_TOKEN,r=s||new WA(n),a=new Map;let c=!1;const d=(t,n)=>{if(c||n.retry.pending||a.get(t)!==n)return;const s=n.retry.schedule(()=>{c||a.get(t)!==n||n.socket||l(t,n)});s&&(n.status="reconnecting",n.nextRetryAt=new Date(Date.now()+s.delay).toISOString(),e.log.info({nodeId:i,tunnelUrl:new URL(n.config.tunnelUrl).origin,attempt:s.attempt,delay:s.delay},"node agent reverse tunnel reconnect scheduled"))},l=(n,s)=>{let r;s.status=s.lastDisconnectedAt?"reconnecting":"connecting",s.error=void 0,s.failureReason=void 0,s.nextRetryAt=void 0;try{r=lT(e,{...s.config,nodeId:i,port:()=>e.nodeAgentState.currentListenerPort,token:o})}catch(e){return s.status="failed",s.lastDisconnectedAt=(new Date).toISOString(),s.error=e instanceof Error?e.message:String(e),void d(n,s)}s.socket=r;const l=new hT({connectTimeoutMs:t.connectTimeoutMs,handshakeTimeoutMs:t.handshakeTimeoutMs,heartbeatIntervalMs:t.heartbeatIntervalMs,heartbeatTimeoutMs:t.heartbeatTimeoutMs,heartbeatMissThreshold:t.heartbeatMissThreshold,stableThresholdMs:t.stableThresholdMs,ping:()=>r.ping(),onTimeout:e=>{a.get(n)===s&&s.socket===r&&(s.status="failed",s.failureReason=`Reverse tunnel ${e} timeout.`,s.error=s.failureReason,r.terminate())},onStable:()=>s.retry.reset()});return s.supervisor=l,l.start(),r.on("open",()=>{a.get(n)===s&&s.socket===r&&(s.status="connecting",l.opened())}),r.on("message",t=>{if(a.get(n)!==s||s.socket!==r)return;if(l.activity(),"connected"===s.status)return;let o;try{o=JSON.parse(String(t))}catch{return}const c=o&&"object"==typeof o?o.type:void 0;"control-plane.hello"!==c&&"control-plane.identified"!==c||(l.activity(),l.healthy(),s.status="connected",s.lastConnectedAt=(new Date).toISOString(),s.nextRetryAt=void 0,s.error=void 0,e.log.info({nodeId:i,tunnelUrl:new URL(s.config.tunnelUrl).origin},"node agent reverse tunnel connected"))}),r.on("pong",()=>l.pong()),r.on("close",(t,o)=>{if(a.get(n)!==s||s.socket!==r)return;l.close(),s.socket=void 0,s.lastDisconnectedAt=(new Date).toISOString();const u=`WebSocket closed${t?` (${t})`:""}${o?`: ${Buffer.isBuffer(o)?o.toString("utf8"):String(o)}`:""}`;s.error=s.failureReason||u,c||(e.log.warn({nodeId:i,tunnelUrl:new URL(s.config.tunnelUrl).origin,code:t,reason:Buffer.isBuffer(o)?o.toString("utf8"):String(o||""),error:s.error,closeOrigin:s.failureReason?"supervisor":"transport"},"node agent reverse tunnel disconnected"),d(n,s))}),r.on("error",e=>{a.get(n)===s&&s.socket===r&&(s.status="failed",s.failureReason=e instanceof Error?e.message:String(e),s.error=s.failureReason,r.terminate())}),r},u=(e,t)=>{const n=a.get(e);n?.retry.cancel(),n?.supervisor?.close();const i={config:t,retry:new el,status:"connecting"};return a.set(e,i),n?.socket?.close(1e3,"Reverse tunnel reconnecting."),l(e,i)},p=(e,t)=>e.tunnelUrl===t.tunnelUrl&&e.keyId===t.keyId&&e.secret===t.secret;return{connectConfigured:()=>{c=!1;const n=new Map,s=r.resolvedControlPlaneAccess(),o=new Set;for(const{connection:t,pairing:r}of s.connections){if(!t.enabled)continue;if(!r){e.log.warn({nodeId:i,connectionId:t.id,pairingKeyId:t.pairingKeyId},"node agent control-plane connection has no pairing");continue}const s=gT(t.url);n.set(t.id,{tunnelUrl:s,keyId:r.keyId,secret:r.secret}),o.add(s)}const d=function(e){const t=e.controlPlaneTunnelUrl||process.env.TASK_HANDOFF_CONTROL_PLANE_TUNNEL_URL;return t?new URL(t).toString():void 0}(t);if(d&&!o.has(d)){const e=r.reverseTunnelSecret(process.env.TASK_HANDOFF_CONTROL_PLANE_URL,t.remoteSecret||process.env.TASK_HANDOFF_NODE_AGENT_REMOTE_SECRET,t.remoteKeyId||process.env.TASK_HANDOFF_NODE_AGENT_REMOTE_KEY_ID);n.set(`explicit:${d}`,{tunnelUrl:d,keyId:e?.keyId,secret:e?.secret}),o.add(d)}const l=s.hasPersistedAccess?void 0:function(){const e=process.env.TASK_HANDOFF_CONTROL_PLANE_URL;if(!e)return;const t=new URL(FA,e);return t.protocol="https:"===t.protocol?"wss:":"ws:",t.toString()}();if(l&&!o.has(l)){const e=r.reverseTunnelSecret(process.env.TASK_HANDOFF_CONTROL_PLANE_URL,t.remoteSecret||process.env.TASK_HANDOFF_NODE_AGENT_REMOTE_SECRET,t.remoteKeyId||process.env.TASK_HANDOFF_NODE_AGENT_REMOTE_KEY_ID);n.set(`bootstrap:${l}`,{tunnelUrl:l,keyId:e?.keyId,secret:e?.secret})}(e=>{for(const[t,n]of a)e.has(t)||(n.retry.cancel(),n.supervisor?.close(),a.delete(t),n.socket?.close(1e3,"Reverse tunnel configuration removed."));for(const[t,n]of e){const e=a.get(t);e&&p(e.config,n)||u(t,n)}})(n)},state:e=>{const t=a.get(e);if(!t)return;const n=t.supervisor?.diagnostics();return{status:t.status,...void 0===n?.pingRttMs?{}:{pingRttMs:n.pingRttMs},...void 0===n?.pingRttP95Ms?{}:{pingRttP95Ms:n.pingRttP95Ms},consecutiveReconnects:t.retry.attempts,...t.lastConnectedAt?{lastConnectedAt:t.lastConnectedAt}:{},...t.lastDisconnectedAt?{lastDisconnectedAt:t.lastDisconnectedAt}:{},...t.nextRetryAt?{nextRetryAt:t.nextRetryAt}:{},...t.error?{error:t.error}:{}}},closeAll:()=>{c=!0;for(const e of a.values())e.retry.cancel(),e.supervisor?.close(),e.socket?.close(1001,"Node agent shutting down.");a.clear()}}}({log:f.log,inject:e=>f.inject(e),nodeAgentEventForwarder:f.nodeAgentEventForwarder,nodeAgentState:y},g,r,E,I);f.decorate("nodeAgentReverseTunnels",A);const T=new jA({app:f,state:y,settings:l,config:u,source:d?"persisted":"bootstrap",onActiveListener:p,validateUpdate:()=>{const e=y.listInstances().filter(e=>!["created","stopped","failed"].includes(e.status)).filter(e=>"reachable"!==e.targetStatus||!hs(e.capabilities).features.nodeAgentConnectionUpdate);if(e.length)throw Object.assign(new Error(`Cannot change the node agent port while ${e.length} controlled instance(s) cannot switch endpoints live.`),{statusCode:409,code:"NODE_AGENT_LISTENER_LIVE_UPDATE_UNSUPPORTED",details:{instanceIds:e.map(e=>e.id)}})},synchronizeUpdate:async()=>{const t=y.listInstances().filter(e=>!["created","stopped","failed"].includes(e.status));await Promise.all(t.map(async t=>{const n=await _(t);return _b(e.fetchImpl||fetch,t,n).then(e=>{if("applied"!==e)throw new Error(`Controlled instance ${t.id} did not apply the node-agent endpoint update (${e}).`)})}))}});let w,b;f.decorate("nodeAgentListenerManager",T),function(e){let t=!1;const n=async n=>{if(!t){t=!0,A.closeAll(),w?.close(),b?.close();try{await e.close()}finally{process.exitCode=n?0:process.exitCode}}},i=()=>{n("SIGINT")},s=()=>{n("SIGTERM")};process.once("SIGINT",i),process.once("SIGTERM",s),e.addHook("onClose",async()=>{process.off("SIGINT",i),process.off("SIGTERM",s)})}(f),f.addHook("onClose",async()=>{w?.close(),b?.close(),a.release()});try{await f.ready(),w=await async function(e,t){Ll(t);const n=i.createServer((t,n)=>{e.server.emit("request",t,n)});return n.on("upgrade",(t,n,i)=>{e.server.emit("upgrade",t,n,i)}),await new Promise((e,i)=>{n.once("error",i),n.listen(t,()=>{n.off("error",i),e()})}),n}(f,m),o("ipc listener ready",{ipcPath:m}),h&&(b=await async function(e,t){Ll(t);const n=i.createServer((t,n)=>{lb.add(t),e.server.emit("request",t,n)});return await new Promise((e,i)=>{n.once("error",i),n.listen(t,()=>{n.off("error",i),e()})}),n}(f,h)),await T.start(),A.connectConfigured(),f.nodeAgentStartRuntimeAvailabilityMonitor?.(),f.nodeAgentStartRecoverySupervisor?.(),f.nodeAgentStartWslSessionSupervisor?.()}catch(e){throw await f.close(),e}}catch(e){throw o("startup failed",{error:e instanceof Error?e.message:String(e)}),a.release(),e}var c}const Nb="task-handoff-node-agent.service",Sb=`/etc/systemd/system/${Nb}`,vb="/etc/task-handoff/node-agent.env",Ob=["@task-handoff/node-agent","@task-handoff/controlled-instance"];function Rb(e,t,n){const i=e.run(t,n);if(0!==i.status){const e=function(e){return[e.stdout,e.stderr].filter(Boolean).map(e=>String(e).trim()).filter(Boolean).join("\n")}(i);throw new Error(`${t} ${n.join(" ")} failed${e?`:\n${e}`:""}`)}}function zb(e,t){for(const n of e.split(/\r?\n/)){const e=n.indexOf("=");if(!(e<0||n.slice(0,e).trim()!==t))return n.slice(e+1).trim()}}const xb={getuid:()=>process.getuid?.(),exists:t.existsSync,readText:e=>t.readFileSync(e,"utf8"),remove:(e,n)=>t.rmSync(e,n),run:(e,t)=>l.spawnSync(e,t,{encoding:"utf8"}),confirmDeleteData:async function(e){if(!R.stdin.isTTY||!R.stdout.isTTY)return!1;const t=O.createInterface({input:R.stdin,output:R.stdout});try{const n=await t.question(`Delete Node Agent data at ${e}? This removes identity, configuration, logs, and managed-instance metadata. Docker volumes are preserved. [y/N] `);return/^(?:y|yes)$/i.test(n.trim())}finally{t.close()}},log:e=>console.log(e)};function Cb(e){const t=Number(e);if(!Number.isInteger(t)||t<=0||t>65535)throw new Error("Port must be a valid TCP port.");return t}function kb(e){if("local-ipc"!==e&&"local-loopback"!==e)throw new Error("Connection mode must be local-ipc or local-loopback.");return e}function Db(e){const t=Number(e);if(!Number.isInteger(t)||t<=0)throw new Error("Expiry must be a positive integer.");return t}(async function(){const t=new e.Command;t.name("task-handoff-node-agent").description("Run a TaskHandoff node agent.").version(k("@task-handoff/cli")).option("--host <host>","Node agent host",process.env.TASK_HANDOFF_NODE_AGENT_HOST||"127.0.0.1").option("-p, --port <port>","Node agent port",Cb,Number(process.env.TASK_HANDOFF_NODE_AGENT_PORT)||8091).option("--data-dir <path>","Node agent data directory").option("--token <token>","Bearer token required by the control plane").option("--connection-mode <mode>","Local control connection mode",kb).option("--ipc-path <path>","Unix socket path used by local-ipc mode").option("--control-plane-tunnel-url <url>","Control plane reverse WebSocket tunnel URL").action(async e=>{await bb({host:e.host,port:e.port,dataDir:e.dataDir,token:e.token,connectionMode:e.connectionMode,ipcPath:e.ipcPath,controlPlaneTunnelUrl:e.controlPlaneTunnelUrl})}),t.command("invite").description("Create a one-time token for pairing this node agent with a control plane.").option("--endpoint <url>","Use the node-agent HTTP endpoint instead of its local IPC socket").option("--ipc-path <path>","Local node-agent IPC socket path").option("--data-dir <path>","Node-agent data directory used to locate its IPC socket").option("--token <token>","Bearer token for local node-agent access",process.env.TASK_HANDOFF_NODE_AGENT_TOKEN).option("--expires-in-ms <ms>","Invite expiry in milliseconds",Db).option("--json","Print raw JSON output").action(async e=>{const n=t.opts(),i=e.ipcPath||n.ipcPath||process.env.TASK_HANDOFF_NODE_AGENT_IPC_PATH,s=e.dataDir||n.dataDir||process.env.TASK_HANDOFF_NODE_AGENT_DATA_DIR,o=e.endpoint?void 0:i||Dl(s||Rl()),r=await async function(e){const t={"content-type":"application/json",...e.token?{authorization:`Bearer ${e.token}`}:{}},n=JSON.stringify({...e.expiresInMs?{expiresInMs:e.expiresInMs}:{}}),i=e.endpoint?await fetch(`${e.endpoint.replace(/\/$/,"")}/api/node-agent/pairing/invites`,{method:"POST",headers:t,body:n}):await Pl(e.ipcPath,"/pairing/invites",{method:"POST",headers:t,body:n}),s=await i.json().catch(()=>({}));if(!i.ok)throw new Error(s.error?.message||`Node agent pairing invite failed with HTTP ${i.status}`);const o="string"==typeof s.data?.joinToken?s.data.joinToken:"";if(!o)throw new Error("Node agent pairing invite response did not include a join token.");return{nodeId:"string"==typeof s.data?.nodeId?s.data.nodeId:"",joinToken:o,expiresAt:"string"==typeof s.data?.expiresAt?s.data.expiresAt:""}}({endpoint:e.endpoint,ipcPath:o,token:e.token,expiresInMs:e.expiresInMs});e.json?console.log(JSON.stringify(r,null,2)):(r.nodeId&&console.log(`Node: ${r.nodeId}`),console.log(`Join token: ${r.joinToken}`),r.expiresAt&&console.log(`Expires: ${r.expiresAt}`))}),t.command("connect").description("Connect this Node Agent to a reachable Control Plane.").requiredOption("--control-plane <url>","Public Control Plane base URL").requiredOption("--join-token <token>","One-time join token issued by the Control Plane").option("--control-plane-name <name>","Control Plane display name").option("--endpoint <url>","Use the Node Agent HTTP endpoint instead of its local IPC socket").option("--ipc-path <path>","Local Node Agent IPC socket path").option("--data-dir <path>","Node Agent data directory used to locate its IPC socket").option("--token <token>","Bearer token for local Node Agent access",process.env.TASK_HANDOFF_NODE_AGENT_TOKEN).option("--json","Print raw JSON output").action(async e=>{const n=t.opts(),i=e.ipcPath||n.ipcPath||process.env.TASK_HANDOFF_NODE_AGENT_IPC_PATH,s=e.dataDir||n.dataDir||process.env.TASK_HANDOFF_NODE_AGENT_DATA_DIR,o=e.endpoint?void 0:i||Dl(s||Rl()),r=await async function(e){const t={"content-type":"application/json",...e.token?{authorization:`Bearer ${e.token}`}:{}},n=JSON.stringify({controlPlaneUrl:e.controlPlane,joinToken:e.joinToken,...e.controlPlaneName?{controlPlaneName:e.controlPlaneName}:{},activate:!0}),i=e.endpoint?await fetch(`${e.endpoint.replace(/\/$/,"")}/api/node-agent/control-plane-connections`,{method:"POST",headers:t,body:n}):await Pl(e.ipcPath,"/control-plane-connections",{method:"POST",headers:t,body:n}),s=await i.json().catch(()=>({}));if(!i.ok)throw new Error(s.error?.message||`Node Agent connection failed with HTTP ${i.status}`);return s.data}({controlPlane:e.controlPlane,joinToken:e.joinToken,controlPlaneName:e.controlPlaneName,endpoint:e.endpoint,ipcPath:o,token:e.token});e.json?console.log(JSON.stringify(r,null,2)):(console.log(`Control Plane: ${String(r?.connection?.url||e.controlPlane)}`),console.log(`Connection: ${String(r?.tunnel?.status||"saved")}`))}),t.command("uninstall").description("Uninstall the Node Agent service and packages; data is preserved by default.").option("--data-dir <path>","Override the installed Node Agent data directory").option("--delete-data","Delete Node Agent data without prompting").option("--keep-data","Preserve Node Agent data without prompting").action(async e=>{await async function(e,t=xb){if(e.deleteData&&e.keepData)throw new Error("--delete-data and --keep-data cannot be used together.");if(0!==t.getuid())throw new Error("Run this command as root so the Node Agent service and packages can be removed.");const i=t.exists(vb)?t.readText(vb):"",s=function(e,t){if(e.dataDir?.trim())return n.resolve(e.dataDir.trim());if(t.exists(vb)){const e=zb(t.readText(vb),"TASK_HANDOFF_NODE_AGENT_DATA_DIR");if(e)return n.resolve(e)}return n.resolve(Rl())}(e,{exists:e=>e===vb&&Boolean(i),readText:()=>i});if(s===n.parse(s).root)throw new Error(`Refusing to use a filesystem root as the Node Agent data directory: ${s}`);const o=zb(i,"TASK_HANDOFF_NPM_COMMAND")||process.env.TASK_HANDOFF_NPM_COMMAND||"npm";if(t.exists(Sb)){const e=t.readText(Sb);if(!/^ExecStart=\S*task-handoff-node-agent(?:\s|$)/m.test(e))throw new Error(`Refusing to remove ${Nb} because it is not owned by a standalone Node Agent installation.`);Rb(t,"systemctl",["disable","--now",Nb]),t.remove(Sb,{force:!0}),Rb(t,"systemctl",["daemon-reload"])}Rb(t,o,["uninstall","--global",...Ob]),t.remove(vb,{force:!0}),t.log("TaskHandoff Node Agent service and packages were removed.");const r=!!e.deleteData||!e.keepData&&await t.confirmDeleteData(s);return r?(t.remove(s,{recursive:!0,force:!0}),t.log(`Node Agent data was deleted from ${s}.`)):t.log(`Node Agent data was preserved at ${s}.`),{dataDir:s,dataDeleted:r}}(e)}),await t.parseAsync(process.argv)})().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});
1
+ "use strict";var e=require("commander"),t=require("node:fs"),n=require("node:path"),i=require("node:http"),s=require("node:os"),r=require("node:url"),o=require("fastify"),a=require("@fastify/websocket"),c=require("zod"),d=require("node:crypto"),l=require("node:child_process"),u=require("@noble/hashes/sha256"),p=require("node-pty"),m=require("write-file-atomic"),h=require("ws"),g=require("node:net"),f=require("node:stream"),y=require("node:fs/promises"),I=require("node:stream/promises"),_=require("tar"),E=require("node:async_hooks"),A=require("drizzle-orm"),T=require("drizzle-orm/sqlite-core"),b=require("node:util"),w=require("node:sqlite"),S=require("drizzle-orm/node-sqlite"),N=require("semver"),v=require("cron-parser"),O=require("node:readline/promises"),R=require("node:process"),z="undefined"!=typeof document?document.currentScript:null;function x(e,n){try{const i=JSON.parse(t.readFileSync(e,"utf8"));if(n&&i.name!==n)return;return"string"==typeof i.version&&i.version.trim()?i.version.trim():void 0}catch{return}}function C(e){if(e)try{return n.dirname(t.realpathSync(e))}catch{return}}function k(e,t=process.env,i=e){const s=t.TASK_HANDOFF_VERSION?.trim();if(s)return s;const r=i.split("/").at(-1),o=process.argv[1]?n.resolve(process.argv[1]):void 0,a=o?n.dirname(o):void 0,c=[C(o),a,process.cwd()].filter(e=>Boolean(e));for(const t of new Set(c)){let i=t;for(;;){const t=x(n.join(i,"package.json"),e);if(t)return t;const s=n.dirname(i);if(s===i)break;i=s}}let d;for(const e of new Set(c)){let t=e;for(;;){if(r){const e=x(n.join(t,"packages",r,"package.json"),i);if(e)return e}d||=x(n.join(t,"package.json"));const e=n.dirname(t);if(e===t)break;t=e}}return d||"unknown"}const D={perMessageDeflate:{threshold:256,serverNoContextTakeover:!0,clientNoContextTakeover:!0,concurrencyLimit:4,zlibDeflateOptions:{level:1}}};function L(e){return e.readyState===(e.OPEN??1)}function P(e){const t=Buffer.isBuffer(e)?e.toString("utf8"):"string"==typeof e?e:"";if(Buffer.byteLength(t,"utf8")<=123)return t;let n="";for(const e of t){const t=`${n}${e}`;if(Buffer.byteLength(t,"utf8")>123)break;n=t}return n}function M(e){if("number"==typeof e&&Number.isInteger(e))return e>=3e3&&e<=4999||e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e?e:void 0}function j(e,t,n){e.close(M(t),P(n)||void 0)}function U(e,t,n,i){if(L(e))for(const e of t.splice(0))if(i(e),!n(e))return}function F(e,t,n={}){const i=n.pendingFrameLimit??256,s=n.maxFrameBytes??8388608,r=n.maxTotalBytes??1073741824,o=n.maxBufferedBytes??16777216;let a=!1,c=L(t);const d=[],l=[];let u,p=0,m=0,h=0;const g=e=>Buffer.isBuffer(e)||e instanceof ArrayBuffer||ArrayBuffer.isView(e)?e.byteLength:Buffer.byteLength("string"==typeof e?e:String(e),"utf8"),f=(i,o)=>{const a=g(o);return h+=a,n.onFrame?.(i,a),!(a>s||h>r)||(j(e,1009,"WebSocket bridge traffic limit exceeded."),j(t,1009,"WebSocket bridge traffic limit exceeded."),!1)},y=()=>{u&&(clearTimeout(u),u=void 0)},I=(n,i)=>{const s=i.bytes;if((n.bufferedAmount??0)+s>o)return j(e,1013,"WebSocket bridge consumer is too slow."),j(t,1013,"WebSocket bridge consumer is too slow."),!1;try{return function(e,t){e.send(t.data,{binary:t.isBinary,compress:!1})}(n,i),!0}catch{return j(e,1011,"WebSocket bridge send failed."),j(t,1011,"WebSocket bridge send failed."),!1}},_=(n,s,r)=>{if(s.length>=i)return j(e,1011,"WebSocket bridge pending frame limit exceeded."),void j(t,1011,"WebSocket bridge pending frame limit exceeded.");const a="upstream"===n?p:m;if((("upstream"===n?t:e).bufferedAmount??0)+a+r.bytes>o)return j(e,1013,"WebSocket bridge consumer is too slow."),void j(t,1013,"WebSocket bridge consumer is too slow.");s.push(r),"upstream"===n?p+=r.bytes:m+=r.bytes};return n.upstreamOpenTimeoutMs&&!c&&(u=setTimeout(()=>{c||a||(j(e,1011,"Upstream websocket did not open."),j(t))},n.upstreamOpenTimeoutMs)),e.on("open",()=>U(e,l,t=>I(e,t),e=>{m-=e.bytes})),t.on("open",()=>{y(),c=!0,n.onUpstreamOpen?.(),U(t,d,e=>I(t,e),e=>{p-=e.bytes})}),e.on("message",(e,n=!1)=>{if(!f("client-to-upstream",e))return;const i={data:e,isBinary:Boolean(n),bytes:g(e)};L(t)?I(t,i):_("upstream",d,i)}),t.on("message",(t,n=!1)=>{if(!f("upstream-to-client",t))return;const i={data:t,isBinary:Boolean(n),bytes:g(t)};L(e)?I(e,i):_("client",l,i)}),t.on("close",(t,i)=>{y(),n.onUpstreamClose?.(t,i),(c||a||!n.onUpstreamCloseBeforeOpen?.())&&j(e,t,i)}),t.on("error",t=>{n.onUpstreamError?.(t),(c||a||!n.onUpstreamErrorBeforeOpen?.(t))&&j(e)}),e.on("close",(e,i)=>{y(),a=!0,n.onClientClose?.(e,i),j(t,e,i)}),e.on("error",e=>{y(),a=!0,n.onClientError?.(e),j(t,1011,"WebSocket bridge client failed.")}),{close:(n,i)=>{y(),j(t,n,i),j(e,n,i)}}}var $,H,B=function(){if(H)return $;H=1;const e=t,{spawnSync:n}=l;return $={processStartIdentity:function(t,i=process.platform){if(Number.isInteger(t)&&!(t<=0)){if("linux"===i)try{const n=e.readFileSync(`/proc/${t}/stat`,"utf8"),i=n.lastIndexOf(")");if(i<0)return;const s=n.slice(i+2).trim().split(/\s+/)[19];return s?`linux:${s}`:void 0}catch{return}if(["darwin","freebsd","openbsd","aix","sunos"].includes(i)){const e=n("ps",["-o","lstart=","-p",String(t)],{encoding:"utf8",timeout:1e3}),s=0===e.status?e.stdout.trim().replace(/\s+/g," "):"";return s?`${i}:${s}`:void 0}if("win32"===i){const e=n("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${t} -ErrorAction Stop).StartTime.ToUniversalTime().Ticks`],{encoding:"utf8",timeout:2e3}),i=0===e.status?e.stdout.trim():"";return/^\d+$/.test(i)?`win32:${i}`:void 0}}}}}();class q extends Error{code;lockPath;owner;constructor(e,t,n={}){const i=t?.pid?` pid ${t.pid}`:"";super(`${n.label||"Process"} is already running${i}. Lock: ${e}`),this.name="ProcessSingletonError",this.code=n.code||"PROCESS_ALREADY_RUNNING",this.lockPath=e,this.owner=t}}function V(e){return n.join(e,"owner.json")}function G(e){return n.join(e,"initializing.json")}function W(e){return n.join(e,"recovering.json")}function K(e){return Number.isInteger(e)&&Number(e)>0}function Y(e){try{const n=JSON.parse(t.readFileSync(V(e),"utf8"));if(K(n.pid)&&"string"==typeof n.startTime){const e=n;return{pid:e.pid,hostname:"string"==typeof e.hostname&&e.hostname?e.hostname:s.hostname(),component:e.component||"server-update",command:"string"==typeof e.command?e.command:"",acquiredAt:"string"==typeof e.createdAt&&Number.isFinite(Date.parse(e.createdAt))?e.createdAt:new Date(0).toISOString(),token:"string"==typeof e.token&&e.token?e.token:`legacy:${e.pid}:${e.startTime}`,startIdentity:e.startTime.startsWith("linux:")?e.startTime:`linux:${e.startTime}`}}if(!(K(n.pid)&&"string"==typeof n.hostname&&n.hostname&&"string"==typeof n.command&&"string"==typeof n.acquiredAt&&Number.isFinite(Date.parse(n.acquiredAt))&&"string"==typeof n.token&&n.token))return;return n}catch{return}}const X=Y;function J(e){if(!K(e))return!1;try{return process.kill(Number(e),0),!0}catch(e){return"EPERM"===e.code}}function Q(e){if(!e||!J(e.pid))return!1;if(!e.startIdentity)return!0;const t=B.processStartIdentity(e.pid);return void 0===t||t===e.startIdentity}function Z(e,i){const s=n.join(e,`.owner-${i.token}.tmp`);t.writeFileSync(s,`${JSON.stringify(i,null,2)}\n`,{encoding:"utf8",mode:384,flag:"wx"});const r=te(e);if(r?.token!==i.token)throw ie(s),new Error(`Process lock initialization was superseded: ${e}`);t.renameSync(s,V(e)),ie(G(e))}function ee(e,i,s){const r=X(e);if(r?.token!==i.token)return!1;const o={...i};for(const[e,t]of Object.entries(s))void 0===t?delete o[e]:Object.assign(o,{[e]:t});const a=n.join(e,`.owner-update-${i.token}-${d.randomUUID()}.tmp`);try{if(t.writeFileSync(a,`${JSON.stringify(o,null,2)}\n`,{encoding:"utf8",mode:384,flag:"wx"}),X(e)?.token!==i.token)return!1;t.renameSync(a,V(e));for(const e of Object.keys(i))delete i[e];return Object.assign(i,o),!0}catch(e){if("ENOENT"===e.code)return!1;throw e}finally{ie(a)}}function te(e){try{return JSON.parse(t.readFileSync(G(e),"utf8"))}catch{return}}function ne(e){const t=te(e);return K(t?.pid)&&Q({pid:t.pid,startIdentity:t.startIdentity})}function ie(e){try{t.unlinkSync(e)}catch(e){if("ENOENT"!==e.code)throw e}}function se(){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,20)}function re(e){try{const n=te(e),i=Date.parse(n?.startedAt||"");return Number.isFinite(i)?Math.max(0,Date.now()-i):Math.max(0,Date.now()-t.statSync(e).mtimeMs)}catch{return 0}}function oe(e,i){try{return t.writeFileSync(W(e),`${JSON.stringify({token:i,pid:process.pid,startedAt:(new Date).toISOString()})}\n`,{encoding:"utf8",mode:384,flag:"wx"}),!0}catch(s){if("EEXIST"===s.code)return!!function(e){const i=W(e),s=ae(i),r=Date.parse(s?.startedAt||"");if(J(s?.pid)||Number.isFinite(r)&&Date.now()-r<2e3)return!1;const o=n.join(e,`.recovering-${d.randomUUID()}.stale`);try{t.renameSync(i,o)}catch(e){if(["ENOENT","EEXIST"].includes(e.code||""))return!1;throw e}const a=ae(o);if(a?.token===s?.token)return ie(o),!0;try{t.linkSync(o,i)}catch(e){if("EEXIST"!==e.code)throw e}finally{ie(o)}return!1}(e)&&oe(e,i);if("ENOENT"===s.code)return!1;throw s}}function ae(e){try{return JSON.parse(t.readFileSync(e,"utf8"))}catch{return}}function ce(e,t){return ae(W(e))?.token===t}function de(){return(new Date).toISOString()}const le=6048e5;function ue(e,t=Date.now()){return`${t}-${e}`}const pe=/(\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z)$/;function me(e){const t=e.split("-",1)[0];if(/^\d+$/.test(t))return Number(t);const n=pe.exec(e)?.[1];if("string"!=typeof n)return;const i=Date.parse(n.replace(/T(\d{2})-(\d{2})-(\d{2})-(\d{3})Z$/,"T$1:$2:$3.$4Z"));return Number.isFinite(i)?i:void 0}function he(e,t){const i=n.resolve(e),s=n.resolve(i,t);if(n.dirname(s)!==i||n.basename(s)!==t)throw new Error(`Retention entry is not a direct child of its managed root: ${t}`);return s}function ge(e){if(t.existsSync(e)){const n=t.lstatSync(e);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`Managed persistence path must be a real directory: ${e}`)}t.mkdirSync(e,{recursive:!0,mode:448}),t.chmodSync(e,448)}const fe=c.z.enum(["openai-responses","openai-chat-completions","anthropic-messages"]),ye="2026-08-27",Ie="2026-10-02",_e=c.z.object({upstreamName:c.z.string().trim().min(1).max(240).optional(),name:c.z.string().trim().min(1).max(240),order:c.z.number().int().min(0).max(1e6)}).strip(),Ee={id:c.z.string().trim().min(1).max(120),protocols:c.z.array(fe).min(1).max(3),modelNames:c.z.array(_e).min(1).max(256)},Ae=c.z.object({protocolVersion:c.z.literal(ye),instanceId:c.z.string().trim().min(1).max(120),entities:c.z.array(c.z.object({...Ee,endpoint:c.z.string().trim().min(1).max(2048),key:c.z.string().trim().min(1).max(4096)}).strip()).max(64),updatedAt:c.z.string().datetime()}).strip(),Te=c.z.object({protocolVersion:c.z.literal(Ie),instanceId:c.z.string().trim().min(1).max(120),entities:c.z.array(c.z.object({...Ee,routes:c.z.array(c.z.object({protocol:fe,baseUrl:c.z.string().trim().min(1).max(2048)}).strip()).min(1).max(3)}).strip().superRefine((e,t)=>{const n=new Set;for(const[i,s]of e.routes.entries())n.has(s.protocol)&&t.addIssue({code:"custom",path:["routes",i,"protocol"],message:`Duplicate relay route for ${s.protocol}.`}),n.add(s.protocol)})).max(64),updatedAt:c.z.string().datetime()}).strip(),be=c.z.discriminatedUnion("protocolVersion",[Ae,Te]);function we(e){return e.upstreamName?.trim()||e.name.trim()}function Se(e,t){const n=e.find(e=>we(e)===t);if(n)return n;const i=e.filter(e=>e.name===t);return 1===i.length?i[0]:void 0}const Ne=c.z.object({id:c.z.string().trim().min(1).max(120),protocols:c.z.array(fe).min(1).max(3),modelNames:c.z.array(_e).min(1).max(256)}).strip();function ve(e,t){if(!e||"object"!=typeof e||Array.isArray(e))return e;const n=e,i=n.protocolVersion===Ie;return{protocolVersion:n.protocolVersion,instanceId:n.instanceId,entities:Array.isArray(n.entities)?n.entities.map((e,t)=>{if(!e||"object"!=typeof e||Array.isArray(e))return e;const n=e,s={id:n.id,protocols:n.protocols,modelNames:Array.isArray(n.modelNames)?n.modelNames.map((e,t)=>{if(!e||"object"!=typeof e||Array.isArray(e))return e;const n=e;for(const e of Object.keys(n));return{..."string"==typeof n.upstreamName?{upstreamName:n.upstreamName}:{},name:n.name,order:n.order}}):n.modelNames};if(i)return{...s,routes:Array.isArray(n.routes)?n.routes.map((e,t)=>{if(!e||"object"!=typeof e||Array.isArray(e))return e;const n=e;for(const e of Object.keys(n));return{protocol:n.protocol,baseUrl:n.baseUrl}}):n.routes};for(const e of Object.keys(n));return{...s,endpoint:n.endpoint,key:n.key}}):n.entities,updatedAt:n.updatedAt}}c.z.object({protocolVersion:c.z.union([c.z.literal(ye),c.z.literal(Ie)]),instanceId:c.z.string().trim().min(1).max(120),updatedAt:c.z.string().datetime(),entities:c.z.array(Ne).max(64)}).strip();const Oe=c.z.string().trim().min(1).max(160),Re=Oe.optional(),ze=c.z.string().trim().min(1).max(120),xe=20971520,Ce=512e3,ke=Ce,De=xe,Le=41943040,Pe="ai.sessions",Me="ai-session.snapshot",je="ai-session.patch",Ue="ai-session.removed",Fe="ai-session.message-delta",$e="ai-session.timeline-item",He="ai-session.timeline-item-delta",Be=c.z.string().trim().min(1).max(80),qe=c.z.enum(["app-session","ai-session"]),Ve=c.z.enum(["image","file"]),Ge={scopeType:c.z.enum(["session","create-request"]),scopeId:c.z.string().trim().min(1).max(160),kind:Ve,name:c.z.string().trim().min(1).max(240),mime:c.z.string().trim().min(1).max(120)};c.z.object({...Ge,size:c.z.coerce.number().int().positive().max(xe)}).strict();const We=c.z.string().regex(/^cia_[a-f0-9]{24}$/);c.z.object({attachmentId:We,...Ge,size:c.z.number().int().positive().max(xe)}).strict(),c.z.object({offset:c.z.coerce.number().int().nonnegative()}).strict(),c.z.object({attachmentId:We,offset:c.z.number().int().nonnegative()}),c.z.object({id:We,kind:Ve,name:c.z.string().trim().min(1).max(240),mime:c.z.string().trim().min(1).max(120),size:c.z.number().int().positive().max(xe),expiresAt:c.z.string().datetime()});const Ke=c.z.object({id:c.z.string().trim().min(1).max(120),kind:Ve,name:c.z.string().trim().min(1).max(240),mime:c.z.string().trim().min(1).max(120),size:c.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER)}),Ye=c.z.enum(["available","expired","missing"]),Xe=Ke.extend({contentState:Ye.default("available")}).strict(),Je=c.z.object({id:c.z.string().trim().min(1).max(240),text:c.z.string(),attachments:c.z.array(Xe).max(6).default([])}).strict(),Qe=c.z.enum(["running","waiting","idle","failed"]),Ze=c.z.enum(["thinking","tool","editing","approval","responding","unknown"]),et=c.z.object({id:c.z.string().trim().min(1).max(240).optional(),kind:c.z.string().trim().min(1).max(80).optional(),name:c.z.string().trim().min(1).max(120),inputPreview:c.z.string().trim().max(500).optional(),startedAt:c.z.string().datetime().optional()}).strict(),tt=c.z.enum(["running","completed","failed","waiting"]),nt=c.z.object({id:c.z.string().trim().min(1).max(240),turnId:c.z.string().trim().min(1).max(240)}).strict(),it=nt.extend({type:c.z.literal("user-message"),text:c.z.string(),attachments:c.z.array(Xe).max(6).optional()}).strict(),st=nt.extend({type:c.z.literal("ai-message"),text:c.z.string()}).strict(),rt=nt.extend({type:c.z.literal("activity"),activityKind:c.z.string().trim().min(1).max(120),title:c.z.string().trim().min(1).max(240),status:tt.optional(),summary:c.z.string().max(4e3).optional(),input:c.z.string().max(1e5).optional(),output:c.z.string().max(1e6).optional(),paths:c.z.array(c.z.string().trim().min(1).max(4096)).max(500).optional(),exitCode:c.z.number().int().optional(),durationMs:c.z.number().int().nonnegative().optional()}).strict(),ot=c.z.discriminatedUnion("type",[it,st,rt]);c.z.object({sessionId:c.z.string().trim().min(1).max(120),providerSessionId:c.z.string().trim().min(1).max(240),items:c.z.array(ot),generatedAt:c.z.string().datetime()}).strict();const at=c.z.object({sessionId:c.z.string().trim().min(1).max(120),turnId:c.z.string().trim().min(1).max(240),items:c.z.array(ot),generatedAt:c.z.string().datetime()}).strict(),ct=c.z.enum(["pending-init","running","interrupted","completed","errored","shutdown","not-found"]),dt=c.z.enum(["started","interacted","interrupted"]),lt=c.z.object({threadId:c.z.string().trim().min(1).max(240),path:c.z.string().trim().max(4096).optional(),status:ct,activity:dt.optional(),message:c.z.string().trim().max(1e3).optional(),updatedAt:c.z.string().datetime()}).strict();function ut(e){return"completed"!==e.status}const pt=c.z.array(lt).max(50).transform(e=>e.filter(ut)),mt=c.z.object({toolCalls:c.z.number().int().min(0).default(0),edits:c.z.number().int().min(0).default(0),approvals:c.z.number().int().min(0).default(0)}).strict().default({toolCalls:0,edits:0,approvals:0}),ht=c.z.object({send:c.z.boolean().optional(),interrupt:c.z.boolean().optional(),approval:c.z.boolean().optional(),fork:c.z.boolean().optional(),rename:c.z.boolean().optional(),openApp:c.z.boolean().optional(),close:c.z.boolean().optional()}),gt=c.z.string().trim().min(1).max(240),ft=c.z.discriminatedUnion("kind",[c.z.object({kind:c.z.literal("fork"),parentProviderSessionId:gt,throughTurnId:c.z.string().trim().min(1).max(240).optional()}).strict(),c.z.object({kind:c.z.literal("subagent"),parentProviderSessionId:gt}).strict()]),yt=c.z.preprocess(function(e){if(!e||"object"!=typeof e||Array.isArray(e))return;const t=e;if("fork"===t.kind){const e=ft.safeParse({kind:"fork",parentProviderSessionId:t.parentProviderSessionId,..."string"==typeof t.throughTurnId?{throughTurnId:t.throughTurnId}:{}});return e.success?e.data:void 0}if("subagent"===t.kind){const e=ft.safeParse({kind:"subagent",parentProviderSessionId:t.parentProviderSessionId});return e.success?e.data:void 0}},ft.optional()),It=c.z.union([Ke.extend({source:c.z.object({type:c.z.literal("inline"),encoding:c.z.literal("base64"),data:c.z.string().min(1).max(31457280)}).strict()}).strict().superRefine((e,t)=>{const n="image"===e.kind?xe:Ce;(e.size<=0||("file"===e.kind?e.size>=n:e.size>n))&&t.addIssue({code:c.z.ZodIssueCode.custom,path:["size"],message:`Inline ${e.kind} must be between 1 byte and ${n} bytes.`})}),Ke.extend({source:c.z.object({type:c.z.literal("runtime-path"),path:c.z.string().trim().min(1).max(4096)}).strict()}).strict()]),_t=Ke.extend({sourceType:c.z.enum(["inline","runtime-path"])}).strict(),Et=c.z.union([c.z.object({id:c.z.string().trim().min(1).max(120),kind:Ve.optional(),source:c.z.object({type:c.z.literal("upload-ref")}).strict().default({type:"upload-ref"})}).strict(),c.z.object({id:c.z.string().trim().min(1).max(120),kind:Ve,name:c.z.string().trim().min(1).max(240),mime:c.z.string().trim().min(1).max(120),size:c.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),source:c.z.object({type:c.z.literal("runtime-path"),path:c.z.string().trim().min(1).max(4096)}).strict()}).strict()]),At=c.z.enum(["auto","queue","steer","immediate"]),Tt=c.z.enum(["ask","auto-review","full-access"]),bt=c.z.enum(["review","rename","goal","compact"]);c.z.object({command:bt,argument:c.z.string().trim().max(4e3).optional()}).strict().superRefine((e,t)=>{"rename"!==e.command||e.argument||t.addIssue({code:"custom",path:["argument"],message:"Rename requires a thread name."}),"review"!==e.command&&"compact"!==e.command||!e.argument||t.addIssue({code:"custom",path:["argument"],message:`${e.command} does not accept an argument.`})}),c.z.object({command:bt,value:c.z.string().max(4e3).optional(),turnId:c.z.string().trim().min(1).max(240).optional()}).strict(),c.z.object({title:c.z.string().trim().max(120),expectedTitle:c.z.string().trim().max(240).optional(),clientRequestId:Oe}).strict(),c.z.object({disposition:c.z.enum(["renamed","already-named"]),aiSessionId:c.z.string().trim().min(1).max(120),appSessionId:c.z.string().trim().min(1).max(120).optional(),title:c.z.string().trim().max(120)}).strict(),c.z.enum(["skill","app","plugin"]);const wt=c.z.object({name:c.z.string().trim().min(1).max(240),path:c.z.string().trim().min(1).max(4096)}),St=c.z.discriminatedUnion("kind",[wt.extend({kind:c.z.literal("skill"),path:c.z.string().trim().min(1).max(4096).refine(e=>e.startsWith("/"),"Skill paths must be absolute.")}).strict(),wt.extend({kind:c.z.literal("app"),path:c.z.string().trim().min(7).max(4096).regex(/^app:\/\/[^\s/]+$/,"App paths must use app://<id>.")}).strict(),wt.extend({kind:c.z.literal("plugin"),path:c.z.string().trim().min(10).max(4096).regex(/^plugin:\/\/[^\s/]+$/,"Plugin paths must use plugin://<id>.")}).strict()]),Nt=c.z.array(St).max(20).default([]),vt=c.z.enum(["plugin","skill","file","directory","app"]),Ot=c.z.object({kind:vt,name:c.z.string().trim().min(1).max(240),description:c.z.string().trim().max(1e3).optional(),path:c.z.string().trim().min(1).max(4096),icon:c.z.string().trim().max(4096).optional()}).strict().superRefine((e,t)=>{"skill"!==e.kind||e.path.startsWith("/")||t.addIssue({code:"custom",path:["path"],message:"Skill paths must be absolute."}),"app"!==e.kind||/^app:\/\/[^\s/]+$/.test(e.path)||t.addIssue({code:"custom",path:["path"],message:"App paths must use app://<id>."}),"plugin"!==e.kind||/^plugin:\/\/[^\s/]+$/.test(e.path)||t.addIssue({code:"custom",path:["path"],message:"Plugin paths must use plugin://<id>."}),"file"!==e.kind&&"directory"!==e.kind||!e.path.startsWith("/")&&!e.path.split(/[\\/]+/).includes("..")||t.addIssue({code:"custom",path:["path"],message:"File and directory paths must be relative to the session cwd."})}),Rt=c.z.object({category:c.z.enum(["skills","plugins","apps","files"]),code:c.z.string().trim().min(1).max(160),message:c.z.string().trim().min(1).max(2e3)}).strict();c.z.object({sessionId:c.z.string().trim().min(1).max(120),providerSessionId:c.z.string().trim().min(1).max(240),cwd:c.z.string().trim().min(1).max(4096),candidates:c.z.array(Ot).max(1e3).default([]),diagnostics:c.z.array(Rt).max(20).default([])}).strict(),c.z.object({query:c.z.string().trim().max(240).default("")}).strict(),c.z.object({sessionId:c.z.string().trim().min(1).max(120),cwd:c.z.string().trim().min(1).max(4096),query:c.z.string().trim().max(240),requestId:c.z.string().trim().min(1).max(160),candidates:c.z.array(Ot.refine(e=>"file"===e.kind||"directory"===e.kind,"File search only returns files and directories.")).max(200).default([]),complete:c.z.boolean().default(!1)}).strict();const zt=c.z.object({message:c.z.string().trim().min(1).max(2e4),mode:At.optional(),permissionMode:Tt.optional(),clientRequestId:Re}),xt=zt.extend({attachments:c.z.array(It).max(6).default([]),references:Nt}).strict().superRefine((e,t)=>{e.attachments.reduce((e,t)=>e+("inline"===t.source.type?t.size:0),0)>Le&&t.addIssue({code:c.z.ZodIssueCode.custom,path:["attachments"],message:"Inline attachments must be 41943040 bytes or less in total."})}),Ct=zt.extend({attachments:c.z.array(Et).max(6).default([]),references:Nt}).strict(),kt=c.z.object({type:c.z.literal("runtime-path"),path:c.z.string().trim().min(1).max(4096).refine(e=>e.startsWith("/")||/^[A-Za-z]:[\\/]/.test(e),"Runtime paths must be absolute in the target controlled instance.")}).strict(),Dt=c.z.object({modelEntityId:c.z.string().trim().min(1).max(120),modelName:c.z.string().trim().min(1).max(240),modelUpstreamName:c.z.string().trim().min(1).max(240).optional()}).strict(),Lt=c.z.enum(["none","minimal","low","medium","high","xhigh","max","ultra"]),Pt=c.z.discriminatedUnion("type",[c.z.object({type:c.z.literal("current-folder"),branch:c.z.string().trim().min(1).max(1024)}).strict(),c.z.object({type:c.z.literal("existing-worktree"),repositoryContextId:c.z.string().trim().min(1).max(160),worktreeId:c.z.string().trim().min(1).max(160)}).strict(),c.z.object({type:c.z.literal("new-worktree"),branchName:c.z.string().trim().min(1).max(255),startRef:c.z.string().trim().min(1).max(2048),expectedSnapshotId:c.z.string().trim().min(1).max(160)}).strict()]),Mt=c.z.object({mode:c.z.enum(["current-folder","worktree"]),branch:c.z.string().trim().min(1).max(1024)}).strict();xt.safeExtend({agent:Be,cwd:kt,cwdFolderId:c.z.string().trim().min(1).max(120).optional(),gitSelection:Mt.optional(),workspaceSelection:Pt.optional(),clientRequestId:Oe,modelSelection:Dt.optional(),reasoningEffort:Lt.optional(),storyId:ze.optional()}).strict(),Ct.extend({agent:Be,cwdFolderId:c.z.string().trim().min(1).max(120).optional(),gitSelection:Mt.optional(),workspaceSelection:Pt.optional(),clientRequestId:Oe,modelSelection:Dt.optional(),reasoningEffort:Lt.optional(),storyId:ze.optional()}).strict(),c.z.object({clientRequestId:Oe,modelSelection:Dt}).strict(),c.z.object({sessionId:c.z.string().trim().min(1).max(120),accepted:c.z.literal(!0)}).strict(),c.z.object({clientRequestId:Oe,reasoningEffort:Lt}).strict(),c.z.object({cwdFolderId:c.z.string().trim().min(1).max(120).optional(),branch:c.z.string().trim().min(1).max(1024)}).strict(),c.z.object({sessionId:c.z.string().trim().min(1).max(120),accepted:c.z.literal(!0)}).strict(),c.z.object({storyId:ze.nullable()}).strict(),c.z.object({sessionId:c.z.string().trim().min(1).max(120),storyId:ze.optional()}).strict(),c.z.object({sessionId:c.z.string().trim().min(1).max(120),unread:c.z.boolean()}).strict(),c.z.object({path:c.z.string().trim().min(1).max(4096),lineCount:c.z.number().int().nonnegative(),tail:c.z.string()}).strict(),c.z.object({disposition:c.z.enum(["created","already-created"]),aiSessionId:c.z.string().trim().min(1).max(120),providerSessionId:c.z.string().trim().min(1).max(240),creationSource:c.z.literal("ai-session")}).strict();const jt=c.z.object({mode:c.z.enum(["current","managed-worktree"]).default("current")}).strict().default({mode:"current"});c.z.object({clientRequestId:Oe,throughTurnId:c.z.string().trim().min(1).max(240).optional(),workspace:jt.optional().default({mode:"current"})}).strict(),c.z.object({disposition:c.z.enum(["created","already-created"]),aiSessionId:c.z.string().trim().min(1).max(120),providerSessionId:c.z.string().trim().min(1).max(240),creationSource:c.z.literal("ai-session")}).strict(),c.z.object({clientRequestId:Oe}).strict(),c.z.object({disposition:c.z.enum(["opened","already-open"]),aiSessionId:c.z.string().trim().min(1).max(120),providerSessionId:c.z.string().trim().min(1).max(240),appSessionId:c.z.string().trim().min(1).max(120),creationSource:qe}).strict(),c.z.object({clientRequestId:Oe}).strict(),c.z.object({disposition:c.z.enum(["closed","already-closed"]),aiSessionId:c.z.string().trim().min(1).max(120),providerSessionId:c.z.string().trim().min(1).max(240),creationSource:qe}).strict(),c.z.object({disposition:c.z.enum(["cleared","already-cleared"]),aiSessionId:c.z.string().trim().min(1).max(120),clearedSessionIds:c.z.array(c.z.string().trim().min(1).max(120))}).strict(),c.z.object({code:c.z.enum(["invalid-request","not-found","unsupported","provider-unavailable","materialization-failed","open-app-failed","close-failed","conflict"]),message:c.z.string().trim().min(1).max(4e3),retryable:c.z.boolean().default(!1),aiSessionId:c.z.string().trim().min(1).max(120).optional(),providerSessionId:c.z.string().trim().min(1).max(240).optional()}).strict(),c.z.object({decision:c.z.enum(["allow","deny","skip"])}).strict(),c.z.object({expectedRevision:c.z.number().int().min(0),queueIds:c.z.array(c.z.string().trim().min(1).max(120)).max(100)}).strict(),c.z.object({paused:c.z.boolean()}).strict(),c.z.object({expectedRevision:c.z.number().int().min(0),message:c.z.string().trim().min(1).max(2e4),attachments:c.z.array(c.z.union([c.z.object({id:c.z.string().trim().min(1).max(120),source:c.z.object({type:c.z.literal("retained")}).strict()}).strict(),Et])).max(6).optional()}).strict(),c.z.object({code:c.z.string().trim().min(1).max(160),message:c.z.string(),instanceId:c.z.string().trim().min(1).max(160).optional(),nodeId:c.z.string().trim().min(1).max(160).optional(),route:c.z.string().trim().min(1).max(4096).optional()}).strict();const Ut=c.z.object({id:c.z.string().trim().min(1).max(120),messageId:c.z.string().trim().min(1).max(240).optional(),message:c.z.string().trim().min(1).max(2e4),attachments:c.z.array(_t).max(6).default([]),references:Nt,permissionMode:Tt.optional(),status:c.z.enum(["queued","sending","failed"]).default("queued"),createdAt:c.z.string().datetime(),updatedAt:c.z.string().datetime(),error:c.z.string().trim().max(4e3).optional()}).strict(),Ft=c.z.object({revision:c.z.number().int().min(0).default(0),pendingCount:c.z.number().int().min(0).default(0),paused:c.z.boolean().optional(),items:c.z.array(Ut).max(100).default([])}).strict().default({revision:0,pendingCount:0,items:[]}),$t=c.z.enum(["control","realtime","adapter-snapshot","transcript-tail","transcript-scan","process-scan","app-session"]),Ht=c.z.object({id:c.z.string().trim().min(1).max(240),status:c.z.enum(["running","completed"]),startedAt:c.z.string().datetime().optional(),completedAt:c.z.string().datetime().optional()}).strict(),Bt=c.z.object({id:c.z.string().trim().min(1).max(240),providerTurnId:c.z.string().trim().max(240).optional(),source:$t.optional(),userPrompt:c.z.string().trim().optional(),userMessages:c.z.array(Je).max(100).optional(),status:c.z.enum(["queued","running","waiting","completed","failed"]).default("running"),phase:Ze.optional(),summary:c.z.string().trim().max(1e3).optional(),lastMessage:c.z.string().trim().optional(),lastMessageItemId:c.z.string().trim().max(240).optional(),contextCompactions:c.z.array(Ht).max(20).optional(),revision:c.z.number().int().min(0).default(0),sourcePriority:c.z.number().int().min(0).max(100).optional(),snapshotVersion:c.z.number().int().min(0).optional(),observedAt:c.z.string().datetime().optional(),startedAt:c.z.string().datetime().optional(),updatedAt:c.z.string().datetime().optional(),completedAt:c.z.string().datetime().optional()}).strict(),qt=Bt.pick({id:!0,providerTurnId:!0,userPrompt:!0,userMessages:!0,status:!0,phase:!0,summary:!0,lastMessage:!0,contextCompactions:!0,startedAt:!0,updatedAt:!0,completedAt:!0}).strict(),Vt=c.z.object({id:c.z.string().trim().min(1).max(120),agent:Be,creationSource:qe.default("app-session"),appSessionId:c.z.string().trim().max(120).optional(),appId:c.z.string().trim().max(120).optional(),providerSessionId:c.z.string().trim().max(240).optional(),lineage:yt,providerMeta:c.z.record(c.z.string(),c.z.unknown()).optional(),modelSelection:Dt.optional(),reasoningEffort:Lt.optional(),storyId:ze.optional(),appBindingKeys:c.z.array(c.z.string().trim().min(1).max(240)).max(20).optional(),actions:ht.optional(),activeTurnId:c.z.string().trim().max(240).optional(),title:c.z.string().trim().max(240).optional(),cwd:c.z.string().trim().max(4096).optional(),cwdFolderId:c.z.string().trim().min(1).max(120).optional(),userPrompt:c.z.string().trim().optional(),turns:c.z.array(Bt).max(50).optional(),status:Qe.default("running"),phase:Ze.default("unknown"),summary:c.z.string().trim().max(1e3).optional(),lastMessage:c.z.string().trim().optional(),lastMessageItemId:c.z.string().trim().max(240).optional(),currentTool:et.optional(),toolCallsSinceLastMessage:c.z.number().int().min(0).default(0),subAgents:pt.default([]),transcriptPath:c.z.string().trim().max(4096).optional(),transcriptSize:c.z.number().int().min(0).optional(),startedAt:c.z.string().datetime(),updatedAt:c.z.string().datetime(),completedAt:c.z.string().datetime().optional(),error:c.z.string().trim().max(4e3).optional(),counters:mt,queue:Ft,unread:c.z.boolean().default(!1)}).strict(),Gt=Vt.pick({id:!0,appBindingKeys:!0,cwd:!0,error:!0,providerMeta:!0,modelSelection:!0,reasoningEffort:!0,queue:!0,subAgents:!0}).strict(),Wt=Bt.pick({id:!0,providerTurnId:!0,status:!0,phase:!0,revision:!0,startedAt:!0,updatedAt:!0,completedAt:!0}).extend({bodyRevision:c.z.string().trim().min(1).max(64)}).strict(),Kt=c.z.object({sessionId:c.z.string().trim().min(1).max(120),revision:c.z.string().trim().min(1).max(64),turns:c.z.array(Wt).max(50)}).strict(),Yt=c.z.object({sessionId:c.z.string().trim().min(1).max(120),revision:c.z.string().trim().min(1).max(64),turn:Bt}).strict(),Xt=c.z.string().trim().min(1).max(64),Jt=c.z.object({kind:c.z.literal("not-modified"),revision:Xt}).strict();c.z.discriminatedUnion("kind",[Jt,c.z.object({kind:c.z.literal("updated"),revision:Xt,detail:Gt}).strict()]),c.z.discriminatedUnion("kind",[Jt,c.z.object({kind:c.z.literal("updated"),revision:Xt,index:Kt}).strict()]),c.z.discriminatedUnion("kind",[Jt,c.z.object({kind:c.z.literal("updated"),revision:Xt,body:Yt}).strict()]);const Qt=c.z.object({session:Vt,provider:c.z.string().trim().min(1).max(80),action:c.z.enum(["send","queue","steer","interrupt","approval"]),decision:c.z.enum(["allow","deny","skip"]).optional(),turnId:c.z.string().trim().min(1).max(240).optional(),providerTurnId:c.z.string().trim().min(1).max(240).optional(),queueId:c.z.string().trim().min(1).max(120).optional()}).strict(),Zt=Qt.omit({session:!0}).extend({sessionId:c.z.string().trim().min(1).max(120),messageId:c.z.string().trim().min(1).max(240).optional()}).strict();c.z.object({sessionId:c.z.string().trim().min(1).max(120),queueRevision:c.z.number().int().min(0),action:c.z.enum(["retry","remove","edit","reorder","pause"]),queueId:c.z.string().trim().min(1).max(120).optional()}).strict(),c.z.union([Zt,Qt.transform(function(e){const t=e.session.turns?.at(-1),n=(e.queueId?e.session.queue?.items.find(t=>t.id===e.queueId)?.messageId:void 0)||("send"===e.action||"queue"===e.action||"steer"===e.action?t?.userMessages?.at(-1)?.id:void 0);return Zt.parse({sessionId:e.session.id,provider:e.provider,action:e.action,...e.decision?{decision:e.decision}:{},...e.turnId||e.session.activeTurnId||t?.id?{turnId:e.turnId||e.session.activeTurnId||t?.id}:{},...e.providerTurnId||t?.providerTurnId?{providerTurnId:e.providerTurnId||t?.providerTurnId}:{},...e.queueId?{queueId:e.queueId}:{},...n?{messageId:n}:{}})})]);const en=500,tn=365,nn=c.z.object({id:c.z.string().trim().min(1).max(120),agent:Be,creationSource:qe,providerSessionId:c.z.string().trim().min(1).max(240),lineage:yt,modelSelection:Dt.optional(),reasoningEffort:Lt.optional(),storyId:ze.optional(),title:c.z.string().trim().max(240).optional(),userPrompt:c.z.string().trim().optional(),lastMessage:c.z.string().trim().optional(),cwd:c.z.string().trim().min(1).max(4096),cwdFolderId:c.z.string().trim().min(1).max(120).optional(),lastActiveAt:c.z.string().datetime(),archivedAt:c.z.string().datetime()}).strict();c.z.object({schemaVersion:c.z.literal(1).default(1),items:c.z.array(nn).max(1e4).default([])}).strict(),c.z.object({items:c.z.array(nn).max(1e4).default([])}).strict(),c.z.object({item:nn,turns:c.z.array(qt).max(50).default([])}).strict(),c.z.object({modelSelection:Dt.optional(),reasoningEffort:Lt.optional()}).strict(),c.z.object({disposition:c.z.enum(["resumed","already-open"]),aiSessionId:c.z.string().trim().min(1).max(120),providerSessionId:c.z.string().trim().min(1).max(240),appSessionId:c.z.string().trim().min(1).max(120).optional(),creationSource:qe}).strict();const sn=Bt.omit({userMessages:!0}),rn=Vt.pick({id:!0,agent:!0,creationSource:!0,appSessionId:!0,appId:!0,providerSessionId:!0,lineage:!0,providerMeta:!0,modelSelection:!0,reasoningEffort:!0,storyId:!0,appBindingKeys:!0,actions:!0,activeTurnId:!0,title:!0,cwd:!0,cwdFolderId:!0,userPrompt:!0,turns:!0,status:!0,phase:!0,summary:!0,lastMessage:!0,lastMessageItemId:!0,currentTool:!0,toolCallsSinceLastMessage:!0,subAgents:!0,queue:!0,startedAt:!0,updatedAt:!0,error:!0,unread:!0}).extend({turns:c.z.array(sn).max(50).optional(),detailRevision:c.z.string().trim().min(1).max(64).optional(),turnsRevision:c.z.string().trim().min(1).max(64).optional(),latestTurnRef:c.z.object({id:Bt.shape.id,bodyRevision:c.z.string().trim().min(1).max(64)}).strict().optional(),turnCount:c.z.number().int().min(0).optional(),subAgentCount:c.z.number().int().min(0).optional(),lastUserMessageAt:c.z.string().datetime().optional()}).strict(),on=c.z.object({runningCount:c.z.number().int().min(0).default(0),waitingCount:c.z.number().int().min(0).default(0),staleCount:c.z.number().int().min(0).default(0),sessions:c.z.array(rn).default([]),updatedAt:c.z.string().datetime()}).strict(),an=c.z.object({streamId:c.z.string().trim().min(1).max(240),revision:c.z.number().int().min(0),lastEventAt:c.z.string().datetime(),snapshot:on}).strict();on.pick({runningCount:!0,waitingCount:!0,staleCount:!0,updatedAt:!0}).extend({idleCount:c.z.number().int().min(0).default(0),problemCount:c.z.number().int().min(0).default(0),revision:c.z.number().int().min(0).optional()});const cn=c.z.enum(["provider-event","app-session-created","app-session-updated","app-session-deleted","discovery-scan","control-action","heartbeat-sync","startup"]),dn=c.z.object({streamId:c.z.string().trim().min(1).max(240),instanceId:c.z.string().trim().min(1).max(160),nodeId:c.z.string().trim().min(1).max(160).optional(),revision:c.z.number().int().min(0),previousRevision:c.z.number().int().min(0).optional(),traceId:c.z.string().trim().min(1).max(160),generatedAt:c.z.string().datetime(),reason:cn}).strict(),ln=c.z.object({meta:dn,snapshot:on}).strict(),un=c.z.object({meta:dn,upserted:c.z.array(rn).default([]),removed:c.z.array(c.z.string().trim().min(1).max(120)).default([])}).strict(),pn=c.z.object({meta:dn,sessionIds:c.z.array(c.z.string().trim().min(1).max(120)).default([]),expiresAt:c.z.string().datetime()}).strict(),mn=c.z.object({instanceId:c.z.string().trim().min(1).max(160),nodeId:c.z.string().trim().min(1).max(160).optional(),sessionId:c.z.string().trim().min(1).max(120),providerSessionId:c.z.string().trim().min(1).max(240).optional(),turnId:c.z.string().trim().min(1).max(240),itemId:c.z.string().trim().min(1).max(240),delta:c.z.string().min(1),generatedAt:c.z.string().datetime()}).strict(),hn=mn.omit({instanceId:!0,nodeId:!0,providerSessionId:!0}).strict();c.z.object({instanceId:c.z.string().trim().min(1).max(160),nodeId:c.z.string().trim().min(1).max(160).optional(),sessionId:c.z.string().trim().min(1).max(120),providerSessionId:c.z.string().trim().min(1).max(240),item:ot,generatedAt:c.z.string().datetime()}).strict();const gn=c.z.object({instanceId:c.z.string().trim().min(1).max(160),nodeId:c.z.string().trim().min(1).max(160).optional(),sessionId:c.z.string().trim().min(1).max(120),providerSessionId:c.z.string().trim().min(1).max(240).optional(),turnId:c.z.string().trim().min(1).max(240),itemId:c.z.string().trim().min(1).max(240),field:c.z.literal("output"),delta:c.z.string().min(1),generatedAt:c.z.string().datetime()}).strict(),fn=gn.omit({instanceId:!0,nodeId:!0,providerSessionId:!0}).strict();function yn(e){return fn.parse({sessionId:e.sessionId,turnId:e.turnId,itemId:e.itemId,field:e.field,delta:e.delta,generatedAt:e.generatedAt})}function In(e,t){if(t?.subagents||"subagent"!==e.lineage?.kind)return e;const{lineage:n,...i}=e;return i}function _n(e,t){return t?.subagents?e:{...e,sessions:e.sessions.map(e=>In(e,t))}}c.z.object({streamId:c.z.string().trim().min(1).max(240),instanceId:c.z.string().trim().min(1).max(160),sinceRevision:c.z.number().int().min(0),latestRevision:c.z.number().int().min(0),earliestRetainedRevision:c.z.number().int().min(0),syncRequired:c.z.boolean().default(!1),events:c.z.array(c.z.discriminatedUnion("type",[c.z.object({type:c.z.literal(Me),payload:ln}).strict(),c.z.object({type:c.z.literal(je),payload:un}).strict(),c.z.object({type:c.z.literal(Ue),payload:pn}).strict()])).default([])}).strict();const En=c.z.object({source:$t,sourcePriority:c.z.number().int().min(0).max(100).optional(),observedAt:c.z.string().datetime().optional(),snapshotVersion:c.z.number().int().min(0).optional()}).strict(),An=En.extend({type:c.z.literal("snapshot"),agent:c.z.string().trim().min(1).max(80),creationSource:qe.optional(),appSessionId:c.z.string().trim().max(120).optional(),appId:c.z.string().trim().max(120).optional(),providerSessionId:c.z.string().trim().max(240).optional(),lineage:ft.optional(),providerMeta:c.z.record(c.z.string(),c.z.unknown()).optional(),modelSelection:Dt.optional(),reasoningEffort:Lt.optional(),storyId:ze.optional(),appBindingKeys:c.z.array(c.z.string().trim().min(1).max(240)).max(20).optional(),actions:ht.optional(),title:c.z.string().trim().max(240).optional(),cwd:c.z.string().trim().max(4096).optional(),cwdFolderId:c.z.string().trim().min(1).max(120).optional(),activeTurnId:c.z.string().trim().max(240).optional(),userPrompt:c.z.string().trim().optional(),turns:c.z.array(Bt).max(50).optional(),status:Qe.optional(),phase:Ze.optional(),summary:c.z.string().trim().max(1e3).optional(),lastMessage:c.z.string().trim().optional(),lastMessageItemId:c.z.string().trim().max(240).optional(),error:c.z.string().trim().max(4e3).optional(),currentTool:et.optional(),toolCallsSinceLastMessage:c.z.number().int().min(0).optional(),subAgents:pt.optional(),transcriptPath:c.z.string().trim().max(4096).optional(),transcriptSize:c.z.number().int().min(0).optional(),replaceActivity:c.z.boolean().optional()}).strict(),Tn=En.extend({type:c.z.literal("event"),sessionId:c.z.string().trim().min(1).max(120),kind:c.z.enum(["lifecycle","send-ack","turn-started","user-message","assistant-message","approval-requested","turn-completed","session-error","tool-activity","sub-agent-activity","context-compaction","model-selection","reasoning-effort"]),modelSelection:Dt.optional(),reasoningEffort:Lt.optional(),activeTurnId:c.z.string().trim().max(240).optional(),providerTurnId:c.z.string().trim().max(240).optional(),userPrompt:c.z.string().trim().optional(),userMessage:Je.optional(),text:c.z.string().optional(),itemId:c.z.string().trim().max(240).optional(),status:Qe.optional(),phase:Ze.optional(),summary:c.z.string().trim().max(1e3).optional(),error:c.z.string().trim().max(4e3).optional(),currentTool:et.nullable().optional(),toolCallsSinceLastMessage:c.z.number().int().min(0).optional(),subAgents:pt.optional(),contextCompaction:Ht.optional(),counters:c.z.object({toolCalls:c.z.number().int().min(0).optional(),edits:c.z.number().int().min(0).optional(),approvals:c.z.number().int().min(0).optional()}).strict().optional()}).strict().superRefine((e,t)=>{if("model-selection"===e.kind?e.modelSelection||t.addIssue({code:"custom",path:["modelSelection"],message:"model-selection events require modelSelection"}):void 0!==e.modelSelection&&t.addIssue({code:"custom",path:["modelSelection"],message:"modelSelection is only valid for model-selection events"}),"reasoning-effort"===e.kind?e.reasoningEffort||t.addIssue({code:"custom",path:["reasoningEffort"],message:"reasoning-effort events require reasoningEffort"}):void 0!==e.reasoningEffort&&t.addIssue({code:"custom",path:["reasoningEffort"],message:"reasoningEffort is only valid for reasoning-effort events"}),"session-error"!==e.kind||e.error||t.addIssue({code:"custom",path:["error"],message:"session-error events require error"}),"context-compaction"===e.kind?e.contextCompaction||t.addIssue({code:"custom",path:["contextCompaction"],message:"context-compaction events require contextCompaction"}):void 0!==e.contextCompaction&&t.addIssue({code:"custom",path:["contextCompaction"],message:"contextCompaction is only valid for context-compaction events"}),"send-ack"!==e.kind&&"user-message"!==e.kind&&void 0!==e.userMessage&&t.addIssue({code:"custom",path:["userMessage"],message:"userMessage is only valid for send-ack and user-message events"}),"sub-agent-activity"===e.kind?e.subAgents||t.addIssue({code:"custom",path:["subAgents"],message:"sub-agent-activity events require subAgents"}):void 0!==e.subAgents&&t.addIssue({code:"custom",path:["subAgents"],message:"subAgents is only valid for sub-agent-activity events"}),"tool-activity"!==e.kind)return void 0!==e.currentTool&&t.addIssue({code:"custom",path:["currentTool"],message:"currentTool is only valid for tool-activity events"}),void(void 0!==e.toolCallsSinceLastMessage&&t.addIssue({code:"custom",path:["toolCallsSinceLastMessage"],message:"toolCallsSinceLastMessage is only valid for tool-activity events"}));"currentTool"in e||t.addIssue({code:"custom",path:["currentTool"],message:"tool-activity events require currentTool"}),void 0===e.toolCallsSinceLastMessage&&t.addIssue({code:"custom",path:["toolCallsSinceLastMessage"],message:"tool-activity events require toolCallsSinceLastMessage"})});c.z.discriminatedUnion("type",[An,Tn]);const bn=c.z.union([c.z.object({type:c.z.literal("schedule"),scheduleKind:c.z.literal("interval").default("interval"),intervalMs:c.z.number().int().min(1e3)}).strict(),c.z.object({type:c.z.literal("schedule"),scheduleKind:c.z.literal("daily"),timeOfDay:c.z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/),timezone:c.z.string().trim().min(1).max(120)}).strict(),c.z.object({type:c.z.literal("schedule"),scheduleKind:c.z.literal("weekly"),weekdays:c.z.array(c.z.number().int().min(0).max(6)).min(1).max(7),timeOfDay:c.z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/),timezone:c.z.string().trim().min(1).max(120)}).strict()]),wn=c.z.union([bn,c.z.object({type:c.z.literal("file-change"),roots:c.z.array(c.z.string().trim().min(1).max(4096)).min(1).max(50),globs:c.z.array(c.z.string().trim().min(1).max(500)).min(1).max(100),ignore:c.z.array(c.z.string().trim().min(1).max(500)).max(100).optional(),debounceMs:c.z.number().int().min(100).max(6e4).default(1500)}).strict(),c.z.object({type:c.z.literal("ai-session"),agent:c.z.string().trim().min(1).max(80).optional(),statuses:c.z.array(c.z.enum(["running","waiting","idle","failed"])).max(20).optional(),phases:c.z.array(c.z.enum(["thinking","tool","editing","approval","responding","unknown"])).max(20).optional()}).strict()]),Sn=c.z.object({promptTemplate:c.z.string().trim().min(1).max(2e4)}).strict(),Nn=c.z.object({cooldownMs:c.z.number().int().min(0).max(864e5).optional(),maxConcurrentRuns:c.z.number().int().min(1).max(20).default(1),whenBusy:c.z.enum(["skip","queue"]).default("skip")}).strict(),vn=c.z.object({configHash:c.z.string().trim().min(8).max(80),name:c.z.string().trim().min(1).max(160),description:c.z.string().trim().max(1e3).optional(),source:wn,action:Sn,policy:Nn.default({maxConcurrentRuns:1,whenBusy:"skip"}),createdAt:c.z.string().datetime(),updatedAt:c.z.string().datetime()}).strict(),On=c.z.object({type:c.z.literal("ai-session"),aiSessionId:c.z.string().trim().min(1).max(160)}).strict(),Rn=c.z.object({configHash:c.z.string().trim().min(8).max(80),deploymentId:c.z.string().trim().min(1).max(240).optional(),instanceId:c.z.string().trim().min(1).max(160),origin:c.z.enum(["control-plane","controlled-instance"]).default("controlled-instance"),enabled:c.z.boolean().default(!0),target:On,localName:c.z.string().trim().min(1).max(160).optional(),createdAt:c.z.string().datetime(),updatedAt:c.z.string().datetime()}).strict(),zn=c.z.object({configHash:c.z.string().trim().min(8).max(80),deploymentId:c.z.string().trim().min(1).max(240).optional(),instanceId:c.z.string().trim().min(1).max(160),status:c.z.enum(["idle","running","disabled","error"]).default("idle"),lastTriggeredAt:c.z.string().datetime().optional(),lastCompletedAt:c.z.string().datetime().optional(),lastSkippedAt:c.z.string().datetime().optional(),lastError:c.z.string().trim().max(4e3).optional(),runCount:c.z.number().int().min(0).default(0),skippedCount:c.z.number().int().min(0).default(0)}).strict(),xn=c.z.object({id:c.z.string().trim().min(1).max(160),configHash:c.z.string().trim().min(8).max(80),deploymentId:c.z.string().trim().min(1).max(240).optional(),instanceId:c.z.string().trim().min(1).max(160),eventType:c.z.enum(["manual","schedule","file-change","ai-session"]),status:c.z.enum(["started","completed","failed","skipped"]),target:On,promptPreview:c.z.string().trim().max(500),eventSummary:c.z.string().trim().max(1e3).optional(),error:c.z.string().trim().max(4e3).optional(),startedAt:c.z.string().datetime(),completedAt:c.z.string().datetime().optional()}).strict();c.z.object({schemaVersion:c.z.literal(1).default(1),configs:c.z.array(vn).default([]),deployments:c.z.array(Rn).default([]),runtime:c.z.array(zn).default([]),recentRuns:c.z.array(xn).default([])}).strict();const Cn=c.z.object({config:vn,deployment:Rn,runtime:zn.optional()}).strict();c.z.object({instanceId:c.z.string().trim().min(1).max(160),sessionId:c.z.string().trim().min(1).max(160),mutation:Cn.optional()}).strip(),c.z.object({instanceId:c.z.string().trim().min(1).max(160),sessionId:c.z.string().trim().min(1).max(160),configHash:vn.shape.configHash}).strip();const kn=c.z.object({instanceId:c.z.string().trim().min(1).max(160),instanceName:c.z.string().trim().min(1).max(160),deployment:Rn,runtime:zn.optional()}).strip(),Dn=xn.extend({instanceName:c.z.string().trim().min(1).max(160).optional()}).strip(),Ln=c.z.object({configHash:c.z.string().trim().min(8).max(80),config:vn,deploymentCount:c.z.number().int().min(0),enabledCount:c.z.number().int().min(0),runningCount:c.z.number().int().min(0),errorCount:c.z.number().int().min(0),ownedByControlPlane:c.z.boolean(),controlPlaneDeploymentCount:c.z.number().int().min(0),deployments:c.z.array(kn),recentRuns:c.z.array(Dn)}).strip();c.z.object({updatedAt:c.z.string().datetime(),triggers:c.z.array(Ln)}).strip(),c.z.object({name:vn.shape.name,description:vn.shape.description,source:wn,action:Sn,policy:Nn.partial().optional()}).strict(),c.z.object({scope:c.z.enum(["node","instance"]),nodeId:c.z.string().trim().min(1).max(160).optional(),instanceId:c.z.string().trim().min(1).max(160).optional(),code:c.z.string().trim().min(1).max(160),message:c.z.string().trim().min(1).max(4e3)}).strip();const Pn=c.z.string().regex(/^\d{4}-\d{2}-\d{2}$/,"Proxy protocol version must use YYYY-MM-DD format."),Mn=c.z.string().trim().min(1).max(160).regex(/^[a-zA-Z0-9][a-zA-Z0-9_.:-]*$/),jn=c.z.string().datetime(),Un=c.z.string().trim().min(32).max(4096),Fn=c.z.string().trim().max(2048).transform((e,t)=>{try{return function(e){const t=new URL(e.trim());if("https:"!==t.protocol||t.username||t.password||"/"!==t.pathname||t.search||t.hash)throw new Error("Proxy origin must be an HTTPS origin without credentials, path, query, or fragment.");return t.origin}(e)}catch(e){return t.addIssue({code:"custom",message:e instanceof Error?e.message:String(e)}),c.z.NEVER}});c.z.string().trim().min(1).max(4096).transform((e,t)=>{try{return function(e){const t=e.trim();if(!t.startsWith("/")||t.startsWith("//")||t.includes("\\")||/%25/i.test(t))throw new Error("Proxy route must be a single-encoded node-agent relative route.");const n=t.split("?",1)[0];let i,s;try{i=n.split("/").map(e=>decodeURIComponent(e))}catch{throw new Error("Proxy route contains invalid percent encoding.")}if(i.some(e=>".."===e||"."===e))throw new Error("Proxy route cannot traverse outside the node-agent API.");try{s=new URL(t,"https://node-agent.invalid")}catch{throw new Error("Proxy route is invalid.")}if("https://node-agent.invalid"!==s.origin||s.username||s.password)throw new Error("Proxy route cannot select an absolute upstream URL.");return`${s.pathname}${s.search}`}(e)}catch(e){return t.addIssue({code:"custom",message:e instanceof Error?e.message:String(e)}),c.z.NEVER}});const $n=c.z.enum(Object.values({ProtocolUnsupported:"CONTROL_PLANE_PROXY_PROTOCOL_UNSUPPORTED",InviteInvalid:"CONTROL_PLANE_PROXY_INVITE_INVALID",InviteExpired:"CONTROL_PLANE_PROXY_INVITE_EXPIRED",InviteConsumed:"CONTROL_PLANE_PROXY_INVITE_CONSUMED",InviteRevoked:"CONTROL_PLANE_PROXY_INVITE_REVOKED",TargetUnavailable:"CONTROL_PLANE_PROXY_TARGET_UNAVAILABLE",TargetMismatch:"CONTROL_PLANE_PROXY_TARGET_MISMATCH",BindingUnknown:"CONTROL_PLANE_PROXY_BINDING_UNKNOWN",BindingRevoked:"CONTROL_PLANE_PROXY_BINDING_REVOKED",BindingIdentityConflict:"CONTROL_PLANE_PROXY_BINDING_IDENTITY_CONFLICT",AuthenticationFailed:"CONTROL_PLANE_PROXY_AUTHENTICATION_FAILED",RouteInvalid:"CONTROL_PLANE_PROXY_ROUTE_INVALID",HeaderInvalid:"CONTROL_PLANE_PROXY_HEADER_INVALID",ResourceLimit:"CONTROL_PLANE_PROXY_RESOURCE_LIMIT",SnapshotRequired:"CONTROL_PLANE_PROXY_SNAPSHOT_REQUIRED",Unavailable:"CONTROL_PLANE_PROXY_UNAVAILABLE",TransportFailed:"CONTROL_PLANE_PROXY_TRANSPORT_FAILED"})),Hn=c.z.object({code:$n,message:c.z.string().trim().min(1).max(2048),retryable:c.z.boolean(),details:c.z.record(c.z.string(),c.z.unknown()).optional()}).strict(),Bn=c.z.enum(["active","revoked"]),qn=c.z.object({id:Mn,targetNodeId:Mn,status:Bn,createdBy:Mn,expiresAt:jn,revokedAt:jn.optional(),createdAt:jn,updatedAt:jn}).strict();c.z.object({targetNodeId:Mn,expiresInSeconds:c.z.number().int().min(60).max(3600).default(600)}).strict(),c.z.object({invite:qn,token:c.z.string().trim().min(24).max(512),proxyOrigin:Fn,protocolVersion:Pn}).strict();const Vn=c.z.enum(["active","revoked"]),Gn=c.z.object({id:Mn,claimId:Mn,sourceControlPlaneId:Mn,targetNodeId:Mn,bindingKeyId:Mn,status:Vn,revision:c.z.number().int().positive(),lastError:Hn.optional(),revokedAt:jn.optional(),createdAt:jn,updatedAt:jn}).strict();c.z.object({protocolVersion:Pn,inviteToken:c.z.string().trim().min(24).max(512).optional(),claimId:Mn,sourceControlPlaneId:Mn,targetNodeId:Mn.optional(),bindingKeyId:Mn,credential:Un}).strict(),c.z.object({sourceControlPlaneId:Mn,bindingKeyId:Mn,credential:Un}).strict();const Wn=c.z.object({id:Mn,name:c.z.string().trim().min(1).max(160),status:c.z.enum(["unknown","online","offline","degraded"]),health:c.z.enum(["unknown","ok","degraded","failed"]),lastSeenAt:jn.optional(),capabilities:c.z.record(c.z.string(),c.z.unknown()).default({})}).strict(),Kn=c.z.object({protocolVersion:Pn,binding:Gn,streamId:Mn,revision:c.z.number().int().nonnegative(),observedAt:jn,target:Wn}).strict(),Yn=c.z.object({type:c.z.literal("control-plane-proxy.event"),protocolVersion:Pn,streamId:Mn,bindingId:Mn,sourceControlPlaneId:Mn,targetNodeId:Mn,revision:c.z.number().int().positive(),source:c.z.object({id:c.z.string().trim().min(1).max(512),seq:c.z.number().int().nonnegative()}).strict(),target:Wn,event:c.z.object({type:c.z.string().trim().min(1).max(240),topic:c.z.string().trim().min(1).max(240),createdAt:jn}).strict()}).strict(),Xn=c.z.object({type:c.z.literal("control-plane-proxy.events.ready"),protocolVersion:Pn,streamId:Mn,bindingId:Mn,sourceControlPlaneId:Mn,targetNodeId:Mn,latestRevision:c.z.number().int().nonnegative(),earliestRetainedRevision:c.z.number().int().nonnegative()}).strict(),Jn=c.z.object({type:c.z.literal("control-plane-proxy.snapshot-required"),protocolVersion:Pn,streamId:Mn,bindingId:Mn,sourceControlPlaneId:Mn,targetNodeId:Mn,sinceRevision:c.z.number().int().nonnegative(),latestRevision:c.z.number().int().nonnegative(),earliestRetainedRevision:c.z.number().int().nonnegative(),error:Hn}).strict();c.z.discriminatedUnion("type",[Yn,Xn,Jn]),c.z.object({protocolVersion:Pn,binding:Gn,target:Kn.shape.target}).strict(),c.z.object({id:Mn,claimId:Mn,proxyOrigin:Fn,requestedName:c.z.string().trim().min(1).max(160).optional(),sourceControlPlaneId:Mn,targetNodeId:Mn.optional(),bindingKeyId:Mn,credential:Un,status:c.z.enum(["pending","compensation-required"]),createdAt:jn,updatedAt:jn,expiresAt:jn}).strict().omit({credential:!0}),c.z.object({id:Mn,nodeId:Mn,proxyOrigin:Fn,proxyBindingId:Mn,targetNodeId:Mn,sourceControlPlaneId:Mn,bindingKeyId:Mn,credential:Un,createdAt:jn,updatedAt:jn}).strict();const Qn=c.z.string().trim().min(1).max(120).regex(/^[a-zA-Z0-9][a-zA-Z0-9_.:-]*$/),Zn=c.z.string().datetime(),ei=c.z.number().int().nonnegative(),ti=c.z.enum(["https-token","ssh-key"]),ni=c.z.enum(["operation-only","instance-retained"]),ii=c.z.enum(["enabled","disabled"]),si=c.z.enum(["pending","synced","deferred","revoking","revoked"]),ri=c.z.object({scheme:c.z.enum(["https","ssh"]),host:c.z.string().trim().min(1).max(253),port:c.z.number().int().min(1).max(65535).optional(),pathPrefix:c.z.string().min(1).max(2048).default("/")}).strict();function oi(e){throw new Error(`Invalid Git credential scope: ${e}`)}function ai(e){const t=e.trim().replace(/^\[|\]$/g,"");(!t||t.includes("*")||/[/?#@\s]/.test(t))&&oi("host is invalid");try{const e=new URL(t.includes(":")?`http://[${t}]/`:`http://${t}/`).hostname.replace(/^\[|\]$/g,"").toLowerCase();return(!e||e.length>253||e.includes("*"))&&oi("host is invalid"),e}catch{oi("host is invalid")}}function ci(e){try{return decodeURIComponent(e)}catch{oi("path contains invalid percent encoding")}}function di(e){const t=e?.trim()||"/";(t.includes("?")||t.includes("#")||t.includes("\\")||t.includes("\0"))&&oi("path contains an unsupported delimiter");const n=(t.startsWith("/")?t:`/${t}`).split("/").filter(Boolean);for(const e of n){const t=ci(e);("."===t||".."===t||t.includes("/")||t.includes("\\")||t.includes("\0"))&&oi("path contains an unsafe segment")}return 0===n.length?"/":`/${n.join("/")}/`}function li(e){const t=ri.parse(e),n="https"===t.scheme?443:22;return ri.parse({scheme:t.scheme,host:ai(t.host),...void 0===t.port||t.port===n?{}:{port:t.port},pathPrefix:di(t.pathPrefix)})}function ui(e){return di(e.replace(/\.git\/?$/,""))}const pi=c.z.object({id:Qn,name:c.z.string().trim().min(1).max(160),kind:ti,scope:ri,secretSet:c.z.literal(!0),status:ii,revision:ei,createdAt:Zn,updatedAt:Zn}).strict(),mi=c.z.object({kind:c.z.literal("https-token"),username:c.z.string().trim().min(1).max(240),token:c.z.string().min(1).max(8192)}).strict(),hi=c.z.object({kind:c.z.literal("ssh-key"),privateKey:c.z.string().min(1).max(131072),passphrase:c.z.string().max(8192).optional(),pinnedKnownHosts:c.z.string().min(1).max(131072)}).strict(),gi=c.z.discriminatedUnion("kind",[mi,hi]);c.z.object({name:c.z.string().trim().min(1).max(160),scope:ri,secret:gi}).strict().superRefine((e,t)=>{"https"===e.scope.scheme!=("https-token"===e.secret.kind)&&t.addIssue({code:"custom",path:["scope","scheme"],message:"Credential kind must match the remote scheme."});try{li(e.scope)}catch(e){t.addIssue({code:"custom",path:["scope"],message:e instanceof Error?e.message:"Invalid Git scope."})}}),c.z.object({name:c.z.string().trim().min(1).max(160).optional(),scope:ri.optional(),secret:gi.optional(),status:ii.optional()}).strict().refine(e=>Object.keys(e).length>0,"At least one credential field must be updated."),c.z.object({items:c.z.array(pi).max(1e4)}).strict(),c.z.object({host:c.z.string().trim().min(1).max(253),port:c.z.number().int().min(1).max(65535).optional()}).strict();const fi=c.z.object({keyType:c.z.string().trim().min(1).max(64),fingerprint:c.z.string().trim().min(1).max(256),publicKey:c.z.string().trim().min(1).max(8192),knownHosts:c.z.string().min(1).max(8192)}).strict();c.z.object({host:c.z.string().trim().min(1).max(253),port:c.z.number().int().min(1).max(65535),fetchedAt:Zn,knownHosts:c.z.string().min(1).max(65536),entries:c.z.array(fi).min(1).max(32)}).strict();const yi=c.z.object({instanceId:Qn,credentialId:Qn,credentialRevision:ei,assignmentRevision:ei,status:si,authorizedAt:Zn,updatedAt:Zn}).strict(),Ii=c.z.object({credential:pi,secret:gi}).strict().superRefine((e,t)=>{e.credential.kind!==e.secret.kind&&t.addIssue({code:"custom",path:["secret","kind"],message:"Credential payload kind mismatch."})}),_i=c.z.object({instanceId:Qn,generation:ei,credentialIds:c.z.array(Qn).max(256).transform(e=>[...new Set(e)].sort()),updatedAt:Zn}).strict(),Ei=c.z.object({remoteUrl:c.z.string().trim().min(1).max(4096)}).strict(),Ai=c.z.discriminatedUnion("status",[c.z.object({status:c.z.literal("ok"),username:c.z.string().min(1).max(240),password:c.z.string().min(1).max(8192)}).strict(),c.z.object({status:c.z.enum(["none","ambiguous","unsupported","missing-host-key","rejected"])}).strict()]),Ti=c.z.object({remoteUrl:c.z.string().trim().min(1).max(4096)}).strict(),bi=c.z.discriminatedUnion("status",[c.z.object({status:c.z.literal("ok"),invocationId:Qn,publicIdentity:c.z.string().min(1).max(131072),pinnedKnownHosts:c.z.string().min(1).max(131072)}).strict(),c.z.object({status:c.z.enum(["none","ambiguous","unsupported","missing-host-key","rejected"])}).strict()]),wi=c.z.object({invocationId:Qn,frame:c.z.string().min(1).max(1048576)}).strict(),Si=c.z.object({frame:c.z.string().min(1).max(1048576)}).strict(),Ni=c.z.object({operationId:Qn,retention:ni,payload:Ii}).strict(),vi=c.z.object({operationId:Qn,instanceId:Qn,remoteUrl:c.z.string().trim().min(1).max(4096),ref:c.z.discriminatedUnion("type",[c.z.object({type:c.z.enum(["branch","tag"]),name:c.z.string().trim().min(1).max(240)}).strict(),c.z.object({type:c.z.literal("commit"),commit:c.z.string().trim().regex(/^[0-9a-fA-F]{4,64}$/,"commit must be a hexadecimal Git object id")}).strict()]),clone:c.z.object({depth:c.z.number().int().positive().max(1e5).optional(),submodules:c.z.boolean().default(!1),lfs:c.z.boolean().default(!1),subdirectory:c.z.string().trim().max(240).refine(e=>!e.startsWith("/")&&!e.split("/").some(e=>".."===e),"subdirectory must be a relative path within the repository").transform(e=>e.split("/").filter(e=>e&&"."!==e).join("/")).default("")}).strict(),credentials:c.z.array(Ni).max(256).default([])}).strict();function Oi(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:void 0}function Ri(e,t){if(e)return Object.fromEntries(t.filter(t=>Object.prototype.hasOwnProperty.call(e,t)).map(t=>[t,e[t]]))}function zi(e,t){let n;try{n=function(e){const t=e.trim();if(t&&!t.includes("\0")||oi("remote is empty or invalid"),/^https?:\/\//i.test(t)||/^ssh:\/\//i.test(t)){let e;di(t.replace(/^[a-z][a-z0-9+.-]*:\/\/[^/]+/i,"").split(/[?#]/,1)[0]||"/");try{e=new URL(t)}catch{oi("remote URL is invalid")}"https:"!==e.protocol&&"ssh:"!==e.protocol&&oi("remote scheme is unsupported"),(e.password||"https:"===e.protocol&&e.username)&&oi("HTTPS userinfo is forbidden"),(e.search||e.hash)&&oi("query and fragment are forbidden");const n="https:"===e.protocol?"https":"ssh",i=e.port?Number(e.port):void 0;return{...li({scheme:n,host:e.hostname,port:i,pathPrefix:ui(e.pathname)}),original:t}}/^[a-z][a-z0-9+.-]*:\/\//i.test(t)&&oi("remote scheme is unsupported");const n=/^(?:([^@/:\s]+)@)?([^/:\s]+):(.+)$/.exec(t);n||oi("remote must use HTTPS, ssh://, or scp-like SSH syntax");const[,,i,s]=n;return(s.includes("?")||s.includes("#"))&&oi("query and fragment are forbidden"),{...li({scheme:"ssh",host:i,pathPrefix:ui(s)}),original:t}}(e)}catch(e){return{status:"unsupported",reason:e instanceof Error?e.message:"Unsupported Git remote."}}const i=t.filter(e=>"enabled"===e.status).filter(e=>"https"===n.scheme==("https-token"===e.kind)).filter(e=>function(e,t){const n=li(e);return n.scheme===t.scheme&&n.host===t.host&&n.port===t.port&&("/"===n.pathPrefix||t.pathPrefix.startsWith(n.pathPrefix))}(e.scope,n)).map(e=>({candidate:e,specificity:li(e.scope).pathPrefix.length}));if(0===i.length)return{status:"none",remote:n};const s=Math.max(...i.map(e=>e.specificity)),r=i.filter(e=>e.specificity===s).map(e=>e.candidate);if(r.length>1)return{status:"ambiguous",remote:n,credentialIds:r.map(e=>e.id).sort()};const o=r[0];return"ssh-key"===o.kind&&!0!==o.pinnedKnownHosts?{status:"missing-host-key",remote:n,credentialId:o.id}:{status:"unique",remote:n,credential:o}}const xi=c.z.enum(["openai-responses","openai-chat-completions","anthropic-messages"]);c.z.object({}).strict();const Ci=c.z.enum(["docker","local","wsl"]),ki=c.z.object({docker:c.z.boolean().default(!1),kubernetes:c.z.boolean().default(!1),local:c.z.boolean().default(!1),wsl:c.z.boolean().default(!1)}).strip(),Di=c.z.object({registry:c.z.boolean().default(!1),runtimeBroker:c.z.boolean().default(!1),workspaceProvisioning:ki.default({docker:!1,kubernetes:!1,local:!1,wsl:!1})}).strip(),Li=c.z.object({multiEntityAssignment:c.z.boolean().default(!1),privateModelCatalog:c.z.boolean().default(!1),stableModelIdentity:c.z.boolean().default(!1),requestMappings:c.z.boolean().default(!1),modelRelay:c.z.object({protocols:c.z.array(xi).max(3).default([]),streaming:c.z.boolean().default(!1),unknownModelPolicy:c.z.boolean().default(!1)}).strip().default(()=>({protocols:[],streaming:!1,unknownModelPolicy:!1}))}).strip(),Pi=c.z.object({policy:c.z.boolean().default(!1),actions:c.z.boolean().default(!1),automations:c.z.boolean().default(!1),aiSessionRead:c.z.boolean().default(!1),decisions:c.z.boolean().default(!1)}).strip(),Mi=c.z.object({enabled:c.z.boolean().default(!1),agentTools:c.z.boolean().default(!1),agentToolCapabilities:Pi.optional(),sessionRetention:c.z.boolean().default(!1),maxFileBytes:c.z.number().int().positive().default(33554432),maxBatchPaths:c.z.number().int().min(1).max(100).default(20)}).strip(),ji=c.z.object({runtime:c.z.enum(["docker","local"]),workspaceMaterializer:c.z.enum(["overlay-copy-on-write","worktree"]),processSandbox:c.z.enum(["instance","container","local-runtime"]),providerId:c.z.string().trim().min(1).max(120)}).strip(),Ui=c.z.object({definitions:c.z.boolean().default(!1),runs:c.z.boolean().default(!1),orchestration:c.z.object({storyEntryAuthorization:c.z.boolean().default(!1),orchestrations:c.z.boolean().default(!1),runMembers:c.z.boolean().default(!1),manualRuns:c.z.boolean().default(!1)}).strip().default({storyEntryAuthorization:!1,orchestrations:!1,runMembers:!1,manualRuns:!1}),sharedSpace:c.z.object({enabled:c.z.boolean().default(!1),runtimes:c.z.array(Ci).default([])}).strip().default({enabled:!1,runtimes:[]}),combinations:c.z.array(ji).default([])}).strip(),Fi=c.z.object({enabled:c.z.boolean().default(!1),runtimes:c.z.array(c.z.string().trim().min(1).max(64)).default([])}).strip().default({enabled:!1,runtimes:[]});Ui.omit({combinations:!0,sharedSpace:!0}).extend({combinations:c.z.array(c.z.unknown()).default([]),sharedSpace:Fi}).strip();const $i=c.z.object({modelEndpointProbe:c.z.boolean().optional(),aiSessionHistoryLimit:c.z.boolean().optional(),aiSessionAttachmentRetention:c.z.boolean().optional(),aiSessionFileAttachmentLimit:c.z.boolean().optional(),folderPlaces:c.z.boolean().optional(),localFolderNameUpdate:c.z.boolean().optional(),managedGitCredentials:Di.optional(),managedModels:Li.optional(),stories:Mi.optional(),codexManagedSettings:c.z.boolean().optional(),agentExecution:Ui.optional()}).strip(),Hi=new TextEncoder;function Bi(e){return u.sha256("string"==typeof e?Hi.encode(e):e)}function qi(e){const t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),t}function Vi(e){const t=atob(e),n=Uint8Array.from(t,e=>e.charCodeAt(0)),i=globalThis.Buffer;return i?i.from(n):n}const Gi=c.z.string().trim().min(1).max(120),Wi=c.z.object({selectModelAtCreate:c.z.boolean().default(!1),selectProviderAtCreate:c.z.boolean().default(!1),selectModelAtResume:c.z.boolean().default(!1),selectProviderAtResume:c.z.boolean().default(!1),switchModelWithinProvider:c.z.boolean().default(!1),switchProviderDuringSession:c.z.boolean().default(!1),stableIdentity:c.z.boolean().default(!1)}).strip().default({selectModelAtCreate:!1,selectProviderAtCreate:!1,selectModelAtResume:!1,selectProviderAtResume:!1,switchModelWithinProvider:!1,switchProviderDuringSession:!1,stableIdentity:!1}),Ki=c.z.object({selectAtCreate:c.z.boolean().default(!1),updateDuringSession:c.z.boolean().default(!1)}).strip().default({selectAtCreate:!1,updateDuringSession:!1}),Yi=c.z.object({subagents:c.z.boolean().default(!1)}).strip().default({subagents:!1}),Xi=c.z.object({agent:Gi,actions:c.z.object({create:c.z.boolean().default(!1),send:c.z.boolean().default(!1),queue:c.z.boolean().default(!1),steer:c.z.boolean().default(!1),interrupt:c.z.boolean().default(!1),archive:c.z.boolean().default(!1),delete:c.z.boolean().default(!1),fork:c.z.boolean().default(!1),rename:c.z.boolean().default(!1),approvalDecisions:c.z.array(c.z.enum(["allow","deny","skip"])).max(3).default([])}).passthrough(),permissionModes:c.z.array(c.z.enum(["ask","auto-review","full-access"])).max(3).default([]),timeline:c.z.object({sessionRead:c.z.boolean().default(!1),turnRead:c.z.boolean().default(!1),liveItems:c.z.boolean().default(!1)}).passthrough(),modelSelection:Wi.optional(),reasoningEffort:Ki.optional(),hierarchy:Yi.optional()}).passthrough(),Ji=c.z.array(Xi).max(100).default([]),Qi="2026-10-02",Zi=new Set(["2026-08-01","2026-08-16","2026-08-17","2026-08-20","2026-09-24","2026-09-29",Qi]),es=c.z.string().regex(/^\d{4}-\d{2}-\d{2}$/,"Protocol version must use YYYY-MM-DD format."),ts=c.z.string().trim().min(1).max(120),ns=c.z.enum(["low","medium","high"]),is=c.z.enum(["none","friendly","pragmatic"]),ss=c.z.object({modelEntityId:c.z.string().trim().min(1).max(120),modelName:c.z.string().trim().min(1).max(240),modelUpstreamName:c.z.string().trim().min(1).max(240).optional()}).strict(),rs=c.z.object({modelVerbosity:ns.optional(),personality:is.optional(),multiAgent:c.z.object({enabled:c.z.boolean().default(!0),maxConcurrentThreads:c.z.number().int().min(1).max(64).optional(),defaultModel:ss.optional(),defaultReasoningEffort:Lt.optional()}).strict().default({enabled:!0})}).strict();function os(){return{features:{appRuntime:!1,tty:!1,gui:!1,browser:!1,browserTunnel:!1,screenshots:!1,logs:!1,aiSessionWorkspaceSelection:!1,aiSessionWorkspaceCheckout:!1,aiSessionPersistenceSettings:!1,privateModelCatalog:!1,codexManagedSettings:!1,nodeAgentConnectionUpdate:!1,gitCliCredentialBroker:!1,gitCredentialProxy:!1,repositoryPathSearch:!1,repositoryWorktreeMoveToMain:!1,modelRelay:{protocols:[],streaming:!1},managedModelEnvironment:{openCodeConfig:!1},aiSessionSendIdempotency:!1,aiSessionQueuePause:!1,aiSessionTimeline:{sessionReadAgents:[],turnReadAgents:[],liveItemAgents:[]},aiSessionConversationAttachments:{metadataAgents:[],contentAgents:[],uploadAgents:[],retentionSettings:!1,fileSizeLimitSettings:!1},aiSessionProviders:[]}}}const as=c.z.object({sessionReadAgents:c.z.array(ts).max(100).default([]),turnReadAgents:c.z.array(ts).max(100).default([]),liveItemAgents:c.z.array(ts).max(100).default([])}).passthrough(),cs=c.z.object({metadataAgents:c.z.array(ts).max(100).default([]),contentAgents:c.z.array(ts).max(100).default([]),uploadAgents:c.z.array(ts).max(100).default([]),retentionSettings:c.z.boolean().default(!1),fileSizeLimitSettings:c.z.boolean().default(!1)}).passthrough(),ds=c.z.object({protocols:c.z.array(xi).max(3).default([]),streaming:c.z.boolean().default(!1)}).strip(),ls=c.z.object({openCodeConfig:c.z.boolean().default(!1)}).strip(),us=c.z.object({appRuntime:c.z.boolean().default(!1),tty:c.z.boolean().default(!1),gui:c.z.boolean().default(!1),browser:c.z.boolean().default(!1),browserTunnel:c.z.boolean().optional(),screenshots:c.z.boolean().default(!1),logs:c.z.boolean().default(!1),aiSessionWorkspaceSelection:c.z.boolean().default(!1),aiSessionWorkspaceCheckout:c.z.boolean().optional(),aiSessionPersistenceSettings:c.z.boolean().default(!1),privateModelCatalog:c.z.boolean().optional(),codexManagedSettings:c.z.boolean().optional(),nodeAgentConnectionUpdate:c.z.boolean().optional(),gitCliCredentialBroker:c.z.boolean().optional(),gitCredentialProxy:c.z.boolean().optional(),repositoryPathSearch:c.z.boolean().optional(),repositoryWorktreeMoveToMain:c.z.boolean().optional(),aiSessionSendIdempotency:c.z.boolean().optional(),aiSessionQueuePause:c.z.boolean().optional(),aiSessionTimeline:as.default(function(){return{sessionReadAgents:[],turnReadAgents:[],liveItemAgents:[]}}),aiSessionConversationAttachments:cs.optional(),aiSessionProviders:Ji.optional(),modelRelay:ds.optional(),managedModelEnvironment:ls.optional()}).passthrough(),ps=c.z.object({features:us.default(function(){return{appRuntime:!1,tty:!1,gui:!1,browser:!1,browserTunnel:!1,screenshots:!1,logs:!1,aiSessionWorkspaceSelection:!1,aiSessionWorkspaceCheckout:!1,aiSessionPersistenceSettings:!1,privateModelCatalog:!1,codexManagedSettings:!1,nodeAgentConnectionUpdate:!1,gitCliCredentialBroker:!1,gitCredentialProxy:!1,repositoryPathSearch:!1,repositoryWorktreeMoveToMain:!1,modelRelay:{protocols:[],streaming:!1},managedModelEnvironment:{openCodeConfig:!1},aiSessionSendIdempotency:!1,aiSessionQueuePause:!1,aiSessionTimeline:{sessionReadAgents:[],turnReadAgents:[],liveItemAgents:[]},aiSessionConversationAttachments:{metadataAgents:[],contentAgents:[],uploadAgents:[],retentionSettings:!1,fileSizeLimitSettings:!1},aiSessionProviders:[]}})}).passthrough(),ms=c.z.object({nodeAgentUrl:c.z.string().trim().url().max(2048).refine(e=>{const t=new URL(e);return/^https?:$/.test(t.protocol)&&!t.username&&!t.password&&"/"===t.pathname&&!t.search&&!t.hash},"Node agent URL must be an HTTP(S) origin.")}).strict();function hs(e){const t={features:{appRuntime:!1,tty:!1,gui:!1,browser:!1,browserTunnel:!1,screenshots:!1,logs:!1,aiSessionWorkspaceSelection:!1,aiSessionWorkspaceCheckout:!1,aiSessionPersistenceSettings:!1,privateModelCatalog:!1,codexManagedSettings:!1,nodeAgentConnectionUpdate:!1,gitCliCredentialBroker:!1,gitCredentialProxy:!1,repositoryPathSearch:!1,repositoryWorktreeMoveToMain:!1,modelRelay:{protocols:[],streaming:!1},managedModelEnvironment:{openCodeConfig:!1},aiSessionSendIdempotency:!1,aiSessionQueuePause:!1,aiSessionTimeline:{sessionReadAgents:[],turnReadAgents:[],liveItemAgents:[]},aiSessionConversationAttachments:{metadataAgents:[],contentAgents:[],uploadAgents:[],retentionSettings:!1,fileSizeLimitSettings:!1},aiSessionProviders:[]}};if(!e||"object"!=typeof e||Array.isArray(e))return t;const n=e,i=n.features;if(!i||"object"!=typeof i||Array.isArray(i))return t;const s=i,r={appRuntime:!1,tty:!1,gui:!1,browser:!1,browserTunnel:!1,screenshots:!1,logs:!1,aiSessionWorkspaceSelection:!1,aiSessionWorkspaceCheckout:!1,aiSessionPersistenceSettings:!1,privateModelCatalog:!1,codexManagedSettings:!1,nodeAgentConnectionUpdate:!1,gitCliCredentialBroker:!1,gitCredentialProxy:!1,repositoryPathSearch:!1,repositoryWorktreeMoveToMain:!1,modelRelay:{protocols:[],streaming:!1},managedModelEnvironment:{openCodeConfig:!1},aiSessionSendIdempotency:!1,aiSessionQueuePause:!1,aiSessionTimeline:{sessionReadAgents:[],turnReadAgents:[],liveItemAgents:[]},aiSessionConversationAttachments:{metadataAgents:[],contentAgents:[],uploadAgents:[],retentionSettings:!1,fileSizeLimitSettings:!1},aiSessionProviders:[]};for(const e of["appRuntime","tty","gui","browser","browserTunnel","screenshots","logs","aiSessionWorkspaceSelection","aiSessionWorkspaceCheckout","aiSessionPersistenceSettings","privateModelCatalog","codexManagedSettings","nodeAgentConnectionUpdate","gitCliCredentialBroker","gitCredentialProxy","repositoryPathSearch","repositoryWorktreeMoveToMain","aiSessionSendIdempotency","aiSessionQueuePause"]){const t=c.z.boolean().safeParse(s[e]);t.success&&(r[e]=t.data)}const o=as.safeParse(s.aiSessionTimeline);o.success&&(r.aiSessionTimeline=o.data);const a=cs.safeParse(s.aiSessionConversationAttachments);a.success&&(r.aiSessionConversationAttachments=a.data);const d=Ji.safeParse(s.aiSessionProviders);d.success&&(r.aiSessionProviders=d.data);const l=ds.safeParse(s.modelRelay);l.success&&(r.modelRelay=l.data);const u=ls.safeParse(s.managedModelEnvironment);return u.success&&(r.managedModelEnvironment=u.data),ps.parse({...n,features:{...s,...r}})}function gs(e){return hs(e).features.modelRelay}function fs(e){return gs(e).protocols.length>0}function ys(e,t){return gs(e).protocols.includes(t)}function Is(e,t){return function(e){return hs(e).features.aiSessionProviders}(e).find(e=>e.agent===t)}function _s(e,t,n){if(void 0===n.modelUpstreamName)return n;if(Is(e,t)?.modelSelection?.stableIdentity)return n;const{modelUpstreamName:i,...s}=n;return s}const Es=c.z.string().trim().min(1).max(120).regex(/^[a-zA-Z0-9][a-zA-Z0-9_.:-]*$/),As=c.z.string().datetime(),Ts=c.z.record(c.z.string(),c.z.string()).default({}),bs=c.z.record(c.z.string(),c.z.string()).default({}),ws=c.z.object({encoding:c.z.enum(["utf8","base64"]),data:c.z.string()}).strict().superRefine((e,t)=>{if("base64"!==e.encoding)return;let n=!1;try{n=function(e){const t=[];for(let n=0;n<e.length;n+=24576)t.push(btoa(String.fromCharCode(...e.subarray(n,n+24576))));return t.join("")}(Vi(e.data))===e.data}catch{n=!1}n||t.addIssue({code:"custom",path:["data"],message:"Node tunnel binary body must use canonical base64 encoding."})}),Ss=/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$/,Ns=/^sha256:([a-fA-F0-9]{64})$/,vs=/^(?:localhost|[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?)(?::[1-9][0-9]{0,4})?$/,Os=/^[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*$/;function Rs(e){const t=e.trim();if(!t||t.length>512||t.includes("://")||/\s/.test(t))throw new Error("Docker image reference must not contain a URL scheme or whitespace.");const n=t.indexOf("@");if(-1!==n&&n!==t.lastIndexOf("@"))throw new Error("Docker image reference contains more than one digest separator.");const i=-1===n?void 0:t.slice(n+1),s=-1===n?t:t.slice(0,n),r=i?Ns.exec(i):void 0;if(i&&!r)throw new Error("Docker image digest must use sha256 followed by 64 hexadecimal characters.");const o=s.lastIndexOf("/"),a=s.lastIndexOf(":"),c=a>o,d=c?s.slice(a+1):void 0,l=c?s.slice(0,a):s;if(d&&!Ss.test(d))throw new Error("Docker image tag is invalid.");if(!d&&!r)throw new Error("Docker image reference must include an explicit tag or sha256 digest.");const u=l.split("/");if(!u.length||u.some(e=>!e))throw new Error("Docker image repository path is invalid.");const p=u.length>1&&(u[0].includes(".")||u[0].includes(":")||"localhost"===u[0]),m=p?u.slice(1):u;if(p&&!vs.test(u[0].toLowerCase()))throw new Error("Docker image registry host or port is invalid.");if(!m.length||m.some(e=>!Os.test(e)))throw new Error("Docker image repository names must be lowercase and use valid separators.");const h=u.map((e,t)=>p&&0===t?e.toLowerCase():e).join("/"),g=r?`sha256:${r[1].toLowerCase()}`:void 0;return`${h}${d?`:${d}`:""}${g?`@${g}`:""}`}function zs(e){const t=Rs(e),n=t.indexOf("@"),i=-1===n?void 0:t.slice(n+1),s=-1===n?t:t.slice(0,n),r=s.lastIndexOf("/"),o=s.lastIndexOf(":"),a=o>r;return{reference:t,repository:a?s.slice(0,o):s,tag:a?s.slice(o+1):void 0,digest:i}}const xs=c.z.string().trim().min(1).max(512).transform((e,t)=>{try{return Rs(e)}catch(e){return t.addIssue({code:"custom",message:e instanceof Error?e.message:String(e)}),c.z.NEVER}}),Cs=c.z.string().trim().transform((e,t)=>{const n=Ns.exec(e);return n?`sha256:${n[1].toLowerCase()}`:(t.addIssue({code:"custom",message:"Docker image digest must use sha256 followed by 64 hexadecimal characters."}),c.z.NEVER)}),ks=c.z.object({modelEntityIds:c.z.array(Es).max(64).transform(e=>[...new Set(e)]).optional(),codexModelHash:Es.nullable().optional(),claudeModelHash:Es.nullable().optional(),opencodeModelHash:Es.nullable().optional()}).strict().default({}),Ds=c.z.object({imageId:Es,tag:c.z.string().trim().min(1).max(128).regex(Ss).optional()}).strict(),Ls=c.z.discriminatedUnion("type",[c.z.object({type:c.z.literal("image"),imageSelection:Ds}).strict(),c.z.object({type:c.z.literal("template"),environmentTemplateId:Es}).strict()]),Ps=c.z.enum(["creating","ready","failed","deleting"]),Ms=c.z.enum(["linux","darwin","win32","freebsd","openbsd","aix","sunos","unknown"]),js=c.z.enum(["x64","arm64","arm","ia32","ppc64","s390x","riscv64","unknown"]),Us=c.z.object({code:c.z.string().trim().min(1).max(120),message:c.z.string().trim().min(1).max(2048),phase:c.z.enum(["validate","commit","inspect","security-check","persist","delete","recovery"]).optional()}).strict(),Fs=c.z.object({templateId:Es,nodeId:Es,imageId:Cs,name:c.z.string().trim().min(1).max(160),platform:Ms,architecture:js}).strict(),$s=c.z.enum(["data","agent-home","workspace"]),Hs=c.z.object({deleteVolumes:c.z.boolean()}).strict(),Bs=c.z.object({role:$s,name:c.z.string().trim().min(1).max(255),mountPath:c.z.string().trim().startsWith("/").max(4096),status:c.z.enum(["deleted","retained","missing","failed"]),error:c.z.object({code:c.z.string().trim().min(1).max(120),message:c.z.string().trim().min(1).max(2048)}).strict().optional()}).strict(),qs=c.z.object({instanceId:Es,containerDeleted:c.z.boolean(),completed:c.z.boolean(),deletedVolumes:c.z.array(Bs),retainedVolumes:c.z.array(Bs),volumeResults:c.z.array(Bs)}).strict(),Vs={img_default:"market_taskhandoff_browser",img_codex:"market_taskhandoff_codex",img_ai:"market_taskhandoff_ai"};function Gs(e,t){if(e&&"object"==typeof e&&!Array.isArray(e)){const t=e;return{imageId:"string"==typeof t.imageId&&Vs[t.imageId]||t.imageId,..."string"==typeof t.tag?{tag:t.tag}:{}}}if("string"==typeof t)return{imageId:Vs[t]||t}}function Ws(e){if(!e||"object"!=typeof e||Array.isArray(e))return e;const t=e,{defaultImageId:n,origin:i,localizedNames:s,...r}=t;return{...r,defaultImageSelection:Gs(t.defaultImageSelection,n)}}const Ks=c.z.object({id:Es,name:c.z.string().trim().min(1).max(120),kind:c.z.enum(["tty","gui","web"]),source:c.z.enum(["builtin","custom"]),availability:c.z.enum(["available","missing-dependency"]),capabilities:c.z.object({automation:c.z.enum(["cdp"]).optional(),supportsCwdSelection:c.z.boolean().default(!1),supportsProfiles:c.z.boolean().default(!1)}).strict().default({supportsCwdSelection:!1,supportsProfiles:!1}),diagnosticCode:c.z.enum(["APP_EXECUTABLE_NOT_FOUND"]).optional()}).strict(),Ys=c.z.object({code:c.z.enum(["APP_CATALOG_INVALID"]),message:c.z.string().trim().min(1).max(500)}).strict(),Xs=c.z.object({items:c.z.array(Ks).max(256),observedAt:As,issues:c.z.array(Ys).max(32).default([])}).strict(),Js=c.z.object({id:Es,name:c.z.string().trim().min(1).max(160),sourceInstanceId:Es,nodeId:Es,imageId:Cs.optional(),internalTag:c.z.string().trim().min(1).max(512).optional(),platform:Ms.optional(),architecture:js.optional(),sizeBytes:c.z.number().int().nonnegative().optional(),status:Ps,error:Us.optional(),createdAt:As,updatedAt:As}).strict().superRefine((e,t)=>{if("ready"===e.status)for(const n of["imageId","internalTag","platform","architecture","sizeBytes"])void 0===e[n]&&t.addIssue({code:"custom",path:[n],message:`Ready environment template requires ${n}.`});"failed"!==e.status||e.error||t.addIssue({code:"custom",path:["error"],message:"Failed environment template requires an error diagnostic."})}),Qs=c.z.enum(["apt","dnf","brew","npm"]),Zs=c.z.enum(["user","passwordless-sudo","root"]),er=c.z.object({platform:Ms,arch:js,installers:c.z.array(Qs).max(8),privilege:Zs,installerAccess:c.z.object({npmGlobalWritable:c.z.boolean().optional()}).strict().optional()}).strict(),tr=c.z.enum(["installed","not-installed","broken","unsupported"]),nr=c.z.enum(["recipe","bundled","external","none"]),ir=c.z.object({code:c.z.enum(["BUNDLED","EXTERNALLY_MANAGED","ALREADY_INSTALLED","NOT_INSTALLED","UNSUPPORTED_PLATFORM","INSTALLER_UNAVAILABLE","INSTALLER_NOT_WRITABLE","INSUFFICIENT_PRIVILEGE","OPERATION_IN_PROGRESS"]),message:c.z.string().trim().min(1).max(500)}).strict(),sr=c.z.enum(["update-available","up-to-date","unknown","unsupported"]),rr=c.z.object({status:sr,installedVersion:c.z.string().trim().max(120).optional(),latestVersion:c.z.string().trim().max(120).optional(),checkedAt:As,reason:c.z.string().trim().max(500).optional()}).strict(),or=rr.extend({appId:Es}).strict(),ar=c.z.object({id:Es,name:c.z.string().trim().min(1).max(120),kind:c.z.enum(["tty","gui","web"]),description:c.z.string().trim().max(500).optional(),state:tr,managementSource:nr,version:c.z.string().trim().max(120).optional(),canInstall:c.z.boolean(),canUninstall:c.z.boolean(),canUpdate:c.z.boolean().optional(),installReason:ir.optional(),uninstallReason:ir.optional(),updateReason:ir.optional(),updateCheck:rr.optional(),activeJobId:Es.optional()}).strict(),cr=c.z.enum(["install","uninstall","update"]),dr=c.z.enum(["queued","running","succeeded","failed","cancelled","interrupted"]),lr=c.z.object({current:c.z.number().finite().nonnegative().optional(),total:c.z.number().finite().positive().optional(),unit:c.z.string().trim().min(1).max(40).optional()}).strict().refine(e=>void 0===e.total||void 0===e.current||e.current<=e.total,{message:"Progress current must not exceed total.",path:["current"]}),ur=c.z.object({executable:c.z.string().trim().min(1).max(4096),args:c.z.array(c.z.string().max(4096)).max(128)}).strict(),pr=c.z.object({code:c.z.string().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),message:c.z.string().trim().min(1).max(4096),retryable:c.z.boolean(),sessionIds:c.z.array(Es).max(64).optional()}).strict(),mr=c.z.object({id:Es,requestId:Es.optional(),appId:Es,operation:cr,state:dr,phase:c.z.string().trim().min(1).max(120).optional(),progress:lr.optional(),command:ur.optional(),logTail:c.z.string().max(32768).optional(),logTruncated:c.z.boolean().optional(),error:pr.optional(),requestedAt:As,startedAt:As.optional(),finishedAt:As.optional(),updatedAt:As}).strict(),hr=c.z.object({streamId:Es,sequence:c.z.number().int().nonnegative(),capabilities:er,apps:c.z.array(ar).max(256),activeJobs:c.z.array(mr).max(256),recentJobs:c.z.array(mr).max(256),observedAt:As}).strict();c.z.object({requestId:Es.optional()}).strict(),c.z.object({job:mr}).strict(),c.z.object({check:or}).strict(),c.z.object({type:c.z.literal("app-management"),streamId:Es,sequence:c.z.number().int().nonnegative(),observedAt:As,job:mr.optional(),snapshot:hr.optional()}).strict().refine(e=>void 0!==e.job||void 0!==e.snapshot,{message:"An app management event requires a job or snapshot."});const gr=c.z.object({component:c.z.enum(["control-plane","node-agent","controlled-instance"]),packageName:c.z.string().trim().max(160).optional(),packageVersion:c.z.string().trim().max(80).optional(),protocolVersion:es.optional(),buildId:c.z.string().trim().max(160).optional(),builtAt:c.z.string().trim().max(120).optional(),gitCommit:c.z.string().trim().max(120).optional(),imageRef:c.z.string().trim().max(512).optional(),imageDigest:c.z.string().trim().max(240).optional()}).strict();c.z.object({data:c.z.object({ok:c.z.literal(!0),role:c.z.literal("control-plane"),protocolVersion:es,build:gr.extend({component:c.z.literal("control-plane"),packageVersion:c.z.string().trim().min(1).max(80)}).loose(),serverTime:As}).loose()}).loose();const fr=c.z.enum(["stable","beta","alpha"]),yr=c.z.object({packageName:c.z.literal("@task-handoff/controlled-instance"),version:c.z.string().trim().min(1).max(80),platform:c.z.string().trim().min(1).max(40),arch:c.z.string().trim().min(1).max(40),formatVersion:c.z.number().int().positive(),launcherAbi:c.z.number().int().positive(),entrypoint:c.z.string().trim().min(1).max(512),sha256:c.z.string().regex(/^[a-f0-9]{64}$/)}).strict(),Ir=c.z.object({code:c.z.enum(["INSTANCE_RUNTIME_VERSION_MISMATCH","INSTANCE_RUNTIME_ARTIFACT_UNAVAILABLE","INSTANCE_RUNTIME_ARTIFACT_INVALID","INSTANCE_RUNTIME_INSTALL_FAILED","INSTANCE_RUNTIME_RESTART_FAILED","INSTANCE_RUNTIME_VERIFICATION_FAILED","INSTANCE_BASE_RUNTIME_INCOMPATIBLE","NODE_UPDATE_PREFLIGHT_FAILED","NODE_UPDATE_FAILED","LEGACY_INSTANCE_UPDATE_RETIRED"]),message:c.z.string().trim().min(1).max(4096),expectedVersion:c.z.string().trim().min(1).max(80).optional(),actualVersion:c.z.string().trim().min(1).max(80).optional(),retryable:c.z.boolean().default(!1)}).strict(),_r=c.z.object({desiredVersion:c.z.string().trim().min(1).max(80),actualVersion:c.z.string().trim().min(1).max(80).optional(),phase:c.z.enum(["pending","draining","installing","restarting","verifying","matched","failed"]),attempt:c.z.number().int().nonnegative().default(0),lastAttemptAt:As.optional(),matchedAt:As.optional(),error:Ir.optional()}).strict(),Er=c.z.object({runningInstanceCount:c.z.number().int().nonnegative(),stoppedInstanceCount:c.z.number().int().nonnegative(),activeInstanceCount:c.z.number().int().nonnegative(),restartInstanceCount:c.z.number().int().nonnegative(),runningInstanceIds:c.z.array(Es).max(1024).default([]),stoppedInstanceIds:c.z.array(Es).max(1024).default([]),activeInstanceIds:c.z.array(Es).max(1024).default([])}).strict(),Ar=c.z.object({phase:c.z.enum(["queued","updating-node","restarting-node","converging-instances","succeeded","degraded","failed"]),desiredVersion:c.z.string().trim().min(1).max(80),nodeVersion:c.z.string().trim().min(1).max(80).optional(),expectedInstanceIds:c.z.array(Es).max(1024).default([]),expectedInstanceCount:c.z.number().int().nonnegative(),matchedInstanceCount:c.z.number().int().nonnegative(),pendingInstanceCount:c.z.number().int().nonnegative(),failedInstanceCount:c.z.number().int().nonnegative(),deferredInstanceCount:c.z.number().int().nonnegative().default(0)}).strict(),Tr=c.z.object({channel:fr.default("stable")}).strict(),br=c.z.object({source:c.z.literal("npm"),channel:fr,currentVersion:c.z.string().trim().max(240).optional(),availableVersion:c.z.string().trim().min(1).max(240),artifactRef:c.z.string().trim().min(1).max(512).optional(),runtimeArtifacts:c.z.array(yr).default([]),impact:Er,updateAvailable:c.z.boolean(),supported:c.z.boolean().default(!0),reason:c.z.string().trim().max(2048).optional(),checkedAt:As,preflightToken:c.z.string().trim().min(16).max(240).optional()}).strict(),wr=c.z.object({id:Es,nodeId:Es,source:c.z.literal("npm"),channel:fr,fromVersion:c.z.string().trim().max(240).optional(),toVersion:c.z.string().trim().min(1).max(240),artifactRef:c.z.string().trim().min(1).max(512).optional(),runtimeArtifacts:c.z.array(yr).default([]),impact:Er,rollout:Ar,status:c.z.enum(["queued","updating-node","restarting-node","converging-instances","succeeded","degraded","failed"]),error:Ir.optional(),startedAt:As.optional(),completedAt:As.optional(),createdAt:As,updatedAt:As}).strict(),Sr=c.z.object({channel:fr,targetVersion:c.z.string().trim().min(1).max(240),preflightToken:c.z.string().trim().min(16).max(240)}).strict(),Nr=c.z.object({type:c.z.enum(["branch","tag"]),name:c.z.string().trim().min(1).max(240)}).strict(),vr=c.z.object({type:c.z.literal("commit"),commit:c.z.string().trim().regex(/^[0-9a-fA-F]{4,64}$/,"commit must be a hexadecimal Git object id")}).strict(),Or=c.z.discriminatedUnion("type",[Nr,vr]),Rr=c.z.object({type:c.z.enum(["none","ssh-key","https-token"]).default("none"),secretId:c.z.string().trim().min(1).max(120).optional()}).strict(),zr=c.z.object({depth:c.z.number().int().positive().max(1e5).optional(),submodules:c.z.boolean().default(!1),lfs:c.z.boolean().default(!1),subdirectory:c.z.string().trim().max(240).refine(e=>!e.startsWith("/")&&!e.split("/").some(e=>".."===e),"subdirectory must be a relative path within the repository").transform(e=>e.split("/").filter(e=>e&&"."!==e).join("/")).default("")}).strict();c.z.object({id:Es,name:c.z.string().trim().min(1).max(160),url:c.z.string().trim().min(1).max(2048),provider:c.z.string().trim().max(80).optional(),ref:Or.default({type:"branch",name:"main"}),auth:Rr.default({type:"none"}),clone:zr.default({submodules:!1,lfs:!1,subdirectory:""}),defaultImageSelection:Ds.optional(),labels:Ts,createdAt:As,updatedAt:As}).strict();const xr=c.z.enum(["user","builtin"]),Cr=c.z.record(c.z.string().trim().min(2).max(35),c.z.string().trim().min(1).max(160)),kr=c.z.object({id:Es,nodeId:Es,name:c.z.string().trim().min(1).max(160),path:c.z.string().trim().min(1).max(4096),origin:xr.default("user"),localizedNames:Cr.optional(),defaultImageSelection:Ds.optional(),labels:Ts,createdAt:As,updatedAt:As}).strict(),Dr=c.z.discriminatedUnion("type",[c.z.object({type:c.z.literal("git-repository"),repositoryId:Es.optional(),url:c.z.string().trim().min(1).max(2048),provider:c.z.string().trim().max(80).optional(),ref:Or.default({type:"branch",name:"main"}),auth:Rr.default({type:"none"}),clone:zr.default({submodules:!1,lfs:!1,subdirectory:""})}).strict(),c.z.object({type:c.z.literal("git-template"),url:c.z.string().trim().min(1).max(2048),templateId:c.z.string().trim().min(1).max(120).optional(),ref:Or.default({type:"branch",name:"main"}),auth:Rr.default({type:"none"}),clone:zr.default({submodules:!1,lfs:!1,subdirectory:""})}).strict(),c.z.object({type:c.z.literal("local-folder"),localFolderId:Es.optional(),path:c.z.string().trim().min(1).max(4096),ownerNodeId:Es.optional()}).strict()]),Lr=c.z.object({mode:c.z.enum(["local-bind","git-clone","empty-volume","persistent-volume"]),path:c.z.string().trim().min(1).max(4096).default("/workspace"),volumeName:c.z.string().trim().max(240).optional(),readOnly:c.z.boolean().default(!1)}).strict(),Pr=c.z.enum(["codex","claude","opencode"]),Mr=c.z.object({name:c.z.string().trim().min(1).max(240),upstreamName:c.z.string().trim().min(1).max(240).optional(),order:c.z.number().int().min(0).max(1e6).default(0)}).strict(),jr=c.z.array(Mr).max(256).default([]).superRefine((e,t)=>{const n=new Set;for(const[i,s]of e.entries())n.has(s.name)&&t.addIssue({code:"custom",path:[i,"name"],message:`Duplicate model name ${s.name}.`}),n.add(s.name)}),Ur=c.z.object({name:c.z.string().trim().min(1).max(240),upstreamName:c.z.string().trim().min(1).max(240),order:c.z.number().int().min(0).max(1e6).default(0)}).strict(),Fr=c.z.array(Ur).max(64).superRefine((e,t)=>{const n=new Set;for(const[i,s]of e.entries())n.has(s.name)&&t.addIssue({code:"custom",path:[i,"name"],message:`Duplicate request mapping ${s.name}.`}),n.add(s.name)}),$r=Fr.default([]),Hr=c.z.object({id:Es,name:c.z.string().trim().min(1).max(160),source:Dr,defaultImageSelection:Ds.optional(),defaultNodeId:Es.optional(),workspacePolicy:Lr,labels:Ts,createdAt:As,updatedAt:As}).strict(),Br=c.z.object({id:Es,name:c.z.string().trim().min(1).max(160),endpoint:c.z.string().trim().min(1).max(2048),key:c.z.string().trim().min(1).max(4096),model:c.z.string().trim().min(1).max(240),modelNames:jr,mappings:$r,protocols:c.z.array(xi).max(3).default([]),app:Pr,enabled:c.z.boolean().default(!0),order:c.z.number().int().min(0).max(1e6).default(0),labels:Ts,createdAt:As,updatedAt:As}).strict(),qr=Br,Vr=Br.omit({key:!0}).extend({keyPreview:c.z.string().trim().min(1).max(160),keySet:c.z.boolean(),revision:c.z.string().trim().min(1).max(160).optional()}).strict(),Gr=Vr.extend({referenceCount:c.z.number().int().min(0)}).strict(),Wr=c.z.object({instanceId:Es,modelEntityIds:c.z.array(Es).max(64).transform(e=>[...new Set(e)]).optional(),codexModelHash:Es.optional(),claudeModelHash:Es.optional(),opencodeModelHash:Es.optional(),updatedAt:As}).strict().transform(e=>({...e,modelEntityIds:void 0!==e.modelEntityIds?e.modelEntityIds:[...new Set([e.codexModelHash,e.claudeModelHash,e.opencodeModelHash].filter(e=>Boolean(e)))]})),Kr=c.z.discriminatedUnion("type",[c.z.object({type:c.z.literal("control-plane"),name:Br.shape.name,enabled:Br.shape.enabled,order:Br.shape.order,revision:c.z.string().trim().min(1).max(160).optional()}).strict(),c.z.object({type:c.z.literal("node"),nodeId:Es,name:Br.shape.name,enabled:Br.shape.enabled,order:Br.shape.order,referenceCount:c.z.number().int().min(0),revision:c.z.string().trim().min(1).max(160).optional()}).strict()]),Yr=c.z.object({id:Es,model:Vr,locations:c.z.array(Kr).min(1),referenceCount:c.z.number().int().min(0).default(0)}).strict(),Xr=c.z.object({nodeId:Es,code:c.z.string().trim().min(1).max(120),message:c.z.string().trim().min(1).max(2e3)}).strict();c.z.object({models:c.z.array(Yr),nodeDiagnostics:c.z.array(Xr).default([]),updatedAt:As}).strict();const Jr=Br.omit({id:!0,createdAt:!0,updatedAt:!0}).extend({mappings:Fr.optional()}).strict(),Qr=Jr.partial().strict(),Zr=Br,eo=c.z.enum(["synced","pending","unsupported","error"]),to=c.z.object({nodeId:Es,state:eo,code:c.z.string().trim().min(1).max(120).optional(),message:c.z.string().trim().min(1).max(2e3).optional()}).strict();c.z.object({model:Vr,locations:c.z.array(to).default([])}).strict();const no=c.z.object({targetModelId:Es}).strict();c.z.object({merged:c.z.literal(!0),reassignedInstances:c.z.array(Es).default([])}).strict();const io=c.z.object({nodeId:Es,merged:c.z.boolean(),reassignedInstances:c.z.array(Es).default([]),code:c.z.string().trim().min(1).max(120).optional(),message:c.z.string().trim().min(1).max(2e3).optional()}).strict();c.z.object({modelId:Es,targetModelId:Es,merged:c.z.boolean(),locations:c.z.array(io).default([])}).strict();const so=c.z.object({modelSelection:ks,modelEntityIds:c.z.array(Es).max(64).transform(e=>[...new Set(e)]).optional(),codexModelHash:Es.optional(),claudeModelHash:Es.optional(),opencodeModelHash:Es.optional()}).strict().transform(e=>({...e,modelEntityIds:e.modelEntityIds||e.modelSelection.modelEntityIds||[...new Set([e.codexModelHash,e.claudeModelHash,e.opencodeModelHash].filter(e=>Boolean(e)))]}));function ro(e,t,n){if(!Array.isArray(e))return e;const i=new Set;return e.flatMap((e,s)=>{if(!e||"object"!=typeof e||Array.isArray(e))return[e];const r=e;for(const e of Object.keys(r))"name"!==e&&"upstreamName"!==e&&"order"!==e&&n?.({field:`${t}[${s}].${e}`});const o="string"==typeof r.name?r.name.trim():void 0,a="string"==typeof r.upstreamName?r.upstreamName.trim():void 0;if(o){if(i.has(o))return n?.({field:`${t}[${s}].name`}),[];i.add(o)}return[{...o?{name:o}:{name:r.name},...a?{upstreamName:a}:{},order:r.order}]})}function oo(e,t,n={}){const i=(e?.length?e:t?.trim()?[{name:t.trim(),order:100}]:[]).map(e=>({name:e.name.trim(),upstreamName:e.upstreamName?.trim()||e.name.trim(),order:e.order})).sort((e,t)=>e.order-t.order||e.name.localeCompare(t.name));return!1===n.renumber?i:i.map((e,t)=>({...e,order:100*(t+1)}))}function ao(e){return e.map(e=>({name:e.name,...e.upstreamName&&e.upstreamName!==e.name?{upstreamName:e.upstreamName}:{},order:e.order}))}function co(e,t={}){const n=(e??[]).map(e=>({name:e.name.trim(),upstreamName:e.upstreamName.trim(),order:e.order})).sort((e,t)=>e.order-t.order||e.name.localeCompare(t.name));return!1===t.renumber?n:n.map((e,t)=>({...e,order:100*(t+1)}))}function lo(e){const t=Pr.parse(e.app),n=oo(e.modelNames,e.model),i=co(e.mappings),s=e.protocols?.length?e.protocols:function(e){return"claude"===e?["anthropic-messages"]:"opencode"===e?["openai-chat-completions"]:["openai-responses"]}(t),r={algorithm:"model-content-revision-v1",app:t,endpoint:Br.shape.endpoint.parse(e.endpoint),key:Br.shape.key.parse(e.key),model:Br.shape.model.parse(e.model),modelNames:n.map(e=>({name:e.name,upstreamName:e.upstreamName,order:e.order})),protocols:[...new Set(s)].sort(),...i.length?{mappings:i.map(e=>({name:e.name,upstreamName:e.upstreamName,order:e.order}))}:{}};return`mdlr_${o=JSON.stringify(r),Array.from(Bi(o),e=>e.toString(16).padStart(2,"0")).join("")}`;var o}const uo=Date.UTC(2026,0,1),po="0123456789abcdefghjkmnpqrstvwxyz",mo=new RegExp(`^mdl_[${po}]{13}$`);function ho(e,t){const n=[];let i=e;for(;i>0n;)n.unshift(po[Number(i%32n)]),i/=32n;return`${"0".repeat(Math.max(0,t-n.length))}${n.join("")}`}let go;function fo(e,t=Date.now()){const n=BigInt(Math.max(0,t-uo))&(1n<<41n)-1n,i=function(e){for(go?.timestamp!==e&&(go={timestamp:e,random:new Set});;){const e=qi(3),t=BigInt(e[0]<<16|e[1]<<8|e[2])>>1n;if(!go.random.has(t))return go.random.add(t),t}}(n);return`${e}_${ho(n<<23n|i,13)}`}function yo(e=Date.now()){return fo("mdl",e)}function Io(e){return mo.test(e)}function _o(e){const t=Bi(`task-handoff:model-entity-migration:v1:${e}`);let n=0n;for(const e of t.subarray(0,8))n=n<<8n|BigInt(e);return`mdl_${ho(n,13)}`}const Eo=c.z.enum(["market","custom"]),Ao=c.z.enum(["active","deprecated","yanked"]),To=c.z.discriminatedUnion("kind",[c.z.object({kind:c.z.literal("builtin"),key:c.z.string().trim().min(1).max(120)}).strict(),c.z.object({kind:c.z.literal("remote"),url:c.z.string().trim().url().max(2048),mediaType:c.z.enum(["image/png","image/jpeg","image/webp"]).optional(),digest:Cs.optional()}).strict()]),bo=c.z.array(c.z.string().trim().min(1).max(80)).default([]),wo=c.z.array(c.z.string().trim().min(1).max(120)).default([]),So=c.z.record(c.z.string().trim().min(2).max(35),c.z.string().trim().min(1).max(4096)),No=c.z.object({os:c.z.string().trim().min(1).max(40),architecture:c.z.string().trim().min(1).max(40),digest:Cs.optional(),downloadSizeBytes:c.z.number().int().positive().optional(),unpackedSizeBytes:c.z.number().int().positive().optional()}).strict(),vo=c.z.object({name:c.z.string().trim().min(1).max(128).regex(Ss),version:c.z.string().trim().min(1).max(160).optional(),reference:xs,manifestDigest:Cs.optional(),publishedAt:As.optional(),platforms:c.z.array(No).default([]),status:Ao.default("active")}).strict(),Oo=c.z.object({id:Es,publisher:c.z.string().trim().min(1).max(160),slug:c.z.string().trim().min(1).max(160),name:c.z.string().trim().min(1).max(160),description:c.z.string().trim().min(1).max(4096),localizedDescriptions:So.optional(),cover:To.optional(),repository:c.z.string().trim().min(1).max(512),defaultTag:c.z.string().trim().min(1).max(128).regex(Ss),tags:c.z.array(vo).min(1),capabilities:bo,optionalApps:wo,defaultEnv:bs,labels:Ts,status:Ao.default("active")}).strict().superRefine((e,t)=>{e.tags.some(t=>t.name===e.defaultTag)||t.addIssue({code:"custom",path:["defaultTag"],message:"Market defaultTag must identify one of the image tags."})});c.z.object({protocolVersion:es,catalogId:Es,revision:c.z.string().trim().min(1).max(240),source:c.z.enum(["embedded","remote","cache"]),generatedAt:As,expiresAt:As.optional(),items:c.z.array(Oo)}).strict(),c.z.object({source:c.z.enum(["embedded","remote","cache"]),state:c.z.enum(["ready","refreshing","stale","failed"]),revision:c.z.string().trim().min(1).max(240),updatedAt:As,error:c.z.string().trim().max(4096).optional()}).strict();const Ro=c.z.object({id:Es,origin:c.z.literal("custom"),name:c.z.string().trim().min(1).max(160),description:c.z.string().trim().max(4096).optional(),localizedDescriptions:So.optional(),cover:To.optional(),reference:xs,repository:c.z.string().trim().min(1).max(512),tag:c.z.string().trim().min(1).max(128).regex(Ss).optional(),pullPolicy:c.z.literal("if-not-present").default("if-not-present"),capabilities:bo,optionalApps:wo,defaultEnv:bs,labels:Ts,createdAt:As,updatedAt:As}).strict(),zo=c.z.object({name:c.z.string().trim().min(1).max(128).regex(Ss),version:c.z.string().trim().min(1).max(160).optional(),reference:xs,manifestDigest:Cs.optional(),status:Ao}).strict(),xo=c.z.object({id:Es,origin:Eo,name:c.z.string().trim().min(1).max(160),description:c.z.string().trim().max(4096).optional(),localizedDescriptions:So.optional(),cover:To,repository:c.z.string().trim().min(1).max(512),tag:c.z.string().trim().min(1).max(128).regex(Ss).optional(),availableTags:c.z.array(zo),reference:xs,digest:Cs.optional(),downloadSizeBytes:c.z.number().int().positive().optional(),unpackedSizeBytes:c.z.number().int().positive().optional(),capabilities:bo,optionalApps:wo,defaultEnv:bs,labels:Ts,readOnly:c.z.boolean(),lifecycleStatus:Ao.optional(),market:c.z.object({catalogId:Es,catalogRevision:c.z.string().trim().min(1).max(240),publisher:c.z.string().trim().min(1).max(160),version:c.z.string().trim().min(1).max(160).optional()}).strict().optional()}).strict(),Co=c.z.object({id:Es,origin:Eo,name:c.z.string().trim().min(1).max(160),description:c.z.string().trim().max(4096).optional(),localizedDescriptions:So.optional(),cover:To.optional(),repository:c.z.string().trim().min(1).max(512),tag:c.z.string().trim().min(1).max(128).regex(Ss).optional(),requestedReference:xs,resolvedDigest:Cs.optional(),resolvedReference:xs.optional(),downloadSizeBytes:c.z.number().int().positive().optional(),pullPolicy:c.z.literal("if-not-present").default("if-not-present"),capabilities:bo,optionalApps:wo,defaultEnv:bs,labels:Ts,market:c.z.object({catalogId:Es,catalogRevision:c.z.string().trim().min(1).max(240),publisher:c.z.string().trim().min(1).max(160),version:c.z.string().trim().min(1).max(160).optional()}).strict().optional(),createdAt:As,updatedAt:As}).strict(),ko=c.z.object({phase:c.z.enum(["checking-image","pulling-image","resolving-image","ready","failed"]),requestedReference:xs,generation:c.z.number().int().nonnegative().default(0),error:c.z.string().trim().max(4096).optional(),startedAt:As,updatedAt:As}).strict(),Do="image.pull.terminal.output",Lo="image.pull.terminal.finished",Po=c.z.object({instanceId:Es,generation:c.z.number().int().nonnegative(),requestedReference:xs,sequence:c.z.number().int().nonnegative(),observedAt:As}).strict(),Mo=Po.extend({data:c.z.string().min(1).max(65536),replay:c.z.boolean().optional()}).strict(),jo=Po.extend({outcome:c.z.enum(["succeeded","failed"])}).strict();Po.extend({status:c.z.enum(["connecting","pulling","extracting","complete","failed"]),layers:c.z.object({total:c.z.number().int().nonnegative(),completed:c.z.number().int().nonnegative(),downloaded:c.z.number().int().nonnegative(),downloading:c.z.number().int().nonnegative(),extracting:c.z.number().int().nonnegative()}).strict(),bytes:c.z.object({current:c.z.number().finite().nonnegative(),total:c.z.number().finite().positive()}).strict().optional(),percent:c.z.number().finite().min(0).max(100).optional(),message:c.z.string().trim().min(1).max(500),terminalTail:c.z.string().max(262144).optional(),terminalTruncated:c.z.boolean().optional()}).strict();const Uo=c.z.enum(["pending","cloning","checking-out","submodules","lfs","finalizing","ready","failed"]),Fo=c.z.object({phase:Uo,remoteUrl:c.z.string().trim().min(1).max(2048),generation:c.z.number().int().nonnegative().default(0),error:c.z.string().trim().max(4096).optional(),startedAt:As,updatedAt:As}).strict(),$o="git.provisioning.terminal.output",Ho="git.provisioning.terminal.finished",Bo=c.z.object({instanceId:Es,generation:c.z.number().int().nonnegative(),remoteUrl:c.z.string().trim().min(1).max(2048),sequence:c.z.number().int().nonnegative(),observedAt:As}).strict(),qo=Bo.extend({data:c.z.string().min(1).max(65536),replay:c.z.boolean().optional()}).strict(),Vo=Bo.extend({outcome:c.z.enum(["succeeded","failed"])}).strict();Bo.extend({status:c.z.enum(["connecting","cloning","checking-out","submodules","lfs","finalizing","complete","failed"]),objects:c.z.object({received:c.z.number().int().nonnegative(),total:c.z.number().int().nonnegative()}).strict().optional(),bytes:c.z.object({current:c.z.number().finite().nonnegative(),total:c.z.number().finite().positive()}).strict().optional(),percent:c.z.number().finite().min(0).max(100).optional(),message:c.z.string().trim().min(1).max(500),terminalTail:c.z.string().max(262144).optional(),terminalTruncated:c.z.boolean().optional()}).strict();const Go=c.z.discriminatedUnion("kind",[c.z.object({kind:c.z.literal("direct")}).strict(),c.z.object({kind:c.z.literal("control-plane-proxy"),proxyId:Es,proxyBindingId:Es,targetNodeId:Es}).strict()]),Wo=c.z.object({pingRttMs:c.z.number().nonnegative().optional(),pingRttP95Ms:c.z.number().nonnegative().optional(),consecutiveReconnects:c.z.number().int().nonnegative(),nextRetryAt:As.optional()}).strict();c.z.object({nodeId:Es,inviteId:Es.optional()}).strict(),c.z.discriminatedUnion("status",[c.z.object({id:Es,status:c.z.literal("pending")}).strict(),c.z.object({id:Es,status:c.z.literal("completed"),nodeId:Es}).strict()]);const Ko=c.z.object({reachability:c.z.enum(["unknown","reachable","unreachable"]),bindingStatus:c.z.enum(["unknown","active","revoked"]),bindingRevision:c.z.number().int().positive().optional(),streamId:c.z.string().trim().min(1).max(160).optional(),revision:c.z.number().int().nonnegative().optional(),observedAt:As.optional(),target:Wn.optional(),lastError:Hn.optional(),updatedAt:As}).strict(),Yo=c.z.object({id:Es,name:c.z.string().trim().min(1).max(160),connectionMode:c.z.enum(["local-ipc","local-loopback","direct-http","reverse-wss","control-plane-proxy"]).default("direct-http"),connectionPath:Go.default({kind:"direct"}),connectionEnabled:c.z.boolean().default(!0),auth:c.z.object({mode:c.z.enum(["local-static-key","paired-hmac","proxy-binding"]).default("local-static-key"),keyId:Es.optional(),secret:c.z.string().trim().max(4096).optional(),pairedAt:As.optional(),pairing:c.z.object({status:c.z.enum(["pending","paired","expired"]).default("pending"),joinToken:c.z.string().trim().max(4096).optional(),expiresAt:As.optional()}).strict().optional()}).strict().default({mode:"local-static-key"}),endpoint:c.z.string().trim().max(2048).optional(),controlEndpoint:c.z.string().trim().max(2048).optional(),containerEndpoint:c.z.string().trim().max(2048).optional(),publicWebBase:c.z.string().trim().max(2048).optional(),status:c.z.enum(["unknown","online","offline","degraded"]).default("unknown"),health:c.z.enum(["unknown","ok","degraded","failed"]).default("unknown"),capabilities:c.z.record(c.z.string(),c.z.unknown()).default({}),proxyState:Ko.optional(),appInventory:Xs.optional(),labels:Ts,lastSeenAt:As.optional(),createdAt:As,updatedAt:As}).strict().superRefine((e,t)=>{"control-plane-proxy"===e.connectionPath.kind&&"control-plane-proxy"!==e.connectionMode&&t.addIssue({code:"custom",path:["connectionPath"],message:"Control-plane proxy paths require control-plane-proxy connection mode."}),"control-plane-proxy"===e.connectionMode&&"control-plane-proxy"!==e.connectionPath.kind&&t.addIssue({code:"custom",path:["connectionPath"],message:"Control-plane proxy nodes require a control-plane-proxy connection path."})});c.z.object({nodeId:Es,status:c.z.enum(["unknown","online","offline","degraded"]),health:c.z.enum(["unknown","ok","degraded","failed"]),lastSeenAt:As.nullable(),connectionPhase:c.z.enum(["connecting","handshaking","healthy","reconnecting","suspect","offline"]).nullable(),connectionDiagnostics:Wo.nullable(),proxyState:Ko.nullable()}).strict();const Xo=["docker","kubernetes","local","wsl"],Jo=c.z.enum(Xo),Qo=c.z.object({id:Es,nodeId:Es,name:c.z.string().trim().min(1).max(160),type:Jo,status:c.z.enum(["unknown","online","offline","degraded"]).default("unknown"),accessStrategy:c.z.enum(["node-proxy","direct-port","kubernetes-ingress","kubernetes-port-forward"]).default("node-proxy"),capabilities:c.z.record(c.z.string(),c.z.unknown()).default({}),labels:Ts,createdAt:As,updatedAt:As}).strict();c.z.array(c.z.unknown()).transform(e=>e.filter(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return!0;const t=e.type;return!("string"==typeof t&&!function(e){return"string"==typeof e&&Xo.includes(e)}(t))})).pipe(c.z.array(Qo));const Zo="bundled-runtime-artifact",ea=c.z.enum(["none","process","distro","container","vm"]),ta=c.z.object({requiresImage:c.z.boolean().default(!1),artifactKind:c.z.enum(["none",Zo]).default(Zo),isolation:ea.default("distro"),supportsControlledInstanceApi:c.z.boolean().default(!0),supportsContainerLifecycle:c.z.boolean().default(!1),supportsAppSessions:c.z.boolean().default(!0),supportsHostSessions:c.z.boolean().default(!1),workspaceProvisioning:c.z.object({git:c.z.boolean().default(!1),localFolder:c.z.boolean().default(!1)}).strip().default({git:!1,localFolder:!1}),baseProfiles:c.z.array(c.z.string().trim().min(1).max(120)).max(8).default([])}).strip();function na(e={}){return ta.parse(e)}const ia=c.z.object({instanceId:Es,runtimeKind:c.z.literal("docker"),state:c.z.enum(["pending","available","stopped","unavailable"]),sampledAt:As,cpu:c.z.object({usagePercent:c.z.number().nonnegative()}).strict().optional(),memory:c.z.object({usageBytes:c.z.number().nonnegative(),limitBytes:c.z.number().nonnegative().optional(),usagePercent:c.z.number().nonnegative().optional()}).strict().optional(),network:c.z.object({rxBytes:c.z.number().nonnegative(),txBytes:c.z.number().nonnegative()}).strict().optional(),blockIo:c.z.object({readBytes:c.z.number().nonnegative(),writeBytes:c.z.number().nonnegative()}).strict().optional(),pids:c.z.number().int().nonnegative().optional(),error:c.z.string().trim().max(2048).optional()}).strict(),sa=c.z.object({status:c.z.enum(["healthy","congested","recovering"]),activeOutputs:c.z.number().int().nonnegative(),bufferedBytes:c.z.number().int().nonnegative(),peakBufferedBytes:c.z.number().int().nonnegative(),coalescedEvents:c.z.number().int().nonnegative(),oversizedEvents:c.z.number().int().nonnegative().optional(),peakEventBytes:c.z.number().int().nonnegative().optional(),congestedSince:As.optional(),lastCongestedAt:As.optional()}).strip();c.z.object({ok:c.z.boolean().optional(),role:c.z.string().optional(),nodeId:Es.optional(),hostname:c.z.string().trim().min(1).max(255).optional(),platform:Ms.optional(),arch:js.optional(),protocolVersion:es.optional(),capabilities:$i.optional(),build:gr.strip().optional(),process:c.z.object({pid:c.z.number().int().positive(),startIdentity:c.z.string().trim().min(1).optional()}).strip().optional(),listener:c.z.object({host:c.z.string().trim().min(1),port:c.z.number().int().min(1).max(65535)}).strip().optional(),instanceProxy:c.z.object({requests:c.z.number().int().nonnegative(),active:c.z.number().int().nonnegative(),completed:c.z.number().int().nonnegative(),aborted:c.z.number().int().nonnegative(),limitRejected:c.z.number().int().nonnegative(),responseBytes:c.z.number().nonnegative(),totalDurationMs:c.z.number().nonnegative(),maxResponseBytes:c.z.number().int().nonnegative()}).partial().strip().optional(),eventTransport:sa.optional(),serverTime:As.optional()}).strip();const ra=c.z.object({bindScope:c.z.enum(["loopback","all-ipv4"]),port:c.z.number().int().min(1).max(65535)}).strict(),oa=ra.extend({host:c.z.enum(["127.0.0.1","0.0.0.0"]),status:c.z.enum(["listening","error"]),source:c.z.enum(["bootstrap","persisted"]),error:c.z.string().trim().max(2048).optional()}).strict(),aa=ra,ca=c.z.enum(["passthrough","reject"]),da=c.z.object({enabled:c.z.boolean(),unknownModelPolicy:ca.optional()}).strict();c.z.object({enabled:c.z.boolean(),unknownModelPolicy:ca.optional(),source:c.z.enum(["default","persisted"])}).strip();const la=da;c.z.object({nodeId:Es,joinToken:c.z.string().trim().min(1),expiresAt:As}).passthrough(),c.z.object({nodeId:Es,keyId:Es,secret:c.z.string().regex(/^[A-Za-z0-9_-]{32,128}$/),pairedAt:As}).strict();const ua=c.z.object({id:Es,keyId:Es,name:c.z.string().trim().min(1).max(160).optional(),pairedAt:As,updatedAt:As,current:c.z.boolean()}).passthrough();c.z.object({keyId:Es,revoked:c.z.literal(!0),revokedAt:As}).strict(),c.z.object({id:Es,pairingKeyId:Es,url:c.z.string().trim().min(1).max(2048),name:c.z.string().trim().min(1).max(160).optional(),enabled:c.z.boolean(),createdAt:As,updatedAt:As,status:c.z.enum(["disabled","connecting","connected","reconnecting","failed"]),pingRttMs:c.z.number().nonnegative().optional(),pingRttP95Ms:c.z.number().nonnegative().optional(),consecutiveReconnects:c.z.number().int().nonnegative().optional(),nextRetryAt:As.optional(),lastConnectedAt:As.optional(),lastDisconnectedAt:As.optional(),error:c.z.string().optional()}).passthrough(),c.z.object({pairing:ua,connection:c.z.object({id:Es,pairingKeyId:Es,url:c.z.string().trim().min(1).max(2048),name:c.z.string().trim().min(1).max(160).optional(),enabled:c.z.boolean(),createdAt:As,updatedAt:As}).passthrough(),tunnel:c.z.object({status:c.z.enum(["disabled","saved","connecting","connected","failed"]),error:c.z.string().trim().max(2048).optional()}).passthrough()}).passthrough(),c.z.object({deleted:c.z.boolean().optional()}).passthrough();const pa=c.z.object({repository:c.z.string().trim().optional(),tag:c.z.string().trim().optional(),id:c.z.string().trim(),createdSince:c.z.string().trim().optional(),size:c.z.string().trim().optional(),sizeBytes:c.z.number().int().nonnegative().optional(),reference:c.z.string().trim().min(1),repoDigests:c.z.array(c.z.string().trim().min(1).max(512)).default([])}).passthrough();c.z.object({image:xo,status:c.z.enum(["available","pull-required","unknown"]),localImage:pa.optional(),localSizeBytes:c.z.number().int().nonnegative().optional(),downloadSizeBytes:c.z.number().int().positive().optional(),unpackedSizeBytes:c.z.number().int().positive().optional(),error:c.z.string().trim().max(2048).optional()}).strict();const ma=c.z.lazy(()=>c.z.object({name:c.z.string().trim().min(1),path:c.z.string().trim().min(1).max(4096),children:c.z.array(ma)}).passthrough());c.z.object({kind:c.z.enum(["home","root"]),name:c.z.string().trim().min(1),path:c.z.string().trim().min(1).max(4096)}).passthrough(),c.z.object({status:c.z.number().int().min(100).max(599).optional(),headers:c.z.record(c.z.string(),c.z.string()).optional(),bodyBase64:c.z.string().optional()}).passthrough();const ha=c.z.object({strategy:c.z.enum(["node-proxy","direct-port","kubernetes-ingress","kubernetes-port-forward"]).default("node-proxy"),web:c.z.string().trim().max(2048).optional(),api:c.z.string().trim().max(2048).optional(),vnc:c.z.string().trim().max(2048).optional(),tty:c.z.string().trim().max(2048).optional(),logs:c.z.string().trim().max(2048).optional(),status:c.z.enum(["unknown","reachable","endpoint-unreachable"]).default("unknown")}).strict(),ga=c.z.object({...ha.shape}).strict(),fa=c.z.object({strategy:c.z.enum(["control-plane-proxy","direct-port","node-proxy","kubernetes-ingress","kubernetes-port-forward"]).default("control-plane-proxy"),web:c.z.string().trim().max(2048).optional(),api:c.z.string().trim().max(2048).optional(),ws:c.z.string().trim().max(2048).optional(),status:c.z.enum(["unknown","reachable","endpoint-unreachable"]).default("unknown")}).strict().default({strategy:"control-plane-proxy",status:"unknown"}),ya=c.z.object({mode:c.z.enum(["local-bind","git-clone","empty-volume","persistent-volume"]).optional(),status:c.z.enum(["unknown","pending","ready","failed"]).default("unknown"),path:c.z.string().trim().max(4096).optional(),resolvedCommit:c.z.string().trim().max(120).optional(),error:c.z.string().trim().max(2048).optional(),gitProvisioning:Fo.optional()}).passthrough(),Ia=c.z.object({id:Es,name:c.z.string().trim().min(1).max(160),projectId:Es.optional(),source:Dr,sourceSnapshot:c.z.record(c.z.string(),c.z.unknown()).default({}),modelSelection:ks,nodeId:Es,runtimeId:Es,imageSelection:Ds.optional(),environmentSource:Ls.optional(),environmentTemplateOrigin:Fs.optional(),imageSnapshot:Co.optional(),imageProvisioning:ko.optional(),stateRevision:c.z.number().int().min(0).default(0),processIncarnationId:c.z.string().trim().min(1).max(120).optional(),status:c.z.enum(["created","provisioning","starting","registering","registered","running","stopping","stopped","deleting","failed","unhealthy"]).default("created"),health:c.z.enum(["unknown","ok","degraded","failed"]).default("unknown"),connectionStatus:c.z.enum(["unknown","online","offline","endpoint-unreachable"]).default("unknown"),agentStatus:c.z.enum(["unknown","online","offline"]).default("unknown"),targetStatus:c.z.enum(["unknown","reachable","endpoint-unreachable"]).default("unknown"),uiAccessStatus:c.z.enum(["unknown","reachable","endpoint-unreachable"]).default("unknown"),controlMode:c.z.enum(["standalone","controlled"]).default("controlled"),protocolVersion:es.optional(),instanceVersion:c.z.string().trim().max(80).optional(),build:gr.optional(),runtimeVersion:_r.optional(),ready:c.z.boolean().default(!1),capabilities:ps.default(os),appInventory:Xs.optional(),config:c.z.object({autoImportAgentConfigs:c.z.boolean().default(!0),codexConfigEnabled:c.z.boolean().default(!0),codexHomeMode:c.z.enum(["default","taskhandoff"]).default("taskhandoff"),defaultCodexPermissionMode:Tt.default("ask"),codexSettings:rs.optional(),aiSessionHistoryLimit:c.z.number().int().min(1).max(en).default(50),aiSessionAttachmentRetentionDays:c.z.number().int().min(0).max(tn).default(30),aiSessionMaxFileAttachmentBytes:c.z.number().int().positive().max(De).default(ke)}).strict().default({autoImportAgentConfigs:!0,codexConfigEnabled:!0,codexHomeMode:"taskhandoff",defaultCodexPermissionMode:"ask",aiSessionHistoryLimit:50,aiSessionAttachmentRetentionDays:30,aiSessionMaxFileAttachmentBytes:ke}),workspace:ya.default({status:"unknown"}),target:ha.default({strategy:"direct-port",status:"unknown"}),access:fa,apps:c.z.object({runningCount:c.z.number().int().min(0).default(0),problemCount:c.z.number().int().min(0).default(0),updatedAt:As.optional(),revision:c.z.number().int().min(0).optional()}).strict().default({runningCount:0,problemCount:0}),aiSessions:on.default(()=>({runningCount:0,waitingCount:0,staleCount:0,sessions:[],updatedAt:(new Date).toISOString()})),triggers:c.z.object({enabledCount:c.z.number().int().min(0).default(0),runningCount:c.z.number().int().min(0).default(0),errorCount:c.z.number().int().min(0).default(0),configs:c.z.array(c.z.object({configHash:c.z.string().trim().min(1),config:vn,deployments:c.z.array(Rn).default([]),runtime:c.z.array(zn).default([])}).strict()).default([]),recentRuns:c.z.array(xn).default([])}).strict().optional(),runtime:c.z.object({kind:c.z.string().trim().max(80).optional(),containerName:c.z.string().trim().max(240).optional(),containerId:c.z.string().trim().max(240).optional(),workspacePath:c.z.string().trim().max(4096).optional(),pid:c.z.number().int().positive().optional(),port:c.z.number().int().positive().max(65535).optional(),labels:c.z.record(c.z.string(),c.z.string()).default({})}).strict().default({labels:{}}),registrationToken:c.z.string().trim().min(1).max(240).optional(),lastHeartbeatAt:As.optional(),createdAt:As,updatedAt:As}).strict(),_a=c.z.object({autoImportAgentConfigs:c.z.boolean().optional(),codexConfigEnabled:c.z.boolean().optional(),codexHomeMode:c.z.enum(["default","taskhandoff"]).optional(),defaultCodexPermissionMode:Tt.optional(),codexSettings:rs.optional(),aiSessionHistoryLimit:c.z.number().int().min(1).max(en).optional(),aiSessionAttachmentRetentionDays:c.z.number().int().min(0).max(tn).optional(),aiSessionMaxFileAttachmentBytes:c.z.number().int().positive().max(De).optional()}).strict();c.z.object({name:Ia.shape.name.optional(),config:_a.optional(),modelSelection:Ia.shape.modelSelection.unwrap().optional()}).strict(),c.z.object({id:Ia.shape.id.optional(),name:Ia.shape.name.optional(),projectId:Ia.shape.projectId,source:Dr.optional(),sourceSnapshot:c.z.record(c.z.string(),c.z.unknown()).optional(),nodeId:Ia.shape.nodeId.optional(),runtimeId:Ia.shape.runtimeId.optional(),environmentSource:Ls.optional(),imageSelection:Ia.shape.imageSelection,config:_a.optional(),modelSelection:Ia.shape.modelSelection.optional(),gitCredentialRetention:ni.optional(),start:c.z.boolean().default(!1)}).strict().superRefine((e,t)=>{e.environmentSource&&e.imageSelection&&t.addIssue({code:"custom",path:["environmentSource"],message:"environmentSource and imageSelection are mutually exclusive."}),e.gitCredentialRetention&&"local-folder"===e.source?.type&&t.addIssue({code:"custom",path:["gitCredentialRetention"],message:"Git credential retention requires a Git source."})});const Ea=c.z.object({status:c.z.enum(["not-requested","started","failed"]),error:c.z.object({code:c.z.string().trim().min(1).max(120),message:c.z.string().trim().min(1).max(2048)}).strict().optional()}).strict();c.z.object({...Ia.omit({registrationToken:!0}).shape,startOutcome:Ea}).strict();const Aa=c.z.union([Ia.transform(e=>({instance:e,gitWorkspaceProvisioningOperationId:void 0})),c.z.object({instance:Ia,gitWorkspaceProvisioningOperationId:Es.optional()}).strict()]);c.z.preprocess(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return e;const t=e;return t.instance&&"object"==typeof t.instance&&!Array.isArray(t.instance)?{instance:Sa(t.instance),..."string"==typeof t.gitWorkspaceProvisioningOperationId?{gitWorkspaceProvisioningOperationId:t.gitWorkspaceProvisioningOperationId}:{}}:Sa(t)},Aa);const Ta="instance.lifecycle.snapshot",ba=c.z.object({instanceId:Ia.shape.id,revision:c.z.number().int().min(0),updatedAt:As,status:Ia.shape.status.unwrap(),health:Ia.shape.health.unwrap(),connectionStatus:Ia.shape.connectionStatus.unwrap(),accessStatus:c.z.enum(["reachable","endpoint-unreachable"]),imageProvisioning:ko.optional(),workspace:ya,runtime:Ia.shape.runtime.unwrap(),runtimeVersion:_r.optional(),ready:c.z.boolean(),lastHeartbeatAt:As.optional()}).strict();function wa(e,t){return Ia.safeParse(Sa(e,t))}function Sa(e,t){if(!e||"object"!=typeof e||Array.isArray(e))return e;const n=e,i=new Set(Object.keys(Ia.shape)),s={};for(const[e,r]of Object.entries(n))i.has(e)?s[e]=r:t?.({instanceId:"string"==typeof n.id?n.id:void 0,field:e});if(n.capabilities&&"object"==typeof n.capabilities&&!Array.isArray(n.capabilities)){const e={...n.capabilities};Object.prototype.hasOwnProperty.call(e,"apps")&&(t?.({instanceId:"string"==typeof n.id?n.id:void 0,field:"capabilities.apps"}),delete e.apps),s.capabilities=hs(e)}else s.capabilities=hs(void 0);s.appInventory=function(e,t,n){if(!e||"object"!=typeof e||Array.isArray(e))return;const i=e;Object.keys(i).some(e=>!["observedAt","items","issues"].includes(e))&&t?.({instanceId:n,field:"appInventory"});const s={observedAt:i.observedAt,items:Array.isArray(i.items)?i.items.map(e=>{e&&"object"==typeof e&&!Array.isArray(e)&&Object.keys(e).some(e=>!["id","name","kind","source","availability","capabilities","diagnosticCode"].includes(e))&&t?.({instanceId:n,field:"appInventory.items"});const i=Oa(e,["id","name","kind","source","availability","diagnosticCode"]);return!i||"object"!=typeof i||Array.isArray(i)?i:{...i,capabilities:Oa(e.capabilities,["automation","supportsCwdSelection","supportsProfiles"])}}):i.items,issues:Array.isArray(i.issues)?i.issues.map(e=>Oa(e,["code","message"])):i.issues},r=Xs.safeParse(s);return r.success?r.data:void 0}(n.appInventory,t,"string"==typeof n.id?n.id:void 0),s.source=function(e,t,n){if(!e||"object"!=typeof e||Array.isArray(e))return e;const i=e,s=i.type,r=Dr.options.find(e=>e.shape.type.value===s);if(!r)return e;const o="local-folder"===s?["type","localFolderId","path","ownerNodeId"]:"git-template"===s?["type","url","templateId","ref","auth","clone"]:["type","repositoryId","url","provider","ref","auth","clone"],a=Oa(i,o);if("local-folder"!==s){const e=function(e,t,n){const i=e&&"object"==typeof e&&!Array.isArray(e)?e:void 0,s=Or.safeParse(Oa(i,["type","name","commit"]));if(s.success)return s.data;const r="string"==typeof i?.commit?i.commit.trim():"",o="string"==typeof i?.name?i.name.trim():"",a=r?Or.safeParse({type:"commit",commit:r}):o?Or.safeParse({type:"tag"===i?.type?"tag":"branch",name:o}):Or.safeParse({type:"branch",name:"main"});return a.success?(t?.({instanceId:n,field:"source.ref"}),a.data):void 0}(i.ref,t,n),s=Na(Rr,Oa(i.auth,["type","secretId"]),"source.auth",t,n),r=Na(zr,Oa(i.clone,["depth","submodules","lfs","subdirectory"]),"source.clone",t,n);e?a.ref=e:delete a.ref,s?a.auth=s:delete a.auth,r?a.clone=r:delete a.clone}const c=Na(r,a,"source",t,n);return c?(Object.keys(i).some(e=>!o.includes(e))&&t?.({instanceId:n,field:"source"}),c):a}(n.source,t,"string"==typeof n.id?n.id:void 0),s.sourceSnapshot=n.sourceSnapshot&&"object"==typeof n.sourceSnapshot&&!Array.isArray(n.sourceSnapshot)?n.sourceSnapshot:{},s.build=Na(gr,n.build,"build",t,"string"==typeof n.id?n.id:void 0),s.aiSessions=function(e,t,n){if(!e||"object"!=typeof e||Array.isArray(e))return;const i=e,s=Array.isArray(i.sessions)?i.sessions.flatMap((e,i)=>{const s=Na(rn,e,`aiSessions.sessions.${i}`,t,n);return s?[s]:[]}):[],r={runningCount:"number"==typeof i.runningCount&&Number.isInteger(i.runningCount)&&i.runningCount>=0?i.runningCount:0,waitingCount:"number"==typeof i.waitingCount&&Number.isInteger(i.waitingCount)&&i.waitingCount>=0?i.waitingCount:0,staleCount:"number"==typeof i.staleCount&&Number.isInteger(i.staleCount)&&i.staleCount>=0?i.staleCount:0,sessions:s,updatedAt:As.safeParse(i.updatedAt).success?i.updatedAt:(new Date).toISOString()};return Object.keys(i).some(e=>!["runningCount","waitingCount","staleCount","sessions","updatedAt"].includes(e))&&t?.({instanceId:n,field:"aiSessions"}),on.parse(r)}(n.aiSessions,t,"string"==typeof n.id?n.id:void 0),s.triggers=function(e,t,n){if(!e||"object"!=typeof e||Array.isArray(e))return;const i=e;Object.keys(i).some(e=>!["enabledCount","runningCount","errorCount","configs","recentRuns"].includes(e))&&t?.({instanceId:n,field:"triggers"});const s=(e,i,s)=>Array.isArray(e)?e.flatMap((e,r)=>{const o=Na(i,e,`${s}.${r}`,t,n);return o?[o]:[]}):[],r=Array.isArray(i.configs)?i.configs.flatMap((e,i)=>{if(!e||"object"!=typeof e||Array.isArray(e))return[];const r=e;Object.keys(r).some(e=>!["configHash","config","deployments","runtime"].includes(e))&&t?.({instanceId:n,field:`triggers.configs.${i}`});const o=function(e,t,n,i){if(!e||"object"!=typeof e||Array.isArray(e))return;const s=e,r=Oa(s,["configHash","name","description","createdAt","updatedAt"]);if(s.source&&"object"==typeof s.source&&!Array.isArray(s.source)){const e=s.source,t="schedule"===e.type?"interval"===e.scheduleKind?["type","scheduleKind","intervalMs"]:"daily"===e.scheduleKind?["type","scheduleKind","timeOfDay","timezone"]:["type","scheduleKind","weekdays","timeOfDay","timezone"]:"file-change"===e.type?["type","roots","globs","ignore","debounceMs"]:["type","agent","statuses","phases"];r.source=Oa(e,t)}return r.action=Oa(s.action,["promptTemplate"]),r.policy=Oa(s.policy,["cooldownMs","maxConcurrentRuns","whenBusy"]),Na(vn,r,t,n,i)}(r.config,`triggers.configs.${i}.config`,t,n);return"string"==typeof r.configHash&&o?[{configHash:r.configHash,config:o,deployments:s(r.deployments,Rn,`triggers.configs.${i}.deployments`),runtime:s(r.runtime,zn,`triggers.configs.${i}.runtime`)}]:[]}):[];return{enabledCount:"number"==typeof i.enabledCount&&Number.isInteger(i.enabledCount)&&i.enabledCount>=0?i.enabledCount:0,runningCount:"number"==typeof i.runningCount&&Number.isInteger(i.runningCount)&&i.runningCount>=0?i.runningCount:0,errorCount:"number"==typeof i.errorCount&&Number.isInteger(i.errorCount)&&i.errorCount>=0?i.errorCount:0,configs:r,recentRuns:s(i.recentRuns,xn,"triggers.recentRuns")}}(n.triggers,t,"string"==typeof n.id?n.id:void 0),s.apps=Na(Ia.shape.apps.unwrap(),Oa(n.apps,["runningCount","problemCount","updatedAt","revision"]),"apps",t,"string"==typeof n.id?n.id:void 0)||{runningCount:0,problemCount:0},s.config=Na(Ia.shape.config.unwrap(),Oa(n.config,["autoImportAgentConfigs","codexConfigEnabled","codexHomeMode","defaultCodexPermissionMode","codexSettings","aiSessionHistoryLimit","aiSessionAttachmentRetentionDays","aiSessionMaxFileAttachmentBytes"]),"config",t,"string"==typeof n.id?n.id:void 0)||{autoImportAgentConfigs:!0,codexConfigEnabled:!0,codexHomeMode:"taskhandoff",defaultCodexPermissionMode:"ask",aiSessionHistoryLimit:50,aiSessionAttachmentRetentionDays:30,aiSessionMaxFileAttachmentBytes:ke},s.modelSelection=Na(ks.unwrap(),Oa(n.modelSelection,["modelEntityIds","codexModelHash","claudeModelHash","opencodeModelHash"]),"modelSelection",t,"string"==typeof n.id?n.id:void 0)||{},s.imageSnapshot=function(e,t,n,i){if(!e||"object"!=typeof e||Array.isArray(e))return e;const s=e,r=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return e;const t=e,n=new Set(["id","origin","name","description","localizedDescriptions","cover","reference","repository","tag","image","registry","pullPolicy","capabilities","optionalApps","defaultEnv","labels","createdAt","updatedAt"]);for(const e of Object.keys(t))n.has(e);"string"==typeof t.id&&t.id;const i="string"==typeof t.image?t.image:void 0;Object.prototype.hasOwnProperty.call(t,"registry");let s,r="string"==typeof t.reference?t.reference:i;if(r)try{r=Rs(r)}catch{if(!r.includes("@")&&r.lastIndexOf(":")<=r.lastIndexOf("/"))try{r=Rs(`${r}:latest`)}catch{}}try{s=r?zs(r):void 0}catch{}return{id:t.id,origin:"custom",name:t.name,description:t.description,localizedDescriptions:t.localizedDescriptions,cover:Oa(t.cover,["kind","key","url","mediaType","digest"]),reference:s?.reference??r,repository:s?.repository??t.repository,tag:s?.tag??t.tag,pullPolicy:t.pullPolicy??"if-not-present",capabilities:t.capabilities,optionalApps:t.optionalApps,defaultEnv:t.defaultEnv,labels:t.labels,createdAt:t.createdAt,updatedAt:t.updatedAt}}(s),{reference:o,...a}=r,c=s.requestedReference??o;let d;try{d="string"==typeof c?zs(c):void 0}catch{}const l={img_default:"market_taskhandoff_browser",img_codex:"market_taskhandoff_codex",img_ai:"market_taskhandoff_ai"},u="string"==typeof s.id?s.id:"string"==typeof t?t:void 0,p="market"===s.origin||u&&l[u]?"market":"custom";return void 0===s.image&&void 0===s.reference||n?.({instanceId:i,field:"imageSnapshot.reference"}),{...a,id:u&&l[u]?l[u]:u,origin:p,repository:d?.repository??s.repository,tag:d?.tag??s.tag,requestedReference:d?.reference??c,resolvedDigest:s.resolvedDigest,resolvedReference:s.resolvedReference,downloadSizeBytes:s.downloadSizeBytes,market:"market"===p?Oa(s.market,["catalogId","catalogRevision","publisher","version"])??{catalogId:"task_handoff_embedded",catalogRevision:"legacy",publisher:"task-handoff"}:void 0}}(n.imageSnapshot,n.imageId,t,"string"==typeof n.id?n.id:void 0);const r="string"==typeof n.imageId?{img_default:"market_taskhandoff_browser",img_codex:"market_taskhandoff_codex",img_ai:"market_taskhandoff_ai"}[n.imageId]||n.imageId:void 0,o=Oa(n.imageSelection,["imageId","tag"]);s.imageSelection=o||(r?{imageId:r,tag:s.imageSnapshot?.tag}:void 0),s.imageProvisioning=Na(ko,Oa(n.imageProvisioning,["phase","requestedReference","generation","error","startedAt","updatedAt"]),"imageProvisioning",t,"string"==typeof n.id?n.id:void 0),s.runtimeVersion=function(e,t,n){if(!e||"object"!=typeof e||Array.isArray(e))return;const i=e,s=e=>{if("string"!=typeof e)return;const t=e.trim();return t&&t.length<=80?t:void 0},r=s(i.desiredVersion);if(!r)return void t?.({instanceId:n,field:"runtimeVersion.desiredVersion"});const o=new Set(_r.shape.phase.options),a="string"==typeof i.phase?i.phase:"pending",c=o.has(a)?a:{idle:"pending",queued:"pending",checking:"pending",downloading:"installing",updating:"installing",completed:"matched",succeeded:"matched",ready:"matched",error:"failed"}[a]||"pending";let d;if(c!==a&&t?.({instanceId:n,field:"runtimeVersion.phase"}),i.error&&"object"==typeof i.error&&!Array.isArray(i.error)){const e=i.error,r="string"==typeof e.message?e.message.trim().slice(0,4096):"";if(r){const i=new Set(Ir.shape.code.options),o="string"==typeof e.code&&i.has(e.code)?e.code:"INSTANCE_RUNTIME_INSTALL_FAILED";o!==e.code&&t?.({instanceId:n,field:"runtimeVersion.error.code"});const a=s(e.expectedVersion),c=s(e.actualVersion);d={code:o,message:r,...a?{expectedVersion:a}:{},...c?{actualVersion:c}:{},retryable:!0===e.retryable}}else t?.({instanceId:n,field:"runtimeVersion.error"})}"string"==typeof i.error&&i.error.trim()&&(d={code:"INSTANCE_RUNTIME_INSTALL_FAILED",message:i.error.trim().slice(0,4096),expectedVersion:r,...s(i.actualVersion)?{actualVersion:s(i.actualVersion)}:{},retryable:!1});const l=s(i.actualVersion),u=As.safeParse(i.lastAttemptAt),p=As.safeParse(i.matchedAt);return void 0===i.lastAttemptAt||u.success||t?.({instanceId:n,field:"runtimeVersion.lastAttemptAt"}),void 0===i.matchedAt||p.success||t?.({instanceId:n,field:"runtimeVersion.matchedAt"}),{desiredVersion:r,...l?{actualVersion:l}:{},phase:c,attempt:"number"==typeof i.attempt&&Number.isInteger(i.attempt)&&i.attempt>=0?i.attempt:0,...u.success?{lastAttemptAt:u.data}:{},...p.success?{matchedAt:p.data}:{},...d?{error:d}:{}}}(n.runtimeVersion,t,"string"==typeof n.id?n.id:void 0),s.workspace=Na(ya,n.workspace,"workspace",t,"string"==typeof n.id?n.id:void 0)||{status:"unknown"},s.environmentSource=Na(Ls,n.environmentSource,"environmentSource",t,"string"==typeof n.id?n.id:void 0),s.environmentTemplateOrigin=Na(Fs,n.environmentTemplateOrigin,"environmentTemplateOrigin",t,"string"==typeof n.id?n.id:void 0),s.runtime=Na(Ia.shape.runtime.unwrap(),n.runtime,"runtime",t,"string"==typeof n.id?n.id:void 0)||{labels:{}},s.target=Na(ha,Oa(n.target??n.endpoints,["strategy","web","api","vnc","tty","logs","status"]),"target",t,"string"==typeof n.id?n.id:void 0)||{strategy:"direct-port",status:"unknown"},s.access=Na(fa,Oa(n.access,["strategy","web","api","ws","status"]),"access",t,"string"==typeof n.id?n.id:void 0)||{strategy:"control-plane-proxy",status:"unknown"};for(const[e,i]of Object.entries(Ia.shape))Object.prototype.hasOwnProperty.call(s,e)&&!i.safeParse(s[e]).success&&i.safeParse(void 0).success&&(delete s[e],t?.({instanceId:"string"==typeof n.id?n.id:void 0,field:e}));return s}function Na(e,t,n,i,s){if(!t||"object"!=typeof t||Array.isArray(t))return;let r=structuredClone(t),o=!1;for(let t=0;t<20;t+=1){const t=e.safeParse(r);if(t.success)return o&&i?.({instanceId:s,field:n}),t.data;let a=!1;for(const e of t.error.issues){if("unrecognized_keys"!==e.code)continue;const t=va(r,e.path);if(t&&"object"==typeof t&&!Array.isArray(t))for(const n of e.keys)Object.prototype.hasOwnProperty.call(t,n)&&(delete t[n],a=!0,o=!0)}if(!a){const o=structuredClone(r);let a=!1;for(const e of t.error.issues){if(!e.path.length||"string"!=typeof e.path.at(-1))continue;const t=va(o,e.path.slice(0,-1)),n=e.path.at(-1);t&&"object"==typeof t&&!Array.isArray(t)&&Object.prototype.hasOwnProperty.call(t,n)&&(delete t[n],a=!0)}if(a){const t=e.safeParse(o);if(t.success)return i?.({instanceId:s,field:n}),t.data}break}}i?.({instanceId:s,field:n})}function va(e,t){let n=e;for(const e of t){if(!n||"object"!=typeof n)return;n=n[e]}return n}function Oa(e,t){if(!e||"object"!=typeof e||Array.isArray(e))return e;const n=e;return Object.fromEntries(t.filter(e=>Object.prototype.hasOwnProperty.call(n,e)).map(e=>[e,n[e]]))}const Ra=c.z.object({instanceId:Es.optional(),projectId:Es.optional(),source:Dr.optional(),nodeId:Es.optional(),runtimeId:Es.optional(),imageSelection:Ds.optional(),instanceVersion:c.z.string().trim().max(80).optional(),protocolVersion:es,build:gr.optional(),controlMode:c.z.enum(["standalone","controlled"]).default("controlled"),capabilities:ps.default(os),appInventory:Xs.optional(),target:ga.optional(),workspace:ya.default({status:"unknown"}),registrationToken:c.z.string().trim().max(240).optional(),processIncarnationId:c.z.string().trim().min(1).max(120).optional()}).strict().superRefine((e,t)=>{Zi.has(e.protocolVersion)&&!e.appInventory&&t.addIssue({code:"custom",path:["appInventory"],message:"Current protocol register payload requires appInventory."})}),za=c.z.object({status:Ia.shape.status.optional(),health:Ia.shape.health.optional(),protocolVersion:es,build:gr.optional(),capabilities:Ia.shape.capabilities.optional(),appInventory:Xs.optional(),apps:Ia.shape.apps.optional(),aiSessions:Ia.shape.aiSessions.optional(),triggers:Ia.shape.triggers.optional(),workspace:ya.optional(),target:ga.optional(),processIncarnationId:c.z.string().trim().min(1).max(120).optional()}).strict().superRefine((e,t)=>{Zi.has(e.protocolVersion)&&!e.appInventory&&t.addIssue({code:"custom",path:["appInventory"],message:"Current protocol heartbeat payload requires appInventory."})}),xa=c.z.enum(["web","telegram","wechat","dingding","lark"]);c.z.object({id:Es,channel:xa,name:c.z.string().trim().min(1).max(160),enabled:c.z.boolean().default(!1),token:c.z.string().trim().max(4096).optional(),defaultChatId:c.z.string().trim().max(240).optional(),allowedUserIds:c.z.array(c.z.string().trim().min(1).max(240)).default([]),pollIntervalMs:c.z.number().int().positive().max(6e4).default(3e3),settings:c.z.record(c.z.string(),c.z.unknown()).default({}),createdAt:As,updatedAt:As}).strict(),c.z.object({id:Es,channel:xa,bridgeId:Es.optional(),chatSessionId:c.z.string().trim().min(1).max(240),userId:c.z.string().trim().max(240).optional(),activeProjectId:Es.optional(),activeInstanceId:Es.optional(),activeAiSessionId:c.z.string().trim().min(1).max(120).optional(),lastUsedAt:As,createdAt:As,updatedAt:As}).strict(),c.z.object({source:c.z.object({type:c.z.literal("chat-gateway").default("chat-gateway"),channel:xa,bridgeId:Es.optional(),chatSessionId:c.z.string().trim().min(1).max(240),userId:c.z.string().trim().max(240).optional()}).strict(),message:c.z.object({text:c.z.string().trim().max(2e4).default(""),attachments:c.z.array(It).max(6).default([])}).strict().superRefine((e,t)=>{e.attachments.reduce((e,t)=>e+("inline"===t.source.type?t.size:0),0)>Le&&t.addIssue({code:c.z.ZodIssueCode.custom,path:["attachments"],message:"Inline attachments must be 41943040 bytes or less in total."})}),target:c.z.object({instanceId:Es,aiSessionId:c.z.string().trim().min(1).max(120)}).strict().optional()}).strict(),c.z.object({id:Es,instanceId:Es,projectId:Es.optional(),aiSessionId:c.z.string().trim().min(1).max(120),providerSessionId:c.z.string().trim().max(240).optional(),result:c.z.string().default(""),timeoutMs:c.z.number().positive().optional(),source:c.z.string().trim().max(120).optional(),kind:c.z.enum(["task","approval"]).default("task"),status:c.z.enum(["pending","unreachable"]).default("pending"),error:c.z.string().trim().max(2048).optional(),lastSeenAt:As}).strict();const Ca=c.z.string().refine(function(e){return 1===Array.from(e).length&&!/[\p{L}\p{N}\s]/u.test(e)&&"/"!==e&&"\\"!==e},"Mention trigger must be one printable non-alphanumeric character other than / or \\."),ka=c.z.string().refine(function(e){return 1===Array.from(e).length&&!/[\p{L}\p{N}\s]/u.test(e)&&"\\"!==e},"Command trigger must be one printable non-alphanumeric character other than \\.");c.z.object({publicBaseUrl:c.z.string().trim().max(2048).optional(),updateChannel:fr.default("stable"),mentionTrigger:Ca.default("@"),commandTrigger:ka.default("/"),diagnosticLogs:c.z.boolean().default(!1)}).strict().refine(e=>e.mentionTrigger!==e.commandTrigger,{path:["commandTrigger"],message:"Command and mention triggers must be different."}),c.z.object({publicBaseUrl:c.z.string().trim().max(2048).optional(),updateChannel:fr.optional(),mentionTrigger:Ca.optional(),commandTrigger:ka.optional(),diagnosticLogs:c.z.boolean().optional()}).strict();const Da=c.z.object({id:Hr.shape.id.optional(),name:Hr.shape.name,source:Dr,defaultImageSelection:Hr.shape.defaultImageSelection,defaultNodeId:Hr.shape.defaultNodeId,workspacePolicy:Lr.optional(),labels:Hr.shape.labels.optional()}),La={defaultRuntimeId:Qo.shape.id.optional()};Da.extend(La).strict().transform(({defaultRuntimeId:e,...t})=>({...t,source:Dr.parse(t.source)})),Da.omit({id:!0}).partial().extend(La).strict().transform(({defaultRuntimeId:e,...t})=>({...t,...t.source?{source:Dr.parse(t.source)}:{}})),c.z.object({id:Ro.shape.id.optional(),name:Ro.shape.name,description:Ro.shape.description,cover:Ro.shape.cover,reference:Ro.shape.reference,pullPolicy:Ro.shape.pullPolicy.optional(),capabilities:c.z.array(c.z.string().trim().min(1).max(80)).optional(),optionalApps:c.z.array(c.z.string().trim().min(1).max(120)).optional(),defaultEnv:Ro.shape.defaultEnv.optional(),labels:Ro.shape.labels.optional()}).strict().omit({id:!0}).partial().strict();const Pa=c.z.object({name:Br.shape.name,endpoint:Br.shape.endpoint,key:Br.shape.key,model:Br.shape.model,modelNames:Br.shape.modelNames.optional(),mappings:Fr.optional(),protocols:Br.shape.protocols.optional(),app:Br.shape.app,enabled:Br.shape.enabled.optional(),order:Br.shape.order.optional(),labels:Br.shape.labels.optional()}).strict();Pa.omit({key:!0}).extend({key:Br.shape.key.optional()}).strict(),Pa.partial().strict(),c.z.object({endpoint:Br.shape.endpoint,key:Br.shape.key.optional(),existingModelId:Br.shape.id.optional()}).strict().extend({model:Br.shape.model,app:Br.shape.app.optional(),protocol:c.z.enum(["openai-responses","openai-chat-completions","anthropic-messages"]).optional()}).strict().refine(e=>Boolean(e.protocol||e.app),{message:"A model protocol is required.",path:["protocol"]});const Ma=c.z.object({mode:c.z.enum(["local-static-key","paired-hmac","proxy-binding"]).default("local-static-key"),keyId:Yo.shape.id.optional(),secret:c.z.string().trim().max(4096).optional(),pairedAt:Yo.shape.createdAt.optional(),pairing:c.z.object({status:c.z.enum(["pending","paired","expired"]).default("pending"),joinToken:c.z.string().trim().max(4096).optional(),expiresAt:Yo.shape.createdAt.optional()}).strict().optional()}).strict();function ja(e,t){let n=Ha(t);for(let t=0;t<100;t+=1){const t=e.safeParse(n);if(t.success)return t;const i=Ua(t.error.issues);let s=!1;for(const e of i){const t=$a(n,e.path);if(t&&"object"==typeof t&&!Array.isArray(t))for(const n of e.keys)Object.prototype.hasOwnProperty.call(t,n)&&(delete t[n],s=!0)}if(!s)return t}return e.safeParse(n)}function Ua(e,t=[]){const n=[];for(const i of e){if("unrecognized_keys"===i.code){n.push({code:"unrecognized_keys",keys:i.keys,path:[...t,...i.path]});continue}if("invalid_union"!==i.code||!Array.isArray(i.errors))continue;const e=i.errors.filter(e=>Array.isArray(e));if(!e.length)continue;const s=e.reduce((e,t)=>Fa(t)<Fa(e)?t:e);n.push(...Ua(s,[...t,...i.path]))}return n}function Fa(e){return e.reduce((e,t)=>{if("unrecognized_keys"===t.code)return e;if("invalid_union"!==t.code||!Array.isArray(t.errors))return e+1;const n=t.errors.filter(e=>Array.isArray(e));return e+(n.length?Math.min(...n.map(Fa)):1)},0)}function $a(e,t){let n=e;for(const e of t){if(!n||"object"!=typeof n)return;n=n[e]}return n}function Ha(e){return Array.isArray(e)?e.map(Ha):e&&"object"==typeof e?Object.getPrototypeOf(e)!==Object.prototype&&null!==Object.getPrototypeOf(e)?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Ha(t)])):e}function Ba(e,t,n={}){return new Promise((i,s)=>{if(n.signal?.aborted)return void s(Object.assign(new Error(`${e} was aborted.`),{code:"RUNTIME_COMMAND_ABORTED"}));const r=l.spawn(e,t,{stdio:["ignore","pipe","pipe"],...n.env?{env:n.env}:{}}),o=[],a=[];let c=!1;const d=n.timeoutMs?setTimeout(()=>{c=!0,r.kill("SIGKILL")},n.timeoutMs):void 0;let u=!1;const p=()=>{u=!0,r.kill("SIGKILL")},m=()=>{d&&clearTimeout(d),n.signal?.removeEventListener("abort",p)};n.signal?.addEventListener("abort",p,{once:!0}),d?.unref?.(),r.stdout.on("data",e=>o.push(Buffer.from(e))),r.stderr.on("data",e=>a.push(Buffer.from(e))),r.on("error",e=>{m(),s(e)}),r.on("close",t=>{m();const r={stdout:Buffer.concat(o).toString("utf8").trim(),stderr:Buffer.concat(a).toString("utf8").trim()};if(c){const t=new Error(`${e} timed out after ${n.timeoutMs}ms`);return Object.assign(t,{statusCode:504,code:"RUNTIME_COMMAND_TIMEOUT",details:r}),void s(t)}if(u)return void s(Object.assign(new Error(`${e} was aborted.`),{code:"RUNTIME_COMMAND_ABORTED",details:r}));if(0===t)return void i(r);const d=new Error(r.stderr||`${e} exited with code ${t}`);Object.assign(d,{statusCode:502,code:"RUNTIME_EXECUTOR_FAILED",details:r}),s(d)})})}function qa(e){try{return t.statSync(e).isFile()}catch{return!1}}c.z.object({id:Yo.shape.id.optional(),name:Yo.shape.name.optional(),connectionMode:Yo.shape.connectionMode.optional(),connectionPath:Yo.shape.connectionPath.optional(),connectionEnabled:Yo.shape.connectionEnabled.optional(),auth:Ma.optional(),joinToken:c.z.string().trim().min(1).max(4096).optional(),endpoint:Yo.shape.endpoint,controlEndpoint:Yo.shape.controlEndpoint,containerEndpoint:Yo.shape.containerEndpoint,publicWebBase:Yo.shape.publicWebBase,status:c.z.enum(["unknown","online","offline","degraded"]).optional(),health:c.z.enum(["unknown","ok","degraded","failed"]).optional(),capabilities:Yo.shape.capabilities.optional(),labels:Yo.shape.labels.optional(),lastSeenAt:Yo.shape.lastSeenAt}).strict(),c.z.object({name:Yo.shape.name.optional(),connectionMode:Yo.shape.connectionMode.unwrap().optional(),connectionPath:Yo.shape.connectionPath.unwrap().optional(),connectionEnabled:Yo.shape.connectionEnabled.unwrap().optional(),auth:Ma.optional(),endpoint:Yo.shape.endpoint,controlEndpoint:Yo.shape.controlEndpoint,containerEndpoint:Yo.shape.containerEndpoint,publicWebBase:Yo.shape.publicWebBase,status:Yo.shape.status.unwrap().optional(),health:Yo.shape.health.unwrap().optional(),capabilities:Yo.shape.capabilities.unwrap().optional(),labels:Yo.shape.labels.unwrap().optional(),lastSeenAt:Yo.shape.lastSeenAt}).strict(),c.z.object({controlPlaneUrl:c.z.string().trim().url().max(2048),joinToken:c.z.string().trim().min(1).max(4096),controlPlaneName:c.z.string().trim().min(1).max(160).optional(),activate:c.z.boolean().optional()}).strict(),c.z.object({nodeName:c.z.string().trim().min(1).max(160).optional(),expiresInMs:c.z.number().int().positive().max(36e5).optional()}).strict();const Va=[".com",".exe"];function Ga(e){return Va.includes(e.toLowerCase())}const Wa=(e,t,i={})=>new Promise((s,r)=>{if(i.signal?.aborted)return void r(Object.assign(new Error(`${e} was aborted.`),{code:"RUNTIME_COMMAND_ABORTED"}));const o=[];let a,c=!1,d=!1;const l=function(e,t={}){if("win32"!==(t.platform??process.platform)||!e)return e;const i=t.env??process.env;if(n.win32.isAbsolute(e)||/[\\/]/.test(e))return e;const s=t.isFile??qa,r=(i.PATH??i.Path??"").split(";").map(e=>e.trim()).filter(Boolean),o=""!==n.win32.extname(e),a=o?[""]:(i.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").map(e=>e.trim()).filter(Boolean),c=o?[]:a.filter(Ga),d=o?[]:a.filter(e=>!Ga(e)),l=o?[a]:[c.length?c:Va,[...d,""]];for(const t of l)for(const i of r)for(const r of t){const t=n.win32.join(i,`${e}${r}`);if(s(t))return t}return e}(e);try{a=p.spawn(l,t,{name:"xterm-256color",cols:i.cols||120,rows:i.rows||40,cwd:process.cwd(),env:process.env})}catch(t){const n=t instanceof Error?t.message:String(t);return void r(Object.assign(new Error(l===e?`${e} could not be started: ${n}`:`${e} could not be started from ${l}: ${n}`),{code:"RUNTIME_EXECUTOR_FAILED",cause:t}))}const u=i.timeoutMs?setTimeout(()=>{c=!0,a.kill("SIGKILL")},i.timeoutMs):void 0,m=()=>{d=!0;try{a.kill("SIGKILL")}catch{}};i.signal?.addEventListener("abort",m,{once:!0}),u?.unref?.(),a.onData(e=>{o.push(e),i.onData?.(e)}),a.onExit(({exitCode:t})=>{u&&clearTimeout(u),i.signal?.removeEventListener("abort",m);const n={stdout:o.join(""),stderr:""};c?r(Object.assign(new Error(`${e} timed out after ${i.timeoutMs}ms`),{statusCode:504,code:"RUNTIME_COMMAND_TIMEOUT",details:n})):d?r(Object.assign(new Error(`${e} was aborted.`),{code:"RUNTIME_COMMAND_ABORTED",details:n})):0!==t?r(Object.assign(new Error(n.stdout.replace(/\u001b\[[0-?]*[ -/]*[@-~]/g,"").split(/\r?\n/).map(e=>e.trim()).filter(Boolean).at(-1)||`${e} exited with code ${t}`),{statusCode:502,code:"RUNTIME_EXECUTOR_FAILED",details:n})):s(n)})});function Ka(e){return e===Ba?Wa:async(t,n,i={})=>{const s=await e(t,n,{timeoutMs:i.timeoutMs,signal:i.signal});return s.stdout&&i.onData?.(s.stdout),s.stderr&&i.onData?.(s.stderr),s}}class Ya{inFlight=new Map;runCommand;runTerminalCommand;constructor(e=Ba,t){this.runCommand=e,this.runTerminalCommand=t||Ka(e)}ensure(e,t,n,i){const s=Rs(e),r=this.inFlight.get(s);if(r)return t&&(r.phaseListeners.add(t),r.phase&&t(r.phase)),n&&(r.terminalListeners.add(n),r.terminalTail&&n({sequence:r.terminalSequence,data:r.terminalTail,replay:!0})),this.bindAbort(r,i),r.promise;const o=new Set,a=new Set;t&&o.add(t),n&&a.add(n);const c={promise:Promise.resolve(void 0),controller:new AbortController,abortDisposers:new Set,phaseListeners:o,terminalListeners:a,terminalSequence:0,terminalTail:""};return this.bindAbort(c,i),c.promise=this.ensureOnce(s,e=>{c.phase=e,o.forEach(t=>t(e))},e=>{c.terminalSequence+=1,c.terminalTail=`${c.terminalTail}${e}`.slice(-262144);const t={sequence:c.terminalSequence,data:e};a.forEach(e=>e(t))},c.controller.signal).finally(()=>{this.inFlight.delete(s);for(const e of c.abortDisposers)e();c.abortDisposers.clear()}),this.inFlight.set(s,c),c.promise}bindAbort(e,t){if(!t)return;if(t.aborted)return void e.controller.abort();const n=()=>e.controller.abort();t.addEventListener("abort",n,{once:!0}),e.abortDisposers.add(()=>t.removeEventListener("abort",n))}async ensureOnce(e,t,n,i){t("checking-image");let s=await this.inspect(e,i).catch(e=>{if(i.aborted)throw e}),r=!1;s||(t("pulling-image"),await this.runTerminalCommand("docker",["pull",e],{cols:120,rows:40,signal:i,onData:n}),r=!0,s=await this.inspect(e,i)),t("resolving-image");const o=(a=s,Array.isArray(a.RepoDigests)?a.RepoDigests.filter(e=>"string"==typeof e):[]).find(e=>/@sha256:[a-fA-F0-9]{64}$/.test(e));var a;const c=o?.split("@").at(-1)?.toLowerCase();return{requestedReference:e,...c?{resolvedDigest:c}:{},resolvedReference:o||e,pulled:r}}async inspect(e,t){const n=await this.runCommand("docker",["image","inspect",e,"--format","{{json .}}"],{signal:t});return JSON.parse(n.stdout.trim()||"{}")}}function Xa(e){if(!e)return;const t=/^([0-9]+(?:\.[0-9]+)?)\s*(B|kB|MB|GB|TB)$/i.exec(e.trim());if(!t)return;const n=Number(t[1])*{b:1,kb:1e3,mb:1e6,gb:1e9,tb:1e12}[t[2].toLowerCase()];return Number.isSafeInteger(Math.round(n))?Math.round(n):void 0}const Ja="TASK_HANDOFF_GIT_PROVISIONING_STAGE=",Qa="TASK_HANDOFF_GIT_PROVISIONING_COMMIT=",Za="TASK_HANDOFF_GIT_PROVISIONING_ERROR=",ec=new Set(["cloning","checking-out","submodules","lfs","finalizing"]);function tc(e){const t=e.trim();if(t.startsWith(Ja)){const e=t.slice(36).trim();return ec.has(e)?{stage:e}:void 0}if(t.startsWith(Qa)){const e=t.slice(37).trim();return e?{commit:e}:void 0}if(t.startsWith(Za)){const e=t.slice(36).trim();return e?{errorCode:e}:void 0}}const nc=/\u001b\[[0-?]*[ -/]*[@-~]/g,ic=/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g;class sc{pending="";recent=[];push(e){const t=`${this.pending}${e}`.split(/(\r\n|\n|\r)/),n=t.pop()??"",i=n.length>8192;this.pending=i?"":n;let s=i?n:"";const r={display:""};for(let e=0;e<t.length;e+=2){const n=t[e],i=t[e+1]||"",o=tc(n);o?Object.assign(r,o):(s+=`${n}${i}`,this.remember(n))}return r.display=s,r}flush(){const e=this.pending;return this.pending="",tc(e)?"":(this.remember(e),e)}failureDetail(){return this.recent.filter(Boolean).at(-1)}remember(e){const t=e.replace(nc,"").replace(ic,"").trim();t&&(this.recent.push(t),this.recent.length>40&&this.recent.splice(0,this.recent.length-40))}}const rc=new Set(["entrypoint.sh","git-provision.sh","instance-launcher.sh","node-agent-unix-proxy.mjs","runtime-installer.mjs"]);function oc(){const e=("undefined"==typeof document?require("url").pathToFileURL(__filename).href:z&&"SCRIPT"===z.tagName.toUpperCase()&&z.src||new URL("cli.js",document.baseURI).href)?n.dirname(r.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(__filename).href:z&&"SCRIPT"===z.tagName.toUpperCase()&&z.src||new URL("cli.js",document.baseURI).href)):__dirname,i=[n.resolve(e,"../../../../../docker"),n.resolve(e,"../docker"),n.resolve(e,"../../docker")];return i.find(e=>t.existsSync(n.join(e,"runtime-installer.mjs")))||i[0]}const ac=c.z.record(c.z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),c.z.string()),cc=c.z.object({version:c.z.literal(1),instanceId:c.z.string().trim().min(1).max(120),instanceCredential:c.z.string().trim().min(1).max(240),environment:ac,modelCatalog:be.optional(),codexSettings:rs.optional(),updatedAt:c.z.string().datetime()}).strict(),dc="private-config.json";function lc(e){return Array.isArray(e)?`[${e.map(lc).join(",")}]`:e&&"object"==typeof e?`{${Object.entries(e).filter(([,e])=>void 0!==e).sort(([e],[t])=>e<t?-1:e>t?1:0).map(([e,t])=>`${JSON.stringify(e)}:${lc(t)}`).join(",")}}`:JSON.stringify(e)??"null"}class uc{directory;constructor(e){this.directory=e.instancePrivateConfigsDir}init(){t.mkdirSync(this.directory,{recursive:!0,mode:448}),t.chmodSync(this.directory,448);for(const e of t.readdirSync(this.directory,{withFileTypes:!0})){const i=n.join(this.directory,e.name);if(e.isDirectory()){t.chmodSync(i,448);const e=n.join(i,dc);t.existsSync(e)&&t.chmodSync(e,384);continue}e.name.endsWith(".json")&&t.chmodSync(i,384)}}filePath(e){return n.join(this.directoryPath(e),dc)}directoryPath(e){return n.join(this.directory,e)}parseStored(e,t){const n=e&&"object"==typeof e&&!Array.isArray(e)?e:{},i=cc.parse({version:n.version,instanceId:n.instanceId,instanceCredential:n.instanceCredential??n.registrationToken,environment:n.environment,modelCatalog:void 0===n.modelCatalog?void 0:ve(n.modelCatalog),codexSettings:void 0===n.codexSettings?void 0:(s=n.codexSettings,rs.parse(function(e){if(!e||"object"!=typeof e||Array.isArray(e))return e;const t=e,n=t.multiAgent,i=!n||"object"!=typeof n||Array.isArray(n)?n:(()=>{const e=n,t=e.defaultModel;return{...void 0===e.enabled?{}:{enabled:e.enabled},...void 0===e.maxConcurrentThreads?{}:{maxConcurrentThreads:e.maxConcurrentThreads},...void 0===t?{}:{defaultModel:!t||"object"!=typeof t||Array.isArray(t)?t:{modelEntityId:t.modelEntityId,modelName:t.modelName,..."string"==typeof t.modelUpstreamName?{modelUpstreamName:t.modelUpstreamName}:{}}},...void 0===e.defaultReasoningEffort?{}:{defaultReasoningEffort:e.defaultReasoningEffort}}})();return{...void 0===t.modelVerbosity?{}:{modelVerbosity:t.modelVerbosity},...void 0===t.personality?{}:{personality:t.personality},...void 0===n?{}:{multiAgent:i}}}(s))),updatedAt:n.updatedAt});var s;if(i.instanceId!==t)throw Object.assign(new Error(`Private config identity mismatch for instance ${t}.`),{statusCode:409,code:"INSTANCE_PRIVATE_CONFIG_IDENTITY_MISMATCH"});return i}readLayout(e,n){let i;try{i=t.readFileSync(n,"utf8")}catch(e){if(function(e){return Boolean(e&&"object"==typeof e&&"code"in e&&"ENOENT"===e.code)}(e))return{value:void 0,error:void 0};throw e}try{return{value:this.parseStored(JSON.parse(i),e),error:void 0}}catch(e){return{value:void 0,error:e}}}readMaterialized(e,t={}){const{value:n,error:i}=this.readLayout(e,this.filePath(e));if(n)return n;if(i&&!t.tolerateInvalid)throw i}inspectMaterialized(e){return this.readMaterialized(e)}put(e){const i=cc.parse(e);this.init();const s=this.filePath(i.instanceId);return t.mkdirSync(n.dirname(s),{recursive:!0,mode:448}),t.chmodSync(n.dirname(s),448),m.sync(s,`${JSON.stringify(i,null,2)}\n`,{encoding:"utf8",mode:384}),t.chmodSync(s,384),i}materialize(e,t,n,i,s){if(!t)throw Object.assign(new Error(`Instance ${e} does not have a long-lived credential.`),{statusCode:409,code:"INSTANCE_PRIVATE_CONFIG_CREDENTIAL_MISSING"});const r=cc.parse({version:1,instanceId:e,instanceCredential:t,environment:n,...i?{modelCatalog:i}:{},...s?{codexSettings:s}:{},updatedAt:(new Date).toISOString()}),o=this.readLayout(e,this.filePath(e)).value;return o&&function(e,t){const n=e=>lc({instanceId:e.instanceId,instanceCredential:e.instanceCredential,environment:e.environment,modelCatalog:e.modelCatalog,codexSettings:e.codexSettings});return n(e)===n(t)}(o,r)?o:this.put(r)}delete(e){t.rmSync(this.directoryPath(e),{recursive:!0,force:!0})}}const pc="/run/task-handoff/bootstrap",mc=`${pc}/entrypoint.sh`,hc="/bin/bash",gc="/run/task-handoff/private",fc=`${gc}/${dc}`,yc=`${pc}/runtime-installer.mjs`,Ic="/opt/task-handoff/instance-runtime",_c="/run/task-handoff/agent-runs",Ec=`${_c}/overlay`,Ac=`${_c}/shared`;function Tc(e){return`${e.replace(/[^a-zA-Z0-9_.-]/g,"-").replace(/^-+|-+$/g,"").slice(0,36)||"unknown"}-${d.createHash("sha256").update(e).digest("hex").slice(0,10)}`}function bc(e,t){return{role:"agent-run",name:`task-handoff-agent-${Tc(e)}-${Tc(t)}-runs`,mountPath:_c,labels:{"task-handoff.owner":"task-handoff","task-handoff.node-id":e,"task-handoff.runtime-id":t,"task-handoff.volume-role":"agent-run"}}}function wc(e){return bc(e.node?.id||"node_unset",e.runtime?.id||"runtime_local_docker")}function Sc(e,t){return{role:"runtime",name:`${qc(e)}-runtime`,mountPath:Ic,labels:{"task-handoff.owner":"task-handoff","task-handoff.instance-id":e,"task-handoff.node-id":t,"task-handoff.volume-role":"runtime"}}}function Nc(e){return function(e,t,n){const i=qc(e);return[{role:"data",suffix:"data",mountPath:"/data"},{role:"agent-home",suffix:"agent-home",mountPath:"/home/agent"},..."local-folder"===n.type?[]:[{role:"workspace",suffix:"workspace",mountPath:"/workspace"}]].map(({role:n,suffix:s,mountPath:r})=>({role:n,name:`${i}-${s}`,mountPath:r,labels:{"task-handoff.owner":"task-handoff","task-handoff.instance-id":e,"task-handoff.node-id":t,"task-handoff.volume-role":n}}))}(e.instance.id,e.node?.id||"node_unset",e.project.source)}const vc=new Set(["TASK_HANDOFF_REGISTRATION_TOKEN","OPENAI_API_KEY","OPENAI_BASE_URL","CODEX_MODEL","TASK_HANDOFF_CODEX_BASE_URL","TASK_HANDOFF_CODEX_MODEL","TASK_HANDOFF_CODEX_MODEL_ID","ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","CLAUDE_MODEL","TASK_HANDOFF_CLAUDE_MODEL","TASK_HANDOFF_CLAUDE_MODEL_ID"]);function Oc(e,t=[]){const n=e&&"object"==typeof e&&!Array.isArray(e)?e:{},i=n.Config&&"object"==typeof n.Config&&!Array.isArray(n.Config)?n.Config:n,s=new Set;for(const e of Array.isArray(i.Env)?i.Env:[]){if("string"!=typeof e)continue;const n=e.indexOf("="),i=-1===n?e:e.slice(0,n),r=-1===n?"":e.slice(n+1);vc.has(i)&&s.add(`Config.Env.${i}`),t.some(e=>e&&r.includes(e))&&s.add(`Config.Env.${i||"unknown"}`)}if(i.Labels&&"object"==typeof i.Labels&&!Array.isArray(i.Labels))for(const[e,n]of Object.entries(i.Labels))(vc.has(e)||"string"==typeof n&&t.some(e=>e&&n.includes(e)))&&s.add(`Config.Labels.${e}`);if(s.size)throw Object.assign(new Error(`Docker configuration contains instance-private values in ${[...s].sort().join(", ")}.`),{statusCode:409,code:"ENVIRONMENT_TEMPLATE_SECRET_IN_DOCKER_CONFIG",findings:[...s].sort()})}class Rc{runCommand;runTerminalCommand;publishHost;images;launcherAssetsDir;nodeAgentContainerIpcPath;portResolutionRetryDelaysMs;constructor(e=Ba,t={}){this.runCommand=e,this.runTerminalCommand=t.terminalCommandRunner||Ka(e),this.images=t.imageService||new Ya(e),this.publishHost=t.publishHost||"127.0.0.1",this.launcherAssetsDir=t.launcherAssetsDir||oc(),this.nodeAgentContainerIpcPath=t.nodeAgentContainerIpcPath,this.portResolutionRetryDelaysMs=t.portResolutionRetryDelaysMs?.length?t.portResolutionRetryDelaysMs:[0,100,250,500,1e3]}async start(e){Wc(e);const t=e.instance.runtime.containerName||qc(e.instance.id),i=await this.inspectContainerForStart(t);if(i){Hc(t,i.id,e.instance.runtime.containerId,"before start","RUNTIME_EXECUTOR_FAILED");const n=i.labels["task-handoff.instance-id"];if(n!==e.instance.id)throw Pc("RUNTIME_EXECUTOR_FAILED",`Docker container ${t} belongs to ${n||"an unknown instance"}, not ${e.instance.id}.`);await this.createRuntimeVolume(e),await this.validatePersistentVolumes(e,i.mounts);try{await this.runCommand("docker",["start",t])}catch(e){throw Pc("RUNTIME_EXECUTOR_FAILED",`Could not start Docker container ${t}.`,e)}return this.resumedContainerResult(e,t,i.id,i.labels)}if(e.instance.environmentTemplateOrigin){const t=await this.inspectEnvironmentTemplateImage(e.instance.environmentTemplateOrigin.imageId);if(t.imageId!==e.instance.environmentTemplateOrigin.imageId||t.platform!==e.instance.environmentTemplateOrigin.platform||t.architecture!==e.instance.environmentTemplateOrigin.architecture)throw Object.assign(new Error(`Environment template image identity or platform changed for instance ${e.instance.id}.`),{statusCode:409,code:"ENVIRONMENT_TEMPLATE_IMAGE_IDENTITY_MISMATCH"})}else await this.images.ensure(e.image.resolvedReference||e.image.requestedReference);if(await this.createPersistentVolumes(e),"local-folder"!==e.project.source.type){const t=e.instance.workspace.gitProvisioning?.phase;if("ready"!==t)throw Pc(jc,`Git workspace provisioning is ${t??"not scheduled"} for ${e.instance.id}.`);e.completeGitWorkspaceProvisioning?.()}let s;try{s=await this.runCommand("docker",function(e,t,i={}){const s=i.publishHost||"127.0.0.1",r=n.resolve(i.launcherAssetsDir||oc()),o=e.node?.id||"node_unset",a=e.runtime?.id||"runtime_local_docker",c=["run","-d","--name",t,"--user","0:0","--label",`task-handoff.instance-id=${e.instance.id}`,"--label",`task-handoff.project-id=${e.project.id}`,"--label",`task-handoff.node-id=${o}`,"--label",`task-handoff.runtime-id=${a}`,"--label",`task-handoff.image-id=${e.image.id}`,"--label","task-handoff.bootstrap-abi=1","--shm-size","1gb","--security-opt","seccomp=unconfined","--network","bridge","--no-healthcheck","--add-host","host.docker.internal:host-gateway","--tmpfs","/tmp:rw,nosuid,nodev,exec,mode=1777","-p",`${s}::8080`];if(!e.privateConfigPath)throw Object.assign(new Error(`Instance ${e.instance.id} private config was not materialized.`),{statusCode:409,code:"INSTANCE_PRIVATE_CONFIG_MISSING"});if(n.basename(e.privateConfigPath)!==dc)throw Object.assign(new Error(`Instance ${e.instance.id} private config path ${e.privateConfigPath} does not use the per-instance directory layout.`),{statusCode:409,code:"INSTANCE_PRIVATE_CONFIG_LAYOUT_INVALID"});c.push("--mount",`type=bind,src=${n.dirname(e.privateConfigPath)},dst=${gc},readonly`,"--mount",`type=bind,src=${r},dst=${pc},readonly`,"--entrypoint",hc);const d=i.nodeAgentContainerIpcPath?`/run/task-handoff/node-agent-transport/${n.basename(i.nodeAgentContainerIpcPath)}`:void 0;i.nodeAgentContainerIpcPath&&d&&c.push("--mount",`type=bind,src=${n.dirname(i.nodeAgentContainerIpcPath)},dst=/run/task-handoff/node-agent-transport,readonly`);for(const t of Nc(e))c.push("--mount",`type=volume,src=${t.name},dst=${t.mountPath}`);const l=Sc(e.instance.id,e.node?.id||"node_unset");c.push("--mount",`type=volume,src=${l.name},dst=${l.mountPath}`);const u=wc(e);c.push("--mount",`type=volume,src=${u.name},dst=${u.mountPath}`);const p={TASK_HANDOFF_CONTROL_MODE:"controlled",TASK_HANDOFF_NODE_AGENT_URL:d?"http://127.0.0.1:19001":e.nodeAgentUrl||e.node?.endpoint||"",...d?{TASK_HANDOFF_NODE_AGENT_SOCKET_PATH:d}:{},TASK_HANDOFF_INSTANCE_ID:e.instance.id,TASK_HANDOFF_INSTANCE_NAME:e.instance.name,TASK_HANDOFF_PROJECT_ID:e.project.id,TASK_HANDOFF_NODE_ID:o,TASK_HANDOFF_RUNTIME_ID:a,TASK_HANDOFF_IMAGE_ID:e.image.id,TASK_HANDOFF_INSTANCE_LAUNCHER:`${pc}/instance-launcher.sh`,...e.image.tag?{TASK_HANDOFF_IMAGE_TAG:e.image.tag}:{},TASK_HANDOFF_CHAT_BRIDGES:"none",TASK_HANDOFF_WORKSPACE:e.project.workspacePolicy.path||"/workspace",TASK_HANDOFF_WORKSPACE_MODE:e.project.workspacePolicy.mode,TASK_HANDOFF_INSTANCE_PRIVATE_CONFIG_PATH:fc,..."local-folder"===e.project.source.type?{}:{TASK_HANDOFF_SKIP_WORKSPACE_BOOTSTRAP:"true"}};for(const[e,t]of Object.entries(p))Vc(c,e,t);if("local-folder"===e.project.source.type)c.push("-v",`${e.project.source.path}:${e.project.workspacePolicy.path||"/workspace"}:${e.project.workspacePolicy.readOnly?"ro":"rw"}`);else{Vc(c,"TASK_HANDOFF_PROJECT_SOURCE",JSON.stringify(e.project.source)),Vc(c,"TASK_HANDOFF_WORKSPACE_POLICY",JSON.stringify(e.project.workspacePolicy));for(const[t,n]of Gc({url:e.project.source.url,ref:e.project.source.ref,clone:e.project.source.clone},{legacy:!0}))Vc(c,t,n);e.project.source.clone?.subdirectory&&Vc(c,"TASK_HANDOFF_WORKSPACE_SUBDIRECTORY",e.project.source.clone.subdirectory)}const m={...e.image.labels["task-handoff.image.profile"]?{TASK_HANDOFF_IMAGE_PROFILE:e.image.labels["task-handoff.image.profile"]}:{},TASK_HANDOFF_IMAGE_CAPABILITIES:e.image.capabilities.join(",")};for(const[t,n]of Object.entries(e.image.defaultEnv))t in m||Vc(c,t,n);for(const[e,t]of Object.entries(m))Vc(c,e,t);return c.push(i.imageReference||e.instance.environmentTemplateOrigin?.imageId||e.image.resolvedReference||e.image.requestedReference,mc,"task-handoff","web"),c}(e,t,{publishHost:this.publishHost,launcherAssetsDir:this.launcherAssetsDir,nodeAgentContainerIpcPath:this.nodeAgentContainerIpcPath}))}catch(e){throw Pc("RUNTIME_EXECUTOR_FAILED",`Could not create Docker container ${t}.`,e)}return this.bootstrapResult(e,t,s.stdout||void 0)}async provisionGitWorkspaceStreaming(e,i={}){const r=e.gitWorkspaceProvisioning;if(!r)throw Pc("GIT_WORKSPACE_PROVISIONING_MISSING",`Git workspace provisioning input is missing for ${e.instance.id}.`);const o=`${qc(e.instance.id)}-git-provision`;await this.createPersistentVolumes(e);const a=t.mkdtempSync(n.join(s.tmpdir(),"task-handoff-git-auth-"));t.chmodSync(a,448);try{await this.runCommand("docker",["rm","-f",o],{timeoutMs:3e4}).catch(()=>({stdout:"",stderr:""})),this.materializeGitProvisioningAuth(a,r);const t=function(e,t,i,s={}){const r=e.gitWorkspaceProvisioning;if(!r||"local-folder"===e.project.source.type)throw Object.assign(new Error("Git provisioning requires a Git source and operation input."),{code:"GIT_WORKSPACE_PROVISIONING_INVALID",statusCode:400});const o=n.resolve(s.launcherAssetsDir||oc()),a=Nc(e).find(e=>"workspace"===e.role);if(!a)throw Object.assign(new Error("Git workspace volume was not found."),{code:"GIT_WORKSPACE_VOLUME_MISSING",statusCode:409});const c=["run","--rm","--name",t,"--label","task-handoff.role=git-provisioning","--label",`task-handoff.instance-id=${e.instance.id}`,"--user","0:0","--network","bridge","--security-opt","no-new-privileges","--cap-drop","ALL","--cap-add","CHOWN","--cap-add","SETUID","--cap-add","SETGID","--cap-add","DAC_OVERRIDE","--mount",`type=volume,src=${a.name},dst=/workspace`,"--mount",`type=bind,src=${o},dst=${pc},readonly`,"--tmpfs","/run/task-handoff/git-runtime:rw,nosuid,nodev,exec,mode=0700"];r.credentials.length&&c.push("--mount",`type=bind,src=${n.resolve(i)},dst=/run/task-handoff/git-auth,readonly`);const d=(e,t)=>c.push("-e",`${e}=${t}`);d("TASK_HANDOFF_INSTANCE_ID",e.instance.id);for(const[e,t]of Gc({url:r.remoteUrl,ref:r.ref,clone:r.clone},{legacy:!1}))d(e,t);return r.clone.subdirectory&&d("TASK_HANDOFF_WORKSPACE_SUBDIRECTORY",r.clone.subdirectory),c.push("--entrypoint","/bin/bash",e.instance.environmentTemplateOrigin?.imageId||e.image.resolvedReference||e.image.requestedReference,`${pc}/git-provision.sh`),c}(e,o,a,{launcherAssetsDir:this.launcherAssetsDir}),s=await this.runTerminalCommand("docker",t,{cols:120,rows:40,timeoutMs:i.timeoutMs??9e5,signal:i.signal??e.signal,onData:i.onOutput});return e.completeGitWorkspaceProvisioning?.(),s}catch(t){throw function(e,t){const n=Uc(t);return Pc(n,"GIT_WORKSPACE_PROVISIONING_TIMEOUT"===n?`Git workspace provisioning timed out for ${e}.`:"GIT_WORKSPACE_PROVISIONING_CANCELLED"===n?`Git workspace provisioning was cancelled for ${e}.`:`Could not provision Git workspace for ${e}.`)}(e.instance.id,t)}finally{await this.runCommand("docker",["rm","-f",o],{timeoutMs:3e4}).catch(()=>({stdout:"",stderr:""})),t.rmSync(a,{recursive:!0,force:!0})}}materializeGitProvisioningAuth(e,i){const s=(e,i,s)=>{const r=n.join(e,i);t.writeFileSync(r,s,{encoding:"utf8",mode:384}),t.chmodSync(r,384)};i.credentials.forEach((i,r)=>{const o=n.join(e,`credential-${r}`);if(t.mkdirSync(o,{recursive:!0,mode:448}),t.chmodSync(o,448),s(o,"scope.json",JSON.stringify(i.payload.credential.scope)),"https-token"===i.payload.secret.kind)return s(o,"username",i.payload.secret.username),void s(o,"token",i.payload.secret.token);s(o,"private-key",i.payload.secret.privateKey),s(o,"known_hosts",i.payload.secret.pinnedKnownHosts),i.payload.secret.passphrase&&s(o,"passphrase",i.payload.secret.passphrase),s(o,"ssh-askpass.sh",`#!/usr/bin/env bash\ncat /run/task-handoff/git-runtime/credential-${r}/passphrase 2>/dev/null || true\n`)})}async inspectContainerConfigSecurity(e,t){Oc(await this.runCommand("docker",["inspect","--format","{{json .}}",e]).then(e=>JSON.parse(e.stdout||"{}")).catch(t=>{throw Pc("ENVIRONMENT_TEMPLATE_CONTAINER_INSPECT_FAILED",`Could not inspect Docker container ${e}.`,t)}),t)}async inspectImageConfigSecurity(e,t){Oc(await this.runCommand("docker",["image","inspect","--format","{{json .}}",e]).then(e=>JSON.parse(e.stdout||"{}")).catch(e=>{throw Pc("ENVIRONMENT_TEMPLATE_IMAGE_INSPECT_FAILED","Could not inspect Docker image configuration.",e)}),t)}async commitEnvironmentTemplate(e,t,n){const i=await this.inspectContainerId(e);if(!i)throw Pc("ENVIRONMENT_TEMPLATE_CONTAINER_NOT_FOUND",`Docker container ${e} does not exist.`);Hc(e,i,t,"before environment template commit","ENVIRONMENT_TEMPLATE_CONTAINER_IDENTITY_MISMATCH");try{const t=(await this.runCommand("docker",["commit",e,n])).stdout.trim();if(!t)throw new Error("Docker commit did not return an image id.");return t}catch(t){throw Pc("ENVIRONMENT_TEMPLATE_COMMIT_FAILED",`Could not save Docker container ${e} as an environment template.`,t)}}async inspectEnvironmentTemplateImage(e){try{const t=await this.runCommand("docker",["image","inspect","--format","{{json .}}",e]),n=JSON.parse(t.stdout||"{}"),i="string"==typeof n.Id?n.Id:"",s=kc(n.Os),r=Dc(n.Architecture),o="number"==typeof n.Size?n.Size:Number.NaN;if(!/^sha256:[a-f0-9]{64}$/.test(i)||!s||!r||!Number.isSafeInteger(o)||o<0)throw new Error("Docker image inspection did not return a valid immutable identity.");return{imageId:i,platform:s,architecture:r,sizeBytes:o}}catch(e){throw Pc("ENVIRONMENT_TEMPLATE_IMAGE_INSPECT_FAILED","Could not inspect the committed environment template image.",e)}}async untagEnvironmentTemplate(e,t){try{const n=t||(await this.inspectEnvironmentTemplateImage(e)).imageId;return await this.runCommand("docker",["tag",n,Lc(n)]),await this.runCommand("docker",["image","rm",e]),n}catch(e){const t=Fc(e)?.toLowerCase()||"";if(t.includes("no such image")||t.includes("no such object"))return;throw Pc("ENVIRONMENT_TEMPLATE_UNTAG_FAILED","Could not remove the environment template tag.",e)}}async garbageCollectEnvironmentTemplateImage(e){try{try{await this.runCommand("docker",["image","rm",Lc(e)])}catch(e){const t=Fc(e)?.toLowerCase()||"";if(t.includes("being used by")||t.includes("is referenced")||t.includes("conflict"))return!1;if(!t.includes("no such image")&&!t.includes("no such object"))throw e}return await this.runCommand("docker",["image","rm",e]),!0}catch(e){const t=Fc(e)?.toLowerCase()||"";if(t.includes("being used by")||t.includes("is referenced")||t.includes("conflict"))return!1;if(t.includes("no such image")||t.includes("no such object"))return!0;throw Pc("ENVIRONMENT_TEMPLATE_GC_FAILED","Could not garbage collect the environment template image.",e)}}async createPersistentVolumes(e,t=new Set){const n=Sc(e.instance.id,e.node?.id||"node_unset");for(const i of[...Nc(e),n])await this.createVolume(i),await this.validateOwnedVolume(e.instance.id,i,t.has(i.name));const i=wc(e);await this.createVolume(i),await this.validateAgentRunRuntimeVolume(e,i)}async createRuntimeVolume(e){await this.createVolume(Sc(e.instance.id,e.node?.id||"node_unset"));const t=wc(e);await this.createVolume(t),await this.validateAgentRunRuntimeVolume(e,t)}async createVolume(e){const t=["volume","create"];for(const[n,i]of Object.entries(e.labels).sort(([e],[t])=>e.localeCompare(t)))t.push("--label",`${n}=${i}`);t.push(e.name);try{await this.runCommand("docker",t)}catch(t){throw Pc("INSTANCE_VOLUME_CREATE_FAILED",`Could not create managed volume ${e.name}.`,t)}}async validatePersistentVolumes(e,t){for(const n of Nc(e)){await this.validateOwnedVolume(e.instance.id,n);const i=t.find(e=>"volume"===e.type&&e.destination===n.mountPath);if(!i||i.name!==n.name)throw Object.assign(new Error(`Docker container mount for ${n.role} does not match managed volume ${n.name}.`),{statusCode:409,code:"INSTANCE_VOLUME_MOUNT_IDENTITY_MISMATCH"})}const i=Sc(e.instance.id,e.node?.id||"node_unset");await this.validateOwnedVolume(e.instance.id,i);const s=t.find(e=>"volume"===e.type&&e.destination===i.mountPath);if(!s||s.name!==i.name)throw Object.assign(new Error(`Docker container runtime mount does not match ${i.name}.`),{statusCode:409,code:"INSTANCE_VOLUME_MOUNT_IDENTITY_MISMATCH"});const r=wc(e);await this.validateAgentRunRuntimeVolume(e,r);const o=t.find(e=>e.destination===r.mountPath);if(o&&("volume"!==o.type||o.name!==r.name))throw Object.assign(new Error(`Docker Agent Run mount does not match managed volume ${r.name}.`),{statusCode:409,code:"AGENT_RUN_VOLUME_MOUNT_IDENTITY_MISMATCH"});if("local-folder"===e.project.source.type){const i=t.find(t=>t.destination===(e.project.workspacePolicy.path||"/workspace"));if(!i||"bind"!==i.type||n.resolve(i.source||"")!==n.resolve(e.project.source.path))throw Object.assign(new Error(`Docker container workspace bind does not match local folder ${e.project.source.path}.`),{statusCode:409,code:"INSTANCE_WORKSPACE_MOUNT_IDENTITY_MISMATCH"})}}async validateAgentRunRuntimeVolume(e,t){let n;try{n=await this.runCommand("docker",["volume","inspect","--format","{{json .}}",t.name])}catch(e){throw Pc("AGENT_RUN_VOLUME_INSPECT_FAILED",`Could not inspect Agent Run volume ${t.name}.`,e)}try{const i=JSON.parse(n.stdout||"{}"),s=i.Labels&&"object"==typeof i.Labels&&!Array.isArray(i.Labels)?i.Labels:{},r=i.Options&&"object"==typeof i.Options&&!Array.isArray(i.Options)?i.Options:{};if(i.Name!==t.name||"task-handoff"!==s["task-handoff.owner"]||s["task-handoff.node-id"]!==(e.node?.id||"node_unset")||s["task-handoff.runtime-id"]!==(e.runtime?.id||"runtime_local_docker")||s["task-handoff.volume-role"]!==t.role||"string"==typeof i.Driver&&"local"!==i.Driver||Object.keys(r).length>0)throw new Error("volume identity, ownership or local driver does not match")}catch(n){throw Object.assign(new Error(`Agent Run volume ${t.name} identity does not match runtime ${e.runtime?.id}.`,{cause:n}),{statusCode:409,code:"AGENT_RUN_VOLUME_IDENTITY_MISMATCH"})}}async validateOwnedVolume(e,t,n=!1){let i;try{i=await this.runCommand("docker",["volume","inspect","--format","{{json .}}",t.name])}catch(e){throw Pc("INSTANCE_VOLUME_INSPECT_FAILED",`Could not inspect managed volume ${t.name}.`,e)}try{const s=JSON.parse(i.stdout||"{}"),r=s.Labels&&"object"==typeof s.Labels&&!Array.isArray(s.Labels)?s.Labels:{},o=s.Name===t.name&&"task-handoff"===r["task-handoff.owner"]&&r["task-handoff.instance-id"]===e&&r["task-handoff.volume-role"]===t.role,a=n&&s.Name===t.name&&0===Object.keys(r).length;if(!o&&!a)throw new Error("volume name or ownership labels do not match")}catch(n){throw Object.assign(new Error(`Managed volume ${t.name} identity does not match instance ${e}.`,{cause:n}),{statusCode:409,code:"INSTANCE_VOLUME_IDENTITY_MISMATCH"})}}async runningResult(e,t,n){const i=await this.publishedEndpoint(t),s=e.node?.id||"node_unset",r=e.runtime?.id||"runtime_local_docker";return{status:"registering",health:"unknown",connectionStatus:"online",agentStatus:"unknown",targetStatus:"unknown",uiAccessStatus:"unknown",target:{strategy:"direct-port",status:"reachable",...i},workspace:{mode:e.project.workspacePolicy.mode,status:"pending",path:e.project.workspacePolicy.path},runtime:{...e.instance.runtime,kind:"docker",containerName:t,...n?{containerId:n}:{},labels:{...e.instance.runtime.labels,"task-handoff.instance-id":e.instance.id,"task-handoff.project-id":e.project.id,"task-handoff.node-id":s,"task-handoff.runtime-id":r,"task-handoff.image-id":e.image.id}}}}async resumedContainerResult(e,t,n,i){const s=this.bootstrapResult(e,t,n);return{...s,target:{...s.target,...await this.publishedEndpoint(t)},runtime:{...s.runtime,labels:{...e.instance.runtime.labels,...i}}}}async publishedEndpoint(e){const t=`http://127.0.0.1:${await this.containerPort(e,"8080/tcp")}`;return{web:t,api:`${t}/api`}}async resolveInstanceWeb(e){const t=e.instance.runtime.containerName||qc(e.instance.id),n=await this.inspectContainerId(t);if(!n)throw Pc("INSTANCE_RUNTIME_ENDPOINT_UNAVAILABLE",`Docker container ${t} does not exist.`);return Hc(t,n,e.instance.runtime.containerId,"while resolving its web endpoint","INSTANCE_RUNTIME_ENDPOINT_UNAVAILABLE"),(await this.publishedEndpoint(t)).web}async resolveNodeAgentUrl(e){const t=e.nodeAgentUrl||e.node?.endpoint||"";if(!this.nodeAgentContainerIpcPath)return t;const i=e.instance.runtime.containerName||qc(e.instance.id),s=await this.inspectContainerForStart(i);if(!s)return t;if(Hc(i,s.id,e.instance.runtime.containerId,"while resolving its node-agent transport","RUNTIME_EXECUTOR_FAILED"),s.labels["task-handoff.instance-id"]!==e.instance.id)throw Pc("RUNTIME_EXECUTOR_FAILED",`Docker container ${i} does not belong to ${e.instance.id}.`);const r=n.dirname(n.resolve(this.nodeAgentContainerIpcPath));return s.mounts.some(e=>"bind"===e.type&&"/run/task-handoff/node-agent-transport"===e.destination&&n.resolve(e.source||"")===r)?"http://127.0.0.1:19001":t}bootstrapResult(e,t,n){return{status:"starting",health:"unknown",connectionStatus:"unknown",agentStatus:"unknown",targetStatus:"unknown",uiAccessStatus:"unknown",target:{strategy:"direct-port",status:"unknown"},workspace:{mode:e.project.workspacePolicy.mode,status:"pending",path:e.project.workspacePolicy.path},runtime:{...e.instance.runtime,kind:"docker",containerName:t,...n?{containerId:n}:{},labels:{...e.instance.runtime.labels,"task-handoff.bootstrap-abi":"1"}}}}async stop(e){const t=e.instance.runtime.containerName||qc(e.instance.id);try{await this.runCommand("docker",["stop",t])}catch(e){if(!$c(e))throw Pc("RUNTIME_EXECUTOR_FAILED",`Could not stop Docker container ${t}.`,e)}return{status:"stopped",health:"unknown",connectionStatus:"offline",target:{...e.instance.target,status:"unknown"},runtime:e.instance.runtime}}async restart(e,t){Wc(e);const n=e.instance.runtime.containerName||qc(e.instance.id),i=await this.inspectContainerId(n);if(!i)throw Pc("INSTANCE_RUNTIME_RESTART_FAILED",`Docker container ${n} does not exist.`);Hc(n,i,t,"before restart","INSTANCE_RUNTIME_RESTART_FAILED"),await this.runCommand("docker",["restart",n]);const s=await this.inspectContainerId(n);if(!s||s!==i)throw Pc("INSTANCE_RUNTIME_RESTART_FAILED",`Docker container identity changed while restarting ${n}.`);return Hc(n,s,t,"after restart","INSTANCE_RUNTIME_RESTART_FAILED"),this.runningResult(e,n,s)}async delete(e,t){const n=e.instance.runtime.containerName||qc(e.instance.id),i=await this.inspectContainerForStart(n),s=new Set;if(i){Hc(n,i.id,e.instance.runtime.containerId,"before delete","RUNTIME_EXECUTOR_FAILED");const t=i.labels["task-handoff.instance-id"];if(t!==e.instance.id)throw Pc("RUNTIME_EXECUTOR_FAILED",`Docker container ${n} belongs to ${t||"an unknown instance"}, not ${e.instance.id}.`);for(const t of Nc(e))i.mounts.some(e=>"volume"===e.type&&e.name===t.name&&e.destination===t.mountPath)&&s.add(t.name);try{await this.runCommand("docker",["rm","-f",i.id])}catch(e){if(!$c(e))throw Pc("RUNTIME_EXECUTOR_FAILED",`Could not delete Docker container ${n}.`,e)}}const r=[];for(const n of Nc(e))if(t.deleteVolumes)try{const t=await this.inspectVolumeForDelete(n.name);if(!t){r.push({role:n.role,name:n.name,mountPath:n.mountPath,status:"missing"});continue}const i=t.name===n.name&&"task-handoff"===t.labels["task-handoff.owner"]&&t.labels["task-handoff.instance-id"]===e.instance.id&&t.labels["task-handoff.volume-role"]===n.role,o=s.has(n.name)&&t.name===n.name&&0===Object.keys(t.labels).length;if(!i&&!o)throw Object.assign(new Error(`Managed volume ${n.name} ownership does not match instance ${e.instance.id}.`),{code:"INSTANCE_VOLUME_IDENTITY_MISMATCH"});await this.runCommand("docker",["volume","rm",n.name]),r.push({role:n.role,name:n.name,mountPath:n.mountPath,status:"deleted"})}catch(e){r.push({role:n.role,name:n.name,mountPath:n.mountPath,status:"failed",error:{code:"object"==typeof e&&e&&"code"in e&&"string"==typeof e.code?e.code:"INSTANCE_VOLUME_DELETE_FAILED",message:e instanceof Error?e.message:String(e)}})}else r.push({role:n.role,name:n.name,mountPath:n.mountPath,status:"retained"});return await this.deleteRuntimeVolume(e),qs.parse({instanceId:e.instance.id,containerDeleted:!0,completed:r.every(e=>"failed"!==e.status),deletedVolumes:r.filter(e=>"deleted"===e.status||"missing"===e.status),retainedVolumes:r.filter(e=>"retained"===e.status),volumeResults:r})}async deleteRuntimeVolume(e){const t=Sc(e.instance.id,e.node?.id||"node_unset"),n=await this.inspectVolumeForDelete(t.name);if(n){if(n.name!==t.name||"task-handoff"!==n.labels["task-handoff.owner"]||n.labels["task-handoff.instance-id"]!==e.instance.id||"runtime"!==n.labels["task-handoff.volume-role"])throw Pc("INSTANCE_VOLUME_IDENTITY_MISMATCH",`Runtime volume ${t.name} ownership does not match instance ${e.instance.id}.`);try{await this.runCommand("docker",["volume","rm",t.name])}catch(e){throw Pc("INSTANCE_VOLUME_DELETE_FAILED",`Could not delete runtime volume ${t.name}.`,e)}}}async inspectVolumeForDelete(e){try{const t=await this.runCommand("docker",["volume","inspect","--format","{{json .}}",e]),n=JSON.parse(t.stdout||"{}");return{name:"string"==typeof n.Name?n.Name:"",labels:n.Labels&&"object"==typeof n.Labels&&!Array.isArray(n.Labels)?Object.fromEntries(Object.entries(n.Labels).filter(e=>"string"==typeof e[1])):{}}}catch(t){if(function(e){const t=Fc(e)?.toLowerCase()||"";return t.includes("no such volume")||t.includes("no such object")}(t))return;throw Pc("INSTANCE_VOLUME_INSPECT_FAILED",`Could not inspect managed volume ${e}.`,t)}}async installRuntime(e){const t=await this.installRuntimeRelease(e);Hc(e.containerName,t,e.expectedContainerId,"before runtime restart","INSTANCE_RUNTIME_RESTART_FAILED");try{await this.runCommand("docker",["restart",t])}catch(t){throw Pc("INSTANCE_RUNTIME_RESTART_FAILED",`Could not restart Docker container ${e.containerName}.`,t)}const n=await this.inspectContainerId(e.containerName);if(!n||n!==t)throw Pc("INSTANCE_RUNTIME_RESTART_FAILED",`Docker container identity changed while updating ${e.containerName}.`);return Hc(e.containerName,n,e.expectedContainerId,"after runtime restart","INSTANCE_RUNTIME_RESTART_FAILED"),this.inspectRuntimeVersion(e.containerName)}async installRuntimeRelease(e){const t=await this.inspectContainerId(e.containerName);if(!t)throw Pc("INSTANCE_RUNTIME_INSTALL_FAILED",`Docker container ${e.containerName} does not exist.`);Hc(e.containerName,t,e.expectedContainerId,"before runtime install","INSTANCE_RUNTIME_INSTALL_FAILED");const n=`/opt/task-handoff/instance-runtime/incoming/task-handoff-runtime-${i=e.identity.version,i.replace(/[^0-9A-Za-z.+_-]/g,"-")}-${e.identity.sha256.slice(0,12)}.tar.gz`;var i;await this.runCommand("docker",["exec","--user","0",t,"install","-d","-o","root","-g","root","-m","0755","/opt/task-handoff/instance-runtime/incoming"]),await this.runCommand("docker",["cp",e.artifactPath,`${t}:${n}`]);try{await this.runCommand("docker",["exec","--user","0",t,"node",yc,"install","--artifact",n,"--version",e.identity.version,"--sha256",e.identity.sha256,"--platform",e.identity.platform,"--arch",e.identity.arch,"--launcher-abi",String(e.identity.launcherAbi)])}catch(t){throw Pc("INSTANCE_RUNTIME_INSTALL_FAILED",`Could not install controlled-instance ${e.identity.version} in ${e.containerName}.`,t)}finally{await this.runCommand("docker",["exec","--user","0",t,"rm","-f",n]).catch(()=>({stdout:"",stderr:""}))}const s=await this.inspectContainerId(e.containerName);if(!s||s!==t)throw Pc("INSTANCE_RUNTIME_INSTALL_FAILED",`Docker container identity changed while installing ${e.containerName}.`);return Hc(e.containerName,s,e.expectedContainerId,"after runtime install","INSTANCE_RUNTIME_INSTALL_FAILED"),t}async inspectRuntimeVersion(e){const t=await this.inspectContainerId(e);if(!t)return{};const n=await this.runCommand("docker",["exec","--user","agent",e,"node",yc,"verify-active"]).catch(()=>{});if(!n?.stdout)return{containerId:t};try{const e=ja(yr,JSON.parse(n.stdout));return e.success?{containerId:t,...e.data}:{containerId:t}}catch{return{containerId:t}}}async runtimeState(e){try{return"true"===(await this.runCommand("docker",["inspect","--format","{{.State.Running}}",e],{timeoutMs:5e3})).stdout.trim()?"running":"stopped"}catch(e){return $c(e)?"absent":"unknown"}}async inspectRuntimeTarget(e){let t,n;if(e){const i=await this.runCommand("docker",["inspect","--format","{{json .}}",e]).then(e=>JSON.parse(e.stdout.trim()||"{}")).catch(()=>{});if(t=i?.Platform,"string"==typeof i?.Image&&i.Image){const e=await this.runCommand("docker",["image","inspect","--format","{{json .}}",i.Image]).then(e=>JSON.parse(e.stdout.trim()||"{}")).catch(()=>{});t=e?.Os||t,n=e?.Architecture}}if(!t||!n){const e=await this.runCommand("docker",["info","--format","{{json .}}"]).then(e=>JSON.parse(e.stdout.trim()||"{}")).catch(e=>{throw Pc("INSTANCE_BASE_RUNTIME_INCOMPATIBLE","Could not inspect the Docker runtime target.",e)});t||=e.OSType,n||=e.Architecture}const i=kc(t),s=Dc(n);if(!i||!s)throw Pc("INSTANCE_BASE_RUNTIME_INCOMPATIBLE",`Docker reported an unsupported runtime target ${String(t||"unknown")}/${String(n||"unknown")}.`);return{platform:i,arch:s,launcherAbi:1}}async installRuntimeReleaseWithRecovery(e){const t=e.containerName,i=await this.inspectContainerForStart(t);if(!i)throw Pc("INSTANCE_RUNTIME_INSTALL_FAILED",`Docker container ${t} does not exist.`);if(Hc(t,i.id,e.expectedContainerId,"before runtime install recovery","INSTANCE_RUNTIME_INSTALL_FAILED"),i.running)return await this.installRuntimeLauncher(t,i.id),void await this.installRuntimeRelease({...e,expectedContainerId:i.id});if(!i.image)throw Pc("INSTANCE_RUNTIME_INSTALL_FAILED",`Docker container ${t} does not expose its immutable image identity.`);const s="/run/task-handoff/runtime-rescue-artifact.tar.gz",r=[`test -r ${mc}`,`test -r ${pc}/instance-launcher.sh`,`test -r ${yc}`,`install -d -o root -g root -m 0755 ${Ic} ${Ic}/releases ${Ic}/staging ${Ic}/incoming`,`chown -R root:root ${Ic}`,`chmod -R go-w ${Ic}`,`node ${yc} install --artifact "$1" --version "$2" --sha256 "$3" --platform "$4" --arch "$5" --launcher-abi "$6"`].join("; ");try{await this.runCommand("docker",["run","--rm","--user","0:0","--volumes-from",i.id,"--mount",`type=bind,source=${n.resolve(e.artifactPath)},target=${s},readonly`,"--entrypoint",hc,i.image,"-ceu",r,"task-handoff-runtime-rescue",s,e.identity.version,e.identity.sha256,e.identity.platform,e.identity.arch,String(e.identity.launcherAbi)])}catch(n){throw Pc("INSTANCE_RUNTIME_INSTALL_FAILED",`Could not rescue controlled-instance ${e.identity.version} in stopped container ${t}.`,n)}const o=await this.inspectContainerForStart(t);if(!o)throw Pc("INSTANCE_RUNTIME_INSTALL_FAILED",`Docker container ${t} disappeared during runtime install recovery.`);if(Hc(t,o.id,i.id,"after runtime install recovery","INSTANCE_RUNTIME_INSTALL_FAILED"),o.running)throw Pc("INSTANCE_RUNTIME_INSTALL_FAILED",`Stopped Docker container ${t} changed lifecycle state during runtime install recovery.`)}async installRuntimeLauncher(e,t){const n=await this.inspectContainerId(e);if(!n)throw Pc("INSTANCE_BASE_RUNTIME_INCOMPATIBLE",`Docker container ${e} does not exist.`);Hc(e,n,t,"before runtime launcher install","INSTANCE_BASE_RUNTIME_INCOMPATIBLE");try{await this.runCommand("docker",["exec","--user","0",n,"bash","-ceu",`test -r ${mc}; test -r ${pc}/instance-launcher.sh; test -r ${yc}; install -d -o root -g root -m 0755 /opt/task-handoff/instance-runtime /opt/task-handoff/instance-runtime/releases /opt/task-handoff/instance-runtime/staging /opt/task-handoff/instance-runtime/incoming; chown -R root:root /opt/task-handoff/instance-runtime; chmod -R go-w /opt/task-handoff/instance-runtime`])}catch(t){throw Pc("INSTANCE_BASE_RUNTIME_INCOMPATIBLE",`Could not install the runtime launcher in ${e}.`,t)}const i=await this.inspectContainerId(e);if(i!==n)throw Pc("INSTANCE_BASE_RUNTIME_INCOMPATIBLE",`Docker container identity changed while installing the runtime launcher in ${e}.`);Hc(e,i,t,"after runtime launcher install","INSTANCE_BASE_RUNTIME_INCOMPATIBLE")}async inspectContainerId(e){try{return(await this.runCommand("docker",["inspect","--format","{{.Id}}",e])).stdout.trim()||void 0}catch(t){if($c(t))return;throw Pc("RUNTIME_EXECUTOR_FAILED",`Could not inspect Docker container ${e}.`,t)}}async inspectContainerForStart(e){let t;try{t=await this.runCommand("docker",["inspect","--format","{{json .}}",e])}catch(t){if($c(t))return;throw Pc("RUNTIME_EXECUTOR_FAILED",`Could not inspect Docker container ${e}.`,t)}try{const e=JSON.parse(t.stdout||"{}");if("string"!=typeof e.Id||!e.Id)throw new Error("Docker inspect did not return a container id.");const n=e.Config?.Labels&&"object"==typeof e.Config.Labels&&!Array.isArray(e.Config.Labels)?Object.fromEntries(Object.entries(e.Config.Labels).filter(e=>"string"==typeof e[1])):{},i=Array.isArray(e.Mounts)?e.Mounts.flatMap(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return[];const t=e,n="volume"===t.Type||"bind"===t.Type?t.Type:void 0,i="string"==typeof t.Destination?t.Destination:void 0;return n&&i?[{type:n,destination:i,name:"string"==typeof t.Name?t.Name:void 0,source:"string"==typeof t.Source?t.Source:void 0}]:[]}):[],s=Array.isArray(e.Config?.Entrypoint)?e.Config.Entrypoint.filter(e=>"string"==typeof e):"string"==typeof e.Config?.Entrypoint?[e.Config.Entrypoint]:[],r=Array.isArray(e.Config?.Cmd)?e.Config.Cmd.filter(e=>"string"==typeof e):"string"==typeof e.Config?.Cmd?[e.Config.Cmd]:[];return{id:e.Id,image:"string"==typeof e.Image?e.Image:void 0,running:!0===e.State?.Running,entrypoint:s,command:r,labels:n,mounts:i}}catch(t){throw Pc("RUNTIME_EXECUTOR_FAILED",`Docker returned invalid inspection data for ${e}.`,t)}}async containerPort(e,t){let n,i=!1;for(const s of this.portResolutionRetryDelaysMs){s>0&&await Cc(s);try{const n=zc((await this.runCommand("docker",["port",e,t])).stdout);if(n)return n}catch(e){n=e}try{const n=xc((await this.runCommand("docker",["inspect","--format","{{json .NetworkSettings.Ports}}",e])).stdout,t);if(i=!0,n)return n}catch(e){n=e}}if(i)throw Pc("RUNTIME_EXECUTOR_FAILED",`Docker container ${e} does not publish ${t}.`);throw Pc("RUNTIME_EXECUTOR_FAILED",`Could not resolve the published port for Docker container ${e}.`,n)}}function zc(e){const t=e.split(/\r?\n/).find(Boolean);return t?.match(/:(\d+)$/)?.[1]}function xc(e,t){const n=JSON.parse(e||"null");if(!n||"object"!=typeof n||Array.isArray(n))return;const i=n[t];if(Array.isArray(i))for(const e of i){if(!e||"object"!=typeof e||Array.isArray(e))continue;const t=e.HostPort;if("string"==typeof t&&/^\d+$/.test(t))return t}}function Cc(e){return new Promise(t=>setTimeout(t,e))}function kc(e){return"linux"===e||"darwin"===e?e:"windows"===e||"win32"===e?"win32":void 0}function Dc(e){return"amd64"===e||"x86_64"===e||"x64"===e?"x64":"arm64"===e||"aarch64"===e?"arm64":void 0}function Lc(e){return`task-handoff/environment-image:${e.replace(/^sha256:/,"")}`}function Pc(e,t,n){const i=Fc(n),s=new Error(i?`${t} Cause: ${i}`:t,void 0===n?void 0:{cause:n});return Object.assign(s,{statusCode:502,code:e}),s}const Mc=new Set(["AUTHENTICATION_REJECTED","CLONE_FAILED","CREDENTIAL_AMBIGUOUS","CREDENTIAL_MISSING","HOST_KEY_REQUIRED","LFS_FAILED","REF_NOT_FOUND","REMOTE_UNSUPPORTED","SSH_AGENT_UNAVAILABLE","SUBDIRECTORY_NOT_FOUND","WORKSPACE_NOT_EMPTY","WORKSPACE_OWNERSHIP_MISMATCH"]),jc="GIT_WORKSPACE_PROVISIONING_PENDING";function Uc(e){const t=e&&"object"==typeof e?e:void 0,n="string"==typeof t?.code?t.code:"";if("RUNTIME_COMMAND_TIMEOUT"===n)return"GIT_WORKSPACE_PROVISIONING_TIMEOUT";if("RUNTIME_COMMAND_ABORTED"===n)return"GIT_WORKSPACE_PROVISIONING_CANCELLED";const i=Fc(e)||"",s=i.match(/TASK_HANDOFF_GIT_PROVISIONING_ERROR=([A-Z_]+)/)?.[1];return`GIT_WORKSPACE_PROVISIONING_${s&&Mc.has(s)?s:"FAILED"}`}function Fc(e){if(!e||"object"!=typeof e)return void 0===e?void 0:String(e);const t=e,n=t.details?.stderr||t.details?.stdout;return"string"==typeof n&&n.trim()?n.trim():"string"==typeof t.message&&t.message.trim()?t.message.trim():void 0}function $c(e){const t=Fc(e)?.toLowerCase()||"";return t.includes("no such container")||t.includes("no such object")}function Hc(e,t,n,i,s){if(n&&t!==n)throw Pc(s,`Docker container ${e} identity mismatch ${i}: expected ${n}, got ${t}.`)}async function Bc(e=Ba){return async function(e=Ba){return(await e("docker",["images","--digests","--format","{{json .}}"])).stdout.split(/\r?\n/).map(e=>e.trim()).filter(Boolean).map(e=>{const t=JSON.parse(e),n=t.Repository||"<none>",i=t.Tag||"<none>",s=t.ID||t.IDShort||"",r="<none>"!==n&&"<none>"!==i?`${n}:${i}`:s,o="<none>"!==n&&t.Digest&&"<none>"!==t.Digest?[`${n}@${t.Digest}`]:[];return{repository:n,tag:i,id:s,createdSince:t.CreatedSince,size:t.Size,sizeBytes:Xa(t.Size),reference:r,repoDigests:o}}).filter(e=>Boolean(e.reference))}(e)}function qc(e){return`task-handoff-${e.replace(/[^a-zA-Z0-9_.-]/g,"-")}`}function Vc(e,t,n){e.push("-e",`${t}=${n}`)}function Gc(e,t){const n="commit"===e.ref.type?"":e.ref.name,i="commit"===e.ref.type?e.ref.commit:"",s=e.clone?.depth?String(e.clone.depth):"",r=e.clone?.submodules?"true":"false",o=e.clone?.lfs?"true":"false",a=[["TASK_HANDOFF_WORKSPACE_GIT_URL",e.url],["TASK_HANDOFF_WORKSPACE_GIT_REF",n],["TASK_HANDOFF_WORKSPACE_GIT_COMMIT",i],["TASK_HANDOFF_WORKSPACE_GIT_DEPTH",s],["TASK_HANDOFF_WORKSPACE_GIT_SUBMODULES",r],["TASK_HANDOFF_WORKSPACE_GIT_LFS",o]];return t.legacy?a.concat([["TASK_HANDOFF_GIT_URL",e.url],["TASK_HANDOFF_GIT_REF",n],["TASK_HANDOFF_GIT_DEPTH",s],["TASK_HANDOFF_GIT_SUBMODULES",r],["TASK_HANDOFF_GIT_LFS",o]]):a}function Wc(e){if("local-folder"===e.project.source.type&&e.project.source.ownerNodeId&&e.project.source.ownerNodeId!==e.node.id){const e=new Error("Local folder projects can only start on the node that owns the folder.");throw Object.assign(e,{statusCode:400,code:"LOCAL_FOLDER_REQUIRES_OWNER_NODE"}),e}if(!e.image.requestedReference?.trim()){const e=new Error("Image profile must reference a registered image.");throw Object.assign(e,{statusCode:400,code:"IMAGE_PROFILE_INVALID"}),e}}const Kc="manifest.json",Yc=c.z.enum(["docker","kubernetes","local"]),Xc=c.z.record(c.z.string().trim().min(2).max(35),c.z.string().trim().min(1).max(160)),Jc=c.z.string().trim().min(1).max(105).regex(/^[a-z0-9][a-z0-9._-]*$/),Qc=c.z.string().trim().min(1).max(160),Zc=c.z.array(Yc).min(1).max(3),ed=c.z.object({schemaVersion:c.z.literal(1),id:Jc,name:Qc,localizedNames:Xc.optional(),runtimes:Zc,contentDigest:c.z.string().trim().regex(/^[a-f0-9]{64}$/)}).strict(),td=c.z.object({name:c.z.string().trim().min(1).max(64).regex(/^[a-z0-9][a-z0-9._-]*$/),targetDir:c.z.string().trim().min(1).max(512).optional()}).strict();function nd(e,t,n){return Object.assign(new Error(t),{code:e,statusCode:500,...n?{details:n}:{}})}function id(){const e=("undefined"==typeof document?require("url").pathToFileURL(__filename).href:z&&"SCRIPT"===z.tagName.toUpperCase()&&z.src||new URL("cli.js",document.baseURI).href)?n.dirname(r.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(__filename).href:z&&"SCRIPT"===z.tagName.toUpperCase()&&z.src||new URL("cli.js",document.baseURI).href)):__dirname,i=[n.resolve(e,"../../../../../builtin-projects"),n.resolve(e,"../builtin-projects"),n.resolve(e,"../../builtin-projects")];return i.find(sd)||i.find(e=>t.existsSync(e))||i[0]}function sd(e){try{return t.readdirSync(e,{withFileTypes:!0}).some(i=>i.isDirectory()&&t.existsSync(n.join(e,i.name,Kc)))}catch{return!1}}function rd(e){const i=[],s=r=>{const o=r?n.join(e,r):e;for(const a of t.readdirSync(o,{withFileTypes:!0}).sort((e,t)=>e.name.localeCompare(t.name))){const o=r?`${r}/${a.name}`:a.name;if(a.isDirectory()){s(o);continue}if(!a.isFile())continue;const c=n.join(e,...o.split("/")),l=t.statSync(c);i.push({path:o,absolutePath:c,mode:511&l.mode,sha256:d.createHash("sha256").update(t.readFileSync(c)).digest("hex"),bytes:l.size})}};return s(""),i.sort((e,t)=>e.path.localeCompare(t.path))}function od(e){const t=d.createHash("sha256");for(const n of e)t.update(`${n.path}\0${n.sha256}\n`);return t.digest("hex")}function ad(e){const i=n.join(e,Kc);let s;try{s=JSON.parse(t.readFileSync(i,"utf8"))}catch(t){throw nd("BUILTIN_PROJECT_MANIFEST_INVALID",`Built-in project manifest ${i} could not be read as JSON.`,{root:e,cause:t instanceof Error?t.message:String(t)})}const r=ed.safeParse(s);if(!r.success)throw nd("BUILTIN_PROJECT_MANIFEST_INVALID",`Built-in project manifest ${i} does not match the current schema.`,{root:e,issues:r.error.issues});return r.data}c.z.object({schemaVersion:c.z.literal(1),id:Jc,name:Qc,localizedNames:Xc.optional(),runtimes:Zc,skill:td.optional()}).strict();const cd=".task-handoff",dd="initialized.json",ld=c.z.object({schemaVersion:c.z.literal(1),projectId:c.z.string().trim().min(1).max(120),contentDigest:c.z.string().trim().regex(/^[a-f0-9]{64}$/),instanceId:c.z.string().trim().min(1).max(120).optional(),createdAt:c.z.string().trim().min(1).max(64)}).strict();function ud(e){try{const i=JSON.parse(t.readFileSync(function(e){return n.join(e,cd,dd)}(e),"utf8")),s=ld.safeParse(i);return s.success?s.data:void 0}catch{return}}function pd(e,t={}){return Object.assign(new Error(`Built-in project target ${e} already contains content this product did not initialize.`),{statusCode:409,code:"BUILTIN_PROJECT_TARGET_NOT_EMPTY",details:{targetDir:e,...t}})}function md(e){return`folder_builtin_${e}`}function hd(e,t){return n.join(e,t)}function gd(e){const i=e.definitions.filter(e=>e.runtimes.includes("local")).sort((e,t)=>e.id.localeCompare(t.id)),s=new Map(i.map(e=>[md(e.id),e])),r=t=>{const n=ud(hd(e.targetsDir,t.id));return n?.projectId===t.id?((t,n)=>kr.parse({id:md(t.id),nodeId:e.nodeId,name:t.name,path:hd(e.targetsDir,t.id),origin:"builtin",...t.localizedNames?{localizedNames:t.localizedNames}:{},labels:{},createdAt:n.createdAt,updatedAt:n.createdAt}))(t,n):void 0};return{list:()=>i.flatMap(e=>{const t=r(e);return t?[t]:[]}),get(e){const t=s.get(e);return t?r(t):void 0},owns:e=>s.has(e),prepare:()=>i.map(i=>function(e,i){const s=hd(i,e.id);try{const i=function(e,i,s={}){const r=ud(i);if(r)return{status:"already-initialized",targetDir:i,projectId:r.projectId,contentDigest:r.contentDigest};const o=t.existsSync(i);if(o){if(!t.statSync(i).isDirectory())throw pd(i,{reason:"target-is-not-a-directory"});if(a=i,0!==t.readdirSync(a).length)throw pd(i,{reason:"target-is-not-empty"})}var a;const c=n.dirname(i);t.mkdirSync(c,{recursive:!0,mode:493});const d=t.mkdtempSync(n.join(c,`.${n.basename(i)}.staging-`));try{for(const i of e.files){const e=n.join(d,...i.path.split("/"));t.mkdirSync(n.dirname(e),{recursive:!0,mode:493}),t.writeFileSync(e,t.readFileSync(i.absolutePath),{mode:i.mode}),t.chmodSync(e,i.mode)}const r={schemaVersion:1,projectId:e.id,contentDigest:e.contentDigest,...s.instanceId?{instanceId:s.instanceId}:{},createdAt:s.createdAt||(new Date).toISOString()};t.mkdirSync(n.join(d,cd),{recursive:!0,mode:493}),t.writeFileSync(n.join(d,cd,dd),`${JSON.stringify(r,null,2)}\n`,{mode:420}),o&&t.rmdirSync(i),t.renameSync(d,i)}catch(e){throw t.rmSync(d,{recursive:!0,force:!0}),e}return{status:"initialized",targetDir:i,projectId:e.id,contentDigest:e.contentDigest,filesWritten:e.files.length}}(e,s);return i.projectId!==e.id?{projectId:e.id,status:"failed",targetDir:s,code:"BUILTIN_PROJECT_TARGET_OWNED",message:`Built-in project target ${s} is marked as ${i.projectId}.`}:{projectId:e.id,status:i.status,targetDir:s,..."initialized"===i.status?{filesWritten:i.filesWritten}:{}}}catch(t){return{projectId:e.id,status:"failed",targetDir:s,code:t.code||"BUILTIN_PROJECT_INITIALIZATION_FAILED",message:t instanceof Error?t.message:String(t)}}}(i,e.targetsDir))}}const fd="app.sessions";c.z.object({type:c.z.literal("snapshot"),data:c.z.string(),pendingEscape:c.z.string(),cols:c.z.number().int().positive(),rows:c.z.number().int().positive()}).passthrough();const yd="app-session.snapshot",Id="app-session.patch",_d="app-session.removed",Ed=c.z.enum(["created","starting","running","stopping","stopped","exited","failed","closed","terminated","unknown"]),Ad=c.z.enum(["tty","vnc","web"]);c.z.object({mode:Ad,url:c.z.string().trim().min(1).max(4096),token:c.z.string().trim().min(1).max(512),expiresAt:c.z.string().datetime()}).strict(),c.z.object({revoked:c.z.boolean()}).strict();const Td=c.z.object({name:c.z.string().trim().min(1).max(240),size:c.z.number().int().nonnegative(),updatedAt:c.z.string().datetime(),truncated:c.z.boolean(),content:c.z.string()}).strict();c.z.object({sessionId:c.z.string().trim().min(1).max(160),logDir:c.z.string().trim().min(1).max(1024),maxBytes:c.z.number().int().positive(),files:c.z.array(Td).max(256)}).strict();const bd=new Set(["stopped","failed","exited","closed","terminated"]),wd=c.z.object({type:c.z.enum(["app-session","provider-session","adapter-key"]),id:c.z.string().trim().min(1).max(240),agent:c.z.string().trim().min(1).max(80).optional(),adapter:c.z.string().trim().min(1).max(80).optional(),key:c.z.string().trim().min(1).max(240).optional()}).strict(),Sd=c.z.record(c.z.string(),c.z.unknown()).and(c.z.object({id:c.z.string().trim().min(1).max(160),appId:c.z.string().trim().min(1).max(160).optional(),title:c.z.string().trim().max(240).optional(),kind:c.z.string().trim().max(80).optional(),status:Ed.default("unknown"),bindings:c.z.array(wd).max(40).default([]),workspace:c.z.object({cwd:c.z.string().trim().max(4096).optional()}).strict().optional(),createdAt:c.z.string().datetime().optional(),updatedAt:c.z.string().datetime().optional()})),Nd=c.z.object({runningCount:c.z.number().int().min(0).default(0),problemCount:c.z.number().int().min(0).default(0),sessions:c.z.array(Sd).default([]),updatedAt:c.z.string().datetime()}).strict(),vd=c.z.object({streamId:c.z.string().trim().min(1).max(240),revision:c.z.number().int().min(0),lastEventAt:c.z.string().datetime(),snapshot:Nd}).strict();Nd.pick({runningCount:!0,problemCount:!0,updatedAt:!0}).extend({revision:c.z.number().int().min(0).optional()});const Od=c.z.enum(["app-session-created","app-session-updated","app-session-deleted","app-session-recovered","control-action","heartbeat-sync","startup"]),Rd=c.z.object({streamId:c.z.string().trim().min(1).max(240),instanceId:c.z.string().trim().min(1).max(160),nodeId:c.z.string().trim().min(1).max(160).optional(),revision:c.z.number().int().min(0),previousRevision:c.z.number().int().min(0).optional(),traceId:c.z.string().trim().min(1).max(160),generatedAt:c.z.string().datetime(),reason:Od}).strict(),zd=c.z.object({meta:Rd,snapshot:Nd}).strict(),xd=c.z.object({meta:Rd,session:Sd}).strict(),Cd=c.z.object({meta:Rd,sessionId:c.z.string().trim().min(1).max(160),tombstone:Sd.optional(),expiresAt:c.z.string().datetime().optional()}).strict();function kd(e,t=(new Date).toISOString()){const n=e.map(e=>function(e){const t=Ld("string"==typeof e.status?e.status:void 0),n="string"==typeof e.id?e.id:"",i=function(e){const t=Fd(e.workspace),n=Fd(e.tty),i=Fd(e.launch),s=Fd(e.ai),r=Fd(s.claude),o=$d(t.cwd)||$d(n.cwd)||$d(r.cwd)||$d(i.cwd);return o?{cwd:o}:void 0}(e),{workspace:s,...r}=e;return Sd.parse({...r,status:t,bindings:Ud([...(o=e.bindings,Array.isArray(o)?o.flatMap(e=>{const t=wd.safeParse(e);return t.success?[t.data]:[]}):[]),...n?[{type:"app-session",id:n}]:[],...jd(e)]),...i?{workspace:i}:{}});var o}(e));return Nd.parse({runningCount:n.filter(e=>"running"===e.status).length,problemCount:n.filter(e=>"failed"===e.status).length,sessions:n,updatedAt:t})}function Dd(e,t=(new Date).toISOString()){return kd(e.filter(e=>Pd("string"==typeof e.status?e.status:void 0)),t)}function Ld(e){const t=(e||"unknown").trim().toLowerCase();return"ended"===t?"closed":"terminating"===t?"stopping":Ed.options.includes(t)?t:"unknown"}function Pd(e){return!bd.has(Ld(e))}function Md(e){return"app-session"===e.type?`app:${e.id}`:"provider-session"===e.type?`provider:${e.agent||""}:${e.id}`:`adapter:${e.adapter||""}:${e.key||e.id}`}function jd(e){const t=Fd(e.ai),n=Fd(t.claude),i=Fd(t.appServer),s=Fd(e.launch),r=[],o=$d(Fd(s.aiSessionResume).providerSessionId),a="codex"===e.appId||"claude"===e.appId||"opencode"===e.appId?e.appId:void 0;a&&o&&r.push({type:"provider-session",agent:a,id:o});const c=$d(n.short);c&&r.push({type:"adapter-key",adapter:"claude",agent:"claude",id:`short:${c}`,key:`short:${c}`});const d=$d(n.providerSessionId);d&&r.push({type:"provider-session",agent:"claude",id:d});const l=Array.isArray(t.threadIds)?t.threadIds.filter(e=>"string"==typeof e&&Boolean(e.trim())):[],u=$d(t.activeThreadId);for(const e of[...new Set([u,...l].filter(Boolean))])r.push({type:"provider-session",agent:"codex",id:e});const p=$d(i.socketPath),m=$d(i.endpoint),h=p?`socket:${p}`:m?`endpoint:${m}`:"";return h&&r.push({type:"adapter-key",adapter:"codex-app-server",agent:"codex",id:h,key:h}),r}function Ud(e){const t=new Map;for(const n of e)t.set(Md(n),n);return[...t.values()]}function Fd(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}function $d(e){return"string"==typeof e&&e.trim()?e.trim():""}c.z.object({streamId:c.z.string().trim().min(1).max(240),instanceId:c.z.string().trim().min(1).max(160),sinceRevision:c.z.number().int().min(0),latestRevision:c.z.number().int().min(0),earliestRetainedRevision:c.z.number().int().min(0),syncRequired:c.z.boolean().default(!1),events:c.z.array(c.z.discriminatedUnion("type",[c.z.object({type:c.z.literal(yd),payload:zd}).strict(),c.z.object({type:c.z.literal(Id),payload:xd}).strict(),c.z.object({type:c.z.literal(_d),payload:Cd}).strict()])).default([])}).strict();const Hd="2026-08-25",Bd=c.z.object({nodeId:c.z.string().optional(),instanceId:c.z.string().optional()}).passthrough(),qd=c.z.object({v:c.z.literal(1),id:c.z.string().min(1),seq:c.z.number().finite(),type:c.z.string().min(1),topic:c.z.string().min(1),createdAt:c.z.string().datetime(),payload:c.z.unknown(),replay:c.z.literal(!0).optional(),scope:Bd.optional()}).passthrough(),Vd=c.z.object({v:c.z.literal(Hd),id:c.z.string().min(1),type:c.z.string().min(1),createdAt:c.z.string().datetime(),payload:c.z.unknown(),topic:c.z.string().min(1).optional(),replay:c.z.literal(!0).optional(),scope:Bd.optional()}).passthrough();function Gd(e){return e.startsWith("ai-session.")||e.startsWith("ai.session.")?"ai.sessions":e.startsWith("app-session.")?"app.sessions":e.startsWith("app.management")?"apps":e.startsWith("trigger.")?"triggers":e.startsWith("instance.")?"instances":e.startsWith("node.")?"nodes":e.startsWith("project.")?"projects":e.startsWith("model.")?"models":e.startsWith("image.")?"images":e.startsWith("market.")?"market":e.startsWith("story.")?"stories":e.startsWith("agent.")?"agents":"system"}c.z.discriminatedUnion("v",[qd,Vd]),c.z.object({v:c.z.literal(1),type:c.z.literal("ping"),sentAt:c.z.string().datetime()}).strict(),c.z.object({v:c.z.literal(1),type:c.z.literal("pong"),sentAt:c.z.string().datetime(),receivedAt:c.z.string().datetime()}).strict();const Wd=c.z.object({replaySince:c.z.string().datetime().optional(),messageDeltas:c.z.object({allInstances:c.z.boolean().default(!1),instanceIds:c.z.array(c.z.string().trim().min(1).max(160)).max(1e3).default([])}).default({allInstances:!1,instanceIds:[]}),timelineAllSessions:c.z.boolean().default(!1),timelineSessions:c.z.array(c.z.object({instanceId:c.z.string().trim().min(1).max(160),sessionId:c.z.string().trim().min(1).max(120)})).max(1e3).default([])}),Kd=c.z.enum(["ai.sessions","app.sessions"]),Yd=c.z.object({topic:Kd,instanceId:c.z.string().trim().min(1).max(160),streamId:c.z.string().trim().min(1).max(240),latestRevision:c.z.number().int().min(0),earliestRetainedRevision:c.z.number().int().min(0)}).strict(),Xd=c.z.object({protocolVersion:c.z.literal(1),streams:c.z.array(Yd)}).strict();function Jd(e,t=Math.random){const n=Math.max(1,Math.floor(e));if(1===n)return 0;if(2===n)return 250;const i=Math.min(6e4,250*2**(n-2));return Math.min(6e4,Math.round(i*(.75+.5*t())))}class Qd{retryNumber=0;random;constructor(e=Math.random){this.random=e}get attempts(){return this.retryNumber}next(){return this.retryNumber+=1,{attempt:this.retryNumber,delay:Jd(this.retryNumber,this.random)}}reset(){this.retryNumber=0}}class Zd{backoff;timer;constructor(e=Math.random){this.backoff=new Qd(e)}get pending(){return Boolean(this.timer)}get attempts(){return this.backoff.attempts}schedule(e,t={}){if(this.timer)return;const n=this.backoff.next(),i=t.setTimeoutFn||setTimeout;return this.timer=i(()=>{this.timer=void 0,e()},n.delay),n}reset(e=clearTimeout){this.timer&&e(this.timer),this.timer=void 0,this.backoff.reset()}cancel(e=clearTimeout){this.timer&&e(this.timer),this.timer=void 0}}class el extends Zd{}function tl(e,t=6e4){const n=[];for(let i=0;i<e.length;i+=t)n.push(e.slice(i,i+t));return n}const nl=262144,il=4194304;class sl{sockets=new Map;socketUrls=new Map;retries=new Map;outputs=new Set;outputSubscriptions=new Map;outputEnvelopeVersions=new Map;outputHierarchy=new Map;outputDiagnostics=new Map;aiSessionProjectionByInstance=new Map;appSessionProjectionByInstance=new Map;sessionStreamsHelloByInstance=new Map;sessionAuthorityReplayedOutputs=new Set;pendingAiSessionAuthorityByOutput=new Map;pendingAiSessionAuthorityFlush=new Map;eventTransportCongestion;imagePullTerminalByInstance=new Map;gitProvisioningTerminalByInstance=new Map;state;token;logger;safetyIntervalMs;lastAiSessionEventByInstance=new Map;lastAppSessionEventByInstance=new Map;timer;stopped=!1;reconnectAttempts=0;safetyReconciliations=0;localSequence=0;outputSequence=0;createSocket;setIntervalFn;clearIntervalFn;setTimeoutFn;clearTimeoutFn;constructor(e,t,n={}){var i;this.state=e,this.token=t,this.logger=n.logger,this.safetyIntervalMs=(i=n.safetyIntervalMs,Math.min(6e4,Math.max(3e4,i??45e3))),this.createSocket=n.createSocket||((e,t)=>new h(e,t)),this.setIntervalFn=n.setIntervalFn||setInterval,this.clearIntervalFn=n.clearIntervalFn||clearInterval,this.setTimeoutFn=n.setTimeoutFn||setTimeout,this.clearTimeoutFn=n.clearTimeoutFn||clearTimeout}start(){this.stopped=!1,this.sync(),this.timer=this.setIntervalFn(()=>{this.safetyReconciliations+=1,this.sync()},this.safetyIntervalMs)}stop(){this.stopped=!0,this.timer&&(this.clearIntervalFn(this.timer),this.timer=void 0);for(const e of this.sockets.values())e.close();this.sockets.clear(),this.socketUrls.clear();for(const e of this.retries.values())e.timer.cancel();this.retries.clear(),this.outputs.clear(),this.outputSubscriptions.clear(),this.outputEnvelopeVersions.clear(),this.outputHierarchy.clear(),this.outputDiagnostics.clear();for(const e of this.pendingAiSessionAuthorityFlush.values())this.clearTimeoutFn(e);this.pendingAiSessionAuthorityFlush.clear(),this.pendingAiSessionAuthorityByOutput.clear(),this.aiSessionProjectionByInstance.clear(),this.appSessionProjectionByInstance.clear(),this.sessionStreamsHelloByInstance.clear(),this.sessionAuthorityReplayedOutputs.clear()}addOutput(e,t={}){let n;this.outputs.add(e),this.outputDiagnostics.set(e,{outputId:"event_output_"+ ++this.outputSequence,kind:t.expectsTransientSubscription?"events-websocket":void 0!==t.legacyFallbackMs?"reverse-tunnel":"legacy"}),this.outputSubscriptions.set(e,t.expectsTransientSubscription?Wd.parse({}):void 0),this.outputEnvelopeVersions.set(e,1),this.outputHierarchy.set(e,Yi.parse(void 0)),t.expectsTransientSubscription||void 0===t.legacyFallbackMs||(n=this.setTimeoutFn(()=>{n=void 0,this.outputs.has(e)&&void 0===this.outputSubscriptions.get(e)&&(this.replaySessionAuthority(e),this.syncNow())},t.legacyFallbackMs));let i=!1;const s=()=>{if(i)return;i=!0,this.outputs.delete(e),this.outputSubscriptions.delete(e),this.outputEnvelopeVersions.delete(e),this.outputHierarchy.delete(e),this.outputDiagnostics.delete(e),this.sessionAuthorityReplayedOutputs.delete(e);const t=this.pendingAiSessionAuthorityFlush.get(e);t&&this.clearTimeoutFn(t),this.pendingAiSessionAuthorityFlush.delete(e),this.pendingAiSessionAuthorityByOutput.delete(e),this.refreshEventTransportRecovery(),n&&clearTimeout(n),this.stopped||this.syncNow()};e.on("close",s),e.on("error",s);for(const t of this.state.listInstances()){const n=rl(t);n?this.sendForwarded(e,this.createEvent(Ta,n,{instanceId:t.id})):this.logger?.warn?.({instanceId:t.id},"instance.lifecycle.snapshot.invalid")}for(const[t,n]of this.imagePullTerminalByInstance)tl(n.tail).forEach((i,s)=>this.sendForwarded(e,this.createEvent(Do,{...n.output,sequence:n.output.sequence+s,data:i,...0===s?{replay:!0}:{}},{instanceId:t}))),n.finished&&this.sendForwarded(e,this.createEvent(Lo,n.finished,{instanceId:t}));for(const[t,n]of this.gitProvisioningTerminalByInstance)tl(n.tail).forEach((i,s)=>this.sendForwarded(e,this.createEvent($o,{...n.output,sequence:n.output.sequence+s,data:i,...0===s?{replay:!0}:{}},{instanceId:t}))),n.finished&&this.sendForwarded(e,this.createEvent(Ho,n.finished,{instanceId:t}));return(t.expectsTransientSubscription||void 0===t.legacyFallbackMs)&&(this.replaySessionAuthority(e),this.syncNow()),s}setOutputSubscription(e,t,n,i){if(!this.outputs.has(e))return!1;const s=Wd.safeParse(t),r=Yi.safeParse(i);if(!s.success||!r.success)return!1;this.outputSubscriptions.set(e,s.data),this.outputEnvelopeVersions.set(e,n===Hd?Hd:1),this.outputHierarchy.set(e,r.data),this.replaySessionAuthority(e),this.syncNow();for(const[e,t]of this.sockets)this.sendInstanceSubscription(e,t);return!0}publish(e,t,n={}){this.rememberImagePullTerminal(e,t),this.rememberGitProvisioningTerminal(e,t);const i=this.createEvent(e,t,n);for(const e of this.outputs)this.sendForwarded(e,i)}rememberImagePullTerminal(e,t){if(e===Do){const e=ja(Mo,t);if(!e.success)return;const n=e.data,i=this.imagePullTerminalByInstance.get(n.instanceId);if(i&&n.generation<i.output.generation)return;const s=i?.output.generation===n.generation,r=n.replay||!s?n.data:`${i.tail}${n.data}`.slice(-262144);return void this.imagePullTerminalByInstance.set(n.instanceId,{output:n,tail:r})}if(e===Lo){const e=ja(jo,t);if(!e.success)return;const n=e.data,i=this.imagePullTerminalByInstance.get(n.instanceId);i?.output.generation===n.generation&&(i.finished=n)}}rememberGitProvisioningTerminal(e,t){if(e===$o){const e=ja(qo,t);if(!e.success)return;const n=e.data,i=this.gitProvisioningTerminalByInstance.get(n.instanceId);if(i&&n.generation<i.output.generation)return;const s=i?.output.generation===n.generation,r=n.replay||!s?n.data:`${i.tail}${n.data}`.slice(-262144);return void this.gitProvisioningTerminalByInstance.set(n.instanceId,{output:n,tail:r})}if(e===Ho){const e=ja(Vo,t);if(!e.success)return;const n=e.data,i=this.gitProvisioningTerminalByInstance.get(n.instanceId);i?.output.generation===n.generation&&(i.finished=n)}}publishInstanceLifecycle(e){this.publish(Ta,function(e){return ba.parse(ol(e))}(e),{instanceId:e.id});const t=this.imagePullTerminalByInstance.get(e.id);"ready"===e.imageProvisioning?.phase&&"succeeded"===t?.finished?.outcome&&this.imagePullTerminalByInstance.delete(e.id);const n=this.gitProvisioningTerminalByInstance.get(e.id);"ready"===e.workspace.gitProvisioning?.phase&&"succeeded"===n?.finished?.outcome&&this.gitProvisioningTerminalByInstance.delete(e.id)}createEvent(e,t,n){const i=++this.localSequence;return{v:1,id:`node_evt_${Date.now().toString(36)}_${i.toString(36)}`,seq:i,type:e,topic:Gd(e),createdAt:(new Date).toISOString(),payload:t,scope:n}}sendForwarded(e,t){const n=cl(t),i=n?function(e,t){return t?.subagents||e.type===Ue?e:e.type===Me?{...e,payload:{...e.payload,snapshot:_n(e.payload.snapshot,t)}}:{...e,payload:{...e.payload,upserted:e.payload.upserted.map(e=>In(e,t))}}}(n,this.outputHierarchy.get(e)):void 0,s=i&&i.payload!==t.payload?{...t,payload:i.payload}:t,r=t.type===Fe?mn.safeParse(t.payload):void 0,o=t.type===He?gn.safeParse(t.payload):void 0,a=this.outputEnvelopeVersions.get(e)===Hd?function(e,t,n={}){const i=e.scope?n.publicScope&&e.scope.instanceId?{instanceId:e.scope.instanceId}:e.scope:void 0;return{v:Hd,id:e.id,type:e.type,createdAt:e.createdAt,payload:void 0===n.payload?e.payload:n.payload,...e.topic!==Gd(e.type)?{topic:e.topic}:{},...e.replay?{replay:!0}:{},...i&&Object.keys(i).length?{scope:i}:{}}}(s,0,{...r?.success?{payload:(c=r.data,hn.parse({sessionId:c.sessionId,turnId:c.turnId,itemId:c.itemId,delta:c.delta,generatedAt:c.generatedAt}))}:{},...o?.success?{payload:yn(o.data)}:{}}):s;var c;const d=JSON.stringify({type:"node-agent.event.forwarded",event:a});this.sendOutput(e,d,s)}sendOutput(e,t,n){const i=Buffer.byteLength(t,"utf8"),s=n?.topic===fd?"app-session":n?.topic===Pe?"ai-session":void 0,r=s?{...this.outputDiagnostics.get(e),instanceId:n.scope?.instanceId,eventType:n.type,...al(n.payload)}:void 0;if(e.readyState!==h.OPEN)return r&&this.logger?.warn?.({...r,readyState:e.readyState,outcome:"not-open"},`${s}.event.output.rejected`),!1;if(n&&this.shouldCoalesceAiSessionAuthority(e,n)&&this.deferAiSessionAuthority(e,n))return!0;if(n&&dl(n)&&i>il){if(n.type!==Me&&this.deferAiSessionAuthority(e,n))return!0;this.observeEventTransportCongestion(e,!1,i),r&&this.logger?.warn?.({...r,bufferedAmount:e.bufferedAmount,bytes:i,maxBytes:il,outcome:"payload-too-large"},`${s}.event.output.rejected`);try{e.close(1009,"AI Session authority event exceeds the transport limit.")}catch{}return!1}if(e.bufferedAmount+i>16777216){this.observeEventTransportCongestion(e,!1),r&&this.logger?.warn?.({...r,bufferedAmount:e.bufferedAmount,outcome:"backpressure"},`${s}.event.output.rejected`);try{e.close(1013,"Event consumer is too slow.")}catch{}return!1}try{return e.send(t),r&&this.logger?.info?.({...r,bufferedAmount:e.bufferedAmount,bytes:i,outcome:"queued"},`${s}.event.output.queued`),!0}catch(t){r&&this.logger?.warn?.({...r,error:t instanceof Error?t.message:String(t),outcome:"send-failed"},`${s}.event.output.rejected`);try{e.close(1011,"Event delivery failed.")}catch{}return!1}}shouldCoalesceAiSessionAuthority(e,t){if(!dl(t))return!1;const n=t.scope?.instanceId;return!!n&&(!!this.pendingAiSessionAuthorityByOutput.get(e)?.has(n)||e.bufferedAmount>=nl)}deferAiSessionAuthority(e,t){const n=t.scope?.instanceId,i=n?this.aiSessionProjectionByInstance.get(n):void 0;if(!n||!i)return!1;const s=function(e,t){const n=cl(e);return n?n.payload.meta.streamId!==t.streamId||n.payload.meta.revision!==t.revision?void 0:ln.parse({meta:n.payload.meta,snapshot:t.snapshot}):void 0}(t,i);if(!s)return!1;const r=this.pendingAiSessionAuthorityByOutput.get(e)||new Map;return r.set(n,{...t,type:Me,topic:Pe,payload:s}),this.pendingAiSessionAuthorityByOutput.set(e,r),this.observeEventTransportCongestion(e,!0),this.logger?.info?.({...this.outputDiagnostics.get(e),instanceId:n,eventType:t.type,...al(s),bufferedAmount:e.bufferedAmount,outcome:"coalesced-latest"},"ai-session.event.output.coalesced"),this.scheduleAiSessionAuthorityFlush(e),!0}scheduleAiSessionAuthorityFlush(e){if(this.pendingAiSessionAuthorityFlush.has(e))return;const t=this.setTimeoutFn(()=>{this.pendingAiSessionAuthorityFlush.delete(e),this.flushAiSessionAuthority(e)},25);t.unref?.(),this.pendingAiSessionAuthorityFlush.set(e,t)}flushAiSessionAuthority(e){const t=this.pendingAiSessionAuthorityByOutput.get(e);if(!t?.size)return void this.pendingAiSessionAuthorityByOutput.delete(e);if(e.readyState!==h.OPEN)return void this.pendingAiSessionAuthorityByOutput.delete(e);const[n,i]=t.entries().next().value;e.bufferedAmount>=nl?this.scheduleAiSessionAuthorityFlush(e):(t.delete(n),t.size||this.pendingAiSessionAuthorityByOutput.delete(e),this.sendForwarded(e,i),this.refreshEventTransportRecovery(),t.size&&this.scheduleAiSessionAuthorityFlush(e))}observeEventTransportCongestion(e,t,n=0){const i=(new Date).toISOString(),s=Math.max(0,Math.floor(e.bufferedAmount)),r=this.eventTransportCongestion;this.eventTransportCongestion={congestedSince:r?.recoveredAt?i:r?.congestedSince||i,lastCongestedAt:i,peakBufferedBytes:Math.max(r?.recoveredAt?0:r?.peakBufferedBytes||0,s),coalescedEvents:(r?.recoveredAt?0:r?.coalescedEvents||0)+(t?1:0),oversizedEvents:(r?.recoveredAt?0:r?.oversizedEvents||0)+(n>0?1:0),peakEventBytes:Math.max(r?.recoveredAt?0:r?.peakEventBytes||0,n)}}eventTransportIsCongested(){return!![...this.pendingAiSessionAuthorityByOutput.values()].some(e=>e.size>0)||[...this.outputs].some(e=>e.readyState===h.OPEN&&e.bufferedAmount>=nl)}refreshEventTransportRecovery(){const e=this.eventTransportCongestion;!e||e.recoveredAt||this.eventTransportIsCongested()||(e.recoveredAt=(new Date).toISOString())}eventTransportHealth(){this.refreshEventTransportRecovery();const e=[...this.outputs].filter(e=>e.readyState===h.OPEN),t=e.reduce((e,t)=>Math.max(e,Math.max(0,Math.floor(t.bufferedAmount))),0),n=this.eventTransportIsCongested();let i=this.eventTransportCongestion;return i?.recoveredAt&&Date.now()-Date.parse(i.recoveredAt)>3e5&&(this.eventTransportCongestion=void 0,i=void 0),{status:n?"congested":i?"recovering":"healthy",activeOutputs:e.length,bufferedBytes:t,peakBufferedBytes:i?.peakBufferedBytes||t,coalescedEvents:i?.coalescedEvents||0,oversizedEvents:i?.oversizedEvents||0,peakEventBytes:i?.peakEventBytes||0,...n&&i?{congestedSince:i.congestedSince}:{},...i?{lastCongestedAt:i.lastCongestedAt}:{}}}syncNow(){this.sync()}diagnostics(){const e=[...this.outputSubscriptions.values()];return{reconnectAttempts:this.reconnectAttempts,safetyReconciliations:this.safetyReconciliations,activeConnections:this.sockets.size,pendingRetries:[...this.retries.values()].filter(e=>e.timer.pending).length,safetyIntervalMs:this.safetyIntervalMs,eventTransport:this.eventTransportHealth(),transientDemand:{legacyOutputs:e.filter(e=>void 0===e).length,scopedOutputs:e.filter(e=>void 0!==e).length,messageDeltaAllInstances:e.some(e=>e?.messageDeltas.allInstances),messageDeltaInstanceCount:new Set(e.flatMap(e=>e?.messageDeltas.instanceIds||[])).size,timelineAllSessions:e.some(e=>e?.timelineAllSessions),timelineSessionCount:new Set(e.flatMap(e=>e?.timelineSessions.map(e=>JSON.stringify([e.instanceId,e.sessionId]))||[])).size}}}sync(){const e=new Set(this.state.listInstances().map(e=>e.id));for(const t of this.aiSessionProjectionByInstance.keys())e.has(t)||this.aiSessionProjectionByInstance.delete(t);for(const t of this.appSessionProjectionByInstance.keys())e.has(t)||this.appSessionProjectionByInstance.delete(t);for(const t of this.sessionStreamsHelloByInstance.keys())e.has(t)||this.sessionStreamsHelloByInstance.delete(t);for(const t of this.imagePullTerminalByInstance.keys())e.has(t)||this.imagePullTerminalByInstance.delete(t);for(const t of this.gitProvisioningTerminalByInstance.keys())e.has(t)||this.gitProvisioningTerminalByInstance.delete(t);if(!this.outputs.size){for(const e of this.sockets.values())e.close();this.sockets.clear(),this.socketUrls.clear();for(const e of this.retries.values())e.timer.cancel();return void this.retries.clear()}const t=new Set;for(const e of this.state.listInstances()){const n=ll(e);if(!n)continue;t.add(e.id);const i=this.retries.get(e.id);i?.timer.pending&&i.url!==n&&(i.timer.cancel(),this.retries.delete(e.id)),this.socketUrls.get(e.id)!==n&&this.sockets.has(e.id)&&(this.sockets.get(e.id)?.close(),this.sockets.delete(e.id)),this.sockets.has(e.id)||this.retries.get(e.id)?.timer.pending||this.connect(e.id,n)}for(const[e,n]of this.sockets)if(!t.has(e)){n.close(),this.sockets.delete(e),this.socketUrls.delete(e);const t=this.retries.get(e);t?.timer.cancel(),this.retries.delete(e)}for(const[e,n]of this.retries)t.has(e)||(n.timer.cancel(),this.retries.delete(e),this.socketUrls.delete(e))}connect(e,t){const n=this.token?{authorization:`Bearer ${this.token}`}:void 0,i=this.createSocket(t,{headers:n});this.sockets.set(e,i),this.socketUrls.set(e,t),i.on("open",()=>{const n=this.retries.get(e);this.retries.set(e,{timer:n?.timer||new el,url:t}),i.readyState===h.OPEN&&(this.sendInstanceSubscription(e,i),this.logger?.info?.({instanceId:e,url:t},"ai-session.event.forward.connect"),this.logger?.info?.({instanceId:e,url:t},"app-session.event.forward.connect"))}),i.on("message",t=>{const n=function(e,t){try{const n=function(e,t={}){if(!e||"object"!=typeof e||Array.isArray(e))return;const n=e,i="string"==typeof n.type?n.type:"";if(!i)return;const s=n.scope&&"object"==typeof n.scope&&!Array.isArray(n.scope)?n.scope:{};return{v:1,id:"string"==typeof n.id?n.id:`event_${Date.now().toString(36)}`,seq:"number"==typeof n.seq&&Number.isFinite(n.seq)?n.seq:0,type:i,topic:"string"==typeof n.topic?n.topic:Gd(i),createdAt:"string"==typeof n.createdAt?n.createdAt:(new Date).toISOString(),payload:"payload"in n?n.payload:{},...!0===n.replay?{replay:!0}:{},scope:{...t,...s}}}(JSON.parse(String(e)),{instanceId:t});if(!n||"events.connected"===n.type)return;if(n.type===Fe){const e=function(e,t){const n=hn.safeParse(e);return n.success?mn.parse({instanceId:t,...n.data}):mn.parse(e)}(n.payload,t);return{...n,payload:e,scope:{...n.scope,instanceId:t}}}if(n.type===He){const e=function(e,t){const n=fn.safeParse(e);return n.success?gn.parse({instanceId:t,...n.data}):gn.parse(e)}(n.payload,t);return{...n,payload:e,scope:{...n.scope,instanceId:t}}}return{...n,scope:{...n.scope,instanceId:t}}}catch{return}}(t,e);if(n){if("streams.hello"===n.type){const t=ja(Xd,n.payload);if(!t.success)return this.logger?.warn?.({instanceId:e,issues:t.error.issues},"session-stream.handshake.invalid"),void i.close(1002,"Incompatible session stream handshake.");this.retries.get(e)?.timer.reset(),this.sessionStreamsHelloByInstance.set(e,t.data);const s=JSON.stringify({type:"node-agent.streams.hello",instanceId:e,payload:t.data});for(const e of this.outputs)this.sendOutput(e,s);return}this.recordAiSessionEvent(e,n),this.recordAppSessionEvent(e,n);for(const e of this.outputs)this.outputAccepts(e,n)&&this.sendForwarded(e,n)}}),i.on("close",()=>{this.sockets.get(e)===i&&(this.sockets.delete(e),this.socketUrls.delete(e),this.scheduleReconnect(e))}),i.on("error",()=>{this.logger?.warn?.({instanceId:e,url:t},"ai-session.event.forward.error"),this.logger?.warn?.({instanceId:e,url:t},"app-session.event.forward.error"),i.close()})}sendInstanceSubscription(e,t){if(t.readyState!==h.OPEN)return;const n=[...this.outputs].map(e=>this.outputSubscriptions.get(e));if(n.some(e=>void 0===e))return void t.send(JSON.stringify({v:1,type:"subscribe",eventEnvelopeVersion:Hd,aiSessionHierarchy:{subagents:!0},topics:[Pe,"app.sessions","apps","instances"]}));const i=n.some(t=>t.messageDeltas.allInstances||t.messageDeltas.instanceIds.includes(e)),s=n.some(e=>e.timelineAllSessions),r=[...new Set(n.flatMap(t=>t.timelineSessions.filter(t=>t.instanceId===e).map(e=>e.sessionId)))],o=n.map(e=>e.replaySince).filter(e=>Boolean(e)).sort()[0];t.send(JSON.stringify({v:1,type:"subscribe",eventEnvelopeVersion:Hd,aiSessionHierarchy:{subagents:!0},topics:[Me,je,Ue,...i?[Fe]:[],...s||r.length?[$e,He]:[],"app.sessions","apps","instances"],aiSessionTransient:{...o?{replaySince:o}:{},messageDeltas:{allInstances:i,instanceIds:[]},timelineAllSessions:s,timelineSessions:r.map(t=>({instanceId:e,sessionId:t}))}}))}outputAccepts(e,t){const n=this.outputSubscriptions.get(e);return!n||function(e,t){if(!e)return!0;if("ai-session.message-delta"!==t.type&&"ai-session.timeline-item"!==t.type&&"ai-session.timeline-item-delta"!==t.type)return!0;const n=t.payload&&"object"==typeof t.payload&&!Array.isArray(t.payload)?t.payload:{},i=String(n.instanceId||t.scope?.instanceId||"");return"ai-session.message-delta"===t.type?e.messageDeltas.allInstances||e.messageDeltas.instanceIds.includes(i):e.timelineAllSessions||e.timelineSessions.some(e=>e.instanceId===i&&e.sessionId===n.sessionId)}(n,t)}scheduleReconnect(e){const t=this.state.listInstances().find(t=>t.id===e),n=t&&ll(t);if(!n||!this.outputs.size)return;const i=this.retries.get(e)??{timer:new el};if(i.timer.pending)return;i.url=n;const s=i.timer.schedule(()=>{this.sockets.has(e)||this.connect(e,n)},{setTimeoutFn:this.setTimeoutFn});s&&(this.reconnectAttempts+=1,this.logger?.info?.({instanceId:e,url:n,attempt:s.attempt,delay:s.delay,reconnectAttempts:this.reconnectAttempts},"session-stream.connection.reconnect-scheduled")),this.retries.set(e,i)}recordAiSessionEvent(e,t){if(t.topic!==Pe)return;if(t.type===Fe||t.type===$e||t.type===He)return;const n=cl(t);if(n){const t=function(e,t){const{meta:n}=t.payload;if(t.type===Me)return e?.streamId===n.streamId&&n.revision===e.revision?{kind:"duplicate",projection:e}:e?.streamId===n.streamId&&n.revision<e.revision?{kind:"stale",projection:e}:{kind:"applied",projection:an.parse({streamId:n.streamId,revision:n.revision,lastEventAt:n.generatedAt,snapshot:t.payload.snapshot})};if(!e||e.streamId!==n.streamId)return{kind:"snapshot-required",projection:e,streamId:n.streamId};if(n.revision===e.revision)return{kind:"duplicate",projection:e};if(n.revision<e.revision)return{kind:"stale",projection:e};if(n.revision!==e.revision+1||n.previousRevision!==e.revision)return{kind:"gap",projection:e,expectedRevision:e.revision+1,receivedRevision:n.revision};const i=new Map(e.snapshot.sessions.map(e=>[e.id,e]));if(t.type===je){for(const e of t.payload.upserted)i.set(e.id,e);for(const e of t.payload.removed)i.delete(e)}else for(const e of t.payload.sessionIds)i.delete(e);const s=[...i.values()],r=on.parse({runningCount:s.filter(e=>"running"===e.status).length,waitingCount:s.filter(e=>"waiting"===e.status).length,staleCount:e.snapshot.staleCount,sessions:s,updatedAt:n.generatedAt});return{kind:"applied",projection:an.parse({streamId:n.streamId,revision:n.revision,lastEventAt:n.generatedAt,snapshot:r})}}(this.aiSessionProjectionByInstance.get(e),n);"applied"!==t.kind&&"duplicate"!==t.kind&&"stale"!==t.kind||this.aiSessionProjectionByInstance.set(e,t.projection)}const i=al(t.payload),s=this.lastAiSessionEventByInstance.get(e);s?.streamId===i.streamId&&void 0!==s.revision&&void 0!==i.revision&&i.revision>s.revision+1&&this.logger?.warn?.({instanceId:e,traceId:i.traceId,streamId:i.streamId,previousRevision:s.revision,revision:i.revision},"ai-session.event.forward.gap"),this.lastAiSessionEventByInstance.set(e,{streamId:i.streamId??s?.streamId,revision:i.revision??s?.revision}),this.logger?.info?.({instanceId:e,traceId:i.traceId,eventType:t.type,streamId:i.streamId,revision:i.revision},"ai-session.event.forward.message")}recordAppSessionEvent(e,t){if(t.topic!==fd)return;const n=function(e){const t=e.type===yd?zd:e.type===Id?xd:e.type===_d?Cd:void 0;if(!t)return;const n=ja(t,e.payload);return n.success?{type:e.type,payload:n.data}:void 0}(t);if(n){const t=function(e,t){const{meta:n}=t.payload;if(t.type===yd)return e?.streamId===n.streamId&&n.revision===e.revision?{kind:"duplicate",projection:e}:e?.streamId===n.streamId&&n.revision<e.revision?{kind:"stale",projection:e}:{kind:"applied",projection:vd.parse({streamId:n.streamId,revision:n.revision,lastEventAt:n.generatedAt,snapshot:Dd(t.payload.snapshot.sessions,t.payload.snapshot.updatedAt)})};if(!e||e.streamId!==n.streamId)return{kind:"snapshot-required",projection:e,streamId:n.streamId};if(n.revision===e.revision)return{kind:"duplicate",projection:e};if(n.revision<e.revision)return{kind:"stale",projection:e};if(n.revision!==e.revision+1||n.previousRevision!==e.revision)return{kind:"gap",projection:e,expectedRevision:e.revision+1,receivedRevision:n.revision};const i=[...e.snapshot.sessions];if(t.type===Id){const e=i.findIndex(e=>e.id===t.payload.session.id);Pd(t.payload.session.status)?e<0?i.push(t.payload.session):i[e]=t.payload.session:e>=0&&i.splice(e,1)}else{const e=i.findIndex(e=>e.id===t.payload.sessionId);e>=0&&i.splice(e,1)}const s=kd(i,n.generatedAt);return{kind:"applied",projection:vd.parse({streamId:n.streamId,revision:n.revision,lastEventAt:n.generatedAt,snapshot:s})}}(this.appSessionProjectionByInstance.get(e),n);"applied"!==t.kind&&"duplicate"!==t.kind&&"stale"!==t.kind||this.appSessionProjectionByInstance.set(e,t.projection)}const i=al(t.payload),s=this.lastAppSessionEventByInstance.get(e);s?.streamId===i.streamId&&void 0!==s.revision&&void 0!==i.revision&&i.revision>s.revision+1&&this.logger?.warn?.({instanceId:e,traceId:i.traceId,streamId:i.streamId,previousRevision:s.revision,revision:i.revision},"app-session.event.forward.gap"),this.lastAppSessionEventByInstance.set(e,{streamId:i.streamId??s?.streamId,revision:i.revision??s?.revision}),this.logger?.info?.({instanceId:e,traceId:i.traceId,eventType:t.type,streamId:i.streamId,revision:i.revision},"app-session.event.forward.message")}replaySessionAuthority(e){if(!this.sessionAuthorityReplayedOutputs.has(e)&&e.readyState===h.OPEN){this.sessionAuthorityReplayedOutputs.add(e);for(const[t,n]of this.sessionStreamsHelloByInstance){const i=n.streams.map(e=>{const n=e.topic===Pe?this.aiSessionProjectionByInstance.get(t):this.appSessionProjectionByInstance.get(t);return n?n.streamId!==e.streamId?{...e,streamId:n.streamId,latestRevision:n.revision,earliestRetainedRevision:n.revision}:{...e,latestRevision:Math.max(e.latestRevision,n.revision)}:e});this.sendOutput(e,JSON.stringify({type:"node-agent.streams.hello",instanceId:t,payload:{...n,streams:i}}))}for(const[t,n]of this.aiSessionProjectionByInstance)this.sendForwarded(e,this.createEvent(Me,{meta:{streamId:n.streamId,instanceId:t,revision:n.revision,traceId:`ais_replay_${Date.now().toString(36)}`,generatedAt:n.lastEventAt,reason:"startup"},snapshot:n.snapshot},{instanceId:t}));for(const[t,n]of this.appSessionProjectionByInstance)this.sendForwarded(e,this.createEvent(yd,{meta:{streamId:n.streamId,instanceId:t,revision:n.revision,traceId:`aps_replay_${Date.now().toString(36)}`,generatedAt:n.lastEventAt,reason:"startup"},snapshot:n.snapshot},{instanceId:t}))}}}function rl(e){const t=ba.safeParse(ol(e));return t.success?t.data:void 0}function ol(e){return{instanceId:e.id,revision:e.stateRevision,updatedAt:e.updatedAt,status:e.status,health:e.health,connectionStatus:e.connectionStatus,accessStatus:"online"===e.connectionStatus||"online"===e.agentStatus?"reachable":"endpoint-unreachable",imageProvisioning:e.imageProvisioning,workspace:e.workspace,runtime:e.runtime,runtimeVersion:e.runtimeVersion,ready:e.ready,lastHeartbeatAt:e.lastHeartbeatAt}}function al(e){const t=e&&"object"==typeof e&&!Array.isArray(e)?e:{},n=t.meta&&"object"==typeof t.meta&&!Array.isArray(t.meta)?t.meta:{};return{streamId:"string"==typeof n.streamId?n.streamId:void 0,revision:"number"==typeof n.revision?n.revision:void 0,traceId:"string"==typeof n.traceId?n.traceId:void 0}}function cl(e){const t=e.type===Me?ln:e.type===je?un:e.type===Ue?pn:void 0;if(!t)return;const n=ja(t,e.payload);return n.success?{type:e.type,payload:n.data}:void 0}function dl(e){return e.topic===Pe&&(e.type===Me||e.type===je||e.type===Ue)}function ll(e){if(!function(e){return!1!==e.ready&&(!e.runtimeVersion||["matched","failed"].includes(e.runtimeVersion.phase))}(e))return;const t=e.target?.api||e.target?.web;if(t)try{const e=new URL("/api/events",t);return e.searchParams.set("aiSessionTransient","1"),e.searchParams.set("aiSessionAuthoritySnapshot","1"),e.searchParams.set("aiSessionHierarchy","subagents"),e.protocol="https:"===e.protocol?"wss:":"ws:",e.toString()}catch{return}}const ul=new Set(["provisioning","starting","registering","registered","running","unhealthy"]),pl=JSON.stringify({id:"{{.ID}}",name:"{{.Name}}",cpu:"{{.CPUPerc}}",memory:"{{.MemUsage}}",memoryPercent:"{{.MemPerc}}",network:"{{.NetIO}}",blockIo:"{{.BlockIO}}",pids:"{{.PIDs}}"});class ml{snapshots=new Map;runCommand;targets;publish;intervalMs;timer;inFlight;pendingTargets=new Map;collectingTargets=new Map;constructor(e,t,n,i=3e3){this.runCommand=e,this.targets=t,this.publish=n,this.intervalMs=i}start(){this.collect().catch(()=>{}),this.timer=setInterval(()=>{this.collect().catch(()=>{})},this.intervalMs)}stop(){this.timer&&clearInterval(this.timer),this.timer=void 0}async snapshot(e){const t=this.targets().find(t=>t.id===e);if(!t)return;if(!ul.has(t.status))return _l(t.id);const n=this.snapshots.get(e);return n&&Date.now()-Date.parse(n.sampledAt)<=this.intervalMs?n:(await this.collect([t]),this.snapshots.get(e))}async collect(e){const t=e||this.targets();if(!e){const e=new Set(t.map(e=>e.id));for(const t of this.snapshots.keys())e.has(t)||this.snapshots.delete(t)}for(const e of t){const t=hl(e);this.collectingTargets.get(e.id)!==t&&this.pendingTargets.set(e.id,e)}this.inFlight||(this.inFlight=this.drain().finally(()=>{this.inFlight=void 0})),await this.inFlight}async drain(){for(;this.pendingTargets.size;){const e=[...this.pendingTargets.values()];this.pendingTargets.clear();for(const t of e)this.collectingTargets.set(t.id,hl(t));try{await this.collectOnce(e)}finally{for(const t of e)this.collectingTargets.delete(t.id)}}}async collectOnce(e){const t=e.filter(e=>ul.has(e.status)&&(e.runtime.containerId||e.runtime.containerName));for(const t of e.filter(e=>ul.has(e.status)&&!e.runtime.containerId&&!e.runtime.containerName))this.update(El(t.id));for(const t of e.filter(e=>!ul.has(e.status)))this.update(_l(t.id));if(!t.length)return;const n=t.map(e=>e.runtime.containerId||e.runtime.containerName),i=(new Date).toISOString();try{const e=await this.runCommand("docker",["stats","--no-stream","--format",pl,...n],{timeoutMs:5e3});this.applyDockerOutput(t,e.stdout,i)}catch(e){if(1===t.length)return void this.update(Al(t[0].id,i,e instanceof Error?e.message:String(e)));await Promise.all(t.map(async e=>{const t=e.runtime.containerId||e.runtime.containerName;try{const n=await this.runCommand("docker",["stats","--no-stream","--format",pl,t],{timeoutMs:5e3});this.applyDockerOutput([e],n.stdout,i)}catch(t){this.update(Al(e.id,i,t instanceof Error?t.message:String(t)))}}))}}applyDockerOutput(e,t,n){const i=function(e,t=(new Date).toISOString()){const n=new Map;for(const i of e.split(/\r?\n/).filter(Boolean)){let e;try{e=JSON.parse(i)}catch{continue}const s=Il(e.id),r=Il(e.name),o=s||r;if(!o)continue;const a=gl(Il(e.memory)),c=gl(Il(e.network)),d=gl(Il(e.blockIo)),l=ia.parse({instanceId:o,runtimeKind:"docker",state:"available",sampledAt:t,cpu:fl(e.cpu,"usagePercent"),memory:a?{usageBytes:a[0],...void 0!==a[1]?{limitBytes:a[1]}:{},...fl(e.memoryPercent,"usagePercent")}:void 0,network:c?{rxBytes:c[0],txBytes:c[1]||0}:void 0,blockIo:d?{readBytes:d[0],writeBytes:d[1]||0}:void 0,pids:yl(e.pids)});s&&n.set(s,l),r&&n.set(r,l)}return n}(t,n);for(const t of e){const e=[t.runtime.containerId,t.runtime.containerName].filter(Boolean),s=[...i.entries()].find(([t])=>e.some(e=>e===t||e.startsWith(t)||t.startsWith(e)))?.[1];this.update(s?{...s,instanceId:t.id}:Al(t.id,n,"Container metrics were not returned by Docker."))}}update(e){const t=ia.parse(e);this.snapshots.set(t.instanceId,t),this.publish?.(t)}}function hl(e){return[e.status,e.runtime.containerId||"",e.runtime.containerName||""].join("\0")}function gl(e){if(!e)return;const[t,n]=e.split("/").map(e=>function(e){const t=e.trim().match(/^([0-9]+(?:\.[0-9]+)?)\s*([kmgtpe]?i?b)$/i);if(!t)return;const n=Number(t[1]),i=t[2].toLowerCase(),s=i.includes("i"),r="b"===i[0]?"":i[0],o=r?"kmgtpe".indexOf(r)+1:0;return Math.round(n*(s?1024:1e3)**o)}(e||""));return void 0===t?void 0:[t,n]}function fl(e,t){const n=Number(Il(e).replace(/%$/,""));return Number.isFinite(n)&&n>=0?{[t]:n}:void 0}function yl(e){const t=Number(Il(e));return Number.isFinite(t)&&t>=0?t:void 0}function Il(e){return"string"==typeof e||"number"==typeof e?String(e).trim():""}function _l(e){return{instanceId:e,runtimeKind:"docker",state:"stopped",sampledAt:(new Date).toISOString()}}function El(e){return{instanceId:e,runtimeKind:"docker",state:"pending",sampledAt:(new Date).toISOString()}}function Al(e,t,n){return{instanceId:e,runtimeKind:"docker",state:"unavailable",sampledAt:t,error:n.slice(0,2048)}}function Tl(e,t,n){return Object.assign(new Error(e),{statusCode:t,code:n})}function bl(e){const i=n.resolve(e);let s;try{s=t.statSync(i)}catch(e){const t=e&&"object"==typeof e?e.code:void 0;if("ENOENT"===t||"ENOTDIR"===t)throw Tl(`Folder ${i} was not found.`,404,"NODE_FOLDER_PATH_NOT_FOUND");throw Tl(`Folder ${i} is not accessible.`,403,"NODE_FOLDER_PATH_UNREADABLE")}if(!s.isDirectory())throw Tl(`Path ${i} is not a folder.`,400,"NODE_FOLDER_PATH_NOT_DIRECTORY");try{t.accessSync(i,t.constants.R_OK|t.constants.X_OK)}catch{throw Tl(`Folder ${i} is not accessible.`,403,"NODE_FOLDER_PATH_UNREADABLE")}return i}function wl(e){try{return t.statSync(e).isDirectory()}catch{return!1}}function Sl(){if("win32"!==process.platform)return[n.parse(n.resolve(process.cwd())).root];const e=n.parse(n.resolve(process.cwd())).root,t=Array.from({length:26},(e,t)=>`${String.fromCharCode(65+t)}:\\`);return[...new Set([e,...t])].filter(wl)}function Nl(){const e=n.resolve(s.homedir()),t=Sl().map(e=>n.resolve(e));return[...wl(e)?[{kind:"home",name:n.basename(e)||e,path:e}]:[],...t.map(e=>({kind:"root",name:e,path:e}))]}function vl(e,i){let s;try{s=t.statSync(e)}catch{return}if(!s.isDirectory())return;const r=n.resolve(e),o=n.basename(r)||r;let a=[];try{a=i>0?t.readdirSync(r,{withFileTypes:!0}):[]}catch{a=[]}const c=i>0?a.filter(e=>e.isDirectory()||e.isSymbolicLink()&&wl(n.join(r,e.name))).sort((e,t)=>e.name.localeCompare(t.name)).slice(0,80).flatMap(e=>{const t=vl(n.join(r,e.name),i-1);return t?[t]:[]}):[];return{name:o,path:r,children:c}}function Ol(e){return(e.path?[bl(e.path)]:Sl()).flatMap(t=>{const n=vl(t,e.depth);return n?[n]:[]})}function Rl(){return process.env.TASK_HANDOFF_NODE_AGENT_DATA_DIR||n.join(s.homedir(),".config","task-handoff","node-agent")}function zl(e=Rl()){const t=n.resolve(e);return{dataDir:t,identityPath:n.join(t,"identity.json"),settingsPath:n.join(t,"runtime-settings.json"),localFoldersDir:n.join(t,"local-folders"),builtinProjectTargetsDir:n.join(t,"builtin-projects"),nodeRuntimesDir:n.join(t,"node-runtimes"),controlledInstancesDir:n.join(t,"controlled-instances"),environmentTemplatesDir:n.join(t,"environment-templates"),instancePrivateConfigsDir:n.join(t,"instance-private-configs"),nodeModelsDir:n.join(t,"models"),modelAssignmentsDir:n.join(t,"model-assignments"),modelEnvironmentsDir:n.join(t,"model-environments"),gitCredentialPayloadsDir:n.join(t,"git-credentials","payloads"),gitCredentialAssignmentsDir:n.join(t,"git-credentials","assignments"),gitCredentialAuthorizationSetsDir:n.join(t,"git-credentials","authorization-sets"),gitWorkspaceProvisioningIntentsDir:n.join(t,"git-credentials","workspace-provisioning-intents"),updatesDir:n.join(t,"updates"),dockerBootstrapDir:n.join(t,"docker-bootstrap"),wslDir:n.join(t,"wsl"),wslDistrosDir:n.join(t,"wsl","distros"),wslBaseTemplateCacheDir:n.join(t,"wsl","base-templates"),wslDistroIndexPath:n.join(t,"wsl","distros.json"),logsDir:n.join(t,"logs"),databasePath:n.join(t,"node-agent.sqlite"),storyRegistryDir:n.join(t,"story-registry"),storyAutomationsDir:n.join(t,"story-automations"),storyContentDir:n.join(t,"stories"),storyMutationsDir:n.join(t,".story-mutations"),storyTrashDir:n.join(t,".story-trash")}}function xl(e,t){const i=n.extname(e);return`${i?e.slice(0,-i.length):e}.${t}${i}`}function Cl(e,n=10485760,i=2){if(!t.existsSync(e))return!1;const s=t.lstatSync(e);if(!s.isFile()||s.isSymbolicLink()||s.size<=n)return!1;if(i>0){!function(e,n){if(!(n<=0)){t.rmSync(xl(e,n),{force:!0});for(let i=n-1;i>=1;i-=1){const n=xl(e,i);t.existsSync(n)&&t.renameSync(n,xl(e,i+1))}}}(e,i);const s=function(e,n){const i=t.statSync(e),s=Math.min(i.size,n),r=Buffer.allocUnsafe(s),o=t.openSync(e,"r");let a=0;try{for(;a<s;){const e=t.readSync(o,r,a,s-a,i.size-s+a);if(0===e)break;a+=e}}finally{t.closeSync(o)}return a===s?r:r.subarray(0,a)}(e,n);t.writeFileSync(xl(e,1),s,{mode:384})}return t.truncateSync(e,0),t.chmodSync(e,384),!0}class kl{logsDir;localInstancesRoot;localInstancesTrashRoot;privateConfigsDir;options;constructor(e,t={}){this.options=t,this.logsDir=e.logsDir,this.localInstancesRoot=n.join(e.dataDir,"local-instances"),this.localInstancesTrashRoot=n.join(e.dataDir,"local-instances-trash"),this.privateConfigsDir=e.instancePrivateConfigsDir}run(e){this.capNodeAgentLogs();const n=new Set(e);if(this.removeOrphanPrivateConfigs(n),t.existsSync(this.localInstancesRoot)){ge(this.localInstancesRoot);for(const e of t.readdirSync(this.localInstancesRoot,{withFileTypes:!0}))e.isDirectory()&&!e.isSymbolicLink()&&(n.has(e.name)?this.capControlledInstanceLogs(e.name):this.retire(e.name))}return function(e){if(!t.existsSync(e.trashRoot))return[];const n=e.nowMs??Date.now(),i=e.retentionMs??le,s=[];for(const r of t.readdirSync(e.trashRoot,{withFileTypes:!0})){const o=he(e.trashRoot,r.name);try{const e=me(r.name);if(void 0===e||e+i>n)continue;const a=t.lstatSync(o);a.isSymbolicLink()?t.unlinkSync(o):a.isDirectory()?t.rmSync(o,{recursive:!0,force:!0}):t.unlinkSync(o),s.push(o)}catch(t){e.logger?.("retired persistence entry cleanup failed",{path:o,error:t instanceof Error?t.message:String(t)})}}return s}({trashRoot:this.localInstancesTrashRoot,retentionMs:this.options.retentionMs??le,nowMs:this.now(),logger:this.options.logger})}capActiveInstanceLogs(e){for(const t of e)this.capControlledInstanceLogs(t)}capNodeAgentLogs(){const e=[];for(const t of["node-agent.out.log","node-agent.err.log"]){const i=n.join(this.logsDir,t);try{Cl(i)&&e.push(i)}catch(e){this.options.logger?.("node-agent log rotation failed",{filePath:i,error:e instanceof Error?e.message:String(e)})}}return e}capControlledInstanceLogs(e){const t=n.resolve(this.localInstancesRoot,e);if(n.dirname(t)!==n.resolve(this.localInstancesRoot))return[];const i=n.join(t,"logs"),s=[];for(const t of["controlled-instance.out.log","controlled-instance.err.log"]){const r=n.join(i,t);try{Cl(r)&&s.push(r)}catch(t){this.options.logger?.("controlled instance log rotation failed",{instanceId:e,filePath:r,error:t instanceof Error?t.message:String(t)})}}return s}retire(e){try{return function(e){const n=he(e.sourceRoot,e.entryName);if(!t.existsSync(n))return;const i=t.lstatSync(n);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`Retention source must be a real directory: ${n}`);ge(e.trashRoot);const s=e.nowMs??Date.now();let r=0,o=ue(e.entryName,s);for(;t.existsSync(he(e.trashRoot,o));)r+=1,o=ue(`${r}-${e.entryName}`,s);const a=he(e.trashRoot,o);return t.renameSync(n,a),a}({sourceRoot:this.localInstancesRoot,entryName:e,trashRoot:this.localInstancesTrashRoot,nowMs:this.now()})}catch(t){return void this.options.logger?.("local instance persistence retirement failed",{instanceId:e,error:t instanceof Error?t.message:String(t)})}}removeOrphanPrivateConfigs(e){if(t.existsSync(this.privateConfigsDir))for(const i of t.readdirSync(this.privateConfigsDir,{withFileTypes:!0})){if(i.isSymbolicLink())continue;const s=i.isDirectory();if(!(s||i.isFile()&&i.name.endsWith(".json")))continue;const r=s?i.name:i.name.slice(0,-5);if(e.has(r))continue;const o=n.join(this.privateConfigsDir,i.name);try{s?(this.options.removeDirectory||(e=>t.rmSync(e,{recursive:!0,force:!0})))(o):(this.options.removeFile||(e=>t.rmSync(e,{force:!0})))(o)}catch(e){this.options.logger?.("orphan instance private config cleanup failed",{instanceId:r,filePath:o,error:e instanceof Error?e.message:String(e)})}}}now(){return this.options.now?.()??Date.now()}}function Dl(e,t=process.platform){const i=n.resolve(e),s=d.createHash("sha256").update(i).digest("hex").slice(0,16);return"win32"===t?`\\\\.\\pipe\\task-handoff-node-agent-${s}`:n.join("/tmp",`task-handoff-node-agent-${process.getuid?.()??"user"}`,`${s}.sock`)}function Ll(e,i=process.platform){if("win32"!==i){t.mkdirSync(n.dirname(e),{recursive:!0,mode:448});try{t.chmodSync(n.dirname(e),448)}catch{}try{t.unlinkSync(e)}catch(e){if("ENOENT"!==e.code)throw e}}}async function Pl(e,t,n={}){const s=n.method||"GET",r="string"==typeof n.body||n.body instanceof Buffer?n.body:void 0===n.body||null===n.body?void 0:String(n.body),o=new Headers(n.headers||{});return void 0===r||o.has("content-length")||o.set("content-length",String(Buffer.byteLength(r))),new Promise((a,c)=>{const d=i.request({socketPath:e,method:s,path:`/api/node-agent${t}`,headers:Object.fromEntries(o.entries())},e=>{const t=e.statusCode||500;a(new Response("HEAD"!==s&&204!==t&&205!==t&&304!==t?f.Readable.toWeb(e):null,{status:t,headers:e.headers}))});d.on("error",c);const l=()=>d.destroy(new DOMException("The operation was aborted.","AbortError"));n.signal?.aborted?l():n.signal?.addEventListener("abort",l,{once:!0}),d.once("close",()=>n.signal?.removeEventListener("abort",l)),void 0!==r&&d.write(r),d.end()})}const Ml="runtime-manifest.json";class jl extends Error{code;retryable;constructor(e,t,n){super(t,void 0===n?.cause?void 0:{cause:n.cause}),this.name="RuntimeArtifactError",this.code=e,this.retryable=n?.retryable??!1}}async function Ul(e,t=""){const i=[],s=await y.readdir(n.join(e,t),{withFileTypes:!0});for(const r of s){const s=t?n.posix.join(t,r.name):r.name;if(!t&&s===Ml)continue;const o=n.join(e,...s.split("/"));if(r.isDirectory()){i.push(...await Ul(e,s));continue}if(r.isSymbolicLink()){const t=await y.readlink(o);if(n.isAbsolute(t))throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`Runtime payload symlink is absolute: ${s}`);const r=n.resolve(n.dirname(o),t),a=n.relative(n.resolve(e),r);if(!a||".."===a||a.startsWith(`..${n.sep}`)||n.isAbsolute(a))throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`Runtime payload symlink escapes the artifact: ${s}`);if(!await y.lstat(r).catch(()=>{}))throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`Runtime payload symlink is broken: ${s}`);i.push({absolutePath:o,relativePath:s,kind:"symlink",target:t,size:Buffer.byteLength(t)});continue}if(!r.isFile())throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`Runtime payload contains unsupported entry: ${s}`);const a=await y.lstat(o);i.push({absolutePath:o,relativePath:s,kind:"file",size:a.size})}return i}async function Fl(e){const n=(await Ul(e)).sort((e,t)=>function(e,t){return Buffer.compare(Buffer.from(e,"utf8"),Buffer.from(t,"utf8"))}(e.relativePath,t.relativePath)),i=d.createHash("sha256");for(const e of n){if(i.update("file"===e.kind?"F":"L","ascii"),i.update(Buffer.from(e.relativePath,"utf8")),i.update(Buffer.from([0])),i.update(Buffer.from(String(e.size),"ascii")),i.update(Buffer.from([0])),"file"===e.kind)for await(const n of t.createReadStream(e.absolutePath))i.update(n);else i.update(Buffer.from(e.target,"utf8"));i.update(Buffer.from([0]))}return i.digest("hex")}function $l(e){for(const[t,n]of[["version",e.version],["platform",e.platform],["arch",e.arch]])if(!/^[0-9A-Za-z._-]+$/.test(n))throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`Invalid runtime artifact ${t}: ${n}`);return`${e.version}-${e.platform}-${e.arch}`}function Hl(e,t){return`${$l(e)}-${e.sha256}-${t}`}async function Bl(e){const n=d.createHash("sha256");for await(const i of t.createReadStream(e))n.update(i);return n.digest("hex")}class ql{#e;#t;#n=new Map;constructor(e){this.#e=e.cacheDir,this.#t=e.fetchImpl??fetch}resolve(e,t){const n=yr.parse(e);if(!/^[a-f0-9]{64}$/.test(t.archiveSha256))throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID","Runtime archive SHA-256 is invalid.");if((t.archiveUrl?1:0)+(t.archivePath?1:0)!=1)throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID","Runtime artifact source must specify exactly one archive location.");const i=Hl(n,t.archiveSha256),s=this.#n.get(i);if(s)return s;const r=this.#i(n,t).finally(()=>this.#n.delete(i));return this.#n.set(i,r),r}async#i(e,i){if(!/^[a-f0-9]{64}$/.test(i.archiveSha256))throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID","Runtime archive SHA-256 is invalid.");const s=Hl(e,i.archiveSha256),r=n.join(this.#e,"archives"),o=n.join(r,`${s}.tar.gz`);if(await y.mkdir(r,{recursive:!0}),await this.#s(o,e,i.archiveSha256))return{identity:e,archivePath:o,cacheHit:!0};await y.rm(o,{force:!0});const a=n.join(r,`.${s}.${d.randomUUID()}.part`);try{const n=await y.open(a,"wx");if(i.archivePath)await I.pipeline(t.createReadStream(i.archivePath),n.createWriteStream());else{const e=await this.#t(i.archiveUrl);if(!e.ok||!e.body)throw await n.close(),new jl("INSTANCE_RUNTIME_ARTIFACT_UNAVAILABLE",`Runtime artifact download failed with HTTP ${e.status}.`,{retryable:e.status>=500});await I.pipeline(e.body,n.createWriteStream())}if(await Bl(a)!==i.archiveSha256)throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID","Downloaded runtime archive SHA-256 does not match release metadata.");return await this.#r(a,e),await y.rename(a,o),{identity:e,archivePath:o,cacheHit:!1}}catch(e){if(e instanceof jl)throw e;throw new jl("INSTANCE_RUNTIME_ARTIFACT_UNAVAILABLE","Could not download runtime artifact.",{cause:e,retryable:!0})}finally{await y.rm(a,{force:!0})}}async#s(e,t,n){try{return await Bl(e)===n&&(await this.#r(e,t),!0)}catch{return!1}}async#r(e,t){const i=n.join(this.#e,"validation",`${$l(t)}-${d.randomUUID()}`);try{await async function(e,t){await y.mkdir(t,{recursive:!0});try{await _.extract({file:e,cwd:t,strict:!0,preservePaths:!1,filter:(e,t)=>{const i=n.posix.normalize(e.replace(/^\.\//,""));if(!i||".."===i||i.startsWith("../")||n.posix.isAbsolute(i))throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`Runtime archive entry escapes the artifact root: ${e}`);const s=t.type;if("File"!==s&&"OldFile"!==s&&"Directory"!==s&&"SymbolicLink"!==s)throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`Runtime archive contains unsupported entry type ${s??"unknown"}: ${e}`);return!0}})}catch(e){throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID","Could not extract runtime artifact safely.",{cause:e})}}(e,i),await async function(e,t,i){const s=await async function(e){let t;try{t=JSON.parse(await y.readFile(n.join(e,Ml),"utf8"))}catch(e){throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID","Runtime artifact manifest is missing or invalid JSON.",{cause:e})}const i=ja(yr,t);if(!i.success)throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`Runtime artifact manifest is invalid: ${i.error.message}`);return i.data}(e);if(function(e,t){for(const n of["packageName","version","platform","arch","formatVersion","launcherAbi","entrypoint","sha256"])if(e[n]!==t[n])throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`Runtime artifact ${"sha256"===n?"SHA-256":n} mismatch: expected ${t[n]}, got ${e[n]}.`)}(s,t),1!==s.formatVersion)throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`Unsupported runtime artifact format ${s.formatVersion}.`);if(i?.platform&&"universal"!==s.platform&&s.platform!==i.platform)throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`Runtime artifact platform ${s.platform} does not match ${i.platform}.`);if(i?.arch&&"universal"!==s.arch&&s.arch!==i.arch)throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`Runtime artifact architecture ${s.arch} does not match ${i.arch}.`);if(void 0!==i?.launcherAbi&&s.launcherAbi>i.launcherAbi)throw new jl("INSTANCE_BASE_RUNTIME_INCOMPATIBLE",`Runtime requires launcher ABI ${s.launcherAbi}, but the base runtime provides ${i.launcherAbi}.`);const r=function(e,t){if(!e||e.includes("\\")||n.posix.isAbsolute(e))throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`${t} must be a non-empty POSIX relative path.`);const i=n.posix.normalize(e);if("."===i||".."===i||i.startsWith("../"))throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`${t} escapes the runtime root.`);return i}(s.entrypoint,"Runtime entrypoint"),o=await y.lstat(n.join(e,...r.split("/"))).catch(()=>{});if(!o?.isFile())throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`Runtime entrypoint is missing: ${r}`);const a=await Fl(e);if(a!==s.sha256)throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`Runtime payload SHA-256 mismatch: expected ${s.sha256}, got ${a}.`);return s}(i,t,{platform:t.platform,arch:t.arch})}finally{await y.rm(i,{recursive:!0,force:!0})}}}function Vl(e){const t=process.env.TASK_HANDOFF_RUNTIME_RELEASE_BASE_URL?.trim();return t?t.replaceAll("{version}",e).replace(/\/$/,""):`https://github.com/edgestorage/task-handoff/releases/download/v${e}`}class Gl{store;desiredVersion;hooks;inFlight=new Map;requests=new Map;cancelled=new Set;now;delay;drainTimeoutMs;drainRequestRetryMs;verificationTimeoutMs;pollIntervalMs;maxAttempts;retryBaseDelayMs;retryMaxDelayMs;constructor(e,t,n,i={}){this.store=e,this.desiredVersion=t,this.hooks=n,this.now=i.now||(()=>new Date),this.delay=i.delay||(e=>new Promise(t=>setTimeout(t,e))),this.drainTimeoutMs=i.drainTimeoutMs??3e5,this.drainRequestRetryMs=function(e){if(!Number.isFinite(e)||e<=0)throw new TypeError("drainRequestRetryMs must be a positive finite number.");return e}(i.drainRequestRetryMs??1e3),this.verificationTimeoutMs=i.verificationTimeoutMs??6e4,this.pollIntervalMs=i.pollIntervalMs??250,this.maxAttempts=function(e){if(!Number.isInteger(e)||e<=0)throw new TypeError("maxAttempts must be a positive integer.");return e}(i.maxAttempts??3),this.retryBaseDelayMs=iu(i.retryBaseDelayMs??1e3,"retryBaseDelayMs"),this.retryMaxDelayMs=iu(i.retryMaxDelayMs??3e4,"retryMaxDelayMs")}schedule(e,t={}){const n=this.requests.get(e)||{startRequested:!1,resumeCancelled:!1};n.startRequested||=!0===t.startRequested,n.resumeCancelled||=!0===t.resumeCancelled||!0===t.startRequested,n.resumeCancelled&&this.cancelled.delete(e),this.requests.set(e,n);const i=this.inFlight.get(e);if(i)return i;const s=Promise.resolve().then(()=>this.reconcile(e,n)).finally(()=>{this.inFlight.delete(e),this.requests.delete(e)});return this.inFlight.set(e,s),s}isRunning(e){return this.inFlight.has(e)}cancel(e){return this.cancelled.add(e),this.inFlight.get(e)}async reconcile(e,t){let n=this.requireInstance(e);const i=this.desiredVersion();if(this.cancelled.has(e)&&!t.resumeCancelled)return this.storePhase(n,"pending");if(Xl(n))return this.storePhase(n,"pending");const s=n.runtimeVersion?.desiredVersion!==i||t.startRequested||Ql(n)?0:this.remainingRetryDelayMs(n.runtimeVersion);if(s>0&&(await this.delay(s),n=this.requireInstance(e),this.cancelled.has(e)))return this.storePhase(n,"pending");const r=Wl(n),o=r===i&&(await(this.hooks.isInstalled?.(n,i))??!0);if(this.cancelled.has(e))return this.storePhase(this.requireInstance(e),"pending");if(r===i&&o)return this.storeState(n,{desiredVersion:i,actualVersion:r,phase:"matched",attempt:n.runtimeVersion?.attempt||0,matchedAt:this.timestamp()},!Ql(n)&&"failed"!==n.health);if(n=this.storeState(n,function(e,t,n,i=!1){const s=e.runtimeVersion,r=s?.desiredVersion===t&&"matched"!==s.phase;return{desiredVersion:t,...n?{actualVersion:n}:{},phase:"pending",attempt:r?s.attempt:0,error:(r?s.error:void 0)||(n!==t||i?Zl(t,n):eu("INSTANCE_RUNTIME_VERIFICATION_FAILED",`Controlled-instance ${t} is running, but the active runtime artifact does not match the desired release identity.`,t,n,!0))}}(n,i,r,o)),Ql(n)&&!t.startRequested)return n;let a=!1,c=0;try{for(;c<this.maxAttempts;){if(this.cancelled.has(e))return this.storePhase(this.requireInstance(e),"pending");let s;try{if(n=this.requireInstance(e),Yl(n))if(n=this.storePhase(n,"draining"),await this.runtimeIsRunning(n)){const t=this.now().getTime()+this.drainTimeoutMs;let i=!1;for(;!i;){if(i=!1!==await(this.hooks.beginDrain?.(n)),i){a=!0;break}if(this.cancelled.has(e))return this.storePhase(this.requireInstance(e),"pending");const s=t-this.now().getTime();if(s<=0)break;await this.delay(Math.min(this.drainRequestRetryMs,s)),n=this.requireInstance(e)}if(n=this.requireInstance(e),!i||Kl(n)){const s=Math.max(0,t-this.now().getTime()),r=i&&await this.waitUntil(e,s,e=>!Kl(e));if(n=this.requireInstance(e),!r){if(this.cancelled.has(e))return this.storePhase(n,"pending");await(this.hooks.onForcedDrain?.(n))}}}else await(this.hooks.onDrainSkipped?.(n));if(n=this.storePhase(this.requireInstance(e),"installing",!0),c+=1,await this.hooks.install(n,i),this.cancelled.has(e)||Ql(this.requireInstance(e))&&!t.startRequested)return this.storePhase(this.requireInstance(e),"pending");if(n=this.storePhase(this.requireInstance(e),"restarting"),await this.hooks.restart(n),this.cancelled.has(e))return this.storePhase(this.requireInstance(e),"pending");n=this.storePhase(this.requireInstance(e),"verifying");const s=await this.waitUntil(e,this.verificationTimeoutMs,e=>Wl(e)===i);if(this.cancelled.has(e))return this.storePhase(this.requireInstance(e),"pending");if(!s)throw eu("INSTANCE_RUNTIME_VERIFICATION_FAILED",`Instance ${e} did not register controlled-instance ${i} after restart.`,i,Wl(this.requireInstance(e)),!0);const r=this.requireInstance(e);if(this.hooks.isInstalled&&!await this.hooks.isInstalled(r,i))throw eu("INSTANCE_RUNTIME_VERIFICATION_FAILED",`Instance ${e} reported controlled-instance ${i}, but its active runtime release is missing.`,i,Wl(r),!0);return this.storeState(r,{desiredVersion:i,actualVersion:i,phase:"matched",attempt:r.runtimeVersion?.attempt||1,matchedAt:this.timestamp()},!Ql(r)&&"failed"!==r.health)}catch(t){if(this.cancelled.has(e))return this.storePhase(this.requireInstance(e),"pending");s=tu(t,i,Wl(this.store.get(e)))}n=this.requireInstance(e);const r=n.runtimeVersion?.attempt||1;if(!s.retryable||c>=this.maxAttempts)return this.storeBatchFailure(n,i,r>=this.maxAttempts&&s.retryable?nu(i,Wl(n),this.maxAttempts,s):s);n=this.storeState(n,{desiredVersion:i,...Wl(n)?{actualVersion:Wl(n)}:{},phase:"pending",attempt:r,lastAttemptAt:this.timestamp(),error:s}),await this.delay(this.retryDelayMs(r))}return this.storeBatchFailure(n,i,nu(i,Wl(n),this.maxAttempts,n.runtimeVersion?.error))}finally{a&&await(this.hooks.endDrain?.(this.requireInstance(e)))}}storeBatchFailure(e,t,n){const i=Wl(e);return this.storeState(e,{desiredVersion:t,...i?{actualVersion:i}:{},phase:"pending",attempt:e.runtimeVersion?.attempt||0,lastAttemptAt:this.timestamp(),error:n})}retryDelayMs(e){return Math.min(this.retryMaxDelayMs,this.retryBaseDelayMs*2**Math.max(0,e-1))}async runtimeIsRunning(e){if(!this.hooks.isRuntimeRunning)return!0;try{return!1!==await this.hooks.isRuntimeRunning(e)}catch{return!0}}remainingRetryDelayMs(e){if(!e?.error||!e.lastAttemptAt)return 0;const t=Date.parse(e.lastAttemptAt);return Number.isFinite(t)?Math.max(0,t+this.retryDelayMs(e.attempt||1)-this.now().getTime()):0}storePhase(e,t,n=!1){const i=this.desiredVersion(),s=Wl(e),r=e.runtimeVersion?.desiredVersion===i?e.runtimeVersion.error:void 0;return this.storeState(e,{desiredVersion:i,...s?{actualVersion:s}:{},phase:t,attempt:(e.runtimeVersion?.attempt||0)+(n?1:0),lastAttemptAt:this.timestamp(),...r?{error:r}:"pending"===t?{error:Zl(i,s)}:{}},"restarting"!==t&&void 0)}storeState(e,t,n){const i=this.store.get(e.id)||e;return this.store.put(Ia.parse({...i,runtimeVersion:t,...void 0===n?{}:{ready:n},updatedAt:this.timestamp()}))}async waitUntil(e,t,n){const i=this.now().getTime()+t;for(;;){const t=this.store.get(e);if(t&&n(t))return!0;if(this.cancelled.has(e))return!1;if(this.now().getTime()>=i)return!1;await this.delay(Math.min(this.pollIntervalMs,Math.max(0,i-this.now().getTime())))}}requireInstance(e){const t=this.store.get(e);if(!t)throw new Error(`Instance ${e} was removed during runtime reconciliation.`);return t}timestamp(){return this.now().toISOString()}}function Wl(e){return e?.build?.packageVersion||e?.instanceVersion}function Kl(e){return e.apps.runningCount>0||e.aiSessions.runningCount>0}function Yl(e){return Boolean(Wl(e))||"online"===e.connectionStatus||"online"===e.agentStatus||Kl(e)}function Xl(e){return Boolean(e.imageProvisioning&&"ready"!==e.imageProvisioning.phase)}function Jl(e){const t=e.workspace?.gitProvisioning;return Boolean(t&&"ready"!==t.phase)}function Ql(e){return["created","stopped","failed"].includes(e.status)}function Zl(e,t){return eu("INSTANCE_RUNTIME_VERSION_MISMATCH",`Expected controlled-instance ${e}, received ${t||"an unknown version"}.`,e,t,!0)}function eu(e,t,n,i,s){return{code:e,message:t,expectedVersion:n,...i?{actualVersion:i}:{},retryable:s}}function tu(e,t,n){if(e&&"object"==typeof e&&"code"in e&&"message"in e){const i=e,s=Ir.shape.code.safeParse(i.code);if(s.success&&"string"==typeof i.message)return eu(s.data,i.message,t,n,"boolean"!=typeof i.retryable||i.retryable)}return eu("INSTANCE_RUNTIME_INSTALL_FAILED",e instanceof Error?e.message:String(e),t,n,!0)}function nu(e,t,n,i){const s=i?.message?` Last error: ${i.message}`:"";return eu(i?.code||"INSTANCE_RUNTIME_INSTALL_FAILED",`Runtime convergence paused after ${n} attempts and will retry.${s}`,e,t,!0)}function iu(e,t){if(!Number.isFinite(e)||e<0)throw new TypeError(`${t} must be a nonnegative finite number.`);return e}function su(e,n=448){t.mkdirSync(e,{recursive:!0,mode:n}),t.chmodSync(e,n)}function ru(e,i,s={}){const r=s.directoryMode??448,o=s.fileMode??384;su(n.dirname(e),r),m.sync(e,`${JSON.stringify(i,null,2)}\n`,{encoding:"utf8",mode:o}),t.chmodSync(e,o)}function ou(e,t){console.warn(JSON.stringify({message:e,...t}))}function au(e){return e&&"object"==typeof e&&"issues"in e?{issues:e.issues}:{error:e instanceof Error?e.message:String(e)}}function cu(e,n){const i=n.logger||ou;let s;try{s=JSON.parse(t.readFileSync(e,"utf8"))}catch(t){if(n.rejectInvalid)throw t;return void i("stored JSON could not be read",{filePath:e,...au(t)})}if(!n.schema)return s;const r=n.sanitize?n.sanitize(s):s,o=n.schema.safeParse(r);if(o.success)return o.data;if(n.rejectInvalid)throw o.error;const a="strip"in n.schema&&"function"==typeof n.schema.strip?n.schema.strip().safeParse(r):void 0;if(a?.success)return i("unknown stored fields were ignored",{filePath:e,issues:o.error.issues}),a.data;i("stored record failed validation and was isolated",{filePath:e,issues:o.error.issues})}function du(e){return fo(e)}function lu(){return d.randomBytes(24).toString("base64url")}class uu{directory;options;permissionsInitialized=!1;constructor(e,t={}){this.directory=e,this.options=t}init(){if(this.permissionsInitialized&&t.existsSync(this.directory))return;su(this.directory,this.options.directoryMode??448);const e=this.options.fileMode??384;for(const i of t.readdirSync(this.directory).filter(e=>e.endsWith(".json")))t.chmodSync(n.join(this.directory,i),e);this.permissionsInitialized=!0}filePath(e){return n.join(this.directory,`${e}.json`)}list(){return this.init(),t.readdirSync(this.directory).filter(e=>e.endsWith(".json")).sort().flatMap(e=>{const t=cu(n.join(this.directory,e),this.options);return t?[t]:[]})}get(e){this.init();const n=this.filePath(e);return t.existsSync(n)?cu(n,this.options):void 0}put(e){const t=this.options.sanitize?this.options.sanitize(e):e,n=this.options.schema?this.options.schema.parse(t):t;return ru(this.filePath(n.id),n,this.options),n}patch(e,t){const n=this.get(e);if(!n)return;const i={...n,...t,id:n.id,createdAt:n.createdAt,updatedAt:(new Date).toISOString()};return this.put(i)}delete(e){const n=this.filePath(e);return!!t.existsSync(n)&&(t.unlinkSync(n),!0)}}class pu{filePathValue;defaults;options;constructor(e,t,n={}){this.filePathValue=e,this.defaults=t,this.options=n}init(){su(n.dirname(this.filePathValue),this.options.directoryMode??448),t.existsSync(this.filePathValue)?t.chmodSync(this.filePathValue,this.options.fileMode??384):this.put(this.defaults())}get(){return this.init(),t.existsSync(this.filePathValue)?cu(this.filePathValue,this.options)??this.defaults():this.defaults()}put(e){const t=this.options.sanitize?this.options.sanitize(e):e,n=this.options.schema?this.options.schema.parse(t):t;return ru(this.filePathValue,n,this.options),n}}T.sqliteTable("na_migration_ledger",{id:T.text("id").primaryKey(),checksum:T.text("checksum").notNull(),appliedAt:T.text("applied_at").notNull(),details:T.text("details",{mode:"json"}).$type().notNull()});const mu=T.sqliteTable("na_stories",{id:T.text("id").primaryKey(),title:T.text("title").notNull(),description:T.text("description"),createdAt:T.text("created_at").notNull(),updatedAt:T.text("updated_at").notNull(),archivedAt:T.text("archived_at"),maxIdleAiSessions:T.integer("max_idle_ai_sessions").notNull().default(5),nextDocumentSequence:T.integer("next_document_sequence").notNull().default(1),agentToolsContent:T.integer("agent_tools_content",{mode:"boolean"}).notNull().default(!0),agentToolsActions:T.integer("agent_tools_actions",{mode:"boolean"}).notNull().default(!1),agentToolsAutomations:T.integer("agent_tools_automations",{mode:"boolean"}).notNull().default(!1),agentToolsAiSessions:T.integer("agent_tools_ai_sessions",{mode:"boolean"}).notNull().default(!1),agentToolsDecisions:T.integer("agent_tools_decisions",{mode:"boolean"}).notNull().default(!1)},e=>[T.check("na_stories_max_idle_check",A.sql`${e.maxIdleAiSessions} BETWEEN 1 AND 50`),T.check("na_stories_next_document_sequence_check",A.sql`${e.nextDocumentSequence} > 0`),T.check("na_stories_agent_tools_content_check",A.sql`${e.agentToolsContent} IN (0, 1)`),T.check("na_stories_agent_tools_actions_check",A.sql`${e.agentToolsActions} IN (0, 1)`),T.check("na_stories_agent_tools_automations_check",A.sql`${e.agentToolsAutomations} IN (0, 1)`),T.check("na_stories_agent_tools_ai_sessions_check",A.sql`${e.agentToolsAiSessions} IN (0, 1)`),T.check("na_stories_agent_tools_decisions_check",A.sql`${e.agentToolsDecisions} IN (0, 1)`),T.index("na_stories_created_idx").on(e.createdAt)]),hu=T.sqliteTable("na_story_decisions",{id:T.text("id").primaryKey(),storyId:T.text("story_id").notNull().references(()=>mu.id,{onDelete:"cascade"}),sessionId:T.text("session_id").notNull(),turnId:T.text("turn_id"),question:T.text("question").notNull(),options:T.text("options_json",{mode:"json"}).$type().notNull().default([]),allowFreeText:T.integer("allow_free_text",{mode:"boolean"}).notNull().default(!0),context:T.text("context"),status:T.text("status",{enum:["pending","decided","cancelled","expired"]}).notNull(),revision:T.integer("revision").notNull(),response:T.text("response"),selectedOptionId:T.text("selected_option_id"),decidedTurnId:T.text("decided_turn_id"),expiredReason:T.text("expired_reason_json",{mode:"json"}).$type(),resumeState:T.text("resume_state",{enum:["resuming"]}),resumeAttemptedAt:T.text("resume_attempted_at"),createdAt:T.text("created_at").notNull(),updatedAt:T.text("updated_at").notNull(),decidedAt:T.text("decided_at")},e=>[T.uniqueIndex("na_story_decisions_session_turn_uq").on(e.storyId,e.sessionId,e.turnId).where(A.sql`${e.turnId} IS NOT NULL`),T.index("na_story_decisions_story_idx").on(e.storyId,e.createdAt),T.index("na_story_decisions_session_idx").on(e.sessionId,e.status),T.check("na_story_decisions_revision_check",A.sql`${e.revision} >= 1`),T.check("na_story_decisions_allow_free_text_check",A.sql`${e.allowFreeText} IN (0, 1)`)]),gu=T.sqliteTable("na_story_actions",{storyId:T.text("story_id").notNull().references(()=>mu.id,{onDelete:"cascade"}),id:T.text("id").notNull(),title:T.text("title").notNull(),promptTemplate:T.text("prompt_template").notNull(),targetInstanceId:T.text("target_instance_id"),sessionPreset:T.text("session_preset_json",{mode:"json"}).$type(),displayOrder:T.integer("display_order").notNull()},e=>[T.primaryKey({columns:[e.storyId,e.id]}),T.index("na_story_actions_order_idx").on(e.storyId,e.displayOrder,e.id)]),fu=T.sqliteTable("na_story_documents",{storyId:T.text("story_id").notNull().references(()=>mu.id,{onDelete:"cascade"}),storyPath:T.text("story_path").notNull(),title:T.text("title").notNull(),indexedSequence:T.integer("indexed_sequence").notNull(),displayOrder:T.integer("display_order").notNull()},e=>[T.primaryKey({columns:[e.storyId,e.storyPath]}),T.uniqueIndex("na_story_documents_sequence_uq").on(e.storyId,e.indexedSequence),T.index("na_story_documents_page_idx").on(e.storyId,e.indexedSequence,e.storyPath),T.index("na_story_documents_display_idx").on(e.storyId,e.displayOrder,e.storyPath),T.check("na_story_documents_sequence_check",A.sql`${e.indexedSequence} > 0`)]),yu=T.sqliteTable("na_story_automations",{id:T.text("id").primaryKey(),storyId:T.text("story_id").notNull(),actionId:T.text("action_id").notNull(),schedule:T.text("schedule_json",{mode:"json"}).$type().notNull(),enabled:T.integer("enabled",{mode:"boolean"}).notNull(),policy:T.text("policy_json",{mode:"json"}).$type().notNull(),scheduleAnchorAt:T.text("schedule_anchor_at").notNull(),createdAt:T.text("created_at").notNull(),updatedAt:T.text("updated_at").notNull()},e=>[T.foreignKey({columns:[e.storyId,e.actionId],foreignColumns:[gu.storyId,gu.id],name:"na_story_automations_action_fk"}).onDelete("restrict"),T.index("na_story_automations_story_idx").on(e.storyId),T.index("na_story_automations_enabled_idx").on(e.enabled)]),Iu=T.sqliteTable("na_story_automation_runs",{id:T.text("id").primaryKey(),automationId:T.text("automation_id").notNull().references(()=>yu.id,{onDelete:"cascade"}),eventType:T.text("event_type",{enum:["manual","schedule"]}).notNull(),status:T.text("status",{enum:["queued","dispatching","running","completed","failed","skipped"]}).notNull(),scheduledFor:T.text("scheduled_for").notNull(),targetInstanceId:T.text("target_instance_id").notNull(),aiSessionId:T.text("ai_session_id"),error:T.text("error_json",{mode:"json"}).$type(),queuedAt:T.text("queued_at").notNull(),startedAt:T.text("started_at"),completedAt:T.text("completed_at"),executionKey:T.text("execution_key").notNull(),requestFingerprint:T.text("request_fingerprint").notNull(),executionInput:T.text("execution_input_json",{mode:"json"}).$type().notNull()},e=>[T.uniqueIndex("na_story_automation_runs_execution_key_uq").on(e.executionKey),T.index("na_story_automation_runs_automation_time_idx").on(e.automationId,e.queuedAt),T.index("na_story_automation_runs_status_idx").on(e.status,e.scheduledFor)]),_u=T.sqliteTable("na_story_file_mutations",{id:T.text("id").primaryKey(),storyId:T.text("story_id").notNull().references(()=>mu.id,{onDelete:"restrict"}),operation:T.text("operation",{enum:["write","rename","delete"]}).notNull(),storyPath:T.text("story_path").notNull(),nextStoryPath:T.text("next_story_path"),title:T.text("title"),temporaryName:T.text("temporary_name"),backupName:T.text("backup_name"),phase:T.text("phase",{enum:["receiving","prepared","files-staged","database-committed","cleanup"]}).notNull(),createdAt:T.text("created_at").notNull(),updatedAt:T.text("updated_at").notNull()},e=>[T.index("na_story_file_mutations_story_idx").on(e.storyId,e.createdAt)]),Eu=T.sqliteTable("na_story_deletion_intents",{storyId:T.text("story_id").primaryKey(),phase:T.text("phase",{enum:["prepared","files-staged","database-committed","cleanup"]}).notNull(),trashName:T.text("trash_name"),createdAt:T.text("created_at").notNull(),updatedAt:T.text("updated_at").notNull()}),Au=["health","connectionStatus","agentStatus","targetStatus","uiAccessStatus","ready","protocolVersion","instanceVersion","build","runtimeVersion","capabilities","appInventory","target","access","apps","aiSessions","triggers","runtime","lastHeartbeatAt"];function Tu(e){return JSON.stringify(e??null)}function bu(e){return JSON.parse(String(e))}function wu(e,t){if(e.isTransaction)return t();e.exec("BEGIN IMMEDIATE");try{const n=t();return e.exec("COMMIT"),n}catch(t){throw e.exec("ROLLBACK"),t}}class Su{client;constructor(e){this.client=e}get(){return this.client.prepare("SELECT node_id, created_at, updated_at FROM na_node_identity WHERE singleton_key = 1").get()}ensure(e,t){const n=this.get();if(n&&n.node_id!==e)throw Du("NODE_AGENT_IDENTITY_MISMATCH",`Stored node identity ${n.node_id} does not match ${e}.`);return n||this.client.prepare("INSERT INTO na_node_identity (singleton_key, node_id, created_at, updated_at) VALUES (1, ?, ?, ?)").run(e,t,t),this.get()}}class Nu{client;constructor(e){this.client=e}list(){return this.client.prepare("SELECT * FROM na_local_folders ORDER BY id").all().map(xu)}get(e){const t=this.client.prepare("SELECT * FROM na_local_folders WHERE id = ?").get(e);return t?xu(t):void 0}put(e){const t=kr.parse(Ws(e));return this.client.prepare("INSERT INTO na_local_folders (id, node_id, name, path, labels_json, created_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(id) DO UPDATE SET node_id=excluded.node_id, name=excluded.name, path=excluded.path,\n labels_json=excluded.labels_json, updated_at=excluded.updated_at").run(t.id,t.nodeId,t.name,t.path,Tu(t.labels),t.createdAt,t.updatedAt),t}delete(e){return Number(this.client.prepare("DELETE FROM na_local_folders WHERE id = ?").run(e).changes)>0}}class vu{client;constructor(e){this.client=e}list(){return this.client.prepare("SELECT * FROM na_runtimes ORDER BY id").all().map(Cu)}get(e){const t=this.client.prepare("SELECT * FROM na_runtimes WHERE id = ?").get(e);return t?Cu(t):void 0}put(e){const t=Qo.parse(e);return this.client.prepare("INSERT INTO na_runtimes (id, node_id, name, type, status, access_strategy, capabilities_json, labels_json, created_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(id) DO UPDATE SET node_id=excluded.node_id, name=excluded.name, type=excluded.type,\n status=excluded.status, access_strategy=excluded.access_strategy, capabilities_json=excluded.capabilities_json,\n labels_json=excluded.labels_json, updated_at=excluded.updated_at").run(t.id,t.nodeId,t.name,t.type,t.status,t.accessStrategy,Tu(t.capabilities),Tu(t.labels),t.createdAt,t.updatedAt),t}delete(e){try{return Number(this.client.prepare("DELETE FROM na_runtimes WHERE id = ?").run(e).changes)>0}catch(t){if(String(t).includes("FOREIGN KEY constraint failed"))throw Du("NODE_RUNTIME_IN_USE",`Runtime ${e} is used by a controlled instance.`,409);throw t}}}class Ou{client;constructor(e){this.client=e}list(){return this.client.prepare("SELECT i.*, o.health, o.connection_status, o.ready, o.observed_json,\n o.last_heartbeat_at, o.updated_at AS observation_updated_at\n FROM na_instances i LEFT JOIN na_instance_observations o ON o.instance_id = i.id ORDER BY i.id").all().map(e=>ku(this.client,e))}get(e){const t=this.client.prepare("SELECT i.*, o.health, o.connection_status, o.ready, o.observed_json,\n o.last_heartbeat_at, o.updated_at AS observation_updated_at\n FROM na_instances i LEFT JOIN na_instance_observations o ON o.instance_id = i.id WHERE i.id = ?").get(e);return t?ku(this.client,t):void 0}put(e){const t=Ia.parse(Sa(e));return wu(this.client,()=>{const e=this.client.prepare("SELECT state_revision, registration_credential FROM na_instances WHERE id = ?").get(t.id),n=Math.max(t.stateRevision||0,Number(e?.state_revision)||0)+1,i=t.registrationToken||e?.registration_credential,s=function(e){const t={...e};for(const e of Au)delete t[e];for(const e of["id","nodeId","runtimeId","name","status","stateRevision","processIncarnationId","registrationToken","createdAt","updatedAt"])delete t[e];return t}({...t,stateRevision:n}),r=zu(t),o="local-folder"===t.source.type?t.source.localFolderId:void 0,a=o&&this.client.prepare("SELECT 1 AS present FROM na_local_folders WHERE id = ?").get(o)?o:void 0;return this.client.prepare("INSERT INTO na_instances\n (id, node_id, runtime_id, source_local_folder_id, name, status, state_revision, process_incarnation_id,\n registration_credential, desired_json, created_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(id) DO UPDATE SET node_id=excluded.node_id, runtime_id=excluded.runtime_id,\n source_local_folder_id=excluded.source_local_folder_id, name=excluded.name, status=excluded.status,\n state_revision=excluded.state_revision, process_incarnation_id=excluded.process_incarnation_id,\n registration_credential=excluded.registration_credential, desired_json=excluded.desired_json,\n updated_at=excluded.updated_at").run(t.id,t.nodeId,t.runtimeId,a??null,t.name,t.status,n,t.processIncarnationId??null,i??null,Tu(s),t.createdAt,t.updatedAt),this.client.prepare("INSERT INTO na_instance_observations\n (instance_id, health, connection_status, ready, observed_json, last_heartbeat_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(instance_id) DO UPDATE SET health=excluded.health, connection_status=excluded.connection_status,\n ready=excluded.ready, observed_json=excluded.observed_json, last_heartbeat_at=excluded.last_heartbeat_at,\n updated_at=excluded.updated_at").run(t.id,t.health,t.connectionStatus,t.ready?1:0,Tu(r),t.lastHeartbeatAt??null,t.updatedAt),this.get(t.id)})}putObservation(e){const t=Ia.parse(Sa(e));return wu(this.client,()=>{const e=this.client.prepare("SELECT state_revision, registration_credential FROM na_instances WHERE id = ?").get(t.id);if(!e)throw Du("NODE_INSTANCE_NOT_FOUND",`Instance ${t.id} was not found.`,404);const n=Math.max(t.stateRevision||0,Number(e.state_revision)||0)+1,i=t.registrationToken||e.registration_credential;return this.client.prepare("UPDATE na_instances SET status = ?, state_revision = ?, process_incarnation_id = ?,\n registration_credential = ?, updated_at = ? WHERE id = ?").run(t.status,n,t.processIncarnationId??null,i??null,t.updatedAt,t.id),this.client.prepare("INSERT INTO na_instance_observations\n (instance_id, health, connection_status, ready, observed_json, last_heartbeat_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(instance_id) DO UPDATE SET health=excluded.health, connection_status=excluded.connection_status,\n ready=excluded.ready, observed_json=excluded.observed_json, last_heartbeat_at=excluded.last_heartbeat_at,\n updated_at=excluded.updated_at").run(t.id,t.health,t.connectionStatus,t.ready?1:0,Tu(zu(t)),t.lastHeartbeatAt??null,t.updatedAt),this.get(t.id)})}delete(e){return Number(this.client.prepare("DELETE FROM na_instances WHERE id = ?").run(e).changes)>0}}function Ru(e){return{nodeIdentity:new Su(e),localFolders:new Nu(e),runtimes:new vu(e),instances:new Ou(e)}}function zu(e){return Object.fromEntries(Au.flatMap(t=>void 0===e[t]?[]:[[t,e[t]]]))}function xu(e){return kr.parse({id:e.id,nodeId:e.node_id,name:e.name,path:e.path,labels:bu(e.labels_json),createdAt:e.created_at,updatedAt:e.updated_at})}function Cu(e){return Qo.parse({id:e.id,nodeId:e.node_id,name:e.name,type:e.type,status:e.status,accessStrategy:e.access_strategy,capabilities:bu(e.capabilities_json),labels:bu(e.labels_json),createdAt:e.created_at,updatedAt:e.updated_at})}function ku(e,t){const n=bu(t.desired_json),i=t.observed_json?bu(t.observed_json):{},s=e.prepare("SELECT * FROM na_instance_model_assignments WHERE instance_id = ?").get(String(t.id)),r=s?e.prepare("SELECT model_id FROM na_instance_model_entities WHERE instance_id = ? ORDER BY display_order").all(String(t.id)).map(e=>String(e.model_id)):void 0,o=s?{modelEntityIds:r,...s.legacy_codex_model_id?{codexModelHash:String(s.legacy_codex_model_id)}:{},...s.legacy_claude_model_id?{claudeModelHash:String(s.legacy_claude_model_id)}:{},...s.legacy_opencode_model_id?{opencodeModelHash:String(s.legacy_opencode_model_id)}:{}}:n.modelSelection;return Ia.parse({...n,...i,modelSelection:o,id:t.id,nodeId:t.node_id,runtimeId:t.runtime_id,name:t.name,status:t.status,stateRevision:t.state_revision,processIncarnationId:t.process_incarnation_id||void 0,registrationToken:t.registration_credential||void 0,health:t.health||"unknown",connectionStatus:t.connection_status||"unknown",ready:Boolean(t.ready),lastHeartbeatAt:t.last_heartbeat_at||void 0,createdAt:t.created_at,updatedAt:t.updated_at})}function Du(e,t,n=409){return Object.assign(new Error(t),{code:e,statusCode:n})}function Lu(e){return JSON.stringify(e??null)}function Pu(e){return JSON.parse(String(e))}class Mu{client;constructor(e){this.client=e}list(){return this.client.prepare("SELECT * FROM na_models ORDER BY display_order, id").all().map(Fu)}get(e){const t=this.client.prepare("SELECT * FROM na_models WHERE id = ?").get(e);return t?Fu(t):void 0}put(e){const t=qr.parse(e);return this.client.prepare("INSERT INTO na_models\n (id, name, endpoint, key, model, app, enabled, display_order, model_names_json, mappings_json, protocols_json, labels_json, created_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(id) DO UPDATE SET name=excluded.name, endpoint=excluded.endpoint, key=excluded.key,\n model=excluded.model, app=excluded.app, enabled=excluded.enabled, display_order=excluded.display_order,\n model_names_json=excluded.model_names_json, mappings_json=excluded.mappings_json, protocols_json=excluded.protocols_json,\n labels_json=excluded.labels_json, updated_at=excluded.updated_at").run(t.id,t.name,t.endpoint,t.key,t.model,t.app,t.enabled?1:0,t.order,Lu(ao(t.modelNames)),Lu(t.mappings),Lu(t.protocols),Lu(t.labels),t.createdAt,t.updatedAt),t}rename(e,t){this.client.prepare("UPDATE na_models SET id = ? WHERE id = ?").run(t,e)}delete(e){try{return Number(this.client.prepare("DELETE FROM na_models WHERE id = ?").run(e).changes)>0}catch(t){if(String(t).includes("FOREIGN KEY constraint failed")){const t=this.referenceIds(e);throw Object.assign(new Error(`Model ${e} is assigned to ${t.length} instance${1===t.length?"":"s"}.`),{statusCode:409,code:"NODE_MODEL_IN_USE",instanceIds:t})}throw t}}referenceIds(e){return this.client.prepare("SELECT DISTINCT instance_id FROM (\n SELECT instance_id FROM na_instance_model_entities WHERE model_id = ?\n UNION ALL SELECT instance_id FROM na_instance_model_assignments WHERE legacy_codex_model_id = ?\n UNION ALL SELECT instance_id FROM na_instance_model_assignments WHERE legacy_claude_model_id = ?\n UNION ALL SELECT instance_id FROM na_instance_model_assignments WHERE legacy_opencode_model_id = ?\n ) ORDER BY instance_id").all(e,e,e,e).map(e=>String(e.instance_id))}}class ju{client;constructor(e){this.client=e}get(e){const t=this.client.prepare("SELECT * FROM na_instance_model_assignments WHERE instance_id = ?").get(e);if(!t)return;const n=this.client.prepare("SELECT model_id FROM na_instance_model_entities WHERE instance_id = ? ORDER BY display_order").all(e).map(e=>String(e.model_id));return Wr.parse({instanceId:e,modelEntityIds:n,codexModelHash:t.legacy_codex_model_id||void 0,claudeModelHash:t.legacy_claude_model_id||void 0,opencodeModelHash:t.legacy_opencode_model_id||void 0,updatedAt:t.updated_at})}put(e){const t=Wr.parse(e);return this.transaction(()=>{this.client.prepare("INSERT INTO na_instance_model_assignments\n (instance_id, legacy_codex_model_id, legacy_claude_model_id, legacy_opencode_model_id, updated_at)\n VALUES (?, ?, ?, ?, ?)\n ON CONFLICT(instance_id) DO UPDATE SET legacy_codex_model_id=excluded.legacy_codex_model_id,\n legacy_claude_model_id=excluded.legacy_claude_model_id,\n legacy_opencode_model_id=excluded.legacy_opencode_model_id, updated_at=excluded.updated_at").run(t.instanceId,t.codexModelHash??null,t.claudeModelHash??null,t.opencodeModelHash??null,t.updatedAt),this.client.prepare("DELETE FROM na_instance_model_entities WHERE instance_id = ?").run(t.instanceId);const e=this.client.prepare("INSERT INTO na_instance_model_entities (instance_id, model_id, display_order) VALUES (?, ?, ?)");for(const[n,i]of t.modelEntityIds.entries())e.run(t.instanceId,i,n)}),this.get(t.instanceId)}delete(e){return Number(this.client.prepare("DELETE FROM na_instance_model_assignments WHERE instance_id = ?").run(e).changes)>0}transaction(e){if(this.client.isTransaction)return e();this.client.exec("BEGIN IMMEDIATE");try{const t=e();return this.client.exec("COMMIT"),t}catch(e){throw this.client.exec("ROLLBACK"),e}}}function Uu(e){return{models:new Mu(e),assignments:new ju(e),transaction(t){if(e.isTransaction)return t();e.exec("BEGIN IMMEDIATE");try{const n=t();return e.exec("COMMIT"),n}catch(t){throw e.exec("ROLLBACK"),t}}}}function Fu(e){const t=ro(Pu(e.model_names_json),"modelNames",t=>{console.warn(JSON.stringify({message:"unknown or invalid stored node model name entry was sanitized",modelId:e.id,field:t.field}))}),n=ro(Pu(e.mappings_json??"[]"),"mappings",t=>{console.warn(JSON.stringify({message:"unknown or invalid stored node model request mapping was sanitized",modelId:e.id,field:t.field}))}),i=qr.parse({id:e.id,name:e.name,endpoint:e.endpoint,key:e.key,model:e.model,modelNames:t,mappings:n,protocols:Pu(e.protocols_json),app:e.app,enabled:Boolean(e.enabled),order:e.display_order,labels:Pu(e.labels_json),createdAt:e.created_at,updatedAt:e.updated_at});return{...i,modelNames:oo(i.modelNames,i.model,{renumber:!1}),mappings:co(i.mappings,{renumber:!1})}}const $u=2e3,Hu=32e3,Bu=c.z.string().trim().min(1).max(120).regex(/^[a-zA-Z0-9][a-zA-Z0-9_.:-]*$/),qu=Bu,Vu=c.z.string().regex(/^[a-f0-9]{64}$/),Gu=c.z.enum(["overlay-copy-on-write","worktree"]),Wu=c.z.enum(["instance","container","local-runtime"]),Ku=Object.freeze([{workspaceMaterializer:"overlay-copy-on-write",processSandbox:"instance"}]),Yu=c.z.object({workspaceMaterializer:Gu.default("overlay-copy-on-write"),processSandbox:Wu.default("instance")}).strict();function Xu(e){return Ku.some(t=>t.workspaceMaterializer===e.workspaceMaterializer&&t.processSandbox===e.processSandbox)}const Ju=c.z.object({id:qu,revision:Vu,name:c.z.string().trim().min(1).max(120),description:c.z.string().trim().max($u).default(""),appendedPrompt:c.z.string().max(Hu).default(""),targetInstanceId:Bu,cwdFolderId:Bu,providerId:Bu,modelEntityId:Bu.optional(),modelName:c.z.string().trim().min(1).max(120).optional(),modelUpstreamName:c.z.string().trim().min(1).max(240).optional(),reasoningEffort:c.z.string().trim().min(1).max(120).optional(),permissionMode:c.z.string().trim().min(1).max(120).optional(),executionPolicy:Yu,createdAt:c.z.string().datetime(),updatedAt:c.z.string().datetime()}).strict(),Qu={name:c.z.string().trim().min(1).max(120),description:c.z.string().trim().max($u).default(""),appendedPrompt:c.z.string().max(Hu).default(""),targetInstanceId:Bu,cwdFolderId:Bu,providerId:Bu,modelEntityId:Bu.optional(),modelName:c.z.string().trim().min(1).max(120).optional(),modelUpstreamName:c.z.string().trim().min(1).max(240).optional(),reasoningEffort:c.z.string().trim().min(1).max(120).optional(),permissionMode:c.z.string().trim().min(1).max(120).optional(),executionPolicy:Yu.optional()},Zu=c.z.object(Qu).strict(),ep=c.z.object({expectedRevision:Vu,name:Qu.name.optional(),description:c.z.string().trim().max($u).nullable().optional(),appendedPrompt:c.z.string().max(Hu).nullable().optional(),targetInstanceId:Qu.targetInstanceId.optional(),cwdFolderId:Qu.cwdFolderId.optional(),providerId:Qu.providerId.optional(),modelEntityId:Bu.nullable().optional(),modelName:c.z.string().trim().min(1).max(120).nullable().optional(),modelUpstreamName:c.z.string().trim().min(1).max(240).nullable().optional(),reasoningEffort:c.z.string().trim().min(1).max(120).nullable().optional(),permissionMode:c.z.string().trim().min(1).max(120).nullable().optional(),executionPolicy:Qu.executionPolicy}).strict(),tp=c.z.object({agents:c.z.array(Ju)}).strict(),np=c.z.object({id:qu,deleted:c.z.literal(!0),deletedOrchestrationIds:c.z.array(c.z.string().trim().min(1).max(160)).default([])}).strict();c.z.object({agents:c.z.array(c.z.object({nodeId:Bu,agent:Ju}).strict()),unavailableNodeIds:c.z.array(Bu).default([])}).strict();const ip=["AGENT_DEFINITION_INVALID_INPUT","AGENT_DEFINITION_NOT_FOUND","AGENT_DEFINITION_REVISION_CONFLICT","AGENT_DEFINITION_TARGET_INSTANCE_UNKNOWN","AGENT_DEFINITION_FOLDER_UNKNOWN","AGENT_DEFINITION_PROVIDER_UNSUPPORTED","AGENT_DEFINITION_POLICY_UNSUPPORTED"],sp=c.z.enum(ip),rp=c.z.object({code:c.z.literal("AGENT_DEFINITION_REVISION_CONFLICT"),expectedRevision:Vu,actualRevision:Vu}).strict();c.z.union([rp,c.z.object({code:sp}).strict()]);const op=c.z.object({agentId:qu,change:c.z.enum(["created","updated","deleted"]),revision:Vu.optional(),definition:Ju.optional()}).strict();c.z.object({nodeId:Bu,event:op}).strict();const ap=Ju.strip().extend({executionPolicy:Yu.strip()});c.z.object({agents:c.z.array(ap)}).strip(),c.z.object({agents:c.z.array(c.z.object({nodeId:Bu,agent:ap}).strip()),unavailableNodeIds:c.z.array(c.z.string().trim().min(1).max(120)).default([])}).strip();const cp=c.z.object({agentId:qu,change:c.z.enum(["created","updated","deleted"]),revision:Vu.optional(),definition:ap.optional()}).strip();c.z.object({nodeId:Bu,event:cp}).strip();const dp=new WeakMap;function lp(e,t){const n=function(e){const t=dp.get(e);if(t)return t;const n={depth:0,afterCommit:[]};return dp.set(e,n),n}(e);if(e.isTransaction){n.depth+=1;try{return t()}finally{n.depth-=1}}e.exec("BEGIN IMMEDIATE"),n.depth+=1;try{const i=t();if(e.exec("COMMIT"),n.depth-=1,0===n.depth){const e=n.afterCommit.splice(0);for(const t of e)t()}return i}catch(t){throw e.exec("ROLLBACK"),n.depth-=1,0===n.depth&&(n.afterCommit.length=0),t}}function up(e,t){const n=dp.get(e);n&&0!==n.depth?n.afterCommit.push(t):t()}const pp=200,mp="default:",hp=c.z.string().trim().min(1).max(160).regex(/^[a-zA-Z0-9][a-zA-Z0-9_.:-]*$/),gp=hp,fp=c.z.string().regex(/^[a-f0-9]{64}$/);function yp(e){return`${mp}${qu.parse(e)}`}function Ip(e){if(!function(e){return e.startsWith(mp)}(e))return;const t=e.slice(8);return qu.safeParse(t).success?t:void 0}const _p=c.z.object({fromAgentId:qu,toAgentId:qu}).strict(),Ep=c.z.object({id:gp,revision:fp,name:c.z.string().trim().min(1).max(120),agentIds:c.z.array(qu).min(1).max(50),edges:c.z.array(_p).max(pp),createdAt:c.z.string().datetime(),updatedAt:c.z.string().datetime()}).strict(),Ap=c.z.object({name:c.z.string().trim().min(1).max(120),agentIds:c.z.array(qu).min(1).max(50),edges:c.z.array(_p).max(pp).default([])}).strict(),Tp=c.z.object({expectedRevision:fp,name:c.z.string().trim().min(1).max(120).optional(),agentIds:c.z.array(qu).min(1).max(50).optional(),edges:c.z.array(_p).max(pp).optional()}).strict(),bp=c.z.object({orchestrations:c.z.array(Ep)}).strict(),wp=c.z.object({id:gp,deleted:c.z.literal(!0)}).strict();c.z.object({orchestrations:c.z.array(c.z.object({nodeId:hp,orchestration:Ep}).strict()),unavailableNodeIds:c.z.array(hp).default([])}).strict();const Sp=c.z.enum(["AGENT_ORCHESTRATION_NOT_FOUND","AGENT_ORCHESTRATION_REVISION_CONFLICT","AGENT_ORCHESTRATION_INVALID_GRAPH","AGENT_ORCHESTRATION_AGENT_UNKNOWN","AGENT_ORCHESTRATION_CYCLE","AGENT_ORCHESTRATION_DEFAULT_PROTECTED"]),Np=c.z.object({code:c.z.literal("AGENT_ORCHESTRATION_CYCLE"),cycle:c.z.array(qu).min(2)}).strict(),vp=c.z.object({code:c.z.literal("AGENT_ORCHESTRATION_REVISION_CONFLICT"),expectedRevision:fp,actualRevision:fp}).strict();c.z.union([Np,vp,c.z.object({code:Sp}).strict()]);const Op=c.z.object({orchestrationId:gp,change:c.z.enum(["created","updated","deleted"]),revision:fp.optional(),orchestration:Ep.optional()}).strict();function Rp(e,t){return e.agentIds.includes(t)}function zp(e){return{agentIds:[...new Set(e.agentIds)].sort(),edges:[...new Map(e.edges.map(e=>[`${e.fromAgentId}${e.toAgentId}`,e])).values()].sort((e,t)=>e.fromAgentId===t.fromAgentId?e.toAgentId.localeCompare(t.toAgentId):e.fromAgentId.localeCompare(t.fromAgentId))}}c.z.object({nodeId:hp,event:Op}).strict();const xp=Ep.strip().extend({agentIds:c.z.array(qu).max(50).default([]),edges:c.z.array(_p).max(pp).default([])});c.z.object({orchestrations:c.z.array(xp)}).strip(),c.z.object({orchestrations:c.z.array(c.z.object({nodeId:c.z.string().trim().min(1).max(160),orchestration:xp}).strip()),unavailableNodeIds:c.z.array(c.z.string().trim().min(1).max(160)).default([])}).strip();const Cp=c.z.object({orchestrationId:gp,change:c.z.enum(["created","updated","deleted"]),revision:fp.optional(),orchestration:xp.optional()}).strip();c.z.object({nodeId:c.z.string().trim().min(1).max(160),event:Cp}).strip();const kp=c.z.string().trim().min(1).max(120).regex(/^[a-zA-Z0-9][a-zA-Z0-9_.:-]*$/),Dp=kp,Lp=kp,Pp=c.z.number().int().nonnegative(),Mp=Object.freeze({maxMembers:16,maxDepth:4,maxConcurrency:4}),jp=32e3,Up=c.z.enum(["queued","preparing","running","finalizing","completed","failed","cancelled"]),Fp=c.z.object({kind:c.z.enum(["control-plane-user","standalone-operator"]),subjectId:kp,authorizationRevision:c.z.number().int().nonnegative().optional()}).strict(),$p=c.z.object({source:c.z.literal("story-session").optional(),initiatingInstanceId:kp,initiatingAiSessionId:kp,storyId:kp,authorizationSubject:Fp.optional()}).strict(),Hp=c.z.object({source:c.z.literal("control-plane"),authorizationSubject:Fp.optional()}).strict(),Bp=c.z.union([$p,Hp]),qp=c.z.object({maxMembers:c.z.number().int().positive(),maxDepth:c.z.number().int().nonnegative(),maxConcurrency:c.z.number().int().positive()}).strict(),Vp=c.z.object({prompt:c.z.string().trim().min(1).max(128e3)}).strict(),Gp=c.z.object({agentRevision:Vu,targetInstanceId:kp,cwdFolderId:kp,appendedPrompt:c.z.string().max(32e3),providerId:kp,modelEntityId:kp.optional(),modelName:c.z.string().trim().min(1).max(120).optional(),modelUpstreamName:c.z.string().trim().min(1).max(240).optional(),reasoningEffort:c.z.string().trim().min(1).max(120).optional(),permissionMode:c.z.string().trim().min(1).max(120).optional(),executionPolicy:Yu}).strict(),Wp=c.z.object({code:c.z.string().trim().min(1).max(120),message:c.z.string().trim().min(1).max(4e3),retryable:c.z.boolean().default(!1),details:c.z.record(c.z.string(),c.z.unknown()).optional()}).strict(),Kp=c.z.object({text:c.z.string().max(128e3),truncated:c.z.boolean().default(!1),source:c.z.literal("provider-final-message").default("provider-final-message")}).strict(),Yp=c.z.object({status:c.z.enum(["pending","delivered","failed"]),attempts:c.z.number().int().nonnegative(),updatedAt:c.z.string().datetime(),deliveredAt:c.z.string().datetime().optional(),error:Wp.optional()}).strict(),Xp=c.z.object({runId:Dp,status:c.z.enum(["completed","failed","cancelled"]),result:c.z.object({text:c.z.string().max(jp),truncated:c.z.boolean()}).strict().optional(),error:Wp.optional()}).strict().superRefine((e,t)=>{"completed"!==e.status||e.result||t.addIssue({code:c.z.ZodIssueCode.custom,message:"A completed Agent Run tool result requires result text."}),"completed"===e.status||e.error||t.addIssue({code:c.z.ZodIssueCode.custom,message:"A failed or cancelled Agent Run tool result requires an error."})}),Jp=c.z.object({status:c.z.enum(["pending","completed","retrying","manual-intervention"]),attempts:c.z.number().int().nonnegative(),message:c.z.string().max(4e3).optional(),updatedAt:c.z.string().datetime()}).strict(),Qp=c.z.object({runtimeId:kp,state:c.z.enum(["preparing","active","retained","expiring","delete-retrying","expired","manual-intervention"]),usageBytes:c.z.number().int().nonnegative(),quotaBytes:c.z.number().int().positive(),expiresAt:c.z.string().datetime().optional()}).strict(),Zp=c.z.object({memberId:Lp,runId:Dp,agentId:qu,parentMemberId:Lp.optional(),instanceId:kp,aiSessionId:kp.optional(),role:c.z.enum(["root","callee"]),depth:c.z.number().int().nonnegative(),status:Up,input:Vp.optional(),executionSnapshot:Gp,result:Kp.optional(),error:Wp.optional(),createdAt:c.z.string().datetime(),updatedAt:c.z.string().datetime(),completedAt:c.z.string().datetime().optional()}).strict(),em=c.z.object({runId:Dp,sequence:c.z.number().int().positive(),timestamp:c.z.string().datetime(),kind:c.z.string().trim().min(1).max(120),memberId:Lp.optional(),data:c.z.record(c.z.string(),c.z.unknown()).default({})}).strict(),tm=c.z.object({runId:Dp,clientRequestId:kp,revision:Pp,status:Up,input:Vp.optional(),provenance:Bp,orchestrationId:gp,rootMemberId:Lp,budget:qp,result:Kp.optional(),resultDelivery:Yp.optional(),error:Wp.optional(),cleanup:Jp.optional(),sharedSpace:Qp.optional(),members:c.z.array(Zp).optional(),timeline:c.z.array(em).optional(),createdAt:c.z.string().datetime(),updatedAt:c.z.string().datetime(),completedAt:c.z.string().datetime().optional()}).strict(),nm=c.z.object({clientRequestId:kp,orchestrationId:gp,entryAgentId:qu.optional(),input:Vp,provenance:Bp,budget:qp.optional()}).strict();c.z.object({clientRequestId:kp,orchestrationId:gp,entryAgentId:qu.optional(),input:Vp,budget:qp.optional()}).strict();const im=c.z.object({expectedRevision:Pp.optional()}).strict(),sm=c.z.object({runs:c.z.array(tm)}).strict(),rm=["AGENT_RUN_NOT_FOUND","AGENT_RUN_MEMBER_NOT_FOUND","AGENT_RUN_IDEMPOTENCY_CONFLICT","AGENT_RUN_REVISION_CONFLICT","AGENT_RUN_INITIATING_INSTANCE_UNKNOWN","AGENT_RUN_ORCHESTRATION_UNKNOWN","AGENT_RUN_ENTRY_REQUIRED","AGENT_RUN_ENTRY_INVALID","AGENT_RUN_INVOCATION_FORBIDDEN","AGENT_RUN_EXECUTION_UNSUPPORTED","AGENT_RUN_ALREADY_TERMINAL"];c.z.enum(rm);const om=c.z.object({runId:Dp,revision:Pp,run:tm}).strict(),am=c.z.object({runId:Dp,memberId:Lp,revision:Pp,member:Zp}).strict();c.z.object({runs:c.z.array(c.z.object({nodeId:kp,run:tm}).strict()),unavailableNodeIds:c.z.array(kp).default([])}).strict(),c.z.object({nodeId:kp,event:c.z.union([om,am])}).strict();const cm=Zp.strip().extend({input:Vp.strip().optional(),executionSnapshot:Gp.strip(),result:Kp.strip().optional(),error:Wp.strip().optional()}),dm=em.strip(),lm=tm.strip().extend({orchestrationId:gp.optional(),input:Vp.strip().optional(),provenance:c.z.union([$p.strip().extend({authorizationSubject:Fp.strip().optional()}),Hp.strip().extend({authorizationSubject:Fp.strip().optional()})]),budget:qp.strip(),result:Kp.strip().optional(),resultDelivery:Yp.strip().extend({error:Wp.strip().optional()}).optional(),error:Wp.strip().optional(),cleanup:Jp.strip().optional(),sharedSpace:Qp.strip().optional(),members:c.z.array(cm).optional(),timeline:c.z.array(dm).optional()}).transform(e=>{const t=e.orchestrationId??(()=>{const t=(e.members??[]).find(t=>t.memberId===e.rootMemberId);if(!t)throw new Error("An Agent Run without an orchestration binding requires its root member to normalize.");return yp(t.agentId)})();return{...e,orchestrationId:t}}),um=c.z.object({runId:Dp,revision:Pp,run:lm}).strip(),pm=c.z.object({runId:Dp,memberId:Lp,revision:Pp,member:cm}).strip();c.z.object({nodeId:kp,event:c.z.union([um,pm])}).strip();const mm=new Set(["completed","failed","cancelled"]),hm={queued:["preparing","finalizing"],preparing:["running","finalizing"],running:["finalizing"],finalizing:["completed","failed","cancelled"],completed:[],failed:[],cancelled:[]};function gm(e){return e??(new Date).toISOString()}function fm(e){return`${e}_${d.randomBytes(10).toString("hex")}`}function ym(e){return JSON.stringify(e)}function Im(e){try{return JSON.parse(String(e))}catch{return}}function _m(e,t,n,i){return Object.assign(new Error(t),{code:e,statusCode:n,...i?{details:i}:{}})}function Em(e,t){if(t.targetInstanceId!==e)throw _m("AGENT_RUN_SNAPSHOT_INSTANCE_MISMATCH","The member instance does not match its immutable execution snapshot.",409,{instanceId:e,snapshotInstanceId:t.targetInstanceId})}class Am{client;constructor(e){this.client=e}transaction(e){return lp(this.client,e)}create(e){return lp(this.client,()=>{const t=this.getByClientRequestId(e.clientRequestId);if(t){const n=t.members?.find(e=>e.memberId===t.rootMemberId);if(t.orchestrationId===e.orchestrationId&&n?.agentId===e.root.agentId&&n.instanceId===e.root.instanceId&&b.isDeepStrictEqual(n.executionSnapshot,e.root.executionSnapshot)&&b.isDeepStrictEqual(t.input,e.input)&&b.isDeepStrictEqual(t.provenance,e.provenance)&&b.isDeepStrictEqual(t.budget,e.budget))return t;throw _m("AGENT_RUN_IDEMPOTENCY_CONFLICT","The client request id is already associated with a different Agent Run request.",409,{clientRequestId:e.clientRequestId,runId:t.runId})}Em(e.root.instanceId,e.root.executionSnapshot);const n=fm("run"),i=fm("member"),s=gm(e.timestamp);return this.client.prepare("INSERT INTO na_agent_runs\n (run_id, client_request_id, revision, status, input_json, provenance_json, orchestration_id, root_member_id, budget_json,\n result_json, error_json, cleanup_json, created_at, updated_at, completed_at)\n VALUES (?, ?, 0, 'queued', ?, ?, ?, ?, ?, NULL, NULL, NULL, ?, ?, NULL)").run(n,e.clientRequestId,ym(e.input),ym(e.provenance),e.orchestrationId,i,ym(e.budget),s,s),this.client.prepare("INSERT INTO na_agent_run_members\n (member_id, run_id, client_request_id, agent_id, parent_member_id, instance_id, ai_session_id, role, depth, status,\n input_json, execution_snapshot_json, result_json, error_json, created_at, updated_at, completed_at)\n VALUES (?, ?, ?, ?, NULL, ?, ?, 'root', 0, 'queued', ?, ?, NULL, NULL, ?, ?, NULL)").run(i,n,e.clientRequestId,e.root.agentId,e.root.instanceId,e.root.aiSessionId??null,ym(e.root.input??e.input),ym(e.root.executionSnapshot),s,s),this.require(n)})}list(){return this.client.prepare("SELECT run_id FROM na_agent_runs ORDER BY created_at DESC, run_id DESC").all().map(e=>this.require(String(e.run_id)))}get(e){const t=this.client.prepare("SELECT * FROM na_agent_runs WHERE run_id = ?").get(e);return t?this.runFromRow(t):void 0}getByClientRequestId(e){const t=this.client.prepare("SELECT * FROM na_agent_runs WHERE client_request_id = ?").get(e);return t?this.runFromRow(t):void 0}addMember(e){return lp(this.client,()=>{const t=this.require(e.runId);if(mm.has(t.status))throw _m("AGENT_RUN_TERMINAL","A terminal run cannot accept another member.",409,{runId:e.runId,status:t.status});const n=this.getMember(e.runId,e.parentMemberId);if(!n)throw _m("AGENT_RUN_PARENT_MEMBER_NOT_FOUND","The parent member does not belong to this run.",404,{runId:e.runId,parentMemberId:e.parentMemberId});const i=this.client.prepare("SELECT * FROM na_agent_run_members WHERE run_id = ? AND client_request_id = ?").get(e.runId,e.clientRequestId);if(i){const t=this.memberFromRow(i);if(t.parentMemberId===e.parentMemberId&&t.agentId===e.agentId&&t.instanceId===e.instanceId&&b.isDeepStrictEqual(t.input,e.input)&&b.isDeepStrictEqual(t.executionSnapshot,e.executionSnapshot))return t;throw _m("AGENT_RUN_MEMBER_IDEMPOTENCY_CONFLICT","The member client request id is already associated with another invocation.",409,{runId:e.runId,clientRequestId:e.clientRequestId,memberId:t.memberId})}if(Number(this.client.prepare("SELECT COUNT(*) AS count FROM na_agent_run_members WHERE run_id = ?").get(e.runId).count)>=t.budget.maxMembers)throw _m("AGENT_RUN_MEMBER_BUDGET_EXCEEDED","The run member budget is exhausted.",409,{runId:e.runId,maxMembers:t.budget.maxMembers});const s=n.depth+1;if(s>t.budget.maxDepth)throw _m("AGENT_RUN_DEPTH_BUDGET_EXCEEDED","The run call depth budget is exhausted.",409,{runId:e.runId,maxDepth:t.budget.maxDepth,requestedDepth:s});Em(e.instanceId,e.executionSnapshot);const r=fm("member"),o=gm(e.timestamp);return this.client.prepare("INSERT INTO na_agent_run_members\n (member_id, run_id, client_request_id, agent_id, parent_member_id, instance_id, ai_session_id, role, depth, status,\n input_json, execution_snapshot_json, result_json, error_json, created_at, updated_at, completed_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, 'callee', ?, 'queued', ?, ?, NULL, NULL, ?, ?, NULL)").run(r,e.runId,e.clientRequestId,e.agentId,e.parentMemberId,e.instanceId,e.aiSessionId??null,s,ym(e.input),ym(e.executionSnapshot),o,o),this.bumpRevision(e.runId,o),this.requireMember(e.runId,r)})}getMember(e,t){const n=this.client.prepare("SELECT * FROM na_agent_run_members WHERE run_id = ? AND member_id = ?").get(e,t);return n?this.memberFromRow(n):void 0}transitionRun(e,t){return lp(this.client,()=>{const n=this.require(e);this.assertTransition(n.status,t.status,{runId:e});const i=gm(t.timestamp),s="result"in t?t.result??void 0:n.result,r="resultDelivery"in t?t.resultDelivery??void 0:n.resultDelivery,o="error"in t?t.error??void 0:n.error,a="cleanup"in t?t.cleanup??void 0:n.cleanup,c=mm.has(t.status)?n.completedAt??i:void 0;return t.status!==n.status||ym(s??null)!==ym(n.result??null)||ym(r??null)!==ym(n.resultDelivery??null)||ym(o??null)!==ym(n.error??null)||ym(a??null)!==ym(n.cleanup??null)?(this.client.prepare("UPDATE na_agent_runs SET status = ?, revision = revision + 1,\n result_json = ?, result_delivery_json = ?, error_json = ?, cleanup_json = ?, updated_at = ?, completed_at = ? WHERE run_id = ?").run(t.status,s?ym(s):null,r?ym(r):null,o?ym(o):null,a?ym(a):null,i,c??null,e),this.require(e)):n})}transitionMember(e,t,n){return lp(this.client,()=>{const i=this.requireMember(e,t);this.assertTransition(i.status,n.status,{runId:e,memberId:t});const s=gm(n.timestamp),r="result"in n?n.result??void 0:i.result,o="error"in n?n.error??void 0:i.error,a="aiSessionId"in n?n.aiSessionId??void 0:i.aiSessionId,c=mm.has(n.status)?i.completedAt??s:void 0;return n.status!==i.status||ym(r??null)!==ym(i.result??null)||ym(o??null)!==ym(i.error??null)||a!==i.aiSessionId?(this.client.prepare("UPDATE na_agent_run_members SET status = ?, result_json = ?, error_json = ?,\n ai_session_id = ?, updated_at = ?, completed_at = ? WHERE run_id = ? AND member_id = ?").run(n.status,r?ym(r):null,o?ym(o):null,a??null,s,c??null,e,t),this.bumpRevision(e,s),this.requireMember(e,t)):i})}appendTimeline(e){return lp(this.client,()=>{if(this.require(e.runId),e.memberId&&!this.getMember(e.runId,e.memberId))throw _m("AGENT_RUN_TIMELINE_MEMBER_NOT_FOUND","The timeline member does not belong to this run.",404,{runId:e.runId,memberId:e.memberId});const t=Number(this.client.prepare("SELECT COALESCE(MAX(sequence), 0) + 1 AS sequence FROM na_agent_run_timeline WHERE run_id = ?").get(e.runId).sequence),n=gm(e.timestamp);this.client.prepare("INSERT INTO na_agent_run_timeline\n (run_id, sequence, timestamp, kind, member_id, data_json) VALUES (?, ?, ?, ?, ?, ?)").run(e.runId,t,n,e.kind,e.memberId??null,ym(e.data??{})),this.bumpRevision(e.runId,n);const i=this.client.prepare("SELECT * FROM na_agent_run_timeline WHERE run_id = ? AND sequence = ?").get(e.runId,t);return this.timelineFromRow(i)})}bumpRevision(e,t){this.client.prepare("UPDATE na_agent_runs SET revision = revision + 1, updated_at = ? WHERE run_id = ?").run(t,e)}assertTransition(e,t,n){if(!function(e,t){return e===t||hm[e].includes(t)}(e,t))throw _m("AGENT_RUN_STATUS_TRANSITION_INVALID",`Cannot transition Agent Run status from ${e} to ${t}.`,409,{...n,from:e,to:t})}require(e){const t=this.get(e);if(!t)throw _m("AGENT_RUN_NOT_FOUND","Agent Run was not found.",404,{runId:e});return t}requireMember(e,t){const n=this.getMember(e,t);if(!n)throw _m("AGENT_RUN_MEMBER_NOT_FOUND","Agent Run member was not found.",404,{runId:e,memberId:t});return n}runFromRow(e){const t=String(e.run_id),n=this.client.prepare("SELECT * FROM na_agent_run_members WHERE run_id = ? ORDER BY created_at, member_id").all(t).map(e=>this.memberFromRow(e)),i=this.client.prepare("SELECT * FROM na_agent_run_timeline WHERE run_id = ? ORDER BY sequence").all(t).map(e=>this.timelineFromRow(e)),s=null==e.orchestration_id||0===String(e.orchestration_id).length?(()=>{const t=n.find(t=>t.memberId===String(e.root_member_id));return t?yp(t.agentId):void 0})():String(e.orchestration_id);try{return r={runId:t,clientRequestId:e.client_request_id,revision:e.revision,status:e.status,input:null==e.input_json?void 0:Im(e.input_json),provenance:Im(e.provenance_json),orchestrationId:s,rootMemberId:e.root_member_id,budget:Im(e.budget_json),result:null==e.result_json?void 0:Im(e.result_json),resultDelivery:null==e.result_delivery_json?void 0:Im(e.result_delivery_json),error:null==e.error_json?void 0:Im(e.error_json),cleanup:null==e.cleanup_json?void 0:Im(e.cleanup_json),members:n,timeline:i,createdAt:e.created_at,updatedAt:e.updated_at,completedAt:e.completed_at??void 0},lm.parse(r)}catch(e){throw _m("NODE_AGENT_AGENT_RUN_INVALID","Stored Agent Run cannot be parsed with the current model.",500,{runId:t,cause:e instanceof Error?e.message:String(e)})}var r}memberFromRow(e){try{return t={memberId:e.member_id,runId:e.run_id,agentId:e.agent_id,parentMemberId:e.parent_member_id??void 0,instanceId:e.instance_id,aiSessionId:e.ai_session_id??void 0,role:e.role,depth:e.depth,status:e.status,input:null==e.input_json?void 0:Im(e.input_json),executionSnapshot:Im(e.execution_snapshot_json),result:null==e.result_json?void 0:Im(e.result_json),error:null==e.error_json?void 0:Im(e.error_json),createdAt:e.created_at,updatedAt:e.updated_at,completedAt:e.completed_at??void 0},cm.parse(t)}catch(t){throw _m("NODE_AGENT_AGENT_RUN_MEMBER_INVALID","Stored Agent Run member cannot be parsed with the current model.",500,{runId:e.run_id,memberId:e.member_id,cause:t instanceof Error?t.message:String(t)})}var t}timelineFromRow(e){try{return t={runId:e.run_id,sequence:e.sequence,timestamp:e.timestamp,kind:e.kind,memberId:e.member_id??void 0,data:Im(e.data_json)},dm.parse(t)}catch(t){throw _m("NODE_AGENT_AGENT_RUN_TIMELINE_INVALID","Stored Agent Run timeline entry cannot be parsed with the current model.",500,{runId:e.run_id,sequence:e.sequence,cause:t instanceof Error?t.message:String(t)})}var t}}const Tm=new Set(["id","name","revision","created_at","updated_at"]),bm=/^[a-f0-9]{64}$/;function wm(e){const t=zp(e);return d.createHash("sha256").update((n=[e.name,t.agentIds,t.edges],JSON.stringify(n??null))).digest("hex");var n}class Sm{client;diagnostic;constructor(e){this.client=e}setDiagnostic(e){this.diagnostic=e}transaction(e){return lp(this.client,e)}afterCommit(e){up(this.client,e)}list(){return this.client.prepare("SELECT * FROM na_agent_orchestrations ORDER BY name COLLATE NOCASE ASC, id ASC").all().map(e=>this.orchestrationFromRow(e))}get(e){const t=this.client.prepare("SELECT * FROM na_agent_orchestrations WHERE id = ?").get(e);return t?this.orchestrationFromRow(t):void 0}idsReferencingAgent(e){return this.client.prepare("SELECT DISTINCT orchestration_id FROM na_agent_orchestration_agents WHERE agent_id = ? ORDER BY orchestration_id").all(e).map(e=>String(e.orchestration_id))}insert(e,t){return lp(this.client,()=>{const n=Nm(e);return this.client.prepare("INSERT INTO na_agent_orchestrations (id, name, revision, created_at, updated_at)\n VALUES (?, ?, ?, ?, ?)").run(e.id,n.name,wm(n),t,t),this.replaceGraph(e.id,n,t),this.requireOrchestration(e.id)})}update(e,t,n,i){return lp(this.client,()=>{const s=this.get(e);if(!s)return{status:"missing"};if(s.revision!==t)return{status:"revision-conflict",orchestration:s};const r=Nm(n);return this.client.prepare("UPDATE na_agent_orchestrations SET name = ?, revision = ?, updated_at = ? WHERE id = ?").run(r.name,wm(r),i,e),this.replaceGraph(e,r,i),{status:"updated",orchestration:this.requireOrchestration(e)}})}delete(e){return lp(this.client,()=>Number(this.client.prepare("DELETE FROM na_agent_orchestrations WHERE id = ?").run(e).changes)>0)}deleteMany(e){e.length&&lp(this.client,()=>{const t=this.client.prepare("DELETE FROM na_agent_orchestrations WHERE id = ?");for(const n of[...new Set(e)])t.run(n)})}replaceGraph(e,t,n){this.client.prepare("DELETE FROM na_agent_orchestration_agents WHERE orchestration_id = ?").run(e),this.client.prepare("DELETE FROM na_agent_orchestration_edges WHERE orchestration_id = ?").run(e);const i=this.client.prepare("INSERT INTO na_agent_orchestration_agents (orchestration_id, agent_id, created_at) VALUES (?, ?, ?)");for(const s of t.agentIds)i.run(e,s,n);const s=this.client.prepare("INSERT INTO na_agent_orchestration_edges (orchestration_id, from_agent_id, to_agent_id, created_at) VALUES (?, ?, ?, ?)");for(const i of t.edges)s.run(e,i.fromAgentId,i.toAgentId,n)}requireOrchestration(e){const t=this.get(e);if(!t)throw Object.assign(new Error(`Agent orchestration ${e} was not found after the write.`),{code:"AGENT_ORCHESTRATION_NOT_FOUND",statusCode:404});return t}orchestrationFromRow(e){const t=String(e.id),n=Object.keys(e).filter(e=>!Tm.has(e));n.length&&this.diagnostic?.("Agent orchestration row contains unknown columns; they are ignored on read.",{orchestrationId:t,columns:n});const i=this.client.prepare("SELECT agent_id FROM na_agent_orchestration_agents WHERE orchestration_id = ? ORDER BY agent_id").all(t).map(e=>String(e.agent_id)),s=this.client.prepare("SELECT from_agent_id, to_agent_id FROM na_agent_orchestration_edges WHERE orchestration_id = ? ORDER BY from_agent_id, to_agent_id").all(t).map(e=>({fromAgentId:String(e.from_agent_id),toAgentId:String(e.to_agent_id)})),r=Nm({name:String(e.name),agentIds:i,edges:s}),o=bm.test(String(e.revision))?String(e.revision):wm(r);try{return a={id:t,revision:o,name:r.name,agentIds:r.agentIds,edges:r.edges,createdAt:e.created_at,updatedAt:e.updated_at},xp.parse(a)}catch(e){throw Object.assign(new Error("Stored agent orchestration cannot be parsed with the current model.",{cause:e}),{code:"NODE_AGENT_AGENT_ORCHESTRATION_INVALID",statusCode:500})}var a}}function Nm(e){const t=zp(e);return{name:e.name,agentIds:t.agentIds,edges:t.edges}}const vm=new Set(["story_id","agent_id","orchestration_id","created_at"]);function Om(e){const t=[...new Map(e.map(e=>[`${e.agentId}${e.orchestrationId}`,e])).values()].sort((e,t)=>e.agentId===t.agentId?e.orchestrationId.localeCompare(t.orchestrationId):e.agentId.localeCompare(t.agentId));return d.createHash("sha256").update(JSON.stringify(t.map(e=>[e.agentId,e.orchestrationId]))).digest("hex")}class Rm{client;diagnostic;constructor(e){this.client=e}setDiagnostic(e){this.diagnostic=e}get(e){const t=this.client.prepare("SELECT * FROM na_story_agent_entries WHERE story_id = ? ORDER BY agent_id, orchestration_id").all(e);for(const n of t){const t=Object.keys(n).filter(e=>!vm.has(e));t.length&&this.diagnostic?.("Story Agent entry row contains unknown columns; they are ignored on read.",{storyId:e,agentId:n.agent_id,columns:t})}const n=t.map(e=>({agentId:String(e.agent_id),orchestrationId:String(e.orchestration_id)}));return{storyId:e,revision:Om(n),entries:n}}replace(e,t,n=(new Date).toISOString()){return lp(this.client,()=>{const i=[...new Map(t.map(e=>[`${e.agentId}${e.orchestrationId}`,e])).values()].sort((e,t)=>e.agentId===t.agentId?e.orchestrationId.localeCompare(t.orchestrationId):e.agentId.localeCompare(t.agentId));this.client.prepare("DELETE FROM na_story_agent_entries WHERE story_id = ?").run(e);const s=this.client.prepare("INSERT INTO na_story_agent_entries (story_id, agent_id, orchestration_id, created_at) VALUES (?, ?, ?, ?)");for(const t of i)s.run(e,t.agentId,t.orchestrationId,n);return this.get(e)})}}function zm(e){return JSON.stringify(e??{})}function xm(e){try{const t=JSON.parse(String(e));return t&&"object"==typeof t&&!Array.isArray(t)?t:{}}catch{return{}}}function Cm(e,t,n){return Object.assign(new Error(t),{code:e,statusCode:409,...n?{details:n}:{}})}class km{client;constructor(e){this.client=e}ensureSharedSpace(e){const t=this.getSharedSpace(e.runId);if(t){if(t.runtimeId!==e.runtimeId||t.generationId!==e.generationId||t.quotaBytes!==e.quotaBytes)throw Cm("AGENT_RUN_SHARED_SPACE_IDENTITY_MISMATCH","The existing shared space has different runtime ownership.",{runId:e.runId});return t}const n=e.timestamp??(new Date).toISOString();return this.client.prepare("INSERT INTO na_agent_run_shared_spaces\n (run_id, runtime_id, generation_id, state, quota_bytes, usage_bytes, diagnostics_json, created_at, updated_at)\n VALUES (?, ?, ?, 'preparing', ?, 0, '{}', ?, ?)").run(e.runId,e.runtimeId,e.generationId,e.quotaBytes,n,n),this.getSharedSpace(e.runId)}getSharedSpace(e){const t=this.client.prepare("SELECT * FROM na_agent_run_shared_spaces WHERE run_id = ?").get(e);return t?this.sharedSpaceFromRow(t):void 0}listSharedSpaces(e={}){const t=[],n=[];e.runtimeId&&(t.push("runtime_id = ?"),n.push(e.runtimeId)),e.expiredBefore&&(t.push("expires_at IS NOT NULL AND expires_at <= ?"),n.push(e.expiredBefore));const i=t.length?` WHERE ${t.join(" AND ")}`:"";return this.client.prepare(`SELECT * FROM na_agent_run_shared_spaces${i} ORDER BY updated_at, run_id`).all(...n).map(e=>this.sharedSpaceFromRow(e))}runtimeSharedSpaceUsage(e,t){const n=t?this.client.prepare("SELECT COALESCE(SUM(usage_bytes), 0) AS usage FROM na_agent_run_shared_spaces WHERE runtime_id = ? AND run_id != ? AND state NOT IN ('expired','manual-intervention')").get(e,t):this.client.prepare("SELECT COALESCE(SUM(usage_bytes), 0) AS usage FROM na_agent_run_shared_spaces WHERE runtime_id = ? AND state NOT IN ('expired','manual-intervention')").get(e);return Number(n?.usage??0)}updateSharedSpace(e,t){const n=this.getSharedSpace(e);if(!n)throw Cm("AGENT_RUN_SHARED_SPACE_NOT_FOUND","The Agent Run shared space was not found.",{runId:e});const i=t.timestamp??(new Date).toISOString();return this.client.prepare("UPDATE na_agent_run_shared_spaces SET state = ?, usage_bytes = ?, expires_at = ?,\n diagnostics_json = ?, updated_at = ? WHERE run_id = ?").run(t.state??n.state,t.usageBytes??n.usageBytes,null===t.expiresAt?null:t.expiresAt??n.expiresAt??null,zm(t.diagnostics??n.diagnostics),i,e),this.getSharedSpace(e)}register(e){const t=this.client.prepare("SELECT * FROM na_agent_run_resources WHERE run_id = ? AND kind = ? AND backend_identity = ?").get(e.runId,e.kind,e.backendIdentity);if(t){const n=this.resourceFromRow(t);if(n.memberId!==e.memberId||n.instanceId!==e.instanceId||n.runtimeId!==e.runtimeId||n.generationId!==e.generationId)throw Cm("AGENT_RUN_RESOURCE_IDENTITY_MISMATCH","The existing runtime resource has different ownership.",{resourceId:n.resourceId});return n}const n=e.timestamp??(new Date).toISOString(),i=`resource_${d.randomBytes(10).toString("hex")}`;return this.client.prepare("INSERT INTO na_agent_run_resources\n (resource_id, run_id, member_id, instance_id, runtime_id, kind, generation_id, backend_identity,\n phase, cleanup_attempts, metadata_json, created_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'preparing', 0, ?, ?, ?)").run(i,e.runId,e.memberId??null,e.instanceId??null,e.runtimeId,e.kind,e.generationId,e.backendIdentity,zm(e.metadata),n,n),this.get(i)}get(e){const t=this.client.prepare("SELECT * FROM na_agent_run_resources WHERE resource_id = ?").get(e);return t?this.resourceFromRow(t):void 0}listForRun(e){return this.client.prepare("SELECT * FROM na_agent_run_resources WHERE run_id = ? ORDER BY created_at, resource_id").all(e).map(e=>this.resourceFromRow(e))}listActiveForInstance(e){return this.client.prepare("SELECT * FROM na_agent_run_resources WHERE instance_id = ?\n AND phase NOT IN ('deleted','manual-intervention') ORDER BY created_at, resource_id").all(e).map(e=>this.resourceFromRow(e))}transition(e,t,n={}){const i=this.get(e);if(!i)throw Cm("AGENT_RUN_RESOURCE_NOT_FOUND","The Agent Run resource was not found.",{resourceId:e});return this.client.prepare("UPDATE na_agent_run_resources SET phase = ?, cleanup_attempts = ?, metadata_json = ?,\n updated_at = ? WHERE resource_id = ?").run(t,i.cleanupAttempts+(n.incrementCleanupAttempts?1:0),zm(n.metadata??i.metadata),n.timestamp??(new Date).toISOString(),e),this.get(e)}sharedSpaceFromRow(e){return{runId:String(e.run_id),runtimeId:String(e.runtime_id),generationId:String(e.generation_id),state:e.state,quotaBytes:Number(e.quota_bytes),usageBytes:Number(e.usage_bytes),expiresAt:null==e.expires_at?void 0:String(e.expires_at),diagnostics:xm(e.diagnostics_json),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}resourceFromRow(e){return{resourceId:String(e.resource_id),runId:String(e.run_id),memberId:null==e.member_id?void 0:String(e.member_id),instanceId:null==e.instance_id?void 0:String(e.instance_id),runtimeId:String(e.runtime_id),kind:e.kind,generationId:String(e.generation_id),backendIdentity:String(e.backend_identity),phase:e.phase,cleanupAttempts:Number(e.cleanup_attempts),metadata:xm(e.metadata_json),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}}const Dm=new Set(["id","name","description","appended_prompt","target_instance_id","cwd_folder_id","provider_id","model_entity_id","model_name","model_upstream_name","reasoning_effort","permission_mode","execution_policy_json","revision","created_at","updated_at"]);function Lm(e){return JSON.stringify(e??null)}function Pm(e){try{return JSON.parse(String(e))}catch{return}}function Mm(e){return d.createHash("sha256").update(Lm([e.name,e.description,e.appendedPrompt,e.targetInstanceId,e.cwdFolderId,e.providerId,e.modelEntityId??null,e.modelName??null,e.modelUpstreamName??null,e.reasoningEffort??null,e.permissionMode??null,e.executionPolicy.workspaceMaterializer,e.executionPolicy.processSandbox])).digest("hex")}class jm{client;diagnostic;constructor(e){this.client=e}setDiagnostic(e){this.diagnostic=e}transaction(e){return lp(this.client,e)}afterCommit(e){up(this.client,e)}list(){return this.client.prepare("SELECT * FROM na_agent_definitions ORDER BY name COLLATE NOCASE ASC, id ASC").all().map(e=>this.definitionFromRow(e))}get(e){const t=this.client.prepare("SELECT * FROM na_agent_definitions WHERE id = ?").get(e);if(t)return this.definitionFromRow(t)}insert(e,t){return lp(this.client,()=>{const n=Mm(e);return this.client.prepare("INSERT INTO na_agent_definitions\n (id, name, description, appended_prompt, target_instance_id, cwd_folder_id, provider_id,\n model_entity_id, model_name, model_upstream_name, reasoning_effort, permission_mode, execution_policy_json,\n revision, created_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(e.id,e.name,e.description,e.appendedPrompt,e.targetInstanceId,e.cwdFolderId,e.providerId,e.modelEntityId??null,e.modelName??null,e.modelUpstreamName??null,e.reasoningEffort??null,e.permissionMode??null,Lm(e.executionPolicy),n,t,t),this.requireDefinition(e.id)})}update(e,t,n,i){return lp(this.client,()=>{const s=this.get(e);if(!s)return{status:"missing"};if(s.revision!==t)return{status:"revision-conflict",definition:s};const r=Mm(n);return this.client.prepare("UPDATE na_agent_definitions SET\n name = ?, description = ?, appended_prompt = ?, target_instance_id = ?, cwd_folder_id = ?, provider_id = ?,\n model_entity_id = ?, model_name = ?, model_upstream_name = ?, reasoning_effort = ?, permission_mode = ?, execution_policy_json = ?,\n revision = ?, updated_at = ?\n WHERE id = ?").run(n.name,n.description,n.appendedPrompt,n.targetInstanceId,n.cwdFolderId,n.providerId,n.modelEntityId??null,n.modelName??null,n.modelUpstreamName??null,n.reasoningEffort??null,n.permissionMode??null,Lm(n.executionPolicy),r,i,e),{status:"updated",definition:this.requireDefinition(e)}})}delete(e){return lp(this.client,()=>Number(this.client.prepare("DELETE FROM na_agent_definitions WHERE id = ?").run(e).changes)>0)}requireDefinition(e){const t=this.get(e);if(!t)throw Object.assign(new Error(`Agent definition ${e} was not found after the write.`),{code:"AGENT_DEFINITION_NOT_FOUND",statusCode:404});return t}definitionFromRow(e){const t=Object.keys(e).filter(e=>!Dm.has(e));return t.length&&this.diagnostic?.("Agent definition row contains unknown columns; they are ignored on read.",{agentId:e.id,columns:t}),function(e){try{return function(e){return ap.parse(e)}(e)}catch(e){throw Object.assign(new Error("Stored agent definition cannot be parsed with the current model.",{cause:e}),{code:"NODE_AGENT_AGENT_DEFINITION_INVALID",statusCode:500})}}({id:e.id,name:e.name,description:e.description??"",appendedPrompt:e.appended_prompt??"",targetInstanceId:e.target_instance_id,cwdFolderId:e.cwd_folder_id,providerId:e.provider_id,modelEntityId:e.model_entity_id??void 0,modelName:e.model_name??void 0,modelUpstreamName:e.model_upstream_name??void 0,reasoningEffort:e.reasoning_effort??void 0,permissionMode:e.permission_mode??void 0,executionPolicy:Pm(e.execution_policy_json),revision:e.revision,createdAt:e.created_at,updatedAt:e.updated_at})}}class Um{client;constructor(e){this.client=e}readIdentity(){const e=this.client.prepare("SELECT node_id, created_at, updated_at FROM na_node_identity WHERE singleton_key = 1").get();if(!e)return;const t=this.client.prepare("SELECT * FROM na_control_plane_pairings ORDER BY updated_at, key_id").all().map(e=>({id:String(e.control_plane_id),keyId:String(e.key_id),...e.name?{name:String(e.name)}:{},secret:String(e.secret),pairedAt:String(e.paired_at),...e.revoked_at?{revokedAt:String(e.revoked_at)}:{},updatedAt:String(e.updated_at)})),n=this.client.prepare("SELECT * FROM na_control_plane_connections ORDER BY updated_at, id").all().map(e=>({id:String(e.id),pairingKeyId:String(e.pairing_key_id),...e.name?{name:String(e.name)}:{},url:String(e.normalized_url),enabled:Boolean(e.enabled),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}));return{nodeId:String(e.node_id),createdAt:String(e.created_at),updatedAt:String(e.updated_at),controlPlanePairings:t,controlPlaneConnections:n}}writeIdentity(e){return this.transaction(()=>{const t=this.readIdentity();if(t&&t.nodeId!==e.nodeId)throw n=`Stored node identity ${t.nodeId} does not match ${e.nodeId}.`,Object.assign(new Error(n),{code:"NODE_AGENT_IDENTITY_MISMATCH",statusCode:409});var n;this.client.prepare("INSERT INTO na_node_identity (singleton_key, node_id, created_at, updated_at) VALUES (1, ?, ?, ?)\n ON CONFLICT(singleton_key) DO UPDATE SET updated_at=excluded.updated_at").run(e.nodeId,e.createdAt,e.updatedAt);const i=(e.controlPlanePairings||[]).map(e=>e.keyId),s=(e.controlPlaneConnections||[]).map(e=>e.id);$m(this.client,"na_control_plane_connections","id",s),$m(this.client,"na_control_plane_pairings","key_id",i);const r=this.client.prepare("INSERT INTO na_control_plane_pairings\n (key_id, control_plane_id, name, secret, paired_at, revoked_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(key_id) DO UPDATE SET control_plane_id=excluded.control_plane_id, name=excluded.name,\n secret=excluded.secret, paired_at=excluded.paired_at, revoked_at=excluded.revoked_at, updated_at=excluded.updated_at");for(const t of e.controlPlanePairings||[])r.run(t.keyId,t.id,t.name??null,t.secret,t.pairedAt,t.revokedAt??null,t.updatedAt);const o=this.client.prepare("INSERT INTO na_control_plane_connections\n (id, pairing_key_id, name, normalized_url, enabled, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(id) DO UPDATE SET pairing_key_id=excluded.pairing_key_id, name=excluded.name,\n normalized_url=excluded.normalized_url, enabled=excluded.enabled, updated_at=excluded.updated_at");for(const t of e.controlPlaneConnections||[])o.run(t.id,t.pairingKeyId,t.name??null,Fm(t.url),t.enabled?1:0,t.createdAt,t.updatedAt);return this.readIdentity()})}listOperations(e){return(e?.length?this.client.prepare(`SELECT * FROM na_control_plane_connection_operations WHERE phase IN (${e.map(()=>"?").join(",")}) ORDER BY created_at`).all(...e):this.client.prepare("SELECT * FROM na_control_plane_connection_operations ORDER BY created_at").all()).map(Hm)}putOperation(e){return this.client.prepare("INSERT INTO na_control_plane_connection_operations\n (id, kind, phase, requested_json, pairing_key_id, connection_id, replaced_connections_json, error_json, created_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(id) DO UPDATE SET phase=excluded.phase, pairing_key_id=excluded.pairing_key_id,\n connection_id=excluded.connection_id, replaced_connections_json=excluded.replaced_connections_json,\n error_json=excluded.error_json, updated_at=excluded.updated_at").run(e.id,e.kind,e.phase,JSON.stringify(e.requested),e.pairingKeyId??null,e.connectionId??null,JSON.stringify(e.replacedConnections),e.error?JSON.stringify(e.error):null,e.createdAt,e.updatedAt),e}deleteOperation(e){return Number(this.client.prepare("DELETE FROM na_control_plane_connection_operations WHERE id = ?").run(e).changes)>0}transaction(e){if(this.client.isTransaction)return e();this.client.exec("BEGIN IMMEDIATE");try{const t=e();return this.client.exec("COMMIT"),t}catch(e){throw this.client.exec("ROLLBACK"),e}}}function Fm(e){return new URL(e).toString().replace(/\/$/,"")}function $m(e,t,n,i){i.length?e.prepare(`DELETE FROM ${t} WHERE ${n} NOT IN (${i.map(()=>"?").join(",")})`).run(...i):e.exec(`DELETE FROM ${t}`)}function Hm(e){return{id:String(e.id),kind:String(e.kind),phase:e.phase,requested:JSON.parse(String(e.requested_json)),...e.pairing_key_id?{pairingKeyId:String(e.pairing_key_id)}:{},...e.connection_id?{connectionId:String(e.connection_id)}:{},replacedConnections:JSON.parse(String(e.replaced_connections_json)),...e.error_json?{error:JSON.parse(String(e.error_json))}:{},createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}class Bm{client;constructor(e){this.client=e}listPayloads(){return this.client.prepare("SELECT * FROM na_git_credential_payloads ORDER BY credential_id").all().map(Vm)}getPayload(e){const t=this.client.prepare("SELECT * FROM na_git_credential_payloads WHERE credential_id = ?").get(e);return t?Vm(t):void 0}putPayload(e){const t=Ii.parse(e.payload);return this.client.prepare("INSERT INTO na_git_credential_payloads\n (credential_id, revision, public_json, secret_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)\n ON CONFLICT(credential_id) DO UPDATE SET revision=excluded.revision, public_json=excluded.public_json,\n secret_json=excluded.secret_json, updated_at=excluded.updated_at").run(e.id,t.credential.revision,JSON.stringify(t.credential),JSON.stringify(t.secret),e.createdAt,e.updatedAt),{...e,payload:t}}deletePayload(e){return Number(this.client.prepare("DELETE FROM na_git_credential_payloads WHERE credential_id = ?").run(e).changes)>0}collectUnreferencedPayloads(){return Number(this.client.prepare("DELETE FROM na_git_credential_payloads\n WHERE NOT EXISTS (SELECT 1 FROM na_git_authorization_members m WHERE m.credential_id = na_git_credential_payloads.credential_id)").run().changes)}listAuthorizations(){return this.client.prepare("SELECT * FROM na_git_authorization_sets ORDER BY instance_id").all().map(e=>this.authorizationFromRow(e))}getAuthorization(e){const t=this.client.prepare("SELECT * FROM na_git_authorization_sets WHERE instance_id = ?").get(e);return t?this.authorizationFromRow(t):void 0}putAuthorization(e){const t=_i.parse({instanceId:e.instanceId,generation:e.generation,credentialIds:e.credentialIds,updatedAt:e.updatedAt});return this.transaction(()=>{this.client.prepare("INSERT INTO na_git_authorization_sets (instance_id, generation, created_at, updated_at)\n VALUES (?, ?, ?, ?) ON CONFLICT(instance_id) DO UPDATE SET generation=excluded.generation, updated_at=excluded.updated_at").run(t.instanceId,t.generation,e.createdAt,t.updatedAt),this.client.prepare("DELETE FROM na_git_authorization_members WHERE instance_id = ?").run(t.instanceId);const n=this.client.prepare("INSERT INTO na_git_authorization_members (instance_id, credential_id, display_order) VALUES (?, ?, ?)");for(const[e,i]of t.credentialIds.entries())n.run(t.instanceId,i,e);return this.getAuthorization(t.instanceId)})}putAuthorizationCas(e){const t=_i.parse({instanceId:e.instanceId,generation:e.generation,credentialIds:e.credentialIds,updatedAt:e.updatedAt});return this.transaction(()=>{const n=this.getAuthorization(t.instanceId);if(n&&n.generation>t.generation)throw qm("GIT_CREDENTIAL_REVISION_STALE",`Refusing stale authorization set revision for ${t.instanceId}.`);if(n&&n.generation===t.generation){if(JSON.stringify(n.credentialIds)!==JSON.stringify(t.credentialIds))throw qm("GIT_CREDENTIAL_REVISION_CONFLICT",`Refusing conflicting authorization set revision for ${t.instanceId}.`);return n}for(const e of t.credentialIds)if(!this.getPayload(e))throw qm("GIT_CREDENTIAL_PAYLOAD_MISSING",`Credential payload ${e} is not deployed.`);if(n){const e=this.client.prepare("UPDATE na_git_authorization_sets\n SET generation = ?, updated_at = ? WHERE instance_id = ? AND generation < ?").run(t.generation,t.updatedAt,t.instanceId,t.generation).changes;if(1!==Number(e))throw qm("GIT_CREDENTIAL_REVISION_STALE",`Authorization set ${t.instanceId} changed concurrently.`)}else this.client.prepare("INSERT INTO na_git_authorization_sets (instance_id, generation, created_at, updated_at)\n VALUES (?, ?, ?, ?)").run(t.instanceId,t.generation,e.createdAt,t.updatedAt);this.client.prepare("DELETE FROM na_git_authorization_members WHERE instance_id = ?").run(t.instanceId);const i=this.client.prepare("INSERT INTO na_git_authorization_members (instance_id, credential_id, display_order) VALUES (?, ?, ?)");for(const[e,n]of t.credentialIds.entries())i.run(t.instanceId,n,e);return this.getAuthorization(t.instanceId)})}deleteAuthorization(e){return Number(this.client.prepare("DELETE FROM na_git_authorization_sets WHERE instance_id = ?").run(e).changes)>0}listProvisioning(){return this.client.prepare("SELECT * FROM na_git_workspace_provisioning ORDER BY instance_id").all().map(Gm)}getProvisioning(e){const t=this.client.prepare("SELECT * FROM na_git_workspace_provisioning WHERE instance_id = ?").get(e);return t?Gm(t):void 0}putProvisioning(e){const t="pending"===e.status?e.input.operationId:e.operationId;return this.client.prepare("INSERT INTO na_git_workspace_provisioning\n (instance_id, status, operation_id, input_json, created_at, updated_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(instance_id) DO UPDATE SET status=excluded.status, operation_id=excluded.operation_id,\n input_json=excluded.input_json, updated_at=excluded.updated_at, expires_at=excluded.expires_at").run(e.id,e.status,t,"pending"===e.status?JSON.stringify(e.input):null,e.createdAt,e.updatedAt,e.expiresAt),this.getProvisioning(e.id)}deleteProvisioning(e){return Number(this.client.prepare("DELETE FROM na_git_workspace_provisioning WHERE instance_id = ?").run(e).changes)>0}deleteExpiredProvisioning(e){return Number(this.client.prepare("DELETE FROM na_git_workspace_provisioning WHERE expires_at <= ?").run(e).changes)}consumeProvisioning(e,t,n,i){return this.transaction(()=>{const s=this.client.prepare("UPDATE na_git_workspace_provisioning\n SET status = 'consumed', input_json = NULL, updated_at = ?, expires_at = ?\n WHERE instance_id = ? AND operation_id = ? AND status = 'pending'").run(n,i,e,t).changes;if(1===Number(s))return!0;const r=this.getProvisioning(e);return"consumed"===r?.status&&r.operationId===t})}authorizationFromRow(e){const t=this.client.prepare("SELECT credential_id FROM na_git_authorization_members WHERE instance_id = ? ORDER BY display_order").all(String(e.instance_id)).map(e=>String(e.credential_id));return{id:String(e.instance_id),instanceId:String(e.instance_id),generation:Number(e.generation),credentialIds:t,createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}transaction(e){if(this.client.isTransaction)return e();this.client.exec("BEGIN IMMEDIATE");try{const t=e();return this.client.exec("COMMIT"),t}catch(e){throw this.client.exec("ROLLBACK"),e}}}function qm(e,t){return Object.assign(new Error(t),{code:e,statusCode:409})}function Vm(e){return{id:String(e.credential_id),payload:Ii.parse({credential:JSON.parse(String(e.public_json)),secret:JSON.parse(String(e.secret_json))}),createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}function Gm(e){const t={id:String(e.instance_id),createdAt:String(e.created_at),updatedAt:String(e.updated_at),expiresAt:String(e.expires_at)};return"pending"===e.status?{...t,status:"pending",input:vi.parse(JSON.parse(String(e.input_json)))}:{...t,status:"consumed",operationId:String(e.operation_id)}}class Wm{tail=Promise.resolve();accepting=!0;run(e){if(!this.accepting)return Promise.reject(ih("NODE_AGENT_REPOSITORY_QUIESCING","Node Agent storage is shutting down.",503));const t=this.tail.then(e,e);return this.tail=t.then(()=>{},()=>{}),t}async barrier(){await this.tail}stopAccepting(){this.accepting=!1}}function Km(e){const t=e.db,n=new Wm,i=new E.AsyncLocalStorage;let s=!1;const r=()=>{if(s)throw ih("NODE_AGENT_REPOSITORY_CLOSED","Node Agent storage is closed.",503)},o=async e=>(r(),i.getStore()||await n.barrier(),e()),a=async e=>(r(),i.getStore()?e():n.run(e));let c;var d;return c={stories:Ym(t,o,a),actions:Xm(t,o,a),documents:Jm(t,o,a),automations:Qm(t,o,a),runs:Zm(t,o,a),decisions:eh(t,o,a),fileMutations:th(t,o,a),deletionIntents:nh(t,o,a),topology:Ru(e.client),model:Uu(e.client),agents:(d=e.client,{definitions:new jm(d),orchestrations:new Sm(d),runs:new Am(d),storyEntries:new Rm(d),resources:new km(d)}),access:new Um(e.client),git:new Bm(e.client),transaction:async t=>i.getStore()?t(c):a(async()=>{e.client.exec("BEGIN IMMEDIATE");try{const n=await i.run(!0,()=>t(c));return e.client.exec("COMMIT"),n}catch(t){throw e.client.exec("ROLLBACK"),t}}),transactionSync:t=>{if(r(),e.client.isTransaction)return t(c);e.client.exec("BEGIN IMMEDIATE");try{const n=t(c);return e.client.exec("COMMIT"),n}catch(t){throw e.client.exec("ROLLBACK"),t}},stopAccepting(){n.stopAccepting()},async drain(){await n.barrier()},async checkpoint(){await n.barrier(),await e.checkpoint()},async close(){s||(n.stopAccepting(),await n.barrier(),await e.checkpoint(),s=!0,await e.close())}},c}function Ym(e,t,n){return{list:()=>t(()=>e.select().from(mu).orderBy(A.desc(mu.createdAt),A.asc(mu.id))),get:async n=>t(async()=>(await e.select().from(mu).where(A.eq(mu.id,n)).limit(1))[0]),insert:async t=>n(async()=>(await e.insert(mu).values(t),t)),update:async(t,i)=>n(async()=>(await e.update(mu).set(i).where(A.eq(mu.id,t)),(await e.select().from(mu).where(A.eq(mu.id,t)).limit(1))[0])),delete:async t=>n(async()=>Number((await e.delete(mu).where(A.eq(mu.id,t))).changes)>0)}}function Xm(e,t,n){return{list:n=>t(()=>e.select().from(gu).where(A.eq(gu.storyId,n)).orderBy(A.asc(gu.displayOrder),A.asc(gu.id))),replace:async(t,i)=>n(async()=>{const n=i.map(e=>e.id);n.length?await e.delete(gu).where(A.and(A.eq(gu.storyId,t),A.notInArray(gu.id,n))):await e.delete(gu).where(A.eq(gu.storyId,t));for(const t of i)await e.insert(gu).values(t).onConflictDoUpdate({target:[gu.storyId,gu.id],set:{title:t.title,promptTemplate:t.promptTemplate,targetInstanceId:t.targetInstanceId,sessionPreset:t.sessionPreset,displayOrder:t.displayOrder}});return i})}}function Jm(e,t,n){return{list:n=>t(()=>e.select().from(fu).where(A.eq(fu.storyId,n)).orderBy(A.asc(fu.displayOrder),A.asc(fu.storyPath))),get:async(n,i)=>t(async()=>(await e.select().from(fu).where(A.and(A.eq(fu.storyId,n),A.eq(fu.storyPath,i))).limit(1))[0]),page:async(n,i,s)=>t(async()=>{const t=Number((await e.select({value:A.count()}).from(fu).where(A.eq(fu.storyId,n)))[0]?.value??0);return{items:await e.select({title:fu.title,storyPath:fu.storyPath}).from(fu).where(A.eq(fu.storyId,n)).orderBy(A.desc(fu.indexedSequence),A.asc(fu.storyPath)).limit(s).offset((i-1)*s),totalItems:t}}),insert:async t=>n(async()=>(await e.insert(fu).values(t),t)),update:async(t,i,s)=>n(async()=>{await e.update(fu).set(s).where(A.and(A.eq(fu.storyId,t),A.eq(fu.storyPath,i)))}),replacePath:async(t,i,s)=>n(async()=>{await e.delete(fu).where(A.and(A.eq(fu.storyId,t),A.eq(fu.storyPath,i))),await e.insert(fu).values(s)}),reorder:async(t,i)=>n(async()=>{for(const[n,s]of i.entries())await e.update(fu).set({displayOrder:n}).where(A.and(A.eq(fu.storyId,t),A.eq(fu.storyPath,s)))}),delete:async(t,i)=>n(async()=>Number((await e.delete(fu).where(A.and(A.eq(fu.storyId,t),A.eq(fu.storyPath,i)))).changes)>0)}}function Qm(e,t,n){return{list:n=>t(()=>n?e.select().from(yu).where(A.eq(yu.storyId,n)).orderBy(A.asc(yu.createdAt),A.asc(yu.id)):e.select().from(yu).orderBy(A.asc(yu.createdAt),A.asc(yu.id))),get:async n=>t(async()=>(await e.select().from(yu).where(A.eq(yu.id,n)).limit(1))[0]),insert:async t=>n(async()=>(await e.insert(yu).values(t),t)),update:async(t,i)=>n(async()=>(await e.update(yu).set(i).where(A.eq(yu.id,t)),(await e.select().from(yu).where(A.eq(yu.id,t)).limit(1))[0])),referencingActions:async(n,i)=>i.length?t(()=>e.select().from(yu).where(A.and(A.eq(yu.storyId,n),A.inArray(yu.actionId,i)))):[],delete:async t=>n(async()=>Number((await e.delete(yu).where(A.eq(yu.id,t))).changes)>0),deleteForStory:async t=>n(async()=>{await e.delete(yu).where(A.eq(yu.storyId,t))})}}function Zm(e,t,n){const i=["queued","dispatching","running"];return{list:n=>t(()=>e.select().from(Iu).where(A.eq(Iu.automationId,n)).orderBy(A.desc(Iu.queuedAt))),get:async n=>t(async()=>(await e.select().from(Iu).where(A.eq(Iu.id,n)).limit(1))[0]),byExecutionKey:async n=>t(async()=>(await e.select().from(Iu).where(A.eq(Iu.executionKey,n)).limit(1))[0]),pending:()=>t(()=>e.select().from(Iu).where(A.inArray(Iu.status,[...i])).orderBy(A.asc(Iu.queuedAt))),activeForStory:async n=>t(()=>e.select({run:Iu}).from(Iu).innerJoin(yu,A.eq(Iu.automationId,yu.id)).where(A.and(A.eq(yu.storyId,n),A.inArray(Iu.status,[...i]))).then(e=>e.map(e=>e.run))),insert:async t=>n(async()=>(await e.insert(Iu).values(t),t)),update:async(t,i)=>n(async()=>(await e.update(Iu).set(i).where(A.eq(Iu.id,t)),(await e.select().from(Iu).where(A.eq(Iu.id,t)).limit(1))[0])),trimTerminal:async(t,i)=>n(async()=>{const n=await e.select({id:Iu.id}).from(Iu).where(A.and(A.eq(Iu.automationId,t),A.inArray(Iu.status,["completed","failed","skipped"]))).orderBy(A.desc(Iu.queuedAt)).limit(2147483647).offset(i);n.length&&await e.delete(Iu).where(A.inArray(Iu.id,n.map(e=>e.id)))})}}function eh(e,t,n){return{list:n=>t(()=>e.select().from(hu).where(A.eq(hu.storyId,n)).orderBy(A.desc(hu.createdAt),A.asc(hu.id))),listPendingBySession:n=>t(()=>e.select().from(hu).where(A.and(A.eq(hu.sessionId,n),A.eq(hu.status,"pending"))).orderBy(A.asc(hu.createdAt),A.asc(hu.id))),get:async n=>t(async()=>(await e.select().from(hu).where(A.eq(hu.id,n)).limit(1))[0]),bySessionTurn:async(n,i,s)=>t(async()=>(await e.select().from(hu).where(A.and(A.eq(hu.storyId,n),A.eq(hu.sessionId,i),A.eq(hu.turnId,s))).limit(1))[0]),insert:async t=>n(async()=>(await e.insert(hu).values(t),t)),updateIfRevision:async(t,i,s)=>n(async()=>{await e.update(hu).set(s).where(A.and(A.eq(hu.id,t),A.eq(hu.revision,i)));const n=(await e.select().from(hu).where(A.eq(hu.id,t)).limit(1))[0];return n&&n.revision!==i?n:void 0}),update:async(t,i)=>n(async()=>(await e.update(hu).set(i).where(A.eq(hu.id,t)),(await e.select().from(hu).where(A.eq(hu.id,t)).limit(1))[0])),expirePendingForSession:async(t,i,s)=>n(async()=>(await e.update(hu).set({status:"expired",revision:A.sql`${hu.revision} + 1`,expiredReason:i,updatedAt:s}).where(A.and(A.eq(hu.sessionId,t),A.eq(hu.status,"pending"))),e.select().from(hu).where(A.and(A.eq(hu.sessionId,t),A.eq(hu.status,"expired"),A.eq(hu.updatedAt,s)))))}}function th(e,t,n){return{list:()=>t(()=>e.select().from(_u).orderBy(A.asc(_u.createdAt))),get:async n=>t(async()=>(await e.select().from(_u).where(A.eq(_u.id,n)).limit(1))[0]),insert:async t=>n(async()=>(await e.insert(_u).values(t),t)),update:async(t,i)=>n(async()=>{await e.update(_u).set(i).where(A.eq(_u.id,t))}),delete:async t=>n(async()=>{await e.delete(_u).where(A.eq(_u.id,t))})}}function nh(e,t,n){return{list:()=>t(()=>e.select().from(Eu).orderBy(A.asc(Eu.createdAt))),get:async n=>t(async()=>(await e.select().from(Eu).where(A.eq(Eu.storyId,n)).limit(1))[0]),put:async t=>n(async()=>(await e.insert(Eu).values(t).onConflictDoUpdate({target:Eu.storyId,set:{phase:t.phase,trashName:t.trashName,updatedAt:t.updatedAt}}),t)),delete:async t=>n(async()=>{await e.delete(Eu).where(A.eq(Eu.storyId,t))})}}function ih(e,t,n){return Object.assign(new Error(t),{code:e,statusCode:n})}function sh(e,t,n={}){return{id:e,sql:t,checksum:d.createHash("sha256").update(t).digest("hex"),...n.foreignKeysOff?{foreignKeysOff:!0}:{}}}const rh=[sh("0001_story_domain","\nCREATE TABLE na_stories (\n id TEXT PRIMARY KEY NOT NULL, title TEXT NOT NULL, description TEXT,\n created_at TEXT NOT NULL, updated_at TEXT NOT NULL, archived_at TEXT,\n max_idle_ai_sessions INTEGER NOT NULL DEFAULT 5 CHECK(max_idle_ai_sessions BETWEEN 1 AND 50),\n next_document_sequence INTEGER NOT NULL DEFAULT 1 CHECK(next_document_sequence > 0)\n);\nCREATE INDEX na_stories_created_idx ON na_stories(created_at);\nCREATE TABLE na_story_actions (\n story_id TEXT NOT NULL REFERENCES na_stories(id) ON DELETE CASCADE, id TEXT NOT NULL,\n title TEXT NOT NULL, prompt_template TEXT NOT NULL, target_instance_id TEXT,\n session_preset_json TEXT, display_order INTEGER NOT NULL,\n PRIMARY KEY(story_id, id)\n);\nCREATE INDEX na_story_actions_order_idx ON na_story_actions(story_id, display_order, id);\nCREATE TABLE na_story_documents (\n story_id TEXT NOT NULL REFERENCES na_stories(id) ON DELETE CASCADE, story_path TEXT NOT NULL,\n title TEXT NOT NULL, indexed_sequence INTEGER NOT NULL CHECK(indexed_sequence > 0), display_order INTEGER NOT NULL,\n PRIMARY KEY(story_id, story_path)\n);\nCREATE UNIQUE INDEX na_story_documents_sequence_uq ON na_story_documents(story_id, indexed_sequence);\nCREATE INDEX na_story_documents_page_idx ON na_story_documents(story_id, indexed_sequence, story_path);\nCREATE INDEX na_story_documents_display_idx ON na_story_documents(story_id, display_order, story_path);\nCREATE TABLE na_story_automations (\n id TEXT PRIMARY KEY NOT NULL, story_id TEXT NOT NULL, action_id TEXT NOT NULL,\n schedule_json TEXT NOT NULL, enabled INTEGER NOT NULL, policy_json TEXT NOT NULL,\n schedule_anchor_at TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL,\n CONSTRAINT na_story_automations_action_fk FOREIGN KEY(story_id, action_id)\n REFERENCES na_story_actions(story_id, id) ON DELETE RESTRICT\n);\nCREATE INDEX na_story_automations_story_idx ON na_story_automations(story_id);\nCREATE INDEX na_story_automations_enabled_idx ON na_story_automations(enabled);\nCREATE TABLE na_story_automation_runs (\n id TEXT PRIMARY KEY NOT NULL, automation_id TEXT NOT NULL REFERENCES na_story_automations(id) ON DELETE CASCADE,\n event_type TEXT NOT NULL CHECK(event_type IN ('manual','schedule')),\n status TEXT NOT NULL CHECK(status IN ('queued','dispatching','running','completed','failed','skipped')),\n scheduled_for TEXT NOT NULL, target_instance_id TEXT NOT NULL, ai_session_id TEXT, error_json TEXT,\n queued_at TEXT NOT NULL, started_at TEXT, completed_at TEXT,\n execution_key TEXT NOT NULL, request_fingerprint TEXT NOT NULL, execution_input_json TEXT NOT NULL\n);\nCREATE UNIQUE INDEX na_story_automation_runs_execution_key_uq ON na_story_automation_runs(execution_key);\nCREATE INDEX na_story_automation_runs_automation_time_idx ON na_story_automation_runs(automation_id, queued_at);\nCREATE INDEX na_story_automation_runs_status_idx ON na_story_automation_runs(status, scheduled_for);\nCREATE TABLE na_story_file_mutations (\n id TEXT PRIMARY KEY NOT NULL, story_id TEXT NOT NULL REFERENCES na_stories(id) ON DELETE RESTRICT,\n operation TEXT NOT NULL CHECK(operation IN ('write','rename','delete')), story_path TEXT NOT NULL,\n next_story_path TEXT, title TEXT, temporary_name TEXT, backup_name TEXT,\n phase TEXT NOT NULL CHECK(phase IN ('receiving','prepared','files-staged','database-committed','cleanup')),\n created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE INDEX na_story_file_mutations_story_idx ON na_story_file_mutations(story_id, created_at);\nCREATE TABLE na_story_deletion_intents (\n story_id TEXT PRIMARY KEY NOT NULL,\n phase TEXT NOT NULL CHECK(phase IN ('prepared','files-staged','database-committed','cleanup')),\n trash_name TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\n"),sh("0002_p0_state_domains","\nCREATE TABLE na_node_identity (\n singleton_key INTEGER PRIMARY KEY NOT NULL DEFAULT 1 CHECK(singleton_key = 1),\n node_id TEXT NOT NULL UNIQUE, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE TABLE na_local_folders (\n id TEXT PRIMARY KEY NOT NULL, node_id TEXT NOT NULL REFERENCES na_node_identity(node_id) ON DELETE RESTRICT ON UPDATE CASCADE,\n name TEXT NOT NULL, path TEXT NOT NULL, labels_json TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL,\n UNIQUE(node_id, path)\n);\nCREATE TABLE na_runtimes (\n id TEXT PRIMARY KEY NOT NULL, node_id TEXT NOT NULL REFERENCES na_node_identity(node_id) ON DELETE RESTRICT ON UPDATE CASCADE,\n name TEXT NOT NULL, type TEXT NOT NULL CHECK(type IN ('docker','kubernetes','local')),\n status TEXT NOT NULL CHECK(status IN ('unknown','online','offline','degraded')), access_strategy TEXT NOT NULL,\n capabilities_json TEXT NOT NULL, labels_json TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE INDEX na_runtimes_node_type_idx ON na_runtimes(node_id, type);\nCREATE TABLE na_instances (\n id TEXT PRIMARY KEY NOT NULL, node_id TEXT NOT NULL REFERENCES na_node_identity(node_id) ON DELETE RESTRICT ON UPDATE CASCADE,\n runtime_id TEXT NOT NULL REFERENCES na_runtimes(id) ON DELETE RESTRICT ON UPDATE CASCADE,\n source_local_folder_id TEXT REFERENCES na_local_folders(id) ON DELETE SET NULL ON UPDATE CASCADE,\n name TEXT NOT NULL, status TEXT NOT NULL, state_revision INTEGER NOT NULL DEFAULT 0 CHECK(state_revision >= 0),\n process_incarnation_id TEXT, registration_credential TEXT, desired_json TEXT NOT NULL,\n created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE INDEX na_instances_runtime_idx ON na_instances(runtime_id);\nCREATE INDEX na_instances_status_idx ON na_instances(status, updated_at);\nCREATE TABLE na_instance_observations (\n instance_id TEXT PRIMARY KEY NOT NULL REFERENCES na_instances(id) ON DELETE CASCADE ON UPDATE CASCADE,\n health TEXT NOT NULL, connection_status TEXT NOT NULL, ready INTEGER NOT NULL,\n observed_json TEXT NOT NULL, last_heartbeat_at TEXT, updated_at TEXT NOT NULL\n);\nCREATE INDEX na_instance_observations_connection_idx ON na_instance_observations(connection_status, updated_at);\nCREATE TABLE na_models (\n id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, endpoint TEXT NOT NULL, key TEXT NOT NULL, model TEXT NOT NULL,\n app TEXT NOT NULL CHECK(app IN ('codex','claude','opencode')), enabled INTEGER NOT NULL,\n display_order INTEGER NOT NULL, model_names_json TEXT NOT NULL, protocols_json TEXT NOT NULL,\n labels_json TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE INDEX na_models_order_idx ON na_models(display_order, id);\nCREATE TABLE na_instance_model_assignments (\n instance_id TEXT PRIMARY KEY NOT NULL REFERENCES na_instances(id) ON DELETE CASCADE ON UPDATE CASCADE,\n legacy_codex_model_id TEXT REFERENCES na_models(id) ON DELETE RESTRICT ON UPDATE CASCADE,\n legacy_claude_model_id TEXT REFERENCES na_models(id) ON DELETE RESTRICT ON UPDATE CASCADE,\n legacy_opencode_model_id TEXT REFERENCES na_models(id) ON DELETE RESTRICT ON UPDATE CASCADE,\n updated_at TEXT NOT NULL\n);\nCREATE TABLE na_instance_model_entities (\n instance_id TEXT NOT NULL REFERENCES na_instance_model_assignments(instance_id) ON DELETE CASCADE ON UPDATE CASCADE,\n model_id TEXT NOT NULL REFERENCES na_models(id) ON DELETE RESTRICT ON UPDATE CASCADE,\n display_order INTEGER NOT NULL, PRIMARY KEY(instance_id, model_id), UNIQUE(instance_id, display_order)\n);\nCREATE TABLE na_control_plane_pairings (\n key_id TEXT PRIMARY KEY NOT NULL, control_plane_id TEXT NOT NULL UNIQUE, name TEXT, secret TEXT NOT NULL,\n paired_at TEXT NOT NULL, revoked_at TEXT, updated_at TEXT NOT NULL\n);\nCREATE TABLE na_control_plane_connections (\n id TEXT PRIMARY KEY NOT NULL,\n pairing_key_id TEXT NOT NULL REFERENCES na_control_plane_pairings(key_id) ON DELETE RESTRICT ON UPDATE CASCADE,\n name TEXT, normalized_url TEXT NOT NULL UNIQUE, enabled INTEGER NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE TABLE na_control_plane_connection_operations (\n id TEXT PRIMARY KEY NOT NULL, kind TEXT NOT NULL,\n phase TEXT NOT NULL CHECK(phase IN ('prepared','remote-accepted','committed','failed')),\n requested_json TEXT NOT NULL, pairing_key_id TEXT, connection_id TEXT, replaced_connections_json TEXT NOT NULL,\n error_json TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE INDEX na_control_plane_connection_operations_phase_idx ON na_control_plane_connection_operations(phase, updated_at);\nCREATE TABLE na_git_credential_payloads (\n credential_id TEXT PRIMARY KEY NOT NULL, revision INTEGER NOT NULL CHECK(revision >= 0),\n public_json TEXT NOT NULL, secret_json TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE TABLE na_git_authorization_sets (\n instance_id TEXT PRIMARY KEY NOT NULL REFERENCES na_instances(id) ON DELETE CASCADE ON UPDATE CASCADE,\n generation INTEGER NOT NULL CHECK(generation >= 0), created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE TABLE na_git_authorization_members (\n instance_id TEXT NOT NULL REFERENCES na_git_authorization_sets(instance_id) ON DELETE CASCADE ON UPDATE CASCADE,\n credential_id TEXT NOT NULL REFERENCES na_git_credential_payloads(credential_id) ON DELETE RESTRICT ON UPDATE CASCADE,\n display_order INTEGER NOT NULL, PRIMARY KEY(instance_id, credential_id), UNIQUE(instance_id, display_order)\n);\nCREATE TABLE na_git_workspace_provisioning (\n instance_id TEXT PRIMARY KEY NOT NULL REFERENCES na_instances(id) ON DELETE CASCADE ON UPDATE CASCADE,\n status TEXT NOT NULL CHECK(status IN ('pending','consumed')), operation_id TEXT NOT NULL, input_json TEXT,\n created_at TEXT NOT NULL, updated_at TEXT NOT NULL, expires_at TEXT NOT NULL,\n CHECK((status = 'pending' AND input_json IS NOT NULL) OR (status = 'consumed' AND input_json IS NULL))\n);\nCREATE INDEX na_git_workspace_provisioning_expiry_idx ON na_git_workspace_provisioning(expires_at);\n"),sh("0003_story_agent_tool_policy","\nALTER TABLE na_stories ADD COLUMN agent_tools_content INTEGER NOT NULL DEFAULT 1 CHECK(agent_tools_content IN (0, 1));\nALTER TABLE na_stories ADD COLUMN agent_tools_actions INTEGER NOT NULL DEFAULT 0 CHECK(agent_tools_actions IN (0, 1));\nALTER TABLE na_stories ADD COLUMN agent_tools_automations INTEGER NOT NULL DEFAULT 0 CHECK(agent_tools_automations IN (0, 1));\nALTER TABLE na_stories ADD COLUMN agent_tools_ai_sessions INTEGER NOT NULL DEFAULT 0 CHECK(agent_tools_ai_sessions IN (0, 1));\n"),sh("0004_agent_definition_domain","\nCREATE TABLE na_agent_definitions (\n id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, description TEXT NOT NULL DEFAULT '',\n appended_prompt TEXT NOT NULL DEFAULT '', target_instance_id TEXT NOT NULL, cwd_folder_id TEXT NOT NULL,\n provider_id TEXT NOT NULL, model_entity_id TEXT, model_name TEXT, reasoning_effort TEXT, permission_mode TEXT,\n execution_policy_json TEXT NOT NULL, revision TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE INDEX na_agent_definitions_target_instance_idx ON na_agent_definitions(target_instance_id);\nCREATE INDEX na_agent_definitions_updated_idx ON na_agent_definitions(updated_at);\nCREATE TABLE na_agent_callable_relations (\n agent_id TEXT NOT NULL, callable_agent_id TEXT NOT NULL, created_at TEXT NOT NULL,\n PRIMARY KEY (agent_id, callable_agent_id),\n FOREIGN KEY (agent_id) REFERENCES na_agent_definitions(id) ON DELETE CASCADE ON UPDATE CASCADE\n);\nCREATE INDEX na_agent_callable_relations_target_idx ON na_agent_callable_relations(callable_agent_id);\n"),sh("0005_agent_run_domain","\nCREATE TABLE na_agent_runs (\n run_id TEXT PRIMARY KEY NOT NULL, client_request_id TEXT NOT NULL UNIQUE,\n revision INTEGER NOT NULL DEFAULT 0 CHECK(revision >= 0),\n status TEXT NOT NULL CHECK(status IN ('queued','preparing','running','finalizing','completed','failed','cancelled')),\n provenance_json TEXT NOT NULL, root_member_id TEXT NOT NULL, budget_json TEXT NOT NULL,\n result_json TEXT, error_json TEXT, cleanup_json TEXT,\n created_at TEXT NOT NULL, updated_at TEXT NOT NULL, completed_at TEXT\n);\nCREATE INDEX na_agent_runs_status_updated_idx ON na_agent_runs(status, updated_at);\nCREATE TABLE na_agent_run_members (\n member_id TEXT PRIMARY KEY NOT NULL, run_id TEXT NOT NULL, agent_id TEXT NOT NULL,\n parent_member_id TEXT, instance_id TEXT NOT NULL, ai_session_id TEXT,\n role TEXT NOT NULL CHECK(role IN ('root','callee')), depth INTEGER NOT NULL CHECK(depth >= 0),\n status TEXT NOT NULL CHECK(status IN ('queued','preparing','running','finalizing','completed','failed','cancelled')),\n execution_snapshot_json TEXT NOT NULL, result_json TEXT, error_json TEXT,\n created_at TEXT NOT NULL, updated_at TEXT NOT NULL, completed_at TEXT,\n FOREIGN KEY (run_id) REFERENCES na_agent_runs(run_id) ON DELETE CASCADE ON UPDATE CASCADE,\n FOREIGN KEY (parent_member_id) REFERENCES na_agent_run_members(member_id) ON DELETE RESTRICT ON UPDATE CASCADE\n);\nCREATE INDEX na_agent_run_members_run_idx ON na_agent_run_members(run_id, created_at, member_id);\nCREATE INDEX na_agent_run_members_parent_idx ON na_agent_run_members(parent_member_id);\nCREATE TABLE na_agent_run_timeline (\n run_id TEXT NOT NULL, sequence INTEGER NOT NULL CHECK(sequence > 0), timestamp TEXT NOT NULL,\n kind TEXT NOT NULL, member_id TEXT, data_json TEXT NOT NULL,\n PRIMARY KEY (run_id, sequence),\n FOREIGN KEY (run_id) REFERENCES na_agent_runs(run_id) ON DELETE CASCADE ON UPDATE CASCADE,\n FOREIGN KEY (member_id) REFERENCES na_agent_run_members(member_id) ON DELETE RESTRICT ON UPDATE CASCADE\n);\n"),sh("0006_story_agent_entry_authorization","\nCREATE TABLE na_story_agent_entries (\n story_id TEXT NOT NULL, agent_id TEXT NOT NULL, created_at TEXT NOT NULL,\n PRIMARY KEY (story_id, agent_id),\n FOREIGN KEY (story_id) REFERENCES na_stories(id) ON DELETE CASCADE ON UPDATE CASCADE\n);\nCREATE INDEX na_story_agent_entries_agent_idx ON na_story_agent_entries(agent_id);\n"),sh("0007_agent_run_result_delivery","\nALTER TABLE na_agent_runs ADD COLUMN result_delivery_json TEXT;\n"),sh("0008_agent_run_resource_ownership","\nCREATE UNIQUE INDEX na_agent_run_members_run_member_uq ON na_agent_run_members(run_id, member_id);\nCREATE TABLE na_agent_run_shared_spaces (\n run_id TEXT PRIMARY KEY NOT NULL, runtime_id TEXT NOT NULL, generation_id TEXT NOT NULL,\n state TEXT NOT NULL CHECK(state IN ('preparing','active','retained','expiring','delete-retrying','expired','manual-intervention')),\n quota_bytes INTEGER NOT NULL CHECK(quota_bytes > 0), usage_bytes INTEGER NOT NULL DEFAULT 0 CHECK(usage_bytes >= 0),\n expires_at TEXT, diagnostics_json TEXT NOT NULL DEFAULT '{}', created_at TEXT NOT NULL, updated_at TEXT NOT NULL,\n FOREIGN KEY (run_id) REFERENCES na_agent_runs(run_id) ON DELETE CASCADE ON UPDATE CASCADE,\n FOREIGN KEY (runtime_id) REFERENCES na_runtimes(id) ON DELETE RESTRICT ON UPDATE CASCADE\n);\nCREATE INDEX na_agent_run_shared_spaces_runtime_expiry_idx ON na_agent_run_shared_spaces(runtime_id, expires_at);\nCREATE TABLE na_agent_run_resources (\n resource_id TEXT PRIMARY KEY NOT NULL, run_id TEXT NOT NULL, member_id TEXT, instance_id TEXT, runtime_id TEXT NOT NULL,\n kind TEXT NOT NULL CHECK(kind IN ('provider-thread','overlay-mount','overlay-run-directory','shared-space-directory','helper-container','sandbox-container')),\n generation_id TEXT NOT NULL, backend_identity TEXT NOT NULL,\n phase TEXT NOT NULL CHECK(phase IN ('preparing','ready','deleting','delete-retrying','deleted','manual-intervention')),\n cleanup_attempts INTEGER NOT NULL DEFAULT 0 CHECK(cleanup_attempts >= 0), metadata_json TEXT NOT NULL DEFAULT '{}',\n created_at TEXT NOT NULL, updated_at TEXT NOT NULL,\n FOREIGN KEY (run_id) REFERENCES na_agent_runs(run_id) ON DELETE CASCADE ON UPDATE CASCADE,\n FOREIGN KEY (run_id, member_id) REFERENCES na_agent_run_members(run_id, member_id) ON DELETE CASCADE ON UPDATE CASCADE,\n UNIQUE (run_id, kind, backend_identity)\n);\nCREATE INDEX na_agent_run_resources_run_phase_idx ON na_agent_run_resources(run_id, phase);\n"),sh("0009_agent_run_input","\nALTER TABLE na_agent_runs ADD COLUMN input_json TEXT;\n"),sh("0010_agent_run_member_input","\nALTER TABLE na_agent_run_members ADD COLUMN input_json TEXT;\n"),sh("0011_agent_run_member_request_identity","\nALTER TABLE na_agent_run_members ADD COLUMN client_request_id TEXT;\nCREATE UNIQUE INDEX na_agent_run_members_request_uq ON na_agent_run_members(run_id, client_request_id)\n WHERE client_request_id IS NOT NULL;\n"),sh("0012_agent_orchestration_domain","\nCREATE TABLE na_agent_orchestrations (\n id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL,\n revision TEXT NOT NULL DEFAULT '', created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nCREATE TABLE na_agent_orchestration_agents (\n orchestration_id TEXT NOT NULL, agent_id TEXT NOT NULL, created_at TEXT NOT NULL,\n PRIMARY KEY (orchestration_id, agent_id),\n FOREIGN KEY (orchestration_id) REFERENCES na_agent_orchestrations(id) ON DELETE CASCADE ON UPDATE CASCADE\n);\nCREATE INDEX na_agent_orchestration_agents_agent_idx ON na_agent_orchestration_agents(agent_id);\nCREATE TABLE na_agent_orchestration_edges (\n orchestration_id TEXT NOT NULL, from_agent_id TEXT NOT NULL, to_agent_id TEXT NOT NULL, created_at TEXT NOT NULL,\n PRIMARY KEY (orchestration_id, from_agent_id, to_agent_id),\n FOREIGN KEY (orchestration_id) REFERENCES na_agent_orchestrations(id) ON DELETE CASCADE ON UPDATE CASCADE\n);\nCREATE INDEX na_agent_orchestration_edges_from_idx ON na_agent_orchestration_edges(from_agent_id);\n\nINSERT INTO na_agent_orchestrations (id, name, revision, created_at, updated_at)\n SELECT 'default:' || id, name, '', updated_at, updated_at FROM na_agent_definitions;\nWITH RECURSIVE reach(origin, node) AS (\n SELECT id, id FROM na_agent_definitions\n UNION\n SELECT reach.origin, relation.callable_agent_id\n FROM reach JOIN na_agent_callable_relations relation ON relation.agent_id = reach.node\n)\nINSERT INTO na_agent_orchestration_agents (orchestration_id, agent_id, created_at)\n SELECT DISTINCT 'default:' || origin, node, strftime('%Y-%m-%dT%H:%M:%fZ','now') FROM reach;\nWITH RECURSIVE reach(origin, node) AS (\n SELECT id, id FROM na_agent_definitions\n UNION\n SELECT reach.origin, relation.callable_agent_id\n FROM reach JOIN na_agent_callable_relations relation ON relation.agent_id = reach.node\n)\nINSERT OR IGNORE INTO na_agent_orchestration_edges (orchestration_id, from_agent_id, to_agent_id, created_at)\n SELECT DISTINCT 'default:' || reach.origin, relation.agent_id, relation.callable_agent_id, strftime('%Y-%m-%dT%H:%M:%fZ','now')\n FROM reach JOIN na_agent_callable_relations relation ON relation.agent_id = reach.node;\nDROP TABLE na_agent_callable_relations;\n\nCREATE TABLE na_story_agent_entries_v2 (\n story_id TEXT NOT NULL, agent_id TEXT NOT NULL, orchestration_id TEXT NOT NULL, created_at TEXT NOT NULL,\n PRIMARY KEY (story_id, agent_id, orchestration_id),\n FOREIGN KEY (story_id) REFERENCES na_stories(id) ON DELETE CASCADE ON UPDATE CASCADE\n);\nINSERT INTO na_story_agent_entries_v2 (story_id, agent_id, orchestration_id, created_at)\n SELECT story_id, agent_id, 'default:' || agent_id, created_at FROM na_story_agent_entries;\nDROP TABLE na_story_agent_entries;\nALTER TABLE na_story_agent_entries_v2 RENAME TO na_story_agent_entries;\nCREATE INDEX na_story_agent_entries_agent_idx ON na_story_agent_entries(agent_id);\n\nALTER TABLE na_agent_runs ADD COLUMN orchestration_id TEXT;\nUPDATE na_agent_runs SET orchestration_id = (\n SELECT 'default:' || agent_id FROM na_agent_run_members WHERE member_id = na_agent_runs.root_member_id\n) WHERE orchestration_id IS NULL;\n"),sh("0013_model_request_mappings","\nALTER TABLE na_models ADD COLUMN mappings_json TEXT NOT NULL DEFAULT '[]';\n"),sh("0014_story_decision_domain","\nALTER TABLE na_stories ADD COLUMN agent_tools_decisions INTEGER NOT NULL DEFAULT 0 CHECK(agent_tools_decisions IN (0, 1));\nCREATE TABLE na_story_decisions (\n id TEXT PRIMARY KEY NOT NULL,\n story_id TEXT NOT NULL REFERENCES na_stories(id) ON DELETE CASCADE,\n session_id TEXT NOT NULL,\n turn_id TEXT,\n question TEXT NOT NULL,\n options_json TEXT NOT NULL DEFAULT '[]',\n allow_free_text INTEGER NOT NULL DEFAULT 1 CHECK(allow_free_text IN (0, 1)),\n context TEXT,\n status TEXT NOT NULL CHECK(status IN ('pending','decided','cancelled','expired')),\n revision INTEGER NOT NULL CHECK(revision >= 1),\n response TEXT,\n selected_option_id TEXT,\n decided_turn_id TEXT,\n expired_reason_json TEXT,\n -- node-agent 私有续接账本:仅用于旧实例不支持发送幂等键时的显式重试判定,不进入公共决策模型或 UI。\n resume_state TEXT CHECK(resume_state IS NULL OR resume_state = 'resuming'),\n resume_attempted_at TEXT,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n decided_at TEXT\n);\nCREATE UNIQUE INDEX na_story_decisions_session_turn_uq ON na_story_decisions(story_id, session_id, turn_id)\n WHERE turn_id IS NOT NULL;\nCREATE INDEX na_story_decisions_story_idx ON na_story_decisions(story_id, created_at);\nCREATE INDEX na_story_decisions_session_idx ON na_story_decisions(session_id, status);\n"),sh("0015_agent_definition_model_identity","\nALTER TABLE na_agent_definitions ADD COLUMN model_upstream_name TEXT;\n"),sh("0016_runtime_type_wsl","\nCREATE TABLE na_runtimes_wsl (\n id TEXT PRIMARY KEY NOT NULL, node_id TEXT NOT NULL REFERENCES na_node_identity(node_id) ON DELETE RESTRICT ON UPDATE CASCADE,\n name TEXT NOT NULL, type TEXT NOT NULL CHECK(type IN ('docker','kubernetes','local','wsl')),\n status TEXT NOT NULL CHECK(status IN ('unknown','online','offline','degraded')), access_strategy TEXT NOT NULL,\n capabilities_json TEXT NOT NULL, labels_json TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL\n);\nINSERT INTO na_runtimes_wsl (id, node_id, name, type, status, access_strategy, capabilities_json, labels_json, created_at, updated_at)\n SELECT id, node_id, name, type, status, access_strategy, capabilities_json, labels_json, created_at, updated_at FROM na_runtimes;\nDROP TABLE na_runtimes;\nALTER TABLE na_runtimes_wsl RENAME TO na_runtimes;\nCREATE INDEX na_runtimes_node_type_idx ON na_runtimes(node_id, type);\n",{foreignKeysOff:!0})],oh=c.z.string().trim().min(1).max(160),ah=c.z.string().datetime(),ch=c.z.string().min(1).max(4096),dh=c.z.string().trim().url().max(2048),lh=c.z.object({id:oh,keyId:oh,name:c.z.string().trim().min(1).max(160).optional(),secret:ch,pairedAt:ah,revokedAt:ah.optional(),updatedAt:ah}).strip(),uh=c.z.object({id:oh,pairingKeyId:oh,name:c.z.string().trim().min(1).max(160).optional(),url:dh,enabled:c.z.boolean().default(!0),createdAt:ah,updatedAt:ah}).strip(),ph=c.z.object({controlPlaneName:c.z.string().trim().min(1).max(160).optional(),controlPlaneUrl:c.z.string().trim().max(2048).optional(),expiresInMs:c.z.number().int().positive().max(36e5).optional()}).strict(),mh=c.z.object({joinToken:c.z.string().trim().min(1).max(4096),controlPlaneId:c.z.string().trim().min(1).max(160).optional(),controlPlaneName:c.z.string().trim().min(1).max(160).optional()}).strict(),hh=c.z.object({controlPlaneUrl:c.z.string().trim().url().max(2048),joinToken:c.z.string().trim().min(1).max(4096),controlPlaneName:c.z.string().trim().min(1).max(160).optional(),activate:c.z.boolean().optional()}).strict(),gh=new Set(["nodeId","createdAt","updatedAt","pairingInvites","controlPlanePairings","controlPlaneConnections","remoteControlPlanes"]),fh=new Set(["id","keyId","name","secret","pairedAt","revokedAt","updatedAt"]),yh=new Set(["id","pairingKeyId","name","url","enabled","createdAt","updatedAt"]),Ih=new Set(["id","keyId","name","url","secret","pairedAt","updatedAt","active"]);function _h(e,t){console.warn(JSON.stringify({message:e,...t}))}function Eh(e,t){return Object.assign(new Error(e,void 0===t?void 0:{cause:t}),{code:"NODE_AGENT_IDENTITY_INVALID"})}function Ah(e,t){return Object.keys(e).filter(e=>!t.has(e))}function Th(e,t,n){const i=ah.safeParse(e);return i.success?i.data:(n("invalid node agent identity timestamp was replaced",{field:t}),de())}function bh(e,t=_h){if(!e||"object"!=typeof e||Array.isArray(e))throw Eh("Node agent identity must be a JSON object.");const n=e,i=oh.safeParse(n.nodeId);if(!i.success)throw Eh("Node agent identity has an invalid nodeId.",i.error);const s=i.data,r=Ah(n,gh);r.length&&t("unknown node agent identity fields were ignored",{fields:r}),Array.isArray(n.pairingInvites)&&n.pairingInvites.length&&t("persisted node agent pairing invites were discarded",{count:n.pairingInvites.length});const o=Array.isArray(n.remoteControlPlanes)?n.remoteControlPlanes.flatMap(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return[];const n=e,i=Ah(n,Ih);i.length&&t("unknown legacy node agent remote control-plane fields were ignored",{fields:i});const s=lh.safeParse(n);if(!s.success)return t("invalid legacy node agent control-plane pairing was ignored",{issues:s.error.issues}),[];const r=n.url?uh.safeParse({id:`connection_${s.data.keyId}`,pairingKeyId:s.data.keyId,name:n.name,url:n.url,enabled:!1!==n.active,createdAt:s.data.pairedAt,updatedAt:s.data.updatedAt}):void 0;return[{pairing:s.data,...r?.success?{connection:r.data}:{}}]}):[],a=(e,n,i,s)=>Array.isArray(e)?e.flatMap(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return t(`invalid node agent ${s} was ignored`,{}),[];const r=Ah(e,n);r.length&&t(`unknown node agent ${s} fields were ignored`,{fields:r});const o=i.safeParse(e);return o.success?[o.data]:(t(`invalid node agent ${s} was ignored`,{issues:o.error.issues}),[])}):[];return{nodeId:s,createdAt:Th(n.createdAt,"createdAt",t),updatedAt:Th(n.updatedAt,"updatedAt",t),controlPlanePairings:n.controlPlanePairings?a(n.controlPlanePairings,fh,lh,"control-plane pairing"):o.map(e=>e.pairing),controlPlaneConnections:n.controlPlaneConnections?a(n.controlPlaneConnections,yh,uh,"control-plane connection"):o.flatMap(e=>e.connection?[e.connection]:[])}}function wh(e){const t={app:qr.shape.app.parse(e.app),endpoint:qr.shape.endpoint.parse(e.endpoint),key:qr.shape.key.parse(e.key),model:qr.shape.model.parse(e.model)};return`mdl_${d.createHash("sha256").update(JSON.stringify(t)).digest("hex")}`}const Sh="1000_import_v0_0_28_p0",Nh=d.createHash("sha256").update(JSON.stringify({sourceTag:"v0.0.28",plannerVersion:3,domains:["identity","folders","runtimes","instances","models","assignments","model-environments","git"],transaction:"begin-immediate"})).digest("hex"),vh=["id","nodeId","name","path","defaultImageSelection","labels","createdAt","updatedAt"],Oh=["id","nodeId","name","type","status","accessStrategy","capabilities","labels","createdAt","updatedAt"],Rh=["id","name","endpoint","key","model","modelNames","mappings","protocols","app","enabled","order","labels","createdAt","updatedAt"],zh=["instanceId","modelEntityIds","codexModelHash","claudeModelHash","opencodeModelHash","updatedAt"],xh=["id","payload","createdAt","updatedAt"],Ch=["id","instanceId","generation","credentialIds","createdAt","updatedAt"],kh=["id","instanceId","credentialId","credentialRevision","assignmentRevision","status","authorizedAt","createdAt","updatedAt"],Dh=["id","status","operationId","input","createdAt","updatedAt","expiresAt"];function Lh(e,i,s={}){const r=e.prepare("SELECT checksum FROM na_migration_ledger WHERE id = ?").get(Sh);if(r){if(r.checksum!==Nh)throw Wh("ledger","Legacy P0 migration checksum mismatch.");return void $h(i,s.rename)}const o=[],a=function(e,i){const s=[],r=new Set,o=(e,r)=>function(e,i,s,r){return t.existsSync(e)?t.readdirSync(e).filter(e=>e.endsWith(".json")).sort().flatMap(o=>{const a=n.join(e,o);let c;try{c=t.readFileSync(a,"utf8")}catch(e){throw Wh(a,"Legacy JSON could not be accessed.",e)}const l={filePath:a,value:void 0,digest:d.createHash("sha256").update(c).digest("hex")};s.push(l);try{return l.value=JSON.parse(c),[l]}catch{return i.push({source:a,field:"unreadable-record"}),r?.(a),[]}}):[]}(e,i,s,r);return{...{folders:o(e.localFoldersDir),runtimes:o(e.nodeRuntimesDir),instances:o(e.controlledInstancesDir,e=>r.add(n.basename(e,".json"))),privateConfigs:o(e.instancePrivateConfigsDir),models:o(e.nodeModelsDir),assignments:o(e.modelAssignmentsDir),modelEnvironments:o(e.modelEnvironmentsDir),gitPayloads:o(e.gitCredentialPayloadsDir),gitAssignments:o(e.gitCredentialAssignmentsDir),gitAuthorizations:o(e.gitCredentialAuthorizationSetsDir),gitProvisioning:o(e.gitWorkspaceProvisioningIntentsDir)},allFiles:s,isolatedInstanceIds:r}}(i,o),l=a.allFiles.length>0,u=function(e){let n;try{n=t.lstatSync(e)}catch(t){if("ENOENT"===t.code)return;throw Wh(e,"Legacy JSON could not be accessed.",t)}if(!n.isFile())throw Wh(e,"Legacy JSON must be a regular file.");return function(e){try{const n=t.readFileSync(e,"utf8");return{filePath:e,value:JSON.parse(n),digest:d.createHash("sha256").update(n).digest("hex")}}catch(t){throw Wh(e,"Legacy JSON could not be read.",t)}}(e)}(i.identityPath);if(l&&!u)throw Wh(i.identityPath,"Legacy P0 data requires a node identity.");try{const t=u?bh(u.value,(e,t)=>o.push({source:i.identityPath,field:String(t.field||t.fields||"legacy")})):void 0,s=a.folders.map(e=>(Gh(e,vh,o),Mh(e,kr,Ws(e.value)))),r=a.runtimes.map(e=>(Gh(e,Oh,o),Mh(e,Qo.strip(),e.value))),d=new Map(Ph(a.privateConfigs,a.isolatedInstanceIds,o).map(e=>{const t=Bh(e.value);return[n.basename(e.filePath,".json"),qh(t.instanceCredential??t.registrationToken)]})),l=a.instances.map(e=>{const t=wa(e.value,t=>o.push({source:e.filePath,field:t.field}));if(!t.success)throw jh(e,t.error);return{...t.data,registrationToken:t.data.registrationToken||d.get(t.data.id)}}),p=a.models.flatMap(e=>{const t=Bh(e.value);Gh(e,Rh,o);const i=Mh(e,qr,Vh(t,["id","name","endpoint","key","model","modelNames","mappings","protocols","app","enabled","order","labels","createdAt","updatedAt"]));return n.basename(e.filePath,".json")!==i.id||wh(i)!==i.id?(o.push({source:e.filePath,field:"identity-or-content-hash"}),[]):[qr.parse({...i,modelNames:i.modelNames.length?i.modelNames:[{name:i.model,order:0}],protocols:i.protocols.length?i.protocols:[(s=i.app,"claude"===s?"anthropic-messages":"opencode"===s?"openai-chat-completions":"openai-responses")]})];var s}),m=Ph(a.assignments,a.isolatedInstanceIds,o).map(e=>{const t=Bh(e.value);return Gh(e,zh,o),Mh(e,Wr,Vh(t,["instanceId","modelEntityIds","codexModelHash","claudeModelHash","opencodeModelHash","updatedAt"]))});!function(e,t,i,s){const r=new Set(t.map(e=>e.id)),o=new Map(s.map(e=>[e.instanceId,e])),a=new Map(i.map(e=>[e.id,e]));let d=i.reduce((e,t)=>Math.max(e,t.order),0)+100;for(const l of e){const e=n.basename(l.filePath,".json");if(!r.has(e))throw Wh(l.filePath,`Legacy model environment references missing instance ${e}.`);if(o.has(e))continue;const u=c.z.record(c.z.string(),c.z.string()).safeParse(l.value);if(!u.success)throw jh(l,u.error);const p=u.data,m=new Set(["OPENAI_API_KEY","OPENAI_BASE_URL","CODEX_MODEL","TASK_HANDOFF_CODEX_BASE_URL","TASK_HANDOFF_CODEX_MODEL","ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","CLAUDE_MODEL","TASK_HANDOFF_CLAUDE_MODEL"]);if(Object.keys(p).some(e=>!m.has(e)))throw Wh(l.filePath,"Legacy model environment contains an unknown field.");const h=[],g={};for(const n of["codex","claude"]){const s=p["codex"===n?"OPENAI_API_KEY":"ANTHROPIC_API_KEY"],r="codex"===n?p.TASK_HANDOFF_CODEX_BASE_URL||p.OPENAI_BASE_URL:p.ANTHROPIC_BASE_URL,o="codex"===n?p.TASK_HANDOFF_CODEX_MODEL||p.CODEX_MODEL:p.TASK_HANDOFF_CLAUDE_MODEL||p.CLAUDE_MODEL;if(!s&&!r&&!o)continue;if(!s||!r||!o)throw Wh(l.filePath,`Legacy ${n} model environment is incomplete.`);const c=wh({app:n,endpoint:r,key:s,model:o});if(!a.has(c)){const l=t.find(t=>t.id===e).updatedAt,u=qr.parse({id:c,name:`Migrated ${"codex"===n?"Codex":"Claude"} model`,endpoint:r,key:s,model:o,app:n,enabled:!0,order:d,labels:{migratedFrom:"instance-model-environment"},createdAt:l,updatedAt:l});d+=100,i.push(u),a.set(c,u)}h.push(c),"codex"===n?g.codexModelHash=c:g.claudeModelHash=c}if(!h.length)throw Wh(l.filePath,"Legacy model environment has no complete model configuration.");const f=Wr.parse({instanceId:e,modelEntityIds:h,...g,updatedAt:t.find(t=>t.id===e).updatedAt});s.push(f),o.set(e,f)}}(Ph(a.modelEnvironments,a.isolatedInstanceIds,o),l,p,m);const h=new Map,g=e=>{let t=h.get(e);return t||(t=Io(e)?e:_o(e),h.set(e,t)),t},f=p.map(e=>qr.parse({...e,id:g(e.id)})),y=m.map(e=>Wr.parse({...e,modelEntityIds:e.modelEntityIds.map(g),codexModelHash:e.codexModelHash?g(e.codexModelHash):e.codexModelHash,claudeModelHash:e.claudeModelHash?g(e.claudeModelHash):e.claudeModelHash,opencodeModelHash:e.opencodeModelHash?g(e.opencodeModelHash):e.opencodeModelHash})),I=l.map(e=>({...e,modelSelection:{...e.modelSelection,modelEntityIds:e.modelSelection.modelEntityIds?.map(g),codexModelHash:e.modelSelection.codexModelHash?g(e.modelSelection.codexModelHash):e.modelSelection.codexModelHash,claudeModelHash:e.modelSelection.claudeModelHash?g(e.modelSelection.claudeModelHash):e.modelSelection.claudeModelHash,opencodeModelHash:e.modelSelection.opencodeModelHash?g(e.modelSelection.opencodeModelHash):e.modelSelection.opencodeModelHash}})),_=a.gitPayloads.map(e=>{const t=Bh(e.value);return Gh(e,xh,o),{id:qh(t.id),payload:Mh(e,Ii,t.payload),createdAt:qh(t.createdAt),updatedAt:qh(t.updatedAt)}}),E=function(e,t){const n=new Map(e.map(e=>[e.instanceId,e]));for(const e of new Set(t.map(e=>e.instanceId))){if(n.has(e))continue;const i=t.filter(t=>t.instanceId===e).sort((e,t)=>e.credentialId.localeCompare(t.credentialId)),s=i.map(e=>e.updatedAt).sort().at(-1);n.set(e,{id:e,instanceId:e,generation:Math.max(0,...i.map(e=>e.assignmentRevision)),credentialIds:i.filter(e=>"revoking"!==e.status&&"revoked"!==e.status).map(e=>e.credentialId),createdAt:s,updatedAt:s})}return[...n.values()].sort((e,t)=>e.instanceId.localeCompare(t.instanceId))}(Ph(a.gitAuthorizations,a.isolatedInstanceIds,o).map(e=>{const t=Bh(e.value);Gh(e,Ch,o);const n=Mh(e,_i,Vh(t,["instanceId","generation","credentialIds","updatedAt"]));return{...n,id:n.instanceId,createdAt:qh(t.createdAt)}}),Ph(a.gitAssignments,a.isolatedInstanceIds,o).map(e=>{const t=Bh(e.value);return Gh(e,kh,o),Mh(e,yi,Vh(t,["instanceId","credentialId","credentialRevision","assignmentRevision","status","authorizedAt","updatedAt"]))})),A=Ph(a.gitProvisioning,a.isolatedInstanceIds,o).map(e=>(Gh(e,Dh,o),function(e){const t=Bh(e.value),n={id:qh(t.id),createdAt:qh(t.createdAt),updatedAt:qh(t.updatedAt),expiresAt:qh(t.expiresAt)};if("consumed"===t.status)return{...n,status:"consumed",operationId:qh(t.operationId)};const i=function(e){const t=Oi(e),n=Oi(t?.ref),i=Oi(t?.clone),s=Array.isArray(t?.credentials)?t.credentials.map(e=>{const t=Oi(e),n=Oi(t?.payload),i=function(e){const t=Oi(e),n=Oi(t?.scope);return pi.safeParse({...Ri(t,["id","name","kind","secretSet","status","revision","createdAt","updatedAt"]),scope:Ri(n,["scheme","host","port","pathPrefix"])})}(n?.credential),s=Oi(n?.secret);return{...Ri(t,["operationId","retention"]),payload:{credential:i.success?i.data:n?.credential,secret:Ri(s,"https-token"===s?.kind?["kind","username","token"]:["kind","privateKey","passphrase","pinnedKnownHosts"])}}}):t?.credentials;return vi.safeParse({...Ri(t,["operationId","instanceId","remoteUrl"]),ref:Ri(n,["type","name","commit"]),clone:Ri(i,["depth","submodules","lfs","subdirectory"]),credentials:s})}(t.input);if(!i.success)throw jh(e,i.error);const s=vi.parse(i.data);return{...n,id:s.instanceId,status:"pending",input:s}}(e)));!function(e){const t=e.identity?.nodeId,n=Uh("local folder",e.folders.map(e=>e.id)),i=Uh("runtime",e.runtimes.map(e=>e.id)),s=Uh("instance",e.instances.map(e=>e.id)),r=Uh("model",e.models.map(e=>e.id)),o=Uh("Git credential payload",e.payloads.map(e=>e.id));Uh("model assignment",e.assignments.map(e=>e.instanceId)),Uh("Git authorization",e.authorizations.map(e=>e.instanceId)),Uh("Git provisioning",e.provisioning.map(e=>e.id));for(const n of[...e.folders,...e.runtimes])if(!t||n.nodeId!==t)throw Fh("node-identity",n.id,n.nodeId,"Legacy topology record references a different or missing node identity.");for(const s of e.instances){if(!t||s.nodeId!==t)throw Fh("node-identity",s.id,s.nodeId,"Legacy instance references a different or missing node identity.");if(!i.has(s.runtimeId))throw Fh("runtime",s.id,s.runtimeId,"Legacy instance references a missing runtime.");if("local-folder"===s.source.type&&s.source.localFolderId&&!n.has(s.source.localFolderId))throw Fh("local-folder",s.id,s.source.localFolderId,"Legacy instance references a missing local folder.")}for(const t of e.privateConfigInstanceIds)if(!s.has(t))throw Fh("instance",t,t,"Legacy private config references a missing instance.");for(const t of e.assignments){if(!s.has(t.instanceId))throw Fh("instance",t.instanceId,t.instanceId,"Legacy model assignment references a missing instance.");for(const e of new Set([...t.modelEntityIds,t.codexModelHash,t.claudeModelHash,t.opencodeModelHash].filter(e=>Boolean(e))))if(!r.has(e))throw Fh("model",t.instanceId,e,"Legacy model assignment references a missing model.")}for(const t of e.payloads)if(t.id!==t.payload.credential.id)throw Fh("Git credential payload",t.id,t.payload.credential.id,"Legacy Git credential wrapper and payload ids do not match.");for(const t of e.authorizations){if(!s.has(t.instanceId))throw Fh("instance",t.instanceId,t.instanceId,"Legacy Git authorization references a missing instance.");for(const e of t.credentialIds)if(!o.has(e))throw Fh("Git credential payload",t.instanceId,e,"Legacy Git authorization references a missing credential payload.")}for(const t of e.provisioning)if(!s.has(t.id))throw Fh("instance",t.id,t.id,"Legacy Git provisioning references a missing instance.");if(e.identity){const t=Uh("Control Plane pairing",e.identity.controlPlanePairings.map(e=>e.keyId));Uh("Control Plane connection",e.identity.controlPlaneConnections.map(e=>e.id));const n=new Set;for(const i of e.identity.controlPlaneConnections){if(!t.has(i.pairingKeyId))throw Fh("Control Plane pairing",i.id,i.pairingKeyId,"Legacy connection references a missing pairing.");const e=new URL(i.url).toString().replace(/\/$/,"");if(n.has(e))throw Fh("Control Plane URL",i.id,e,"Legacy connections contain a duplicate normalized URL.");n.add(e)}}}({identity:t,folders:s,runtimes:r,instances:I,privateConfigInstanceIds:[...d.keys()],models:f,assignments:y,payloads:_,authorizations:E,provisioning:A}),e.exec("BEGIN IMMEDIATE");try{const n=new Um(e),i=Ru(e),c=Uu(e),d=new Bm(e);t&&n.writeIdentity(t);for(const e of s)i.localFolders.put(e);for(const e of r)i.runtimes.put(e);for(const e of I)i.instances.put(e);for(const e of f)c.models.put(e);for(const e of y)c.assignments.put(e);for(const e of _)d.putPayload(e);for(const e of E)d.putAuthorization(e);for(const e of A)d.putProvisioning(e);const h={sourceTag:"v0.0.28",counts:{identities:t?1:0,folders:s.length,runtimes:r.length,instances:l.length,models:p.length,assignments:m.length,pairings:t?.controlPlanePairings?.length||0,connections:t?.controlPlaneConnections?.length||0,gitPayloads:_.length,gitAuthorizations:E.length,gitProvisioning:A.length},inputDigest:Hh([...u?[u]:[],...a.allFiles]),warningCount:o.length};e.prepare("INSERT INTO na_migration_ledger (id, checksum, applied_at, details) VALUES (?, ?, ?, ?)").run(Sh,Nh,(new Date).toISOString(),JSON.stringify(h)),e.exec("COMMIT")}catch(t){throw e.exec("ROLLBACK"),t}}catch(e){if(e&&"object"==typeof e&&"code"in e&&"NODE_AGENT_LEGACY_MIGRATION_FAILED"===e.code)throw e;throw Wh("p0","Legacy P0 data failed validation.",e)}$h(i,s.rename);for(const e of o)console.warn(JSON.stringify({message:"legacy node agent field was ignored",...e}))}function Ph(e,t,i){return e.filter(e=>{const s=Bh(e.value),r="string"==typeof s.instanceId?s.instanceId:n.basename(e.filePath,".json");return!t.has(r)||(i.push({source:e.filePath,field:"isolated-instance-owner"}),!1)})}function Mh(e,t,n){const i=t.safeParse(n);if(!i.success)throw jh(e,i.error);return i.data}function jh(e,t){return Wh(e.filePath,"Legacy record is missing a required field or has an invalid type.",void 0,{issues:t.issues.map(e=>({path:e.path.join("."),code:e.code}))})}function Uh(e,t){const n=new Set;for(const i of t){if(n.has(i))throw Wh(e,`Legacy ${e} id is duplicated.`,void 0,{recordId:i});n.add(i)}return n}function Fh(e,t,n,i){return Wh(e,i,void 0,{relation:e,recordId:t,referencedId:n})}function $h(e,n=t.renameSync){const i=[e.identityPath,e.localFoldersDir,e.nodeRuntimesDir,e.controlledInstancesDir,e.nodeModelsDir,e.modelAssignmentsDir,e.gitCredentialPayloadsDir,e.modelEnvironmentsDir,e.gitCredentialAssignmentsDir,e.gitCredentialAuthorizationSetsDir,e.gitWorkspaceProvisioningIntentsDir];for(const e of i){if(!t.existsSync(e))continue;const i=`${e}.migrated-v0.0.28`;let s=i;for(let e=1;t.existsSync(s);e+=1)s=`${i}.${e}`;try{n(e,s)}catch(t){console.warn(JSON.stringify({message:"legacy node agent persistence archive failed",source:e,target:s,error:t instanceof Error?t.message:String(t)}))}}}function Hh(e){const t=d.createHash("sha256");for(const i of[...e].sort((e,t)=>e.filePath.localeCompare(t.filePath)))t.update(n.basename(i.filePath)),t.update(i.digest);return t.digest("hex")}function Bh(e){if(!e||"object"!=typeof e||Array.isArray(e))throw Wh("record","Legacy record must be an object.");return e}function qh(e){if("string"!=typeof e||!e)throw Wh("record","Legacy record is missing a required string.");return e}function Vh(e,t){return Object.fromEntries(t.flatMap(t=>Object.prototype.hasOwnProperty.call(e,t)?[[t,e[t]]]:[]))}function Gh(e,t,n){const i=Bh(e.value),s=new Set(t);for(const t of Object.keys(i).filter(e=>!s.has(e)).sort())n.push({source:e.filePath,field:t})}function Wh(e,t,n,i={}){return Object.assign(new Error(t,void 0===n?void 0:{cause:n}),{code:"NODE_AGENT_LEGACY_MIGRATION_FAILED",statusCode:500,details:{source:e,...i}})}function Kh(e,t){return Object.assign(new Error(`Node Agent database ${e} failed: ${t instanceof Error?t.message:String(t)}`,{cause:t}),{code:"NODE_AGENT_DATABASE_STARTUP_FAILED",statusCode:500,details:{phase:e,recovery:"Restore or remove the invalid node-agent.sqlite before restarting the Node Agent."}})}function Yh(e,t){const n=e.prepare(t).get();return n?Object.values(n)[0]:void 0}function Xh(e){for(const n of[e.databasePath,`${e.databasePath}-wal`,`${e.databasePath}-shm`])t.existsSync(n)&&t.chmodSync(n,384)}function Jh(e,i={}){try{!function(e=process.versions.node){const[t,n]=e.split(".").map(Number);if(24!==t||n<15)throw new Error(`Node.js 24.15 or newer within the Node.js 24 release line is required; received ${e}.`)}()}catch(e){throw Kh("runtime",e)}let s;t.mkdirSync(n.dirname(e.databasePath),{recursive:!0,mode:448}),t.chmodSync(n.dirname(e.databasePath),448);try{if(s=new w.DatabaseSync(e.databasePath),function(e,t){e.exec("PRAGMA foreign_keys = ON"),e.exec("PRAGMA busy_timeout = 5000"),e.exec("PRAGMA journal_mode = WAL"),e.exec("PRAGMA synchronous = FULL");const n=Number(Yh(e,"PRAGMA application_id"));if(0===n)e.exec("PRAGMA application_id = 1414024769");else if(1414024769!==n)throw new Error(`Unexpected application_id ${n}.`);if(1!==Number(Yh(e,"PRAGMA foreign_keys")))throw new Error("foreign_keys could not be enabled.");if("wal"!==String(Yh(e,"PRAGMA journal_mode")).toLowerCase())throw new Error("WAL could not be enabled.");if(5e3!==Number(Yh(e,"PRAGMA busy_timeout")))throw new Error("busy_timeout=5000 could not be enabled.");if(2!==Number(Yh(e,"PRAGMA synchronous")))throw new Error("synchronous=FULL could not be enabled.");if("ok"!==String(Yh(e,"PRAGMA quick_check")))throw new Error("quick_check failed.");Xh(t)}(s,e),function(e){e.exec("CREATE TABLE IF NOT EXISTS na_migration_ledger (\n id TEXT PRIMARY KEY NOT NULL, checksum TEXT NOT NULL, applied_at TEXT NOT NULL, details TEXT NOT NULL\n )");const t=e.prepare("SELECT checksum FROM na_migration_ledger WHERE id = ?"),n=e.prepare("INSERT INTO na_migration_ledger (id, checksum, applied_at, details) VALUES (?, ?, ?, ?)"),i=e=>n.run(e.id,e.checksum,(new Date).toISOString(),JSON.stringify({domain:"node-agent-story"}));let s=!1;const r=()=>{e.exec("BEGIN IMMEDIATE"),s=!0},o=()=>{e.exec("COMMIT"),s=!1};r();try{for(const n of rh){const s=t.get(n.id);if(s){if(s.checksum!==n.checksum)throw new Error(`Migration checksum mismatch for ${n.id}.`)}else{if(n.foreignKeysOff){if(o(),e.exec("PRAGMA foreign_keys = OFF"),0!==Number(Yh(e,"PRAGMA foreign_keys")))throw new Error(`foreign_keys could not be disabled for migration ${n.id}.`);r(),e.exec(n.sql);const t=e.prepare("PRAGMA foreign_key_check").all();if(t.length)throw new Error(`Migration ${n.id} left ${t.length} foreign key violation(s).`);if(i(n),o(),e.exec("PRAGMA foreign_keys = ON"),1!==Number(Yh(e,"PRAGMA foreign_keys")))throw new Error(`foreign_keys could not be restored after migration ${n.id}.`);r();continue}e.exec(n.sql),i(n)}}o()}catch(t){throw(()=>{if(s)try{e.exec("ROLLBACK")}finally{s=!1}})(),t}}(s),Lh(s,e,i.legacyMigration),"ok"!==String(Yh(s,"PRAGMA quick_check")))throw new Error("post-migration quick_check failed.");Xh(e);const t=S.drizzle({client:s});let n=!1;return{db:t,client:s,async checkpoint(){n||(s.exec("PRAGMA wal_checkpoint(TRUNCATE)"),Xh(e))},async close(){n||(n=!0,s.close())}}}catch(e){try{s?.close()}catch{}throw Kh(s?"initialize":"connect",e)}}function Qh(e){return e.protocols?.length?[...new Set(e.protocols)]:"claude"===e.app?["anthropic-messages"]:"opencode"===e.app?["openai-chat-completions"]:["openai-responses"]}function Zh(e,t,n){return`rly_${d.createHash("sha256").update(`${e}\0${t}\0${n}`).digest("hex").slice(0,16)}`}function eg(e,t,n,i){return`${e.replace(/\/+$/,"")}${function(e,t,n){return`/api/node-agent/model-relay/instances/${e}/routes/${Zh(e,t,n)}/v1`}(t,n,i)}`}function tg(e){const t=/^\/api\/node-agent\/model-relay\/instances\/([^/]+)\/routes\/([^/]+)\/v1(?:\/(.*))?$/.exec(e);if(!t)return;let n;try{n=decodeURIComponent(t[1])}catch{return}return{instanceId:n,routeId:t[2],operationPath:`/${t[3]||""}`}}function ng(e,t,n){return Object.assign(new Error(n),{statusCode:e,code:t})}class ig{registry;constructor(e){this.registry=e}relayEnabled(){return this.registry.modelRelayEnabled()}instance(e){return this.registry.instance(e)}resolveRoute(e,t){if(!this.registry.modelRelayEnabled())throw ng(503,"MODEL_RELAY_DISABLED","The node model relay is disabled.");let n;try{n=this.registry.instance(e)}catch{throw ng(404,"MODEL_RELAY_ROUTE_NOT_FOUND","The requested model relay route does not exist.")}if(!fs(n.capabilities))throw ng(409,"MODEL_RELAY_UNSUPPORTED",`Instance ${e} does not consume node model relay routes.`);if(!this.registry.assignment(e))throw ng(404,"MODEL_RELAY_ROUTE_NOT_FOUND","The requested model relay route does not exist.");for(const i of this.registry.assignedModelIds(e)){const s=this.registry.getModel(i);if(s)for(const r of Qh(s))if(Zh(e,i,r)===t){if(!s.enabled)throw ng(409,"MODEL_RELAY_ENTITY_DISABLED",`Model ${i} is disabled.`);if(!ys(n.capabilities,r))throw ng(409,"MODEL_RELAY_UNSUPPORTED",`Instance ${e} does not consume ${r} relay routes.`);return{instance:n,model:s,protocol:r,routeId:t}}}throw ng(404,"MODEL_RELAY_ROUTE_NOT_FOUND","The requested model relay route does not exist.")}resolveUpstreamModelName(e,t){const n=oo(e.modelNames,e.model);if(n.some(e=>e.upstreamName===t))return t;const i=n.filter(e=>e.name===t);if(i.length>1)throw ng(409,"MODEL_RELAY_AMBIGUOUS_MODEL_NAME",`Model name ${JSON.stringify(t)} is ambiguous on this relay route.`);if(i.length)return i[0].upstreamName;const s=co(e.mappings).filter(e=>e.name===t);if(s.length>1)throw ng(409,"MODEL_RELAY_AMBIGUOUS_MODEL_NAME",`Model name ${JSON.stringify(t)} is ambiguous on this relay route.`);if(s.length)return s[0].upstreamName;if("passthrough"===this.registry.modelRelayUnknownModelPolicy())return t;throw ng(400,"MODEL_RELAY_UNKNOWN_MODEL_NAME",`Model name ${JSON.stringify(t)} is not assigned to this relay route.`)}}class sg{models;assignments;transaction;nodeId;instances;modelRelay;constructor(e,t,n,i,s){this.nodeId=t,this.instances=n,this.modelRelay=s;const r=i||Km(Jh(e)).model;this.models=r.models,this.assignments=r.assignments,this.transaction=r.transaction.bind(r)}init(){}upgradeModelIdentity(e){if(this.models.get(e))return Io(e)?e:this.renameModel(e,_o(e));const t=Io(e)?e:_o(e),n=this.legacyReplicaFor(t);return n?this.renameModel(n.id,t):t}legacyReplicaFor(e){return this.models.list().find(t=>!Io(t.id)&&_o(t.id)===e)}renameModel(e,t){if(e===t)return t;if(!this.models.get(t))return this.models.rename(e,t),t;for(const n of this.instances.list()){const i=this.assignments.get(n.id);i&&this.assignmentModelIds(i).includes(e)&&this.assignments.put(Wr.parse({...i,modelEntityIds:[...new Set(i.modelEntityIds.map(n=>n===e?t:n))],codexModelHash:i.codexModelHash===e?t:i.codexModelHash,claudeModelHash:i.claudeModelHash===e?t:i.claudeModelHash,opencodeModelHash:i.opencodeModelHash===e?t:i.opencodeModelHash,updatedAt:de()}))}return this.models.delete(e),t}mintModelEntityId(){let e=yo();for(;this.models.get(e);)e=yo();return e}modelRelayEnabled(){return!0===this.modelRelay?.enabled()}modelRelayUnknownModelPolicy(){return this.modelRelay?.unknownModelPolicy()??"passthrough"}instance(e){return this.instances.require(e)}assignment(e){return this.assignments.get(e)}assignedModelIds(e){const t=this.assignments.get(e);return t?this.assignmentModelIds(t):[]}getModel(e){return this.models.get(e)||(Io(e)?this.legacyReplicaFor(e):this.models.get(_o(e)))}isMappedModel(e){return co(e.mappings).length>0}assignedInstanceIds(){return this.instances.list().flatMap(e=>{const t=this.assignments.get(e.id);return t&&this.assignmentModelIds(t).length?[e.id]:[]})}mappedAssignmentInstanceIds(){return this.instances.list().flatMap(e=>{if(!fs(e.capabilities))return[];const t=this.assignments.get(e.id);if(!t)return[];const n=this.assignmentModelIds(t).some(e=>{const t=this.models.get(e);return Boolean(t&&this.isMappedModel(t))});return n?[e.id]:[]})}list(){const e=new Map;for(const t of this.instances.list()){const n=this.assignments.get(t.id);for(const t of new Set([...n?.modelEntityIds||[],n?.codexModelHash,n?.claudeModelHash,n?.opencodeModelHash]))t&&e.set(t,(e.get(t)||0)+1)}return this.models.list().map(t=>this.toPublic(t,e.get(t.id)||0))}create(e){const t=de(),n=ag(e.modelNames,e.model),i={...e,model:n[0].name,modelNames:n,mappings:co(e.mappings),protocols:e.protocols?.length?e.protocols:og(e.app)},s=this.mintModelEntityId(),r=qr.parse({...i,id:s,enabled:e.enabled??!0,order:e.order??this.nextOrder(),labels:e.labels||{},createdAt:t,updatedAt:t});return this.toPublic(this.models.put(r),this.referenceIds(s).length)}deploy(e){const t=ag(e.modelNames,e.model),n=co(e.mappings),i={...e,model:t[0].name,modelNames:t,mappings:n,protocols:e.protocols?.length?e.protocols:og(e.app)},s=Io(e.id)?e.id:_o(e.id),r=this.transaction(()=>this.upgradeModelIdentity(s)),o=this.models.get(r),a=this.models.put(qr.parse({...i,id:r,createdAt:o?.createdAt||i.createdAt}));return this.toPublic(a,this.referenceIds(a.id).length)}update(e,t){const n=this.transaction(()=>this.upgradeModelIdentity(e)),i=this.requireModel(n),s=t.modelNames?.length?ag(t.modelNames,t.model||i.model):t.model?ag(void 0,t.model):ag(i.modelNames,i.model),r=t.protocols?.length?t.protocols:i.protocols?.length?i.protocols:og(t.app||i.app),o=void 0!==t.mappings?co(t.mappings):co(i.mappings),a=qr.parse({...i,...t,key:t.key?.trim()?t.key:i.key,protocols:r,model:s[0].name,modelNames:s,mappings:o,createdAt:i.createdAt,updatedAt:de()}),c=this.models.put(qr.parse({...a,id:n}));return this.toPublic(c,this.referenceIds(n).length)}delete(e){const t=this.requireModel(e),n=this.referenceIds(t.id);if(n.length)throw Object.assign(new Error(`Model ${t.id} is assigned to ${n.length} instance${1===n.length?"":"s"}.`),{statusCode:409,code:"NODE_MODEL_IN_USE",instanceIds:n});return this.models.delete(t.id)}resolveProbeKey(e,t){const n=t?.trim()||(e?this.requireModel(e).key:"");if(!n)throw Object.assign(new Error("An API key is required to contact the model endpoint."),{statusCode:400,code:"MODEL_API_KEY_REQUIRED"});return n}assign(e,t){const n=this.instances.require(e);for(const e of t.modelEntityIds)this.validateEntityRef(e);if(void 0!==t.modelSelection.modelEntityIds&&JSON.stringify(t.modelSelection.modelEntityIds)!==JSON.stringify(t.modelEntityIds))throw Object.assign(new Error("Ordered model entity selection does not match its node assignment."),{statusCode:400,code:"NODE_MODEL_SELECTION_MISMATCH"});if(this.validateRef("codex",t.codexModelHash),this.validateRef("claude",t.claudeModelHash),this.validateRef("opencode",t.opencodeModelHash),void 0!==t.modelSelection.codexModelHash&&(t.modelSelection.codexModelHash??void 0)!==t.codexModelHash)throw Object.assign(new Error("Codex model selection does not match its node assignment."),{statusCode:400,code:"NODE_MODEL_SELECTION_MISMATCH"});if(void 0!==t.modelSelection.claudeModelHash&&(t.modelSelection.claudeModelHash??void 0)!==t.claudeModelHash)throw Object.assign(new Error("Claude model selection does not match its node assignment."),{statusCode:400,code:"NODE_MODEL_SELECTION_MISMATCH"});if(void 0!==t.modelSelection.opencodeModelHash&&(t.modelSelection.opencodeModelHash??void 0)!==t.opencodeModelHash)throw Object.assign(new Error("OpenCode model selection does not match its node assignment."),{statusCode:400,code:"NODE_MODEL_SELECTION_MISMATCH"});const i=Wr.parse({instanceId:e,modelEntityIds:t.modelEntityIds,codexModelHash:t.codexModelHash,claudeModelHash:t.claudeModelHash,opencodeModelHash:t.opencodeModelHash,updatedAt:de()});return this.transaction(()=>({assignment:this.assignments.put(i),instance:this.instances.put(Ia.parse({...n,modelSelection:t.modelSelection,updatedAt:de()}))}))}resolvedEnvironment(e){const t=this.assignments.get(e);if(!t)return{};const n=this.instances.has(e)?this.instances.require(e):void 0;if(n&&this.usesRelayProjection(n))return this.relayEnvironment(n,t);const i=e=>t.modelEntityIds.find(t=>{const n=this.requireModel(t);return this.modelSupportsApp(n,e)});return{...this.environmentForRef("codex",i("codex")||t.codexModelHash),...this.environmentForRef("claude",i("claude")||t.claudeModelHash),...this.environmentForOpenCode(t)}}usesRelayProjection(e){return Boolean(this.modelRelay?.enabled()&&fs(e.capabilities))}relayEnvironment(e,t){const n=this.modelRelay?.originFor(e)||"",i=e.registrationToken,s=t.modelEntityIds.map(e=>{const t=this.requireModel(e);return this.validateEntityRef(e),t}),r=(t,i)=>ys(e.capabilities,i)&&n?eg(n,e.id,t.id,i):void 0,o={},a=s.find(e=>this.modelSupportsApp(e,"claude")&&r(e,"anthropic-messages"));if(a&&i){const e=r(a,"anthropic-messages"),t=ag(a.modelNames,a.model).slice().sort((e,t)=>e.order-t.order||e.name.localeCompare(t.name))[0];t&&(o.ANTHROPIC_API_KEY=i,o.ANTHROPIC_BASE_URL=e,o.TASK_HANDOFF_CLAUDE_MODEL=we(t))}const c=s.filter(e=>this.modelSupportsApp(e,"opencode")&&r(e,"openai-chat-completions"));if(c.length&&i){const e=c[0],t=ag(e.modelNames,e.model).slice().sort((e,t)=>e.order-t.order||e.name.localeCompare(t.name))[0],n=Object.fromEntries(c.map(e=>[`task-handoff-${e.id}`,rg(e,ag(e.modelNames,e.model).map(e=>we(e)),{baseUrl:r(e,"openai-chat-completions"),apiKey:i})]));o.TASK_HANDOFF_OPENCODE_CONFIG_CONTENT=JSON.stringify({$schema:"https://opencode.ai/config.json",model:`task-handoff-${e.id}/${t?we(t):e.model}`,provider:n})}return o}privateCatalog(e){const t=this.assignments.get(e),n=t?.updatedAt||de(),i=(t?.modelEntityIds||[]).map(e=>{const t=this.requireModel(e);return this.validateEntityRef(e),t}),s=this.instances.has(e)?this.instances.require(e):void 0;if(s&&this.usesRelayProjection(s)){const t=this.modelRelay?.originFor(s)||"";return be.parse({protocolVersion:Ie,instanceId:e,entities:i.map(n=>{const i=n.protocols?.length?n.protocols:og(n.app);return{id:n.id,protocols:i,modelNames:ao(ag(n.modelNames,n.model)),routes:i.filter(e=>ys(s.capabilities,e)).map(i=>({protocol:i,baseUrl:eg(t,e,n.id,i)}))}}).filter(e=>e.routes.length>0),updatedAt:n})}return be.parse({protocolVersion:"2026-08-27",instanceId:e,entities:i.flatMap(e=>[{id:e.id,endpoint:e.endpoint,key:e.key,protocols:e.protocols?.length?e.protocols:og(e.app),modelNames:ao(ag(e.modelNames,e.model))}]),updatedAt:n})}privateSecretValues(e){const t=this.assignments.get(e);return t?[...new Set(this.assignmentModelIds(t).map(e=>this.models.get(e)?.key).filter(e=>Boolean(e)))]:[]}deleteInstanceMetadata(e){this.assignments.delete(e)}referencingInstanceIds(e){return this.requireModel(e),this.referenceIds(e)}merge(e,t){const n=this.requireModel(e),i=this.requireModel(t);if(n.id===i.id)throw Object.assign(new Error("A model cannot be merged into itself."),{statusCode:400,code:"NODE_MODEL_MERGE_SAME"});this.validateEntityRef(i.id);for(const e of["codex","claude","opencode"])if(this.modelSupportsApp(n,e)&&!this.modelSupportsApp(i,e))throw Object.assign(new Error(`Model ${i.id} does not support the ${e} runtime protocol required by ${n.id}.`),{statusCode:409,code:"NODE_MODEL_MERGE_APP_MISMATCH"});const s=this.referenceIds(n.id);return this.transaction(()=>{for(const e of s){const t=this.instances.require(e),s=this.assignments.get(e);if(!s)continue;const r=[...new Set(s.modelEntityIds.map(e=>e===n.id?i.id:e))],o=(e,t)=>t&&t!==n.id?t:r.find(t=>this.modelSupportsApp(this.requireModel(t),e)),a=o("codex",s.codexModelHash),c=o("claude",s.claudeModelHash),d=o("opencode",s.opencodeModelHash);this.assignments.put(Wr.parse({instanceId:e,modelEntityIds:r,codexModelHash:a,claudeModelHash:c,opencodeModelHash:d,updatedAt:de()})),this.instances.put(Ia.parse({...t,modelSelection:{...t.modelSelection,modelEntityIds:r,codexModelHash:a??null,claudeModelHash:c??null,opencodeModelHash:d??null},updatedAt:de()}))}this.models.delete(n.id)}),{merged:!0,reassignedInstances:s}}validateRef(e,t){if(!t)return;const n=this.requireModel(t);if(!this.modelSupportsApp(n,e))throw Object.assign(new Error(`Model ${n.id} does not support the ${e} runtime protocol.`),{statusCode:400,code:"NODE_MODEL_APP_MISMATCH"});if(!n.enabled)throw Object.assign(new Error(`Model ${n.id} is disabled.`),{statusCode:409,code:"NODE_MODEL_DISABLED"})}modelSupportsApp(e,t){const n="claude"===t?"anthropic-messages":"opencode"===t?"openai-chat-completions":"openai-responses";return e.protocols?.length?e.protocols.includes(n):e.app===t}validateEntityRef(e){const t=this.requireModel(e);if(!t.enabled)throw Object.assign(new Error(`Model ${t.id} is disabled.`),{statusCode:409,code:"NODE_MODEL_DISABLED"});if(!t.protocols?.length&&!og(t.app).length)throw Object.assign(new Error(`Model ${t.id} does not expose a supported protocol.`),{statusCode:400,code:"NODE_MODEL_PROTOCOL_UNSUPPORTED"})}assignmentModelIds(e){return[...new Set([...e.modelEntityIds||[],e.codexModelHash,e.claudeModelHash,e.opencodeModelHash].filter(e=>Boolean(e)))]}environmentForRef(e,t){if(!t)return{};this.validateRef(e,t);const n=this.requireModel(t),i=we(ag(n.modelNames,n.model)[0]);return"codex"===e?{OPENAI_API_KEY:n.key,OPENAI_BASE_URL:n.endpoint,TASK_HANDOFF_CODEX_BASE_URL:n.endpoint,TASK_HANDOFF_CODEX_MODEL:i}:{ANTHROPIC_API_KEY:n.key,ANTHROPIC_BASE_URL:n.endpoint,TASK_HANDOFF_CLAUDE_MODEL:i}}environmentForOpenCode(e){const t=e.modelEntityIds.map(e=>this.requireModel(e)).filter(e=>this.modelSupportsApp(e,"opencode"));if(!t.length)return{};const n=t[0],i=e=>ag(e.modelNames,e.model).map(e=>we(e)),s=i(n)[0],r=Object.fromEntries(t.map(e=>[`task-handoff-${e.id}`,rg(e,i(e))]));if(e.opencodeModelHash){const t=this.requireModel(e.opencodeModelHash);r["task-handoff"]=rg(t,i(t))}return{TASK_HANDOFF_OPENCODE_CONFIG_CONTENT:JSON.stringify({$schema:"https://opencode.ai/config.json",model:`task-handoff-${n.id}/${s}`,provider:r})}}requireModel(e){const t=this.getModel(e);if(!t)throw Object.assign(new Error(`Model ${e} was not found on node ${this.nodeId}.`),{statusCode:404,code:"NODE_MODEL_NOT_FOUND"});return t}referenceIds(e){return this.instances.list().filter(t=>{const n=this.assignments.get(t.id);return n?.modelEntityIds.includes(e)||n?.codexModelHash===e||n?.claudeModelHash===e||n?.opencodeModelHash===e}).map(e=>e.id)}toPublic(e,t){const{key:n,...i}=e;return Gr.parse({...i,modelNames:ao(e.modelNames),keyPreview:n.length<=8?"set":`${n.slice(0,4)}...${n.slice(-4)}`,keySet:!0,referenceCount:t,revision:lo(e)})}nextOrder(){return this.models.list().reduce((e,t)=>Math.max(e,t.order),0)+100}}function rg(e,t,n){return{npm:"@ai-sdk/openai-compatible",name:e.name,options:n?{baseURL:n.baseUrl,apiKey:n.apiKey}:{baseURL:e.endpoint,apiKey:e.key},models:Object.fromEntries(t.map(t=>[t,{name:e.name,variants:Object.fromEntries(["none","minimal","low","medium","high","xhigh","max","ultra"].map(e=>[e,{reasoningEffort:e}]))}]))}}function og(e){return"claude"===e?["anthropic-messages"]:"opencode"===e?["openai-chat-completions"]:["openai-responses"]}function ag(e,t){return oo(e,t)}const cg=!0;class dg{enabledValue=cg;unknownModelPolicyValue="passthrough";enabled(){return this.enabledValue}unknownModelPolicy(){return this.unknownModelPolicyValue}set(e){this.enabledValue=e.enabled,this.unknownModelPolicyValue=e.unknownModelPolicy}}class lg{settings;registry;relaySwitch;constructor(e){this.settings=e.settings,this.registry=e.registry,this.relaySwitch=e.relaySwitch}restore(){const e=this.effective();return this.relaySwitch.set({enabled:e.enabled,unknownModelPolicy:e.unknownModelPolicy}),e}effective(){const e=this.settings.get().modelRelay;return{enabled:e?.enabled??cg,unknownModelPolicy:e?.unknownModelPolicy??"passthrough",source:e?"persisted":"default"}}enabled(){return this.relaySwitch.enabled()}update(e){const t=la.parse(e);t.enabled||this.assertDisableAllowed();const n=t.unknownModelPolicy??this.effective().unknownModelPolicy;return this.settings.put({...this.settings.get(),version:1,modelRelay:{enabled:t.enabled,unknownModelPolicy:n}}),this.relaySwitch.set({enabled:t.enabled,unknownModelPolicy:n}),this.effective()}assertDisableAllowed(){const e=this.registry.mappedAssignmentInstanceIds();if(e.length)throw Object.assign(new Error(`Cannot disable the node model relay while ${e.length} instance${1===e.length?"":"s"} use a model name mapping.`),{statusCode:409,code:"NODE_MODEL_RELAY_IN_USE",details:{instanceIds:e}})}}function ug(e,t){if(!e)return!0;const n=N.valid(e),i=N.valid(t);return n&&i?N.gt(i,n):e!==t}function pg(){return process.env.TASK_HANDOFF_NPM_COMMAND||"npm"}function mg(e,i){const s=n.join(e,...i.split("/"),"package.json");try{const e=JSON.parse(t.readFileSync(s,"utf8"));if(e.name!==i||"string"!=typeof e.version||!e.version.trim())throw new Error(`Installed package manifest is invalid: ${s}`);return{name:i,version:e.version.trim()}}catch(e){if("ENOENT"===e.code)return;throw e}}async function hg(e,i){const s=i?function(e){const i=function(e){let t=n.resolve(e);for(;t!==n.dirname(t);){if("node_modules"===n.basename(t)&&"lib"===n.basename(n.dirname(t)))return n.dirname(n.dirname(t));t=n.dirname(t)}}(e);if(!i)return;let s,r=n.resolve(e);for(;r!==n.dirname(r);){try{const e=JSON.parse(t.readFileSync(n.join(r,"package.json"),"utf8"));if("@task-handoff/node-agent"===e.name&&"string"==typeof e.version&&e.version.trim()&&(s=e.version.trim()),"@task-handoff/server"===e.name&&"string"==typeof e.version&&e.version.trim())return{packageName:"@task-handoff/server",currentVersion:e.version.trim(),relatedCurrentVersions:s?[s]:[],installPrefix:i}}catch(e){if("ENOENT"!==e.code)throw e}r=n.dirname(r)}return s?{packageName:"@task-handoff/node-agent",currentVersion:s,relatedCurrentVersions:[],installPrefix:i}:void 0}(i):void 0;if(s)return s;const r=(await e(pg(),["root","--global"])).stdout.trim();if(!r)throw new Error("npm did not return its global module root.");const o=(await e(pg(),["prefix","--global"])).stdout.trim();if(!n.isAbsolute(o))throw new Error(`npm did not return an absolute global prefix: ${o||"empty"}`);const a=mg(r,"@task-handoff/server"),c=mg(r,"@task-handoff/node-agent");return a?{packageName:"@task-handoff/server",currentVersion:a.version,relatedCurrentVersions:c?[c.version]:[],installPrefix:o}:{packageName:"@task-handoff/node-agent",currentVersion:c?.version,relatedCurrentVersions:[],installPrefix:o}}function gg(e){if(!e||"object"!=typeof e||Array.isArray(e))return e;const t=e,n="string"==typeof t.updatedAt?t.updatedAt:de(),i=t.target&&"object"==typeof t.target&&!Array.isArray(t.target)?t.target:void 0,s="controlled-instance"===i?.component,r={updating:"updating-node",downloading:"updating-node",installing:"updating-node",restarting:"restarting-node",completed:"succeeded",success:"succeeded",error:"failed"},o=new Set(["queued","updating-node","restarting-node","converging-instances","succeeded","degraded","failed"]),a="string"==typeof t.status?t.status:"queued",c=s?"failed":o.has(a)?a:r[a]||"failed",d="string"==typeof t.toVersion&&t.toVersion?t.toVersion:"unknown",l=Er.strip().safeParse(t.impact).success?Er.strip().parse(t.impact):{runningInstanceCount:0,stoppedInstanceCount:0,activeInstanceCount:0,restartInstanceCount:0,runningInstanceIds:[],stoppedInstanceIds:[],activeInstanceIds:[]},u=s?{code:"LEGACY_INSTANCE_UPDATE_RETIRED",message:"Independent controlled-instance update jobs were retired in favor of Node reconciliation.",retryable:!1}:"failed"!==c||t.error||o.has(a)||a in r?"string"==typeof t.error?{code:"NODE_UPDATE_FAILED",message:t.error,retryable:!1}:Ir.strip().safeParse(t.error).success?Ir.strip().parse(t.error):t.error&&"object"==typeof t.error?{code:"NODE_UPDATE_FAILED",message:"string"==typeof t.error.message?t.error.message:"Stored update job contained an unknown error.",retryable:!1}:void 0:{code:"NODE_UPDATE_FAILED",message:`Stored update job used an unknown status: ${a}.`,retryable:!1},{target:p,error:m,...h}=t,g={phase:"succeeded"===c?"succeeded":"failed"===c?"failed":c||"queued",desiredVersion:d,expectedInstanceIds:[],expectedInstanceCount:0,matchedInstanceCount:0,pendingInstanceCount:0,failedInstanceCount:s||"failed"===c?1:0,deferredInstanceCount:0},f=Ar.strip().safeParse(t.rollout);return{...h,source:"npm",status:c,impact:l,runtimeArtifacts:Array.isArray(t.runtimeArtifacts)?t.runtimeArtifacts.flatMap(e=>{const t=yr.strip().safeParse(e);return t.success?[t.data]:[]}):[],rollout:f.success?f.data:g,...u?{error:u}:{},...s?{completedAt:t.completedAt||n}:{}}}class fg{records;constructor(e){this.records=new uu(e.updatesDir,{schema:wr,sanitize:gg})}init(){this.records.init()}list(){return this.records.list().sort((e,t)=>t.createdAt.localeCompare(e.createdAt))}create(e,t){const n=de();return this.records.put(wr.parse({id:du("update"),nodeId:e,source:t.source,channel:t.channel,fromVersion:t.currentVersion,toVersion:t.availableVersion,artifactRef:t.artifactRef,runtimeArtifacts:t.runtimeArtifacts,impact:t.impact,status:"queued",rollout:{phase:"queued",desiredVersion:t.availableVersion,expectedInstanceIds:[],expectedInstanceCount:0,matchedInstanceCount:0,pendingInstanceCount:0,failedInstanceCount:0,deferredInstanceCount:0},createdAt:n,updatedAt:n}))}patch(e,t){const n=this.records.get(e);if(!n)throw Object.assign(new Error(`Update job ${e} was not found.`),{statusCode:404,code:"UPDATE_JOB_NOT_FOUND"});return this.records.put(wr.parse({...n,...t,id:e,createdAt:n.createdAt,updatedAt:de()}))}reconcileServerUpdates(e,t={}){if(t.processStarted)for(const e of this.list().filter(e=>"queued"===e.status))this.patch(e.id,{status:"failed",rollout:{...e.rollout,phase:"failed"},error:{code:"NODE_UPDATE_FAILED",message:"The node agent restarted before the update worker claimed this job.",retryable:!0},completedAt:de()});for(const n of this.list().filter(e=>["updating-node","restarting-node","converging-instances"].includes(e.status)))t.processStarted&&["restarting-node","converging-instances"].includes(n.status)&&e!==n.toVersion?this.patch(n.id,{status:"failed",rollout:{...n.rollout,phase:"failed",nodeVersion:e},error:{code:"NODE_UPDATE_FAILED",message:`Node agent restarted with version ${e}, expected ${n.toVersion}.`,retryable:!1},completedAt:de()}):e===n.toVersion&&this.patch(n.id,{status:"succeeded",rollout:{...n.rollout,phase:"succeeded",nodeVersion:e,expectedInstanceIds:[],expectedInstanceCount:0,matchedInstanceCount:0,pendingInstanceCount:0,failedInstanceCount:0,deferredInstanceCount:0},error:void 0,completedAt:de()})}}class yg{records;constructor(e){this.records=new uu(e.environmentTemplatesDir,{schema:Js,sanitize:e=>function(e,t){if(!e||"object"!=typeof e||Array.isArray(e))return e;const n=e,i=new Set(["id","name","sourceInstanceId","nodeId","imageId","internalTag","platform","architecture","sizeBytes","status","error","createdAt","updatedAt"]),s="string"==typeof n.id?n.id:void 0;for(const e of Object.keys(n))i.has(e)||t?.({templateId:s,field:e});const r=Oa(n,[...i]);if(n.error&&"object"==typeof n.error&&!Array.isArray(n.error)){const e=n.error;for(const n of Object.keys(e))["code","message","phase"].includes(n)||t?.({templateId:s,field:`error.${n}`});r.error=Oa(e,["code","message","phase"])}return r}(e,e=>{console.warn(JSON.stringify({message:"unknown stored environment template field was ignored",...e}))})})}init(){this.records.init();for(const e of this.records.list())"creating"===e.status&&this.records.put(Js.parse({...e,status:"failed",error:{code:"ENVIRONMENT_TEMPLATE_CREATION_INTERRUPTED",message:"Environment template creation was interrupted by a node-agent restart.",phase:"recovery"},updatedAt:de()}))}list(){return this.records.list()}get(e){return this.records.get(e)}put(e){return this.records.put(Js.parse(e))}patch(e,t){return this.records.patch(e,t)}delete(e){return this.records.delete(e)}}const Ig=c.z.object({id:c.z.string().trim().min(1).max(120),status:c.z.literal("pending"),input:vi,createdAt:c.z.string().datetime(),updatedAt:c.z.string().datetime(),expiresAt:c.z.string().datetime()}).strict();class _g{repository;workspaceProvisioningTtlMs;workspaceProvisioningCleanupTimer;constructor(e,t={}){this.workspaceProvisioningTtlMs=t.workspaceProvisioningTtlMs??864e5,this.repository=t.repository||Km(Jh(e)).git}init(){this.repository.deleteExpiredProvisioning((new Date).toISOString()),this.scheduleWorkspaceProvisioningCleanup()}putPayload(e){const t=Ii.parse(e),n=this.repository.getPayload(t.credential.id);if(n&&n.payload.credential.revision>t.credential.revision)throw function(e,t){return Object.assign(new Error(`Refusing stale payload revision for ${t}.`),{code:"GIT_CREDENTIAL_REVISION_STALE",statusCode:409})}(0,t.credential.id);if(n&&n.payload.credential.revision===t.credential.revision&&JSON.stringify(n.payload)!==JSON.stringify(t))throw function(e,t){return Object.assign(new Error(`Refusing conflicting payload revision for ${t}.`),{code:"GIT_CREDENTIAL_REVISION_CONFLICT",statusCode:409})}(0,t.credential.id);const i=(new Date).toISOString();return this.repository.putPayload({id:t.credential.id,payload:t,createdAt:n?.createdAt||i,updatedAt:i}).payload}getPayload(e){return this.repository.getPayload(e)?.payload}putAuthorizationSet(e){const t=_i.parse(e),n=this.repository.getAuthorization(t.instanceId),i=(new Date).toISOString();return this.publicAuthorizationSet(this.repository.putAuthorizationCas({id:t.instanceId,...t,createdAt:n?.createdAt||i}))}getAuthorizationSet(e){const t=this.repository.getAuthorization(e);return t?this.publicAuthorizationSet(t):{instanceId:e,generation:0,credentialIds:[],updatedAt:new Date(0).toISOString()}}resolve(e,t){const n=this.getAuthorizationSet(e).credentialIds.flatMap(e=>{const t=this.getPayload(e);return t?[t]:[]}),i=zi(t,n.map(e=>({id:e.credential.id,kind:e.credential.kind,scope:e.credential.scope,status:e.credential.status,pinnedKnownHosts:"ssh-key"===e.secret.kind&&Boolean(e.secret.pinnedKnownHosts.trim())}))),s="unique"===i.status?n.find(e=>e.credential.id===i.credential.id):void 0;return{match:i,payload:s}}removePayload(e){if(this.repository.listAuthorizations().some(t=>t.credentialIds.includes(e)))throw Object.assign(new Error(`Credential payload ${e} is still authorized.`),{code:"GIT_CREDENTIAL_PAYLOAD_IN_USE",statusCode:409});return this.repository.deletePayload(e)}collectUnreferencedPayloads(){return this.repository.collectUnreferencedPayloads()}removeInstance(e){const t=this.repository.deleteAuthorization(e)?1:0;return this.repository.deleteProvisioning(e),this.scheduleWorkspaceProvisioningCleanup(),t}putWorkspaceProvisioning(e){const t=vi.parse(e);if(!Eg(t))throw Object.assign(new Error("Only operation-only Git provisioning may be persisted."),{code:"GIT_CREDENTIAL_PROVISIONING_RETENTION_INVALID",statusCode:400});const n=this.repository.getProvisioning(t.instanceId);if("consumed"===n?.status&&n.operationId===t.operationId)return t;const i=(new Date).toISOString(),s=Ig.parse(this.repository.putProvisioning({id:t.instanceId,status:"pending",input:t,createdAt:n?.createdAt||i,updatedAt:i,expiresAt:new Date(Date.now()+this.workspaceProvisioningTtlMs).toISOString()})).input;return this.scheduleWorkspaceProvisioningCleanup(),s}getWorkspaceProvisioning(e){const t=this.repository.getProvisioning(e);if(t&&"pending"===t.status)return!Eg(t.input)||Date.parse(t.expiresAt)<=Date.now()?(this.repository.deleteProvisioning(e),void this.scheduleWorkspaceProvisioningCleanup()):t.input}removeWorkspaceProvisioning(e){const t=this.repository.deleteProvisioning(e);return this.scheduleWorkspaceProvisioningCleanup(),t}discardPendingWorkspaceProvisioning(e){const t=this.repository.getProvisioning(e);return!(!t||"pending"!==t.status)&&this.removeWorkspaceProvisioning(e)}completeWorkspaceProvisioning(e,t){const n=(new Date).toISOString(),i=this.repository.consumeProvisioning(e,t,n,new Date(Date.now()+6048e5).toISOString());return this.scheduleWorkspaceProvisioningCleanup(),i}workspaceProvisioningStatus(e){const t=this.repository.getProvisioning(e);if(t){if(!(Date.parse(t.expiresAt)<=Date.now()))return"pending"===t.status?{status:t.status,operationId:t.input.operationId}:{status:t.status,operationId:t.operationId};this.removeWorkspaceProvisioning(e)}}scheduleWorkspaceProvisioningCleanup(){this.workspaceProvisioningCleanupTimer&&clearTimeout(this.workspaceProvisioningCleanupTimer),this.workspaceProvisioningCleanupTimer=void 0;const e=Math.min(...this.repository.listProvisioning().map(e=>Date.parse(e.expiresAt)));Number.isFinite(e)&&(this.workspaceProvisioningCleanupTimer=setTimeout(()=>{this.workspaceProvisioningCleanupTimer=void 0;const e=Date.now();this.repository.deleteExpiredProvisioning(new Date(e).toISOString()),this.scheduleWorkspaceProvisioningCleanup()},Math.min(2147483647,Math.max(0,e-Date.now()))),this.workspaceProvisioningCleanupTimer.unref?.())}publicAuthorizationSet(e){const{id:t,createdAt:n,...i}=e;return _i.parse(i)}}function Eg(e){return e.credentials.length>0&&e.credentials.every(e=>"operation-only"===e.retention)}const Ag=function(e,t=process.env,n=e){let i;return()=>{const s=t.TASK_HANDOFF_VERSION?.trim();return s||(i||=k(e,t,n),i)}}("@task-handoff/node-agent",process.env,"@task-handoff/control-plane");function Tg(){return Ag()}function bg(e,t){return{code:"INSTANCE_RUNTIME_VERSION_MISMATCH",message:`Expected controlled-instance ${e}, received ${t||"an unknown version"}.`,expectedVersion:e,...t?{actualVersion:t}:{},retryable:!0}}function wg(e){const t=Tg();return e===t?{desiredVersion:t,actualVersion:e,phase:"matched",attempt:0,matchedAt:(new Date).toISOString()}:{desiredVersion:t,...e?{actualVersion:e}:{},phase:"pending",attempt:0,error:bg(t,e)}}function Sg(e,t,n=!0){if(!n){const n=Tg(),i=e.runtimeVersion;return"matched"===i?.phase&&i.desiredVersion===n&&i.actualVersion===t?i:wg(t)}const i=Tg(),s=e.runtimeVersion;if(!s||s.desiredVersion!==i)return wg(t);const r="INSTANCE_RUNTIME_VERSION_MISMATCH"!==s.error?.code?s.error:t===i?void 0:bg(i,t);return _r.parse({...s,desiredVersion:i,...t?{actualVersion:t}:{actualVersion:void 0},..."pending"===s.phase?{error:r||(t!==i?bg(i,t):void 0)}:{}})}const Ng={requiresImage:!1,supportsControlledInstanceApi:!0,supportsContainerLifecycle:!1,supportsAppSessions:!0,supportsHostSessions:!0,artifactKind:"none",isolation:"none"};function vg(e){return"local"===e?{...Ng}:{}}function Og(e,t={}){return{...t,...vg(e)}}function Rg(e){return"none"!==e.capabilities.artifactKind}const zg=c.z.object({version:c.z.literal(1),externalListener:ra,modelRelay:da.optional(),wslRuntime:c.z.object({enabled:c.z.boolean()}).strict().optional()}).strict();function xg(e){return"all-ipv4"===e?"0.0.0.0":"127.0.0.1"}function Cg(e,t){return ra.parse({bindScope:"0.0.0.0"===e.trim()?"all-ipv4":"loopback",port:t})}function kg(e){if(!e||"object"!=typeof e||Array.isArray(e))return e;const t=e,n=t.externalListener&&"object"==typeof t.externalListener&&!Array.isArray(t.externalListener)?t.externalListener:{},i=t.modelRelay,s=t.wslRuntime,r=Object.keys(t).filter(e=>"version"!==e&&"externalListener"!==e&&"modelRelay"!==e&&"wslRuntime"!==e),o=Object.keys(n).filter(e=>"bindScope"!==e&&"port"!==e);let a,c,d;if(void 0!==i)if(i&&"object"==typeof i&&!Array.isArray(i)&&"boolean"==typeof i.enabled){const e=i,t=Object.keys(e).filter(e=>"enabled"!==e&&"unknownModelPolicy"!==e),n=e.unknownModelPolicy,s=void 0!==n&&"passthrough"!==n&&"reject"!==n;t.length&&console.warn(JSON.stringify({message:"unknown stored node agent runtime setting fields were ignored",filePath:"runtime-settings.json",fields:t.map(e=>`modelRelay.${e}`)})),s&&console.warn(JSON.stringify({message:"invalid stored node agent model relay unknown model policy was normalized to passthrough",filePath:"runtime-settings.json",field:"modelRelay.unknownModelPolicy"})),a={enabled:e.enabled,..."passthrough"===n||"reject"===n?{unknownModelPolicy:n}:{}}}else c=i&&"object"==typeof i&&!Array.isArray(i)?"enabled":"modelRelay";let l=!1;if(void 0!==s)if(s&&"object"==typeof s&&!Array.isArray(s)&&"boolean"==typeof s.enabled){const e=s,t=Object.keys(e).filter(e=>"enabled"!==e);t.length&&console.warn(JSON.stringify({message:"unknown stored node agent runtime setting fields were ignored",filePath:"runtime-settings.json",fields:t.map(e=>`wslRuntime.${e}`)})),d={enabled:e.enabled}}else l=!0;return(r.length||o.length)&&console.warn(JSON.stringify({message:"unknown stored node agent runtime setting fields were ignored",filePath:"runtime-settings.json",fields:[...r,...o.map(e=>`externalListener.${e}`)]})),l&&console.warn(JSON.stringify({message:"invalid stored node agent wsl runtime setting was normalized to disabled",filePath:"runtime-settings.json",field:"wslRuntime.enabled"})),c&&console.warn(JSON.stringify({message:"invalid stored node agent model relay setting was normalized to disabled",filePath:"runtime-settings.json",field:"modelRelay"===c?"modelRelay":"modelRelay.enabled"})),{version:t.version,externalListener:{bindScope:n.bindScope,port:n.port},...a?{modelRelay:a}:{},...d?{wslRuntime:d}:{}}}function Dg(e,t){return new pu(e.settingsPath,()=>({version:1,externalListener:t}),{schema:zg,sanitize:kg})}const Lg="runtime_local_host",Pg="runtime_wsl_host",Mg="task-handoff.node-agent.builtin";function jg(e){const t={...e};return delete t[Mg],t}function Ug(e){return"local-folder"===e.type?Lr.parse({mode:"local-bind",path:"/workspace",readOnly:!1}):Lr.parse({mode:"git-clone",path:"/workspace",readOnly:!1})}function Fg(e){const t=Dr.parse(e.source),n=e.projectId||("local-folder"===t.type?t.localFolderId:void 0)||("git-repository"===t.type?t.repositoryId:void 0)||("git-template"===t.type?t.templateId:void 0)||`project_${e.id}`;return Hr.parse({id:n,name:"string"==typeof e.sourceSnapshot.name?e.sourceSnapshot.name:e.name,source:t,defaultImageSelection:e.imageSelection,defaultNodeId:e.nodeId,workspacePolicy:Ug(t),labels:{},createdAt:e.createdAt,updatedAt:e.updatedAt})}function $g(e,t){throw Object.assign(new Error(t),{statusCode:403,code:e})}function Hg(e,t){e!==Qi&&console.warn(JSON.stringify({message:"protocol version mismatch",peer:t,expectedProtocolVersion:Qi,actualProtocolVersion:e||"missing",errorCode:"PROTOCOL_VERSION_MISMATCH"}))}function Bg(e={}){return Og("local",e)}class qg{onStored;records;constructor(e){this.records=e}init(){}setOnStored(e){this.onStored=e}put(e){const t=this.records.put(Ia.parse(e));return this.onStored?.(t),t}putObservation(e){const t=this.records.putObservation(Ia.parse(e));return this.onStored?.(t),t}get(e){return this.records.get(e)}list(){return this.records.list()}delete(e){return this.records.delete(e)}}class Vg{nodeId;paths;persistence;localFolders;nodeRuntimes;controlledInstances;environmentTemplates;instancePrivateConfigs;modelRegistry;modelRelaySwitch;gitCredentials;updateJobs;node;listenerPort;platform;containerUrlOverride;builtinFolders;constructor(e,t,n,i,r,o,a){this.paths=e,this.nodeId=t,this.platform=o;const c=a||Km(Jh(e));this.persistence=c,c.topology.nodeIdentity.ensure(t,de()),this.localFolders=c.topology.localFolders,this.nodeRuntimes=c.topology.runtimes,this.instancePrivateConfigs=new uc(e),this.controlledInstances=new qg(c.topology.instances),this.environmentTemplates=new yg(e),this.gitCredentials=new _g(e,{repository:c.git}),this.modelRelaySwitch=new dg,this.modelRegistry=new sg(e,t,{has:e=>Boolean(this.controlledInstances.get(e)),list:()=>this.listInstances(),require:e=>this.requireInstance(e),put:e=>this.controlledInstances.put(e)},c.model,{enabled:()=>this.modelRelaySwitch.enabled(),unknownModelPolicy:()=>this.modelRelaySwitch.unknownModelPolicy(),originFor:e=>"docker"===e.runtime.kind?this.containerUrl:`http://127.0.0.1:${this.listenerPort}`}),this.updateJobs=new fg(e),this.listenerPort=r,this.containerUrlOverride=i;const d=de();this.node=Yo.parse({id:t,name:Yo.shape.name.safeParse(s.hostname()).data||t,connectionMode:"direct-http",endpoint:n,controlEndpoint:n,containerEndpoint:this.containerUrl,publicWebBase:n?n.replace(/:\d+$/,""):void 0,status:"online",health:"ok",capabilities:{},labels:{},createdAt:d,updatedAt:d})}init(){for(const e of this.localFolders.list())this.localFolders.put(e);if(this.instancePrivateConfigs.init(),this.controlledInstances.init(),this.environmentTemplates.init(),this.gitCredentials.init(),this.modelRegistry.init(),this.updateJobs.init(),this.updateJobs.reconcileServerUpdates(Tg(),{processStarted:!0}),!this.nodeRuntimes.get("runtime_local_docker")){const e=de();this.nodeRuntimes.put(Qo.parse({id:"runtime_local_docker",nodeId:this.nodeId,name:"Local Docker",type:"docker",status:"unknown",accessStrategy:"direct-port",capabilities:{},labels:{},createdAt:e,updatedAt:e}))}const e=this.nodeRuntimes.get(Lg),t=de();this.nodeRuntimes.put(Qo.parse({id:Lg,nodeId:this.nodeId,name:"Local Runtime",type:"local",status:e?.status||"unknown",accessStrategy:"node-proxy",capabilities:Bg(e?.capabilities),labels:{...e?.labels,[Mg]:"true"},createdAt:e?.createdAt||t,updatedAt:e?.updatedAt||t}));const n=this.nodeRuntimes.get(Pg),i=Dg(this.paths,Cg("127.0.0.1",this.listenerPort)).get();if("win32"===this.platform&&function(e,t=process.env){const n=function(e){const t=String(e??"").trim().toLowerCase();if(t)return!!["1","true","yes","on"].includes(t)||!["0","false","no","off"].includes(t)&&void 0}(t.TASK_HANDOFF_WSL_RUNTIME_ENABLED);return void 0!==n?n:!0===e.wslRuntime?.enabled}(i)){const e=de();this.nodeRuntimes.put(Qo.parse({id:Pg,nodeId:this.nodeId,name:"WSL",type:"wsl",status:n?.status||"unknown",accessStrategy:"node-proxy",capabilities:na(n?.capabilities),labels:{...n?.labels,[Mg]:"true"},createdAt:n?.createdAt||e,updatedAt:e}))}for(const e of this.nodeRuntimes.list())e.nodeId!==this.nodeId&&this.nodeRuntimes.put(Qo.parse({...e,nodeId:this.nodeId,updatedAt:de()}));for(const e of this.localFolders.list())e.nodeId!==this.nodeId&&this.localFolders.put(kr.parse({...e,nodeId:this.nodeId,updatedAt:de()}));this.normalizeInstanceRuntimeVersions()}normalizeInstanceRuntimeVersions(){for(const e of this.controlledInstances.list()){const t=wg(e.build?.packageVersion||e.instanceVersion),n=Rg(this.requireRuntime(e.runtimeId)),i=["created","stopped","failed"].includes(e.status),s=n&&e.runtimeVersion?.desiredVersion===t.desiredVersion?e.runtimeVersion:void 0,r=n?"matched"===t.phase?i?t:{...t,phase:"verifying",matchedAt:void 0}:{...t,phase:"pending",attempt:s?.attempt||0,lastAttemptAt:s?.lastAttemptAt,error:s?.error||t.error}:t;this.controlledInstances.put(Ia.parse({...e,ready:!1,runtimeVersion:r,updatedAt:de()}))}}get localNodeAgentUrl(){return`http://127.0.0.1:${this.listenerPort}`}get currentListenerPort(){return this.listenerPort}get containerUrl(){return this.containerUrlOverride||`http://host.docker.internal:${this.listenerPort}`}setListenerPort(e){this.listenerPort=e,this.node.containerEndpoint=this.containerUrl,this.node.updatedAt=de()}runningInstanceCount(){const e=new Set(["created","stopped","failed"]);return this.listInstances().filter(t=>!e.has(t.status)).length}createLocalFolder(e){const t=de(),i=bl(e.path),s=kr.parse({...e,name:e.name.trim()||n.basename(i),path:i,id:e.id||du("folder"),nodeId:this.nodeId,labels:e.labels||{},createdAt:t,updatedAt:t});return this.localFolders.put(s)}attachBuiltinProjectFolders(e){this.builtinFolders=e}listLocalFolders(){return[...this.localFolders.list(),...this.builtinFolders?.list()||[]]}resolveLocalFolder(e){return this.localFolders.get(e)||this.builtinFolders?.get(e)}updateLocalFolder(e,t){const i=this.localFolders.get(e);if(!i)throw this.builtinFolderReadOnlyError(e,"renamed");return this.localFolders.put(kr.parse({...i,name:t.name.trim()||n.basename(i.path),updatedAt:de()}))}deleteLocalFolder(e){if(this.localFolders.get(e))return this.localFolders.delete(e);if(this.builtinFolders?.owns(e))throw this.builtinFolderReadOnlyError(e,"removed");return!1}builtinFolderReadOnlyError(e,t){return this.builtinFolders?.owns(e)?Object.assign(new Error(`Built-in project folder ${e} is owned by the node agent and cannot be ${t}.`),{statusCode:409,code:"NODE_LOCAL_FOLDER_BUILTIN_READONLY"}):Object.assign(new Error(`Local folder ${e} was not found.`),{statusCode:404,code:"NODE_LOCAL_FOLDER_NOT_FOUND"})}createRuntime(e){if("local"===e.type){const e=new Error("Local Runtime is built in and cannot be added manually.");throw Object.assign(e,{statusCode:409,code:"LOCAL_RUNTIME_BUILTIN"}),e}const t=de(),n=Qo.parse({...e,id:e.id||du("runtime"),nodeId:this.nodeId,accessStrategy:e.accessStrategy||(i=e.type,"docker"===i?"direct-port":"node-proxy"),capabilities:e.capabilities||{},labels:jg(e.labels),createdAt:t,updatedAt:t});var i;return this.nodeRuntimes.put(n)}updateRuntime(e,t){const n=this.requireRuntime(e);if("true"===n.labels[Mg]){const t=new Error(`Built-in runtime ${e} cannot be modified.`);throw Object.assign(t,{statusCode:400,code:"NODE_RUNTIME_BUILTIN"}),t}if("local"===n.type||"local"===t.type){const e=new Error("Local Runtime is built in and cannot be configured manually.");throw Object.assign(e,{statusCode:409,code:"LOCAL_RUNTIME_BUILTIN"}),e}const i=Qo.parse({...n,...t,id:n.id,nodeId:this.nodeId,accessStrategy:t.accessStrategy||n.accessStrategy,capabilities:t.capabilities||n.capabilities,labels:t.labels?jg(t.labels):n.labels,createdAt:n.createdAt,updatedAt:de()});return this.nodeRuntimes.put(i)}deleteRuntime(e){if("true"===this.requireRuntime(e).labels[Mg]){const t=new Error(`Built-in runtime ${e} cannot be deleted.`);throw Object.assign(t,{statusCode:400,code:"NODE_RUNTIME_BUILTIN"}),t}const t=this.listInstances().filter(t=>t.runtimeId===e);if(t.length){const n=new Error(`Runtime ${e} is used by ${t.length} instance${1===t.length?"":"s"}.`);throw Object.assign(n,{statusCode:409,code:"NODE_RUNTIME_IN_USE"}),n}return this.nodeRuntimes.delete(e)}recordRuntimeProbe(e,t){const n=this.requireRuntime(e),i=Qo.parse({...n,...t,id:n.id,nodeId:this.nodeId,accessStrategy:t.accessStrategy||n.accessStrategy,capabilities:t.capabilities||n.capabilities,labels:t.labels||n.labels,createdAt:n.createdAt,updatedAt:de()});return this.nodeRuntimes.put(i)}checkRuntime(e,t){if(!t.check)return this.recordRuntimeProbe(e,{status:"unknown"});const n=this.requireRuntime(e);return Promise.resolve(t.check(n)).then(t=>this.recordRuntimeProbe(e,t))}requireRuntime(e){const t=this.nodeRuntimes.get(e);if(!t){const t=new Error(`Node runtime ${e} was not found.`);throw Object.assign(t,{statusCode:404,code:"NODE_RUNTIME_NOT_FOUND"}),t}return t}requireInstance(e){const t=this.controlledInstances.get(e);if(!t){const t=new Error(`Instance ${e} was not found on node ${this.nodeId}.`);throw Object.assign(t,{statusCode:404,code:"NODE_INSTANCE_NOT_FOUND"}),t}const n=wa(t);if(!n.success)throw function(e,t){const n=t.map(e=>`${e.path.join(".")||"body"}: ${e.message}`).join("; ");return Object.assign(new Error(`Stored instance ${e} is not compatible with protocol ${Qi}: ${n}`),{statusCode:409,code:"NODE_INSTANCE_PAYLOAD_INVALID"})}(e,n.error.issues);return n.data}applyInstanceLifecycle(e,t){return this.controlledInstances.put(function(e,t,n=(new Date).toISOString()){switch(t.type){case"start-requested":return Ia.parse({...e,status:"starting",ready:!1,updatedAt:n});case"stop-requested":return Ia.parse({...e,status:"stopping",ready:!1,updatedAt:n});case"stop-failed":return"stopping"!==e.status?e:Ia.parse({...e,status:t.baseline.status,health:t.baseline.health,connectionStatus:t.baseline.connectionStatus,agentStatus:t.baseline.agentStatus,targetStatus:t.baseline.targetStatus,uiAccessStatus:t.baseline.uiAccessStatus,ready:t.baseline.ready,target:{...e.target,status:t.baseline.target.status},updatedAt:n});case"convergence-restart-requested":return Ia.parse({...e,build:void 0,instanceVersion:void 0,ready:!1,updatedAt:n});case"runtime-lifecycle-completed":return function(e,t,n,i){if(t.stateRevision>e.stateRevision&&["failed","stopping","stopped","deleting"].includes(t.status))return t;const s=t.stateRevision>e.stateRevision&&t.lastHeartbeatAt!==e.lastHeartbeatAt&&"online"===t.agentStatus;return Ia.parse({...t,...n,...s?{status:t.status,health:t.health,connectionStatus:t.connectionStatus,agentStatus:t.agentStatus,targetStatus:t.targetStatus,uiAccessStatus:t.uiAccessStatus}:{},ready:!!s&&t.ready,target:n.target?{...t.target,...n.target}:t.target,workspace:n.workspace?s?{...n.workspace,...t.workspace}:{...t.workspace,...n.workspace}:t.workspace,runtime:n.runtime?{...t.runtime,...n.runtime}:t.runtime,updatedAt:i})}(t.baseline,e,t.observation,n);case"stop-completed":return Ia.parse({...e,status:"stopped",health:"unknown",connectionStatus:"offline",ready:!1,agentStatus:"offline",targetStatus:"unknown",uiAccessStatus:"unknown",target:{...e.target,status:"unknown"},updatedAt:n});case"runtime-exited":case"start-failed":return Ia.parse({...e,status:"failed",ready:!1,health:"failed",connectionStatus:"offline",agentStatus:"offline",targetStatus:"unknown",uiAccessStatus:"unknown",workspace:{...e.workspace,error:(i=t.error,i instanceof Error?i.message:String(i))},updatedAt:n})}var i}(this.requireInstance(e),t))}listInstances(){return this.controlledInstances.list().flatMap(e=>{const t=wa(e);return t.success?[t.data]:[]})}resolvedAssignedModelEnvironment(e){return this.modelRegistry.resolvedEnvironment(e)}createInstance(e){const t=this.requireRuntime(e.runtimeId),i=de(),s=e.id||du("inst"),r=function(e){const t=Dr.parse(e);return"local-folder"===t.type?t:Dr.parse({...t,auth:{type:"none"}})}(e.source),o=e.environmentSource||(e.imageSelection?{type:"image",imageSelection:e.imageSelection}:void 0);if("template"===o?.type&&"docker"!==t.type){const e=new Error(`Runtime ${t.name} does not support environment templates.`);throw Object.assign(e,{statusCode:409,code:"ENVIRONMENT_TEMPLATE_RUNTIME_UNSUPPORTED"}),e}const a="template"===o?.type?this.environmentTemplates.get(o.environmentTemplateId):void 0;if("template"===o?.type&&(!a||"ready"!==a.status)){const e=new Error(`Environment template ${o.environmentTemplateId} is not ready on node ${this.nodeId}.`);throw Object.assign(e,{statusCode:a?409:404,code:a?"ENVIRONMENT_TEMPLATE_NOT_READY":"ENVIRONMENT_TEMPLATE_NOT_FOUND"}),e}if(a&&a.nodeId!==this.nodeId){const e=new Error(`Environment template ${a.id} belongs to node ${a.nodeId}, not ${this.nodeId}.`);throw Object.assign(e,{statusCode:409,code:"ENVIRONMENT_TEMPLATE_NODE_MISMATCH"}),e}if(function(e){return"boolean"==typeof e.capabilities.requiresImage?e.capabilities.requiresImage:"local"!==e.type}(t)&&(!o||"image"===o.type&&!e.image)){const e=new Error(`Runtime ${t.name} requires an image.`);throw Object.assign(e,{statusCode:400,code:"NODE_RUNTIME_IMAGE_REQUIRED"}),e}if("local"===t.type&&"local-folder"!==r.type){const e=new Error("Localhost runtime currently supports local folder sources only.");throw Object.assign(e,{statusCode:400,code:"LOCAL_RUNTIME_REQUIRES_LOCAL_FOLDER"}),e}if("local"===t.type&&this.listInstances().some(e=>"local"===this.requireRuntime(e.runtimeId).type)){const e=new Error("A localhost instance already exists on this node.");throw Object.assign(e,{statusCode:409,code:"LOCAL_RUNTIME_INSTANCE_EXISTS"}),e}const c=a?Co.parse({id:a.id,origin:"custom",name:a.name,repository:"task-handoff/environment-template",tag:a.id.toLowerCase().replace(/[^a-z0-9_.-]/g,"-"),requestedReference:a.internalTag,resolvedDigest:a.imageId,resolvedReference:a.internalTag,downloadSizeBytes:a.sizeBytes||void 0,pullPolicy:"if-not-present",capabilities:[],optionalApps:[],defaultEnv:{},labels:{},createdAt:a.createdAt,updatedAt:a.updatedAt}):e.image?Co.parse(e.image):void 0,d="local"===t.type&&"local-folder"===r.type?n.resolve(r.path):void 0,l=Ug(r),u=Ia.parse({id:s,name:e.name||`instance-${s.replace(/^inst_?/,"").slice(0,6)}`,source:r,sourceSnapshot:e.sourceSnapshot||{},modelSelection:e.modelSelection,projectId:e.projectId,nodeId:this.nodeId,runtimeId:t.id,imageSelection:"image"===o?.type?o.imageSelection:void 0,environmentSource:o,environmentTemplateOrigin:a?{templateId:a.id,nodeId:a.nodeId,imageId:a.imageId,name:a.name,platform:a.platform,architecture:a.architecture}:void 0,imageSnapshot:c,imageProvisioning:c&&"docker"===t.type&&"template"!==o?.type?{phase:"checking-image",requestedReference:c.requestedReference,generation:0,startedAt:i,updatedAt:i}:void 0,status:c&&"docker"===t.type&&"template"!==o?.type?"provisioning":"created",health:"unknown",connectionStatus:"unknown",agentStatus:"unknown",targetStatus:"unknown",uiAccessStatus:"unknown",controlMode:"controlled",ready:!1,runtimeVersion:wg(),capabilities:{},config:{autoImportAgentConfigs:e.config?.autoImportAgentConfigs??!0,codexConfigEnabled:e.config?.codexConfigEnabled??!0,codexHomeMode:e.config?.codexHomeMode??("local"===t.type?"taskhandoff":"default"),defaultCodexPermissionMode:e.config?.defaultCodexPermissionMode??("docker"===t.type?"full-access":"ask"),...e.config?.codexSettings?{codexSettings:e.config.codexSettings}:{},aiSessionHistoryLimit:e.config?.aiSessionHistoryLimit??50,aiSessionAttachmentRetentionDays:e.config?.aiSessionAttachmentRetentionDays??30,aiSessionMaxFileAttachmentBytes:e.config?.aiSessionMaxFileAttachmentBytes??ke},workspace:"local"===t.type?{mode:"local-bind",status:"unknown",path:d}:"local-folder"===r.type?{status:"unknown"}:{mode:"git-clone",status:"pending",path:l.path,gitProvisioning:{phase:"pending",remoteUrl:r.url,generation:0,startedAt:i,updatedAt:i}},target:{strategy:"node-proxy",status:"unknown"},runtime:"local"===t.type?{kind:"local",workspacePath:d,labels:{"task-handoff.runtime-kind":"local"}}:{labels:{}},registrationToken:lu(),createdAt:i,updatedAt:i}),p=this.persistence.transactionSync(()=>{let t=this.controlledInstances.put(u);const n=e.modelSelection;return n&&Object.values(n).some(e=>Array.isArray(e)?e.length>0:Boolean(e))&&(t=this.modelRegistry.assign(s,{modelSelection:n,modelEntityIds:n.modelEntityIds,codexModelHash:n.codexModelHash,claudeModelHash:n.claudeModelHash,opencodeModelHash:n.opencodeModelHash}).instance),e.gitWorkspaceProvisioning?.credentials.every(e=>"operation-only"===e.retention)&&this.gitCredentials.putWorkspaceProvisioning(e.gitWorkspaceProvisioning),t});return this.instancePrivateConfigs.materialize(p.id,p.registrationToken,this.resolvedAssignedModelEnvironment(p.id),this.modelRegistry.privateCatalog(p.id),p.config.codexSettings),p}takeGitWorkspaceProvisioning(e){const t=this.gitCredentials.getWorkspaceProvisioning(e);return this.gitCredentials.removeWorkspaceProvisioning(e),t}setGitWorkspaceProvisioning(e){const t=this.requireInstance(e.instanceId);if("local-folder"===t.source.type||t.source.url!==e.remoteUrl)throw Object.assign(new Error(`Git provisioning does not match instance ${t.id}.`),{code:"GIT_WORKSPACE_PROVISIONING_INSTANCE_MISMATCH",statusCode:409});this.gitCredentials.putWorkspaceProvisioning(e)}gitWorkspaceProvisioningFor(e){if("local-folder"===e.source.type)return;const t=this.gitCredentials.getWorkspaceProvisioning(e.id);if(t)return t;const n=this.gitCredentials.getAuthorizationSet(e.id).credentialIds.flatMap(e=>{const t=this.gitCredentials.getPayload(e);return t?[t]:[]}),i=n.map(e=>({id:e.credential.id,kind:e.credential.kind,scope:e.credential.scope,status:e.credential.status,pinnedKnownHosts:"ssh-key"===e.secret.kind&&Boolean(e.secret.pinnedKnownHosts.trim())})),s=zi(e.source.url,i);if("ambiguous"===s.status||"missing-host-key"===s.status)throw Object.assign(new Error(`Git credential resolution failed for instance ${e.id}: ${s.status}.`),{code:`GIT_CREDENTIAL_${s.status.replace(/-/g,"_").toUpperCase()}`,statusCode:409});return{operationId:`gitop_${e.id}_${e.stateRevision}`,instanceId:e.id,remoteUrl:e.source.url,ref:e.source.ref,clone:e.source.clone,credentials:n.map((t,n)=>({operationId:`gitcredop_${e.id}_${e.stateRevision}_${n}`,retention:"instance-retained",payload:t}))}}discardGitWorkspaceProvisioning(e){return this.gitCredentials.discardPendingWorkspaceProvisioning(e)}gitWorkspaceProvisioningStatus(e){return this.gitCredentials.workspaceProvisioningStatus(e)}registerInstance(e,t,n){const i=Ra.parse(t),s=de(),r=this.controlledInstances.get(e);if(!r){const t=new Error(`Instance ${e} was not found on node ${this.nodeId}.`);throw Object.assign(t,{statusCode:404,code:"NODE_INSTANCE_NOT_FOUND"}),t}if(this.validateInstanceReport(r,i,n),i.processIncarnationId&&i.processIncarnationId===r.processIncarnationId)return r;Hg(i.protocolVersion,`Instance ${e}`);const o=i.build?.packageVersion||i.instanceVersion,a=Rg(this.requireRuntime(r.runtimeId)),c=Sg(r,o,a),d=Ia.parse({...r,status:"registered",health:o===Tg()?"ok":"degraded",ready:!a&&o===Tg(),connectionStatus:"online",agentStatus:"online",targetStatus:r.targetStatus,uiAccessStatus:r.uiAccessStatus,controlMode:i.controlMode,protocolVersion:i.protocolVersion,instanceVersion:i.instanceVersion,build:i.build,runtimeVersion:c,processIncarnationId:i.processIncarnationId||r.processIncarnationId,capabilities:i.capabilities,appInventory:i.appInventory,workspace:{...i.workspace,...r.workspace.gitProvisioning?{gitProvisioning:r.workspace.gitProvisioning}:{}},target:r.target,registrationToken:r.registrationToken||i.registrationToken,lastHeartbeatAt:s,updatedAt:s});return this.controlledInstances.putObservation(d)}heartbeatInstance(e,t,n){const i=this.requireInstance(e);this.validateInstanceToken(i,n);const s=za.parse(t);i.processIncarnationId&&s.processIncarnationId&&s.processIncarnationId!==i.processIncarnationId&&function(e,t){throw Object.assign(new Error(t),{statusCode:409,code:"INSTANCE_PROCESS_INCARNATION_MISMATCH"})}(0,`Instance ${e} report belongs to an obsolete controlled-instance process.`),Hg(s.protocolVersion,`Instance ${e}`);const r=de(),o=i.target,a=i.targetStatus,c=Sg(i,s.build?.packageVersion||i.build?.packageVersion||i.instanceVersion,Rg(this.requireRuntime(i.runtimeId))),d=s.health||i.health,l="running"===(s.status||i.status)&&"failed"!==d,u=Ia.parse({...i,...s,...s.workspace&&i.workspace.gitProvisioning?{workspace:{...s.workspace,gitProvisioning:i.workspace.gitProvisioning}}:{},target:o,ready:l,health:d,runtimeVersion:c,processIncarnationId:s.processIncarnationId||i.processIncarnationId,agentStatus:"online",targetStatus:a,uiAccessStatus:a,connectionStatus:"online",build:s.build||i.build,lastHeartbeatAt:r,updatedAt:r});return this.controlledInstances.putObservation(u)}validateInstanceReport(e,t,n){this.validateInstanceToken(e,n||t.registrationToken),t.instanceId&&t.instanceId!==e.id&&$g("INSTANCE_ID_MISMATCH",`Instance ${t.instanceId} cannot register as ${e.id}.`),t.nodeId&&t.nodeId!==this.nodeId&&$g("INSTANCE_NODE_MISMATCH",`Instance ${e.id} belongs to node ${this.nodeId}.`),t.runtimeId&&t.runtimeId!==e.runtimeId&&$g("INSTANCE_RUNTIME_MISMATCH",`Instance ${e.id} belongs to runtime ${e.runtimeId}.`),t.imageSelection&&t.imageSelection.imageId!==e.imageSelection?.imageId&&$g("INSTANCE_IMAGE_MISMATCH",`Instance ${e.id} belongs to image ${e.imageSelection?.imageId}.`)}validateInstanceToken(e,t){e.registrationToken&&t===e.registrationToken||$g("INSTANCE_REGISTRATION_TOKEN_INVALID",`Invalid registration token for instance ${e.id}.`)}authenticateInstance(e,t){const n=this.requireInstance(e);return this.validateInstanceToken(n,t),n}context(e,t=this.resolvedAssignedModelEnvironment(e.id)){const n=t,i=e.imageSnapshot||Co.parse({id:"img_localhost",origin:"custom",name:"Localhost",repository:"localhost",tag:"local",requestedReference:"localhost:local",pullPolicy:"if-not-present",capabilities:[],optionalApps:[],defaultEnv:{},labels:{},createdAt:e.createdAt,updatedAt:e.updatedAt}),s=this.instancePrivateConfigs.materialize(e.id,e.registrationToken,n,this.modelRegistry.privateCatalog(e.id),e.config.codexSettings),r=this.gitWorkspaceProvisioningFor(e);return{project:Fg(e),image:i,node:this.node,runtime:this.requireRuntime(e.runtimeId),instance:e,nodeAgentUrl:this.containerUrl,modelEnv:n,privateConfigPath:this.instancePrivateConfigs.filePath(s.instanceId),...r?{gitWorkspaceProvisioning:r,completeGitWorkspaceProvisioning:()=>this.gitCredentials.completeWorkspaceProvisioning(e.id,r.operationId)}:{}}}}async function Gg(e,t){const n=function(e){const t=Xg(e),n=[],i=t.pathname.split("/").filter(Boolean).at(-1)||"";return tf(n,Kg(t.toString(),/^v\d+$/.test(i)?"models":"v1/models")),tf(n,new URL("/v1/models",t.origin).toString()),tf(n,new URL("/models",t.origin).toString()),n}(t.endpoint),i=Date.now();let s;for(const r of n){const n=await Jg(e,r,{method:"GET",headers:{accept:"application/json",authorization:`Bearer ${t.key}`}});if(404===n.status||405===n.status){s=n.status;continue}if(!n.ok)throw Zg("MODEL_DISCOVERY_FAILED",n.status);const o=await Qg(n,"MODEL_DISCOVERY_RESPONSE_INVALID"),a=Array.isArray(o.data)?o.data:void 0;if(!a)throw ef("MODEL_DISCOVERY_RESPONSE_INVALID","The model endpoint returned an invalid model list.",502);const c=a.flatMap(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return[];const t=e,n="string"==typeof t.id?t.id.trim():"";if(!n)return[];const i="string"==typeof t.owned_by?t.owned_by.trim():"";return[{id:n,...i?{ownedBy:i}:{}}]}).sort((e,t)=>e.id.localeCompare(t.id));return{models:nf(c),latencyMs:Date.now()-i}}throw ef("MODEL_DISCOVERY_UNSUPPORTED","No compatible model-list endpoint was found for this endpoint.",502,s)}async function Wg(e,t){const n=Date.now(),i=t.protocol||("claude"===t.app?"anthropic-messages":"opencode"===t.app?"openai-chat-completions":"openai-responses"),s="openai-responses"===i?await Jg(e,Yg(t.endpoint,"responses"),{method:"POST",headers:{accept:"application/json",authorization:`Bearer ${t.key}`,"content-type":"application/json"},body:JSON.stringify({model:t.model,input:"Reply with OK.",max_output_tokens:32,stream:!1})}):"openai-chat-completions"===i?await Jg(e,Yg(t.endpoint,"chat/completions"),{method:"POST",headers:{accept:"application/json",authorization:`Bearer ${t.key}`,"content-type":"application/json"},body:JSON.stringify({model:t.model,messages:[{role:"user",content:"Reply with OK."}],max_tokens:32,stream:!1})}):await Jg(e,function(e){const t=Xg(e);if(/\/messages\/?$/.test(t.pathname))return t.toString();const n=t.pathname.split("/").filter(Boolean).at(-1)||"";return Kg(t.toString(),/^v\d+$/.test(n)?"messages":"v1/messages")}(t.endpoint),{method:"POST",headers:{accept:"application/json","anthropic-version":"2023-06-01","content-type":"application/json","x-api-key":t.key},body:JSON.stringify({model:t.model,max_tokens:8,messages:[{role:"user",content:"Reply with OK."}]})});if(!s.ok)throw Zg("MODEL_TEST_FAILED",s.status);if((await Qg(s,"MODEL_TEST_RESPONSE_INVALID")).error)throw ef("MODEL_TEST_RESPONSE_INVALID","The model endpoint returned an error payload.",502);return{success:!0,latencyMs:Date.now()-n}}function Kg(e,t){const n=Xg(e);return n.pathname=`${n.pathname.replace(/\/+$/,"")}/${t.replace(/^\/+/,"")}`,n.search="",n.hash="",n.toString()}function Yg(e,t){const n=Xg(e);return n.pathname.replace(/\/+$/,"").endsWith(`/${t}`)?n.toString():Kg(n.toString(),t)}function Xg(e){let t;try{t=new URL(e.trim())}catch{throw ef("MODEL_ENDPOINT_INVALID","The model endpoint must be a valid HTTP or HTTPS URL.",400)}if("http:"!==t.protocol&&"https:"!==t.protocol||t.username||t.password)throw ef("MODEL_ENDPOINT_INVALID","The model endpoint must be an HTTP or HTTPS URL without embedded credentials.",400);return t}async function Jg(e,t,n){try{return await e(t,{...n,redirect:"error",signal:AbortSignal.timeout(15e3)})}catch(e){const t=e&&"object"==typeof e&&"name"in e&&"TimeoutError"===e.name;throw ef(t?"MODEL_ENDPOINT_TIMEOUT":"MODEL_ENDPOINT_UNREACHABLE",t?"The model endpoint timed out.":"The model endpoint could not be reached.",t?504:502)}}async function Qg(e,t){const n=await e.text();if(n.length>1e6)throw ef(t,"The model endpoint response was too large.",502);try{const e=JSON.parse(n);if(!e||"object"!=typeof e||Array.isArray(e))throw new Error("not an object");return e}catch{throw ef(t,"The model endpoint returned invalid JSON.",502)}}function Zg(e,t){return ef(e,401===t||403===t?"The model endpoint rejected the API key.":"The model endpoint rejected the request.",502,t)}function ef(e,t,n,i){return Object.assign(new Error(t),{code:e,statusCode:n,...i?{details:{upstreamStatus:i}}:{}})}function tf(e,t){e.includes(t)||e.push(t)}function nf(e){const t=new Set;return e.filter(e=>!t.has(e.id)&&(t.add(e.id),!0))}const sf=c.z.object({endpoint:c.z.string().trim().url().max(2048),key:c.z.string().trim().min(1).max(4096).optional(),existingModelId:c.z.string().trim().min(1).max(120).optional()}).strict(),rf=sf.extend({model:c.z.string().trim().min(1).max(240),app:c.z.enum(["codex","claude","opencode"]).optional(),protocol:c.z.enum(["openai-responses","openai-chat-completions","anthropic-messages"]).optional()}).strict().refine(e=>Boolean(e.protocol||e.app),{message:"A model protocol is required.",path:["protocol"]}),of="MODEL_RELAY_UNAUTHORIZED",af="MODEL_RELAY_ROUTE_NOT_FOUND",cf="MODEL_RELAY_OPERATION_NOT_ALLOWED",df="MODEL_RELAY_INVALID_REQUEST_MODEL",lf="MODEL_RELAY_UPSTREAM_UNAVAILABLE";function uf(e,t,n,i){return Object.assign(new Error(n),{statusCode:e,code:t,...i?{details:i}:{}})}function pf(e){return 32===e||9===e||10===e||13===e}function mf(e){const t=[];return e<=127?t.push(e):e<=2047?t.push(192|e>>6,128|63&e):e<=65535?t.push(224|e>>12,128|e>>6&63,128|63&e):t.push(240|e>>18,128|e>>12&63,128|e>>6&63,128|63&e),Buffer.from(t)}function hf(e,t){if(t+4>e.length-1)return;const n=e.subarray(t,t+4).toString("ascii");return/^[0-9a-fA-F]{4}$/.test(n)?Number.parseInt(n,16):void 0}function gf(e){if(e.length<2||34!==e[0]||34!==e[e.length-1])return;const t=e.length-1,n=[];let i=1,s=1;for(;s<t;){if(92!==e[s]){s+=1;continue}if(s>i&&n.push(e.subarray(i,s)),s+=1,s>=t)return;const r=e[s],o={34:'"',92:"\\",47:"/",98:"\b",102:"\f",110:"\n",114:"\r",116:"\t"};if(void 0!==o[r]){n.push(o[r]),s+=1,i=s;continue}if(117!==r)return;const a=hf(e,s+1);if(void 0===a)return;if(s+=5,a>=55296&&a<=56319&&s+6<=t&&92===e[s]&&117===e[s+1]){const t=hf(e,s+2);if(void 0!==t&&t>=56320&&t<=57343){n.push(mf(65536+(a-55296<<10)+(t-56320))),s+=6,i=s;continue}}n.push(mf(a)),i=s}return s>i&&n.push(e.subarray(i,s)),Buffer.concat(n.map(e=>"string"==typeof e?Buffer.from(e,"utf8"):e)).toString("utf8")}class ff{paths;onModelValue;onInvalidModelValue;failOnOversizedValue;maxStringBytes;keys=[];containers=[];depth=0;slot="none";valuePath=[];inString=!1;stringRole="value";stringCandidate=!1;stringEscaped=!1;stringBytes=0;stringParts=[];stringStart=-1;stringDiscarded=!1;matchedValue=!1;constructor(e){this.paths=e.paths,this.onModelValue=e.onModelValue,this.onInvalidModelValue=e.onInvalidModelValue,this.failOnOversizedValue=e.failOnOversizedValue??!1,this.maxStringBytes=e.maxStringBytes??1024}get matched(){return this.matchedValue}push(e){return this.scan(e,!1).output}pushUntilMatch(e){return this.scan(e,!0)}scan(e,t){const n=[];let i=0;for(let s=0;s<e.length;s+=1){const r=e[s];if(this.inString){if(this.stringEscaped)this.stringEscaped=!1;else if(92===r)this.stringEscaped=!0;else if(34===r&&(this.finishString(e,s+1,n),i=s+1,t&&this.matchedValue))return{output:n,consumed:s+1}}else if(34!==r){if("value"===this.slot&&this.isModelPath()&&this.onInvalidModelValue&&!pf(r))throw this.onInvalidModelValue();if(123===r?(this.depth+=1,this.containers[this.depth-1]="object",this.keys.length=this.depth,this.keys[this.depth-1]=void 0,this.valuePath=[],this.slot="key"):91===r?(this.depth+=1,this.containers[this.depth-1]="array",this.keys.length=this.depth,this.keys[this.depth-1]=void 0,this.valuePath=[],this.slot="value"):125===r||93===r?(this.depth>0&&(this.depth-=1),this.containers.length=this.depth,this.keys.length=this.depth,this.valuePath=[],this.slot="none"):44===r?this.slot="object"===this.containers[this.depth-1]?"key":"value":58===r?(this.valuePath=[...this.keys.slice(0,this.depth-1),this.keys[this.depth-1]],this.slot="value"):pf(r)||"value"!==this.slot||(this.slot="none"),t&&this.matchedValue)return{output:n,consumed:s+1}}else s>i&&n.push(e.subarray(i,s)),this.startString(s),i=s}return this.inString&&(this.appendStringPart(e.subarray(this.stringStart>=0?this.stringStart:0),n),this.stringStart=-1,i=e.length),i<e.length&&n.push(e.subarray(i)),{output:n,consumed:e.length}}end(){const e=[...this.stringParts];return this.stringParts=[],e}isModelPath(){return this.paths.some(e=>function(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}(this.valuePath,e))}startString(e){this.inString=!0,this.stringEscaped=!1,this.stringBytes=0,this.stringParts=[],this.stringDiscarded=!1,this.stringRole="key"===this.slot&&"object"===this.containers[this.depth-1]?"key":"value",this.stringCandidate="value"===this.stringRole&&this.isModelPath(),this.stringStart=e}appendStringPart(e,t){if(!e.length)return;if(this.stringDiscarded||"key"!==this.stringRole&&!this.stringCandidate)return void t.push(e);this.stringParts.push(e),this.stringBytes+=e.length;const n="key"===this.stringRole?1024:this.maxStringBytes;if(!(this.stringBytes<=n)){if("value"===this.stringRole&&this.failOnOversizedValue&&this.onInvalidModelValue)throw this.onInvalidModelValue();this.stringDiscarded=!0,t.push(...this.stringParts),this.stringParts=[]}}finishString(e,t,n){this.appendStringPart(e.subarray(this.stringStart>=0?this.stringStart:0,t),n),this.stringStart=-1;const i=this.stringParts.length?Buffer.concat(this.stringParts):void 0;this.stringParts=[],this.inString=!1;const s=this.stringRole,r=this.stringCandidate;if(this.stringRole="value",this.stringCandidate=!1,"key"===s)return this.keys[this.depth-1]=i?gf(i):void 0,i&&n.push(i),void(this.slot="none");if(this.slot="none",!r||!i)return void(i&&n.push(i));const o=gf(i);if(void 0!==o)this.matchedValue=!0,n.push(this.onModelValue(o)??i);else{if(this.onInvalidModelValue)throw this.onInvalidModelValue();n.push(i)}}}function yf(e){let t=!1;return n=>{if(void 0!==e.expectedUpstreamName&&void 0!==e.externalName)return n===e.expectedUpstreamName?Buffer.from(JSON.stringify(e.externalName),"utf8"):void(t||(t=!0,e.onMismatch?.()))}}function If(e){return Buffer.isBuffer(e)?e:"string"==typeof e?Buffer.from(e,"utf8"):Buffer.from(e)}function _f(e,t,n){const i=e.subarray(t,n);let s=n;return i.length&&10===i[i.length-1]&&(s-=1),s>t&&13===e[s-1]&&(s-=1),{raw:Buffer.from(i),content:Buffer.from(e.subarray(t,s)),terminator:Buffer.from(e.subarray(s,n))}}function Ef(e,t,n){return f.Readable.from(async function*(){let i=[],s=0;const r=function*(){const e=[],n=[];i.forEach((t,i)=>{const s=function(e){if(e.length<5||"data:"!==e.subarray(0,5).toString("ascii"))return;let t=e.subarray(5);return t.length&&32===t[0]&&(t=t.subarray(1)),t}(t.content);void 0!==s&&(e.push(s),n.push(i))});const s=n.length?function(e,t){if(!e.length)return;const n=1===e.length?e[0]:Buffer.concat(e.flatMap((e,t)=>0===t?[e]:[Buffer.from("\n","utf8"),e]));if(!function(e){for(const t of e)if(32!==t&&9!==t)return 123===t;return!1}(n))return;const i=function(e,t){const n=new ff({paths:t.paths,onModelValue:yf(t)}),i=[...n.push(e),...n.end()];return 1===i.length?i[0]:Buffer.concat(i)}(n,t);if(i.equals(n))return;const s=function(e){const t=[];let n=0;for(let i=0;i<e.length;i+=1)10===e[i]&&(t.push(e.subarray(n,i)),n=i+1);return t.push(e.subarray(n)),t}(i);return s.length===e.length?s:void 0}(e,t):void 0,r=new Map;if(s)for(const[t,o]of n.entries()){const n=i[o],a=n.content.subarray(0,n.content.length-e[t].length);r.set(o,Buffer.concat([a,s[t],n.terminator]))}for(const[e,t]of i.entries())yield r.get(e)??t.raw};for await(const t of async function*(e){let t=Buffer.alloc(0);for await(const n of e){const e=Buffer.isBuffer(n)?n:Buffer.from(n,"utf8"),i=t.length?Buffer.concat([t,e]):e;let s=0,r=0;for(;r<i.length;){const e=i[r];if(10===e)yield _f(i,s,r+1),s=r+1;else if(13===e){if(r+1>=i.length)break;const e=10===i[r+1]?r+2:r+1;yield _f(i,s,e),s=e,r=e-1}r+=1}t=s<i.length?Buffer.from(i.subarray(s)):Buffer.alloc(0)}t.length&&(yield _f(t,0,t.length))}(e)){if(s+=t.raw.length,s>n.maxEventBytes)throw uf(502,"MODEL_RELAY_UPSTREAM_STREAM_ERROR","The upstream SSE event exceeded the relay frame limit.");0!==t.content.length?i.push(t):(yield*r(),i=[],s=0,yield t.raw)}yield*r()}(),{objectMode:!1})}function Af(e){return oo(e.modelNames,e.model).slice().sort((e,t)=>e.order-t.order||e.name.localeCompare(t.name)).map(e=>e.name)}function Tf(e,t,n){return`${e.replace(/\/+$/,"")}${t}${n}`}function bf(e){return{kind:"reject",name:"unknown",status:404,code:cf,message:`The node model relay does not allow this ${e} operation.`}}function wf(e){return JSON.stringify({object:"list",data:Af(e).map(e=>({id:e,object:"model",created:0,owned_by:"task-handoff"}))})}function Sf(e,t,n,i){return{kind:"upstream",name:e,method:t,url:n,responseMode:i}}function Nf(e,t){return{kind:"synthetic",name:e,status:200,headers:{"content-type":"application/json"},body:t}}function vf(e){return{protocol:e.protocol,planOperation:()=>bf(e.protocol),prepareRequest:async({body:e,plan:t,resolveUpstreamModelName:n,maxPrologueBytes:i})=>{if(!e||"GET"===t.method||"HEAD"===t.method)return{};const s=await async function(e){let t,n;const i=new ff({paths:e.paths??[["model"]],maxStringBytes:e.maxStringBytes,failOnOversizedValue:!0,onInvalidModelValue:()=>uf(400,df,"The relay request must contain exactly one top-level string model field."),onModelValue:i=>{if(void 0!==t)throw uf(400,"MODEL_RELAY_AMBIGUOUS_MODEL_NAME","The relay request contains more than one model field.");const s=e.resolveUpstreamModelName(i);return t=i,n=s,s===i?void 0:Buffer.from(JSON.stringify(s),"utf8")}}),s=[];let r=0;const o=t=>{for(const n of t){if(r+=n.length,r>e.maxPrologueBytes)throw uf(413,"MODEL_RELAY_REQUEST_PROLOGUE_TOO_LARGE","The relay request model field was not found within the configured limit.");s.push(n)}},a=async function*(e){for await(const t of e)yield If(t)}(e.body);let c;for(;void 0===t;){const e=await a.next();if(e.done)break;const n=i.pushUntilMatch(e.value);o(n.output),void 0!==t&&(c=e.value.subarray(n.consumed))}if(void 0===t||void 0===n)throw a.return?.(void 0),uf(400,df,"The relay request does not contain a top-level model field.");return{body:f.Readable.from(async function*(){let e=!1;try{for(const e of s)yield e;if(c?.length)for(const e of i.push(c))yield e;for(;;){const t=await a.next();if(t.done){e=!0;break}for(const e of i.push(t.value))yield e}for(const e of i.end())yield e}finally{e||await(a.return?.(void 0))}}(),{objectMode:!1}),externalModelName:t,upstreamModelName:n}}({body:e,resolveUpstreamModelName:n,maxPrologueBytes:i});return{body:s.body,externalModelName:s.externalModelName,upstreamModelName:s.upstreamModelName}},prepareResponse:({body:t,plan:n,externalModelName:i,upstreamModelName:s,maxResponseEventBytes:r,onDiagnostic:o})=>{if("raw"===n.responseMode)return t;const a=void 0!==i&&void 0!==s&&i!==s,c={paths:e.responsePaths,externalName:i,expectedUpstreamName:s,...a?{onMismatch:()=>o?.({code:"MODEL_RELAY_UPSTREAM_MODEL_MISMATCH"})}:{}};return"sse"===n.responseMode?Ef(t,c,{maxEventBytes:r}):function(e,t){const n=new ff({paths:t.paths,onModelValue:yf(t)});return f.Readable.from(async function*(){for await(const t of e)for(const e of n.push(If(t)))yield e;for(const e of n.end())yield e}(),{objectMode:!1})}(t,c)}}}const Of=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","content-length","expect","host","forwarded","x-forwarded-for","x-forwarded-host","x-forwarded-proto","x-forwarded-port","x-real-ip","via","authorization","x-api-key","cookie","x-provider","x-upstream","x-upstream-url","x-target-endpoint","x-api-base-url","x-model-endpoint","x-relay-target","x-original-url","accept-encoding"]),Rf=new Set(["connection","keep-alive","proxy-authenticate","trailer","transfer-encoding","upgrade","content-encoding","content-length","set-cookie","cookie","location","server","x-powered-by"]);function zf(e,t,n){if(void 0===n)return;const i=Array.isArray(n)?n.join(", "):n;i&&(e[t]=i)}function xf(e,t){const n={};for(const[t,i]of Object.entries(e))Of.has(t)||zf(n,t,i);return"anthropic-messages"===t.protocol?(n["x-api-key"]=t.credential,delete n.authorization):(n.authorization=`Bearer ${t.credential}`,delete n["x-api-key"]),n}function Cf(e,t){const n=Number(e);return Number.isFinite(n)&&n>0?Math.floor(n):t}function kf(e=process.env){return{responseHeadersTimeoutMs:Cf(e.TASK_HANDOFF_MODEL_RELAY_HEADER_TIMEOUT_MS,3e5),firstByteTimeoutMs:Cf(e.TASK_HANDOFF_MODEL_RELAY_FIRST_BYTE_TIMEOUT_MS,12e4),idleTimeoutMs:Cf(e.TASK_HANDOFF_MODEL_RELAY_IDLE_TIMEOUT_MS,3e5),maxRequestPrologueBytes:Cf(e.TASK_HANDOFF_MODEL_RELAY_MAX_PROLOGUE_BYTES,262144),maxRequestHeaderBytes:Cf(e.TASK_HANDOFF_MODEL_RELAY_MAX_HEADER_BYTES,16384),maxResponseEventBytes:Cf(e.TASK_HANDOFF_MODEL_RELAY_MAX_EVENT_BYTES,1048576),maxConcurrentRequests:Cf(e.TASK_HANDOFF_MODEL_RELAY_MAX_CONCURRENT,64),maxConcurrentRequestsPerInstance:Cf(e.TASK_HANDOFF_MODEL_RELAY_MAX_CONCURRENT_PER_INSTANCE,8),shutdownDrainMs:Cf(e.TASK_HANDOFF_MODEL_RELAY_SHUTDOWN_DRAIN_MS,5e3)}}class Df{adapters=new Map;constructor(e=[]){for(const t of e)this.register(t)}register(e){this.adapters.set(e.protocol,e)}get(e){return this.adapters.get(e)}protocols(){return[...this.adapters.keys()]}}const Lf="/api/node-agent/model-relay/instances/:instanceId/routes/:routeId/v1",Pf=["GET","POST","HEAD","PUT","PATCH","DELETE"];function Mf(e){return d.createHash("sha256").update(e).digest()}function jf(e){const t=e.authorization;if("string"!=typeof t)return;const n=/^Bearer\s+(.+)$/i.exec(t.trim());return n?.[1]?.trim()||void 0}function Uf(e){const t=e["x-api-key"];return"string"==typeof t&&t.trim()?t.trim():void 0}function Ff(e){const t=e=>{if(!e||"object"!=typeof e)return;const t=e,n="string"==typeof t.name&&/^[A-Za-z][A-Za-z0-9]{0,31}$/.test(t.name)?t.name:void 0,i="string"==typeof t.code&&/^[A-Za-z0-9_]{1,32}$/.test(t.code)?t.code:void 0;return n||i?{name:n,code:i}:void 0},n=t(e),i=t(e?.cause);return{...n?.name?{errorName:n.name}:{},...n?.code?{code:n.code}:{},...i?.name?{causeName:i.name}:{},...i?.code?{causeCode:i.code}:{}}}function $f(e){return new Promise(t=>{const n=()=>{e.off("drain",n),e.off("close",n),t()};e.once("drain",n),e.once("close",n)})}function Hf(e){return new Promise(t=>setTimeout(t,e))}class Bf{resolver;adapters;limits;fetchImpl;log;closing=!1;activeTotal=0;activeByInstance=new Map;activeControllers=new Set;constructor(e){this.resolver=e.resolver,this.adapters=new Df(e.adapters),this.limits={...kf(),...e.limits},this.fetchImpl=e.fetchImpl||fetch,this.log=e.log}registerAdapter(e){this.adapters.register(e)}protocolCapabilities(){return this.adapters.protocols()}registerRoutes(e){const t=(e,t)=>this.handle(e,t);e.register(async e=>{e.removeAllContentTypeParsers(),e.addContentTypeParser(/^.*$/,(e,t,n)=>n(null,t));for(const n of[Lf,`${Lf}/*`])e.route({method:[...Pf],url:n,handler:t})}),e.addHook("preClose",async()=>{await this.shutdown()})}async shutdown(){this.closing=!0,await this.drainActive()}async drainActive(){const e=Date.now()+this.limits.shutdownDrainMs;for(;this.activeTotal>0&&Date.now()<e;)await Hf(20);for(const e of this.activeControllers)e.abort()}tryAcquire(e){if(this.closing)throw uf(503,"MODEL_RELAY_SHUTTING_DOWN","The node model relay is shutting down.");return!(this.activeTotal>=this.limits.maxConcurrentRequests||(this.activeByInstance.get(e)||0)>=this.limits.maxConcurrentRequestsPerInstance||(this.activeTotal+=1,this.activeByInstance.set(e,(this.activeByInstance.get(e)||0)+1),0))}release(e){this.activeTotal=Math.max(0,this.activeTotal-1);const t=this.activeByInstance.get(e)||0;t<=1?this.activeByInstance.delete(e):this.activeByInstance.set(e,t-1)}async handle(e,t){const n=Date.now(),i=e.url,s=i.indexOf("?"),r=-1===s?i:i.slice(0,s),o=-1===s?"":i.slice(s),a=tg(r);if(!a)throw uf(404,af,"The requested model relay route does not exist.");if(Object.entries(e.headers).reduce((e,[t,n])=>e+t.length+(Array.isArray(n)?n.join(", ").length:n?.length||0),0)>this.limits.maxRequestHeaderBytes)throw uf(431,"MODEL_RELAY_REQUEST_HEADERS_TOO_LARGE","The relay request headers are too large.");let c;try{c=this.resolver.instance(a.instanceId)}catch{throw uf(404,af,"The requested model relay route does not exist.")}const l=jf(e.headers)??Uf(e.headers);if(!l||(u=l,p=c.registrationToken,!d.timingSafeEqual(Mf(u),Mf(p))))throw uf(401,of,"Model relay credentials are invalid for this instance.");var u,p;if(!this.tryAcquire(a.instanceId))throw uf(429,"MODEL_RELAY_BUSY","The node model relay is at capacity; retry later.",{retryable:!0});const m={instanceId:a.instanceId,routeId:a.routeId,operation:"unknown",protocol:void 0,modelEntityId:void 0};try{const i=this.resolver.resolveRoute(a.instanceId,a.routeId);if(m.protocol=i.protocol,m.modelEntityId=i.model.id,h=e.headers,!("anthropic-messages"===i.protocol?Uf(h):jf(h)))throw uf(401,of,"Model relay credentials are invalid for this instance.");const s=this.adapters.get(i.protocol);if(!s)throw uf(404,cf,"The node does not relay this model protocol.");const r=s.planOperation({method:e.method,operationPath:a.operationPath,search:o,model:i.model});if(m.operation=r.name,"reject"===r.kind)throw uf(r.status,r.code,r.message);if("synthetic"===r.kind)return t.code(r.status).headers(r.headers||{}).send(r.body??""),void this.logCompleted(n,{...m,status:r.status,requestBytes:0,responseBytes:r.body?Buffer.byteLength(r.body):0});await this.proxyUpstream(e,t,i,s,r,m,n)}catch(e){const i=e&&"object"==typeof e&&"number"==typeof e.statusCode?e.statusCode:500,s=e&&"object"==typeof e&&"string"==typeof e.code?e.code:"MODEL_RELAY_ERROR";if(this.log?.warn({...m,status:i,code:s,...Ff(e),latencyMs:Date.now()-n,relayEnabled:this.resolver.relayEnabled()},"model relay request failed"),t.raw.headersSent||t.raw.writableEnded)return;throw e}finally{this.release(a.instanceId)}var h}logCompleted(e,t){this.log?.info({...t,latencyMs:Date.now()-e,relayEnabled:this.resolver.relayEnabled()},"model relay request completed")}async proxyUpstream(e,t,n,i,s,r,o){const a=n.model,c=this.allowedUpstreamUrl(s.url,a.endpoint),d="GET"!==e.method&&"HEAD"!==e.method;let l=0;const u=await i.prepareRequest({body:d?e.raw:void 0,plan:s,model:a,resolveUpstreamModelName:e=>this.resolver.resolveUpstreamModelName(a,e),maxPrologueBytes:this.limits.maxRequestPrologueBytes}),p=u.body?function(e){const t=new f.Transform({transform(e,t,n){var i;i=e.length,l+=i,n(null,e)}});return t.on("error",()=>{}),e.once("error",e=>t.destroy(e)),e.pipe(t)}(u.body):void 0,m=new AbortController;let h;this.activeControllers.add(m);const g=()=>{t.raw.writableEnded||(h="client",m.abort())};t.raw.once("close",g);const y=setTimeout(()=>{h="headers-timeout",m.abort()},this.limits.responseHeadersTimeoutMs);let I;try{I=await this.fetchImpl(c,{method:s.method,headers:xf(e.headers,{protocol:n.protocol,credential:a.key}),body:p,...p?{duplex:"half"}:{},redirect:"manual",signal:m.signal})}catch(e){if(clearTimeout(y),t.raw.off("close",g),this.activeControllers.delete(m),"client"===h)return void this.log?.debug({...r,status:499},"model relay client closed before upstream response");if("shutdown"===h||this.closing)return void this.log?.debug({...r,status:503},"model relay aborted for node-agent shutdown");if("headers-timeout"===h)throw uf(504,"MODEL_RELAY_UPSTREAM_TIMEOUT","The upstream model endpoint did not respond in time.",{phase:"headers"});if(e&&"object"==typeof e&&"number"==typeof e.statusCode)throw e;throw uf(502,lf,"The upstream model endpoint could not be reached.")}if(clearTimeout(y),I.status>=300&&I.status<400)throw await(I.body?.cancel().catch(()=>{})),t.raw.off("close",g),this.activeControllers.delete(m),uf(502,"MODEL_RELAY_UPSTREAM_REDIRECT","The upstream model endpoint attempted a redirect.");const _=function(e){const t={};for(const[n,i]of e.entries())Rf.has(n.toLowerCase())||(t[n]=i);return t}(I.headers),E=I.body,A="raw"!==s.responseMode&&/text\/event-stream/i.test(I.headers.get("content-type")||"")?"sse":s.responseMode,T=I.ok&&"raw"!==A&&E?i.prepareResponse({body:E,plan:{...s,responseMode:A},model:a,externalModelName:u.externalModelName,upstreamModelName:u.upstreamModelName,maxResponseEventBytes:this.limits.maxResponseEventBytes,onDiagnostic:e=>this.log?.warn({...r,code:e.code},"model relay response diagnostic")}):E;t.hijack(),t.raw.writeHead(I.status,_);let b,w=0,S=!0,N=0,v=0;const O=()=>{b&&clearTimeout(b),b=setTimeout(()=>{h=S?"first-byte-timeout":"idle-timeout",m.abort()},S?this.limits.firstByteTimeoutMs:this.limits.idleTimeoutMs)};T&&O();const R=()=>({...r,status:I.status,...N?{firstChunkMs:N-o}:{},...v?{lastChunkMs:v-o,msSinceLastChunk:Date.now()-v}:{},upstreamContentType:I.headers.get("content-type")||void 0,upstreamContentEncoding:I.headers.get("content-encoding")||void 0,requestBytes:l,responseBytes:w,relayEnabled:this.resolver.relayEnabled()});let z="completed";try{if(T)for await(const e of T){const n=Date.now();if(S?(S=!1,N=n,O()):O(),v=n,w+=e.length,"client"===h)break;t.raw.write(e)||await $f(t.raw)}z=h||"completed","completed"===z?t.raw.end():t.raw.destroy()}catch(e){return t.raw.destroy(),void this.log?.warn({...R(),reason:h||"upstream-stream-error",...Ff(e),latencyMs:Date.now()-o},"model relay stream interrupted")}finally{b&&clearTimeout(b),t.raw.off("close",g),this.activeControllers.delete(m)}"completed"===z?this.logCompleted(o,{...r,status:I.status,requestBytes:l,responseBytes:w}):this.log?.debug({...R(),reason:z,latencyMs:Date.now()-o},"model relay stream ended")}allowedUpstreamUrl(e,t){let n,i;try{n=new URL(t),i=new URL(e)}catch{throw uf(502,lf,"The assigned model endpoint is not a valid upstream URL.")}if(i.origin!==n.origin)throw uf(502,cf,"The relay operation resolved outside the assigned model endpoint.");return i.toString()}}function qf(e,t){return Object.assign(new Error(t),{code:e})}function Vf(e,t=process.platform){return"win32"===t&&"host-ipc"===e?"named-pipe":"unix-socket"}function Gf(e){if("string"!=typeof e.scope||!e.scope.trim())throw qf("LOCAL_IPC_SCOPE_INVALID","A local IPC endpoint requires a non-empty scope.");if("string"!=typeof e.key||!e.key.trim())throw qf("LOCAL_IPC_KEY_INVALID","A local IPC endpoint requires a non-empty key.");if(void 0!==e.hashLength&&(!Number.isInteger(e.hashLength)||e.hashLength<1||e.hashLength>64))throw qf("LOCAL_IPC_HASH_LENGTH_INVALID","hashLength must be an integer between 1 and 64.");if(void 0!==e.explicitPath&&(!e.explicitPath.trim()||e.explicitPath.includes("\0")))throw qf("LOCAL_IPC_PATH_INVALID","explicitPath must be a non-empty path without NUL bytes.");if(void 0!==e.directoryName&&(!e.directoryName.trim()||/[\/\\\0]/.test(e.directoryName)))throw qf("LOCAL_IPC_DIRECTORY_NAME_INVALID","directoryName must be a non-empty name without path separators or NUL bytes.")}function Wf(e=process.platform,n){if("darwin"===e)return"/private/tmp";if(n)return n;const i=s.tmpdir();try{return t.realpathSync(i)}catch{return i}}function Kf(e,t,n=16){return Gf({scope:e,key:t,hashLength:n}),`${e}-${function(e,t){return d.createHash("sha256").update(e).digest("hex").slice(0,t)}(t,n)}`}function Yf(e,n,i=process.platform){"win32"!==i&&t.chmodSync(e,n)}class Xf{invocations=new Map;store;idleTtlMs;maxTtlMs;cleanupTimer;constructor(e,t={}){this.store=e,this.idleTtlMs=t.idleTtlMs??6e4,this.maxTtlMs=t.maxTtlMs??3e5}resolveHttps(e,t){const{match:n,payload:i}=this.store.resolve(e,t);return"unique"!==n.status||"https-token"!==i?.secret.kind?{status:n.status}:{status:"ok",username:i.secret.username,password:i.secret.token}}async prepareSsh(e,i){this.cleanupExpired();const{match:s,payload:r}=this.store.resolve(e,i);if("unique"!==s.status||"ssh-key"!==r?.secret.kind)return{status:s.status};const o=`gitssh_${d.randomUUID()}`,a=t.mkdtempSync(n.join(Wf(),"task-handoff-node-git-ssh-"));Yf(a,448);const c=function(e,t){Gf({scope:t.scope,key:t.key});const i=t.platform??process.platform;if("named-pipe"===Vf("host-ipc",i))return{path:`\\\\.\\pipe\\${Kf(t.scope,t.key)}`,transport:"named-pipe",kind:"host-ipc",platform:i,filesystemBacked:!1};const s={path:n.join(e,t.fileName??"ipc.sock"),transport:"unix-socket",kind:"host-ipc",platform:i,filesystemBacked:!0};return function(e){if("unix-socket"!==e.transport)return;const t=function(e=process.platform){return"darwin"===e?103:107}(e.platform);if(Buffer.byteLength(e.path)>t)throw qf("LOCAL_IPC_PATH_TOO_LONG",`Local IPC socket path exceeds the ${t}-byte limit on ${e.platform}: ${e.path}`)}(s),s}(a,{scope:"task-handoff-git-agent",key:o,fileName:"agent.sock"}),l={...process.env,SSH_AUTH_SOCK:c.path};let u;try{const s=await Qf("ssh-agent",["-s","-a",c.path]);if(u=Number(/SSH_AGENT_PID=(\d+)/.exec(s)?.[1]),!Number.isInteger(u)||u<=0)throw new Error("ssh-agent did not report a process id.");await async function(e,i,s,r){if("win32"!==process.platform){const o=n.join(e,"askpass.sh");t.writeFileSync(o,"#!/bin/sh\nprintf '%s' \"${TASK_HANDOFF_SSH_KEY_PASSPHRASE:-}\"\n",{mode:448});try{await Zf("ssh-add",["-"],i,{...r,SSH_ASKPASS:o,SSH_ASKPASS_REQUIRE:"force",DISPLAY:process.env.DISPLAY||":0",TASK_HANDOFF_SSH_KEY_PASSPHRASE:s||""})}finally{t.rmSync(o,{force:!0})}return}const o=n.join(e,"identity");t.writeFileSync(o,i,{mode:384});try{s&&await Qf("ssh-keygen",["-p","-P",s,"-N","","-f",o]),await Qf("ssh-add",[o],r)}finally{t.rmSync(o,{force:!0})}}(a,r.secret.privateKey,r.secret.passphrase,l);const d=await Qf("ssh-add",["-L"],l),p=Date.now();return this.invocations.set(o,{instanceId:e,remoteUrl:i,credentialId:r.credential.id,credentialRevision:r.credential.revision,socketPath:c.path,agentPid:u,directory:a,idleExpiresAt:p+this.idleTtlMs,absoluteExpiresAt:p+this.maxTtlMs}),this.scheduleCleanup(),{status:"ok",invocationId:o,publicIdentity:d,pinnedKnownHosts:r.secret.pinnedKnownHosts}}catch(e){if(u)try{process.kill(u,"SIGTERM")}catch{}throw t.rmSync(a,{recursive:!0,force:!0}),e}}async exchangeAgentFrame(e,t,n){this.cleanupExpired();const i=this.invocations.get(t);if(!i||i.instanceId!==e)throw Jf("GIT_CREDENTIAL_SSH_INVOCATION_INVALID",404);const{match:s,payload:r}=this.store.resolve(e,i.remoteUrl);if("unique"!==s.status||"ssh-key"!==r?.secret.kind||r.credential.id!==i.credentialId||r.credential.revision!==i.credentialRevision)throw this.release(t,e),Jf("GIT_CREDENTIAL_SSH_INVOCATION_REVOKED",403);const o=Buffer.from(n,"base64");if(o.length<5||o.length>1048576||o.readUInt32BE(0)!==o.length-4)throw Jf("GIT_CREDENTIAL_SSH_AGENT_FRAME_INVALID",400);i.idleExpiresAt=Math.min(i.absoluteExpiresAt,Date.now()+this.idleTtlMs),this.scheduleCleanup();const a=Math.max(1,Math.min(i.idleExpiresAt,i.absoluteExpiresAt)-Date.now());try{const e=await function(e,t,n){return new Promise((i,s)=>{const r=g.createConnection(e),o=[];let a=0,c=!1;const d=(e,t)=>{c||(c=!0,r.destroy(),e?s(e):i(t))};r.setTimeout(n),r.once("timeout",()=>d(new Error("Managed Git SSH agent exchange timed out."))),r.once("error",e=>d(e)),r.once("end",()=>d(new Error("Managed Git SSH agent closed before returning a complete frame."))),r.once("close",()=>d(new Error("Managed Git SSH agent closed before returning a complete frame."))),r.on("data",e=>{o.push(e);const t=Buffer.concat(o);!a&&t.length>=4&&(a=t.readUInt32BE(0)+4,a<5||a>1048576)?d(new Error("Managed Git SSH agent returned an invalid frame length.")):a&&t.length>=a&&d(void 0,t.subarray(0,a))}),r.once("connect",()=>r.write(t,e=>{e&&d(e)}))})}(i.socketPath,o,a);return{frame:e.toString("base64")}}catch{throw this.release(t,e),Jf("GIT_CREDENTIAL_SSH_AGENT_UNAVAILABLE",502)}}release(e,n){const i=this.invocations.get(e);if(!i||void 0!==n&&i.instanceId!==n)return!1;this.invocations.delete(e);try{process.kill(i.agentPid,"SIGTERM")}catch{}return t.rmSync(i.directory,{recursive:!0,force:!0}),this.scheduleCleanup(),!0}close(){this.cleanupTimer&&clearTimeout(this.cleanupTimer),this.cleanupTimer=void 0;for(const e of[...this.invocations.keys()])this.release(e)}cleanupExpired(){const e=Date.now();for(const[t,n]of this.invocations)(n.idleExpiresAt<=e||n.absoluteExpiresAt<=e)&&this.release(t)}scheduleCleanup(){this.cleanupTimer&&clearTimeout(this.cleanupTimer),this.cleanupTimer=void 0;const e=Math.min(...[...this.invocations.values()].map(e=>Math.min(e.idleExpiresAt,e.absoluteExpiresAt)));Number.isFinite(e)&&(this.cleanupTimer=setTimeout(()=>{this.cleanupTimer=void 0,this.cleanupExpired(),this.scheduleCleanup()},Math.max(0,e-Date.now())),this.cleanupTimer.unref?.())}}function Jf(e,t){return Object.assign(new Error("Managed Git broker request was rejected."),{code:e,statusCode:t})}function Qf(e,t,n=process.env){return Zf(e,t,void 0,n)}function Zf(e,t,n,i){return new Promise((s,r)=>{const o=l.spawn(e,t,{shell:!1,env:i,stdio:[void 0===n?"ignore":"pipe","pipe","pipe"]}),a=[];o.stdout.on("data",e=>a.push(e)),o.once("error",()=>r(new Error(`Managed Git SSH broker could not start ${e}.`))),o.once("close",t=>0===t?s(Buffer.concat(a).toString("utf8")):r(new Error(`Managed Git SSH broker command ${e} failed.`))),void 0!==n&&o.stdin.end(n)})}const ey=c.z.object({credentialId:c.z.string().trim().min(1).max(120)}).strict(),ty=c.z.object({id:c.z.string().trim().min(1).max(120)}).strict(),ny=ty.extend({invocationId:c.z.string().trim().min(1).max(120)}).strict();function iy(e){const t=e.authorization;return"string"==typeof t&&t.startsWith("Bearer ")?t.slice(7).trim():void 0}const sy=c.z.object({maxIdleAiSessions:c.z.number().int().min(1).max(50).default(5)}).strict(),ry=c.z.string().trim().min(1).max(1024).refine(e=>!e.startsWith("/")&&!e.includes("\\")&&e.split("/").every(e=>e.length>0&&"."!==e&&".."!==e),"Story paths must be normalized relative POSIX paths."),oy=c.z.string().regex(/^[a-f0-9]{64}$/),ay=c.z.object({title:c.z.string().trim().min(1).max(240),storyPath:ry,revision:oy}).strict(),cy=c.z.object({agent:Be.optional(),mode:At.optional(),permissionMode:Tt.optional(),modelSelection:Dt.optional(),reasoningEffort:Lt.optional(),cwdFolderId:c.z.string().trim().min(1).max(120).optional(),gitSelection:Mt.optional(),workspaceSelection:Pt.optional()}).strict().refine(e=>!(e.gitSelection&&e.workspaceSelection),{message:"gitSelection and workspaceSelection are mutually exclusive.",path:["workspaceSelection"]}),dy=c.z.object({id:c.z.string().trim().min(1).max(120),title:c.z.string().trim().min(1).max(120),promptTemplate:c.z.string().trim().min(1).max(32e3),targetInstanceId:c.z.string().trim().min(1).max(120).optional(),sessionPreset:cy.optional()}).strict(),ly=dy.omit({id:!0,targetInstanceId:!0}).extend({targetInstanceId:dy.shape.targetInstanceId.unwrap()}).strict(),uy=ly.extend({id:dy.shape.id.optional()}).strict(),py=c.z.object({targetInstanceId:c.z.string().trim().min(1).max(120),aiSessionId:c.z.string().trim().min(1).max(120)}).strict(),my=c.z.discriminatedUnion("scheduleKind",[c.z.object({scheduleKind:c.z.literal("interval"),intervalMs:c.z.number().int().min(6e4)}).strict(),c.z.object({scheduleKind:c.z.literal("daily"),timeOfDay:c.z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/),timezone:c.z.string().trim().min(1).max(120)}).strict(),c.z.object({scheduleKind:c.z.literal("weekly"),weekdays:c.z.array(c.z.number().int().min(0).max(6)).min(1).max(7).refine(e=>new Set(e).size===e.length,"Weekdays must be unique."),timeOfDay:c.z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/),timezone:c.z.string().trim().min(1).max(120)}).strict(),c.z.object({scheduleKind:c.z.literal("monthly"),dayOfMonth:c.z.number().int().min(-3).max(31).refine(e=>0!==e,"Day of month must not be zero."),timeOfDay:c.z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/),timezone:c.z.string().trim().min(1).max(120)}).strict()]),hy=c.z.object({cooldownMs:c.z.number().int().min(0).max(864e5).optional(),maxConcurrentRuns:c.z.number().int().min(1).max(20).default(1),whenBusy:c.z.enum(["skip","queue"]).default("skip")}).strict(),gy=c.z.object({id:c.z.string().trim().min(1).max(120),storyId:ze,actionId:dy.shape.id,schedule:my,enabled:c.z.boolean().default(!0),policy:hy.default({maxConcurrentRuns:1,whenBusy:"skip"}),createdAt:c.z.string().datetime(),updatedAt:c.z.string().datetime()}).strict(),fy=gy.omit({id:!0,createdAt:!0,updatedAt:!0}).strict(),yy=c.z.object({action:dy.extend({targetInstanceId:dy.shape.targetInstanceId.unwrap()}).strict(),automation:fy.omit({storyId:!0,actionId:!0}).strict()}).strict(),Iy=c.z.object({actionId:gy.shape.actionId.optional(),schedule:my.optional(),enabled:c.z.boolean().optional(),policy:hy.optional()}).strict().refine(e=>Object.keys(e).length>0,"At least one Automation field is required."),_y=c.z.object({code:c.z.string().trim().min(1).max(120),message:c.z.string().trim().min(1).max(2e3)}).strict(),Ey=c.z.enum(["queued","dispatching","running","completed","failed","skipped"]),Ay=c.z.object({id:c.z.string().trim().min(1).max(160),automationId:gy.shape.id,eventType:c.z.enum(["manual","schedule"]),status:Ey,scheduledFor:c.z.string().datetime(),targetInstanceId:c.z.string().trim().min(1).max(120),aiSessionId:c.z.string().trim().min(1).max(120).optional(),error:_y.optional(),queuedAt:c.z.string().datetime(),startedAt:c.z.string().datetime().optional(),completedAt:c.z.string().datetime().optional()}).strict(),Ty=c.z.enum(["disabled","blocked","scheduled","running","error"]),by=c.z.object({automation:gy,effectiveStatus:Ty,blockedReason:_y.optional(),nextRunAt:c.z.string().datetime().optional(),currentRuns:c.z.array(Ay).max(20).default([]),lastRun:Ay.optional()}).strict(),wy=c.z.object({automations:c.z.array(by).default([])}).strict(),Sy=c.z.object({runs:c.z.array(Ay).max(120).default([])}).strict(),Ny=c.z.object({clientRequestId:Oe}).strict(),vy="story.automation.changed";c.z.object({storyId:ze,automationId:gy.shape.id,change:c.z.enum(["created","updated","deleted","status","run"]),status:by.optional(),run:Ay.optional()}).strict();const Oy=c.z.enum(["pending","decided","cancelled","expired"]),Ry=c.z.object({id:c.z.string().trim().min(1).max(120),label:c.z.string().trim().min(1).max(240),description:c.z.string().trim().max(2e3).optional()}).strict(),zy=c.z.object({code:c.z.string().trim().min(1).max(120),message:c.z.string().trim().min(1).max(2e3)}).strict(),xy=c.z.object({id:c.z.string().trim().min(1).max(160),storyId:ze,sessionId:c.z.string().trim().min(1).max(120),turnId:c.z.string().trim().min(1).max(240).optional(),question:c.z.string().trim().min(1).max(32e3),options:c.z.array(Ry).max(20).default([]),allowFreeText:c.z.boolean().default(!0),context:c.z.string().trim().max(8e3).optional(),status:Oy,revision:c.z.number().int().min(1),response:c.z.string().trim().max(2e4).optional(),selectedOptionId:c.z.string().trim().min(1).max(120).optional(),decidedTurnId:c.z.string().trim().min(1).max(240).optional(),expiredReason:zy.optional(),createdAt:c.z.string().datetime(),updatedAt:c.z.string().datetime(),decidedAt:c.z.string().datetime().optional()}).strict(),Cy=c.z.object({question:c.z.string().trim().min(1).max(32e3),options:c.z.array(Ry).max(20).optional(),allowFreeText:c.z.boolean().optional(),context:c.z.string().trim().max(8e3).optional()}).strict().superRefine((e,t)=>{const n=e.options||[];new Set(n.map(e=>e.id)).size!==n.length&&t.addIssue({code:c.z.ZodIssueCode.custom,path:["options"],message:"Decision option ids must be unique."}),!1===e.allowFreeText&&0===n.length&&t.addIssue({code:c.z.ZodIssueCode.custom,path:["allowFreeText"],message:"A decision without free text requires at least one option."})}),ky=c.z.object({optionId:c.z.string().trim().min(1).max(120).optional(),response:c.z.string().trim().min(1).max(2e4).optional(),expectedRevision:c.z.number().int().min(1),retry:c.z.boolean().optional()}).strict().refine(e=>Boolean(e.optionId)||Boolean(e.response),{message:"A decision requires a selected option or a free-text response.",path:["response"]}),Dy=c.z.object({expectedRevision:c.z.number().int().min(1)}).strict(),Ly=c.z.object({decisions:c.z.array(xy).default([])}).strict();xy.strip(),c.z.object({decisions:c.z.array(c.z.unknown()).default([])}).strip(),c.z.object({storyId:ze,decisionId:xy.shape.id,revision:c.z.number().int().min(1),change:c.z.enum(["created","decided","cancelled","expired"]),decision:xy.optional()}).strict();const Py=c.z.object({id:ze,ownerNodeId:c.z.string().trim().min(1).max(120),title:c.z.string().trim().min(1).max(240),description:c.z.string().trim().max(4e3).optional(),documents:c.z.array(ay).max(500).default([]),actions:c.z.array(dy).max(50).default([]),createdAt:c.z.string().datetime(),updatedAt:c.z.string().datetime(),archivedAt:c.z.string().datetime().optional()}).strict();c.z.object({stories:c.z.array(Py).default([])}).strict();const My=c.z.object({title:Py.shape.title,description:Py.shape.description,actions:c.z.array(ly).max(50).optional(),maxIdleAiSessions:sy.shape.maxIdleAiSessions.optional()}).strict(),jy=c.z.object({title:Py.shape.title.optional(),description:Py.shape.description.nullable().optional(),actions:c.z.array(uy).max(50).optional(),maxIdleAiSessions:sy.shape.maxIdleAiSessions.optional()}).strict().refine(e=>Object.keys(e).length>0,"At least one Story field is required."),Uy=c.z.object({title:ay.shape.title.optional(),storyPath:ry.optional()}).strict().refine(e=>Object.keys(e).length>0,"At least one document field is required."),Fy=c.z.object({storyPaths:c.z.array(ry).max(500)}).strict();c.z.object({storyPath:ry,title:ay.shape.title.optional(),expectedRevision:oy.optional()}).strict();const $y=c.z.object({documents:c.z.array(ay).max(500)}).strict(),Hy=c.z.union([c.z.number(),c.z.string().regex(/^\d+$/).transform(Number)]),By=c.z.object({page:Hy.pipe(c.z.number().int().min(1).max(500)).default(1),pageSize:Hy.pipe(c.z.number().int().min(1).max(100)).default(20)}).strict(),qy=c.z.object({title:ay.shape.title,storyPath:ry}).strict(),Vy=c.z.object({page:c.z.number().int().min(1).max(500),pageSize:c.z.number().int().min(1).max(100),totalItems:c.z.number().int().nonnegative(),totalPages:c.z.number().int().nonnegative(),hasMore:c.z.boolean()}).strict(),Gy=c.z.object({storyCreatedAt:Py.shape.createdAt,documents:c.z.array(qy).max(100),pagination:Vy}).strict();c.z.object({storyCreatedAt:Py.shape.createdAt,documents:c.z.array(qy.strip()).max(100),pagination:Vy.strip()}).strip(),c.z.object({storyPath:ry,revision:oy,content:c.z.string(),size:c.z.number().int().nonnegative()}).strict();const Wy=c.z.object({storyPaths:c.z.array(ry).min(1).max(20),destinationPath:c.z.string().trim().min(1).max(4096)}).strict(),Ky=c.z.object({storyPath:ry,title:ay.shape.title.optional(),sourcePath:c.z.string().trim().min(1).max(4096),expectedRevision:oy.optional()}).strict(),Yy=c.z.object({storyPath:ry,path:c.z.string().trim().min(1).max(4096).optional(),revision:oy.optional(),error:c.z.object({code:c.z.string().trim().min(1).max(120),message:c.z.string().trim().min(1).max(2e3)}).strict().optional()}).strict();c.z.object({items:c.z.array(Yy).min(1).max(20)}).strict(),c.z.object({storyId:ze,nodeId:c.z.string().trim().min(1).max(120),change:c.z.enum(["created","updated","archived","restored","deleted","content.written","document.updated","document.reordered","document.deleted"]).optional(),storyPath:ry.optional()}).strict();const Xy=["agent_run"],Jy=c.z.enum(Xy),Qy=c.z.object({agentId:qu,orchestrationId:gp}).strict(),Zy=c.z.object({enabledTools:c.z.array(Jy).max(Xy.length),allowedTargets:c.z.array(Qy).max(50)}).strict(),eI=c.z.object({agentId:qu,orchestrationId:gp.optional(),prompt:c.z.string().trim().min(1).max(128e3),budget:qp.optional()}).strict(),tI=c.z.object({clientRequestId:Oe,input:eI}).strict();function nI(e){const t=[...new Map(e.map(e=>[`${e.agentId}${e.orchestrationId}`,e])).values()].sort((e,t)=>e.agentId===t.agentId?e.orchestrationId.localeCompare(t.orchestrationId):e.agentId.localeCompare(t.agentId));return Zy.parse({enabledTools:t.length?Xy:[],allowedTargets:t})}function iI(e,t){const n=Zy.parse(t);return JSON.stringify(["2026-09-28",e,n.enabledTools,n.allowedTargets])}c.z.object({enabledTools:c.z.array(c.z.string()).max(100).optional(),allowedTargets:c.z.array(Qy).max(50).optional()}).strip(),c.z.enum(["content","actions","automations","aiSessions","decisions"]);const sI=c.z.object({content:c.z.boolean(),actions:c.z.boolean(),automations:c.z.boolean(),aiSessions:c.z.boolean(),decisions:c.z.boolean()}).strict(),rI=Object.freeze({content:!0,actions:!1,automations:!1,aiSessions:!1,decisions:!0}),oI=Object.freeze({content:!1,actions:!1,automations:!1,aiSessions:!1,decisions:!1}),aI=sI.strip().partial();function cI(e){const t=sI.parse(e);return`2026-09-28:${Number(t.content)}${Number(t.actions)}${Number(t.automations)}${Number(t.aiSessions)}${Number(t.decisions)}`}const dI=["story_list_content","story_get_content","story_set_content","story_list_actions","story_run_action","story_list_automations","story_create_automation","story_update_automation","story_delete_automation","story_run_automation","story_list_automation_runs","story_list_ai_sessions","story_get_ai_session","story_get_ai_session_turn","story_request_decision"],lI=c.z.enum(dI),uI=Object.freeze({content:["story_list_content","story_get_content","story_set_content"],actions:["story_list_actions","story_run_action"],automations:["story_list_automations","story_create_automation","story_update_automation","story_delete_automation","story_run_automation","story_list_automation_runs"],aiSessions:["story_list_ai_sessions","story_get_ai_session","story_get_ai_session_turn"],decisions:["story_request_decision"]}),pI=new Set(["story_list_content","story_get_content","story_list_actions","story_list_automations","story_list_automation_runs","story_list_ai_sessions","story_get_ai_session","story_get_ai_session_turn"]);function mI(e,t={}){const n=sI.parse(e),i=Object.keys(uI).filter(e=>n[e]).flatMap(e=>uI[e]);return t.archived?i.filter(e=>pI.has(e)):i}const hI=c.z.object({policy:sI,revision:c.z.string().regex(/^[a-f0-9]{64}$/)}).strict(),gI=c.z.object({policy:sI}).strict(),fI=hI.extend({storyId:ze,enabledTools:c.z.array(lI).max(dI.length),agentInvocation:Zy}).strict(),yI=c.z.object({storyId:ze,revision:hI.shape.revision}).strict();c.z.object({policy:sI.extend({decisions:c.z.boolean().default(!1)}).strip(),revision:hI.shape.revision}).strip().extend({storyId:ze,enabledTools:c.z.array(c.z.string()).max(100),agentInvocation:c.z.unknown().optional()}).strip();const II=c.z.object({page:c.z.number().int().min(1).max(500).default(1),pageSize:c.z.number().int().min(1).max(100).default(20)}).strict(),_I=c.z.object({totalItems:c.z.number().int().nonnegative(),nextPage:c.z.number().int().min(2).max(500).optional()}).strict();function EI(e,t,n){return _I.parse({totalItems:e,...t<500&&t*n<e?{nextPage:t+1}:{}})}const AI=II,TI=c.z.object({documents:c.z.array(c.z.object({title:ay.shape.title,storyPath:ry}).strict()).max(100),pagination:_I}).strict(),bI=c.z.object({items:c.z.array(c.z.object({storyPath:ry,path:c.z.string().trim().min(1).max(4096).optional(),revision:oy.optional(),error:c.z.object({code:c.z.string().trim().min(1).max(120),message:c.z.string().trim().min(1).max(2e3)}).strict().optional()}).strict()).min(1).max(20)}).strict(),wI=c.z.object({title:ay.shape.title,storyPath:ry,revision:oy,size:c.z.number().int().nonnegative()}).strict(),SI=c.z.enum(["STORY_ARCHIVED","STORY_ACTION_TARGET_REQUIRED","STORY_ACTION_TARGET_UNAVAILABLE"]),NI=II,vI=c.z.object({actions:c.z.array(c.z.object({id:dy.shape.id,title:dy.shape.title,promptPreview:c.z.string().max(500),promptTruncated:c.z.boolean(),executable:c.z.boolean(),unavailableReason:SI.optional()}).strict()).max(100),pagination:_I}).strict(),OI=c.z.object({actionId:dy.shape.id,clientRequestId:Oe}).strict(),RI=c.z.object({session:c.z.object({instanceId:c.z.string().trim().min(1).max(120),sessionId:c.z.string().trim().min(1).max(120)}).strict()}).strict(),zI=II,xI=c.z.object({actionId:dy.shape.id,schedule:my,enabled:c.z.boolean().default(!0),policy:hy.default({maxConcurrentRuns:1,whenBusy:"skip"})}).strict(),CI=c.z.object({automationId:c.z.string().trim().min(1).max(120),expectedUpdatedAt:c.z.string().datetime(),actionId:dy.shape.id.optional(),schedule:my.optional(),enabled:c.z.boolean().optional(),policy:hy.optional()}).strict().refine(e=>Object.keys(e).some(e=>!["automationId","expectedUpdatedAt"].includes(e)),"At least one Automation field is required."),kI=c.z.object({automationId:c.z.string().trim().min(1).max(120),expectedUpdatedAt:c.z.string().datetime()}).strict(),DI=c.z.object({automationId:c.z.string().trim().min(1).max(120),clientRequestId:Oe}).strict(),LI=c.z.object({automationId:c.z.string().trim().min(1).max(120),page:II.shape.page,pageSize:II.shape.pageSize}).strict(),PI=c.z.object({deleted:c.z.boolean()}).strict(),MI=c.z.object({id:c.z.string().trim().min(1).max(160),eventType:c.z.enum(["manual","schedule"]),status:Ey,scheduledFor:c.z.string().datetime(),session:c.z.object({instanceId:c.z.string().trim().min(1).max(120),sessionId:c.z.string().trim().min(1).max(120)}).strict().optional(),error:_y.optional(),startedAt:c.z.string().datetime().optional(),completedAt:c.z.string().datetime().optional()}).strict(),jI=c.z.object({id:c.z.string().trim().min(1).max(120),actionId:dy.shape.id,schedule:my,enabled:c.z.boolean(),policy:hy,updatedAt:c.z.string().datetime(),effectiveStatus:Ty,blockedReason:_y.optional(),nextRunAt:c.z.string().datetime().optional(),activeRunCount:c.z.number().int().nonnegative(),lastRun:MI.optional()}).strict(),UI=c.z.object({automations:c.z.array(jI).max(100),pagination:_I}).strict(),FI=c.z.object({runs:c.z.array(MI).max(100),pagination:_I}).strict(),$I=c.z.object({instanceId:c.z.string().trim().min(1).max(120),sessionId:c.z.string().trim().min(1).max(120)}).strict(),HI=II,BI=$I.extend({title:c.z.string().trim().max(240).optional(),agent:c.z.string().trim().min(1).max(120),status:c.z.enum(["running","waiting","idle"]),updatedAt:c.z.string().datetime()}).strict(),qI=c.z.object({sessions:c.z.array(BI).max(100),pagination:_I}).strict(),VI=$I.extend({page:II.shape.page,pageSize:c.z.number().int().min(1).max(50).default(10)}).strict(),GI=c.z.object({detail:Gt,turnIndex:Kt}).strict(),WI=c.z.object({cwd:Gt.shape.cwd,modelName:c.z.string().trim().min(1).max(240).optional(),reasoningEffort:Gt.shape.reasoningEffort,error:Gt.shape.error}).strict(),KI=qt.pick({id:!0,status:!0,phase:!0,updatedAt:!0,completedAt:!0}).strict(),YI=qt.pick({id:!0,status:!0,phase:!0,contextCompactions:!0,startedAt:!0,updatedAt:!0,completedAt:!0}).strict(),XI=c.z.object({ref:$I,session:WI,turns:c.z.array(KI).max(50),pagination:_I}).strict(),JI=$I.extend({turnId:c.z.string().trim().min(1).max(240),page:II.shape.page,pageSize:c.z.number().int().min(1).max(50).default(20),maxTextChars:c.z.number().int().min(256).max(32e3).default(8e3)}).strict(),QI=c.z.array(c.z.enum(["text","summary","input","output","paths"])).max(5).optional(),ZI=c.z.object({id:c.z.string().trim().min(1).max(240),truncatedFields:QI}).strict(),e_=ZI.extend({type:c.z.literal("user-message"),text:c.z.string().max(32e3),attachments:c.z.array(Xe).max(6).optional()}).strict(),t_=ZI.extend({type:c.z.literal("ai-message"),text:c.z.string().max(32e3)}).strict(),n_=ZI.extend({type:c.z.literal("activity"),activityKind:c.z.string().trim().min(1).max(120),title:c.z.string().trim().min(1).max(240),status:c.z.enum(["running","completed","failed","waiting"]).optional(),summary:c.z.string().max(32e3).optional(),input:c.z.string().max(32e3).optional(),output:c.z.string().max(32e3).optional(),paths:c.z.array(c.z.string().trim().min(1).max(4096)).max(100).optional(),exitCode:c.z.number().int().optional(),durationMs:c.z.number().int().nonnegative().optional()}).strict(),i_=c.z.discriminatedUnion("type",[e_,t_,n_]),s_=c.z.object({ref:$I,turn:YI,items:c.z.array(i_).max(50),pagination:_I}).strict(),r_=c.z.object({body:Yt,timeline:at}).strict(),o_=c.z.object({detail:Gt.strip(),turnIndex:Kt.strip()}).strip(),a_=c.z.object({body:Yt.strip(),timeline:at.strip()}).strip(),c_=Cy,d_=c.z.object({decisionId:c.z.string().trim().min(1).max(160),status:Oy}).strict(),l_={story_list_content:{input:AI,output:TI},story_get_content:{input:Wy,output:bI},story_set_content:{input:Ky,output:wI},story_list_actions:{input:NI,output:vI},story_run_action:{input:OI,output:RI},story_list_automations:{input:zI,output:UI},story_create_automation:{input:xI,output:jI},story_update_automation:{input:CI,output:jI},story_delete_automation:{input:kI,output:PI},story_run_automation:{input:DI,output:MI},story_list_automation_runs:{input:LI,output:FI},story_list_ai_sessions:{input:HI,output:qI},story_get_ai_session:{input:VI,output:XI},story_get_ai_session_turn:{input:JI,output:s_},story_request_decision:{input:c_,output:d_}},u_=c.z.object({storyId:ze}).strict(),p_=u_.extend({storyPath:c.z.string().min(1).max(2048)}).strict(),m_=u_.extend({automationId:c.z.string().trim().min(1).max(120)}).strict(),h_=c.z.object({id:c.z.string().trim().min(1).max(120),sessionId:c.z.string().trim().min(1).max(120)}).strict(),g_=h_.extend({tool:lI}).strict(),f_=u_.extend({actionId:c.z.string().trim().min(1).max(120)}).strict(),y_=u_.extend({decisionId:c.z.string().trim().min(1).max(160)}).strict(),I_=c.z.object({storyPath:ry}).strict(),__=I_.extend({title:c.z.string().trim().min(1).max(240).optional(),expectedRevision:c.z.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),E_=c.z.object({storyId:ze}).strict();function A_(e){const t=e.authorization;return"string"==typeof t&&t.startsWith("Bearer ")?t.slice(7).trim():void 0}function T_(e){return MI.parse({id:e.id,eventType:e.eventType,status:e.status,scheduledFor:e.scheduledFor,session:e.aiSessionId?{instanceId:e.targetInstanceId,sessionId:e.aiSessionId}:void 0,error:e.error,startedAt:e.startedAt,completedAt:e.completedAt})}function b_(e){return jI.parse({id:e.automation.id,actionId:e.automation.actionId,schedule:e.automation.schedule,enabled:e.automation.enabled,policy:e.automation.policy,updatedAt:e.automation.updatedAt,effectiveStatus:e.effectiveStatus,blockedReason:e.blockedReason,nextRunAt:e.nextRunAt,activeRunCount:e.currentRuns.length,lastRun:e.lastRun?T_(e.lastRun):void 0})}async function w_(e,t,n,i,s){const r=e.authenticateInstance(n,s).aiSessions.sessions.find(e=>e.id===i);if(!r)throw Object.assign(new Error("AI Session was not found in the authoritative instance snapshot."),{code:"AI_SESSION_NOT_FOUND",statusCode:404});if(!r.storyId)throw Object.assign(new Error("AI Session is not assigned to a Story."),{code:"STORY_CONTEXT_REQUIRED",statusCode:409});return await t.get(r.storyId)||(()=>{throw Object.assign(new Error("Story was not found."),{code:"STORY_NOT_FOUND",statusCode:404})})()}function S_(e,t,n,i){return e.header("content-type","application/octet-stream"),e.header("content-length",String(i)),e.header("x-story-revision",n),e.send(t)}function N_(){return Object.assign(new Error("Story Automation belongs to another Story."),{code:"STORY_AUTOMATION_STORY_MISMATCH",statusCode:409})}const v_=c.z.object({agentId:qu,orchestrationId:gp,status:c.z.enum(["available","missing-reference"])}).strict(),O_=c.z.object({storyId:ze,revision:Vu,entries:c.z.array(v_)}).strict(),R_=c.z.object({expectedRevision:Vu,entries:c.z.array(c.z.object({agentId:qu,orchestrationId:gp.optional()}).strict()).max(50)}).strict(),z_=["STORY_AGENT_ENTRY_STORY_NOT_FOUND","STORY_AGENT_ENTRY_AGENT_NOT_FOUND","STORY_AGENT_ENTRY_ORCHESTRATION_NOT_FOUND","STORY_AGENT_ENTRY_ORCHESTRATION_MISMATCH","STORY_AGENT_ENTRY_REVISION_CONFLICT"];c.z.enum(z_);const x_=v_.strip();O_.strip().extend({entries:c.z.array(x_)});const C_=c.z.object({agentId:qu}).strict(),k_=c.z.object({referencingOrchestrations:c.z.enum(["keep","delete"]).optional()}).strict(),D_=c.z.object({orchestrationId:gp}).strict(),L_=c.z.object({runId:Dp}).strict(),P_=c.z.object({runId:Dp,memberId:Lp}).strict(),M_=P_.extend({sessionId:c.z.string().trim().min(1).max(120)}).strict(),j_=c.z.object({storyId:ze}).strict();function U_(e,t,i){const s=e.resolveLocalFolder(i);if(!s)return{status:"unknown-folder"};const r=t.runtime.workspacePath||t.workspace.path||"/workspace";if("local"===e.requireRuntime(t.runtimeId).type){const e=n.resolve(s.path);return{status:"resolved",folderId:s.id,folderPath:e,workspacePath:r,runtimePath:e}}if("local-folder"!==t.source.type)return{status:"unsupported-source"};const o=n.relative(n.resolve(t.source.path),n.resolve(s.path));return".."===o||o.startsWith(`..${n.sep}`)||n.isAbsolute(o)?{status:"outside-workspace"}:{status:"resolved",folderId:s.id,folderPath:n.resolve(s.path),workspacePath:r,runtimePath:o?n.posix.join(r,...o.split(n.sep)):r}}class F_{state;definitions;orchestrations;publish;constructor(e,t,n,i){this.state=e,this.definitions=t,this.orchestrations=n,this.publish=i}list(){return this.definitions.list()}get(e){const t=this.definitions.get(e);if(!t)throw $_("AGENT_DEFINITION_NOT_FOUND",`Agent definition ${e} was not found.`,404);return t}has(e){return Boolean(this.definitions.get(e))}resolveExecution(e){const t=this.get(e),n=this.requireTargetInstance(t.targetInstanceId);if(this.requireFolder(n,t.cwdFolderId),!Is(n.capabilities,t.providerId))throw $_("AGENT_DEFINITION_PROVIDER_UNSUPPORTED",`Instance ${n.id} does not support provider ${t.providerId}.`,409);if(!Xu(t.executionPolicy))throw $_("AGENT_DEFINITION_POLICY_UNSUPPORTED",`Execution policy ${t.executionPolicy.workspaceMaterializer}/${t.executionPolicy.processSandbox} is not published by this Node Agent.`,409);return{definition:t,runtimeType:this.state.requireRuntime(n.runtimeId).type}}create(e){const t=Zu.parse(e),n=du("agent"),i=(new Date).toISOString(),s=this.definitions.transaction(()=>{const e=function(e){return{name:e.name,description:e.description,appendedPrompt:e.appendedPrompt,targetInstanceId:e.targetInstanceId,cwdFolderId:e.cwdFolderId,providerId:e.providerId,modelEntityId:e.modelEntityId,modelName:e.modelName,modelUpstreamName:e.modelUpstreamName,reasoningEffort:e.reasoningEffort,permissionMode:e.permissionMode,executionPolicy:e.executionPolicy??{workspaceMaterializer:"overlay-copy-on-write",processSandbox:"instance"}}}(t);return this.validate(e),{definition:this.definitions.insert({id:n,...e},i),defaultOrchestration:this.orchestrations.insertDefaultForAgent(n,e.name,i)}});return this.definitions.afterCommit(()=>{this.emit("created",s.definition),this.orchestrations.publishChange("created",s.defaultOrchestration)}),s.definition}update(e,t){const n=ep.parse(t),i=(new Date).toISOString(),s=this.definitions.transaction(()=>{const t=this.definitions.get(e);if(!t)return{status:"missing"};const s=function(e,t){const n=(e,t)=>null===e?void 0:void 0===e?t:e;return{name:t.name??e.name,description:null===t.description?"":t.description??e.description,appendedPrompt:null===t.appendedPrompt?"":t.appendedPrompt??e.appendedPrompt,targetInstanceId:t.targetInstanceId??e.targetInstanceId,cwdFolderId:t.cwdFolderId??e.cwdFolderId,providerId:t.providerId??e.providerId,modelEntityId:n(t.modelEntityId,e.modelEntityId),modelName:n(t.modelName,e.modelName),modelUpstreamName:n(t.modelUpstreamName,e.modelUpstreamName),reasoningEffort:n(t.reasoningEffort,e.reasoningEffort),permissionMode:n(t.permissionMode,e.permissionMode),executionPolicy:t.executionPolicy??e.executionPolicy}}(t,n);return this.validate(s),this.definitions.update(e,n.expectedRevision,s,i)});if("missing"===s.status)throw $_("AGENT_DEFINITION_NOT_FOUND",`Agent definition ${e} was not found.`,404);if("revision-conflict"===s.status)throw Object.assign($_("AGENT_DEFINITION_REVISION_CONFLICT","Agent definition changed since it was read.",409),{details:{code:"AGENT_DEFINITION_REVISION_CONFLICT",expectedRevision:n.expectedRevision,actualRevision:s.definition.revision}});return this.definitions.afterCommit(()=>this.emit("updated",s.definition)),s.definition}delete(e,t={}){const n=this.get(e),i=this.definitions.transaction(()=>{const n=this.orchestrations.deleteForAgent(e,t.referencingOrchestrations??"keep");if(this.definitions.delete(e))return n});if(!i)throw $_("AGENT_DEFINITION_NOT_FOUND",`Agent definition ${e} was not found.`,404);return this.definitions.afterCommit(()=>{this.emit("deleted",n);for(const e of i)this.orchestrations.publishChange("deleted",e)}),{deletedOrchestrationIds:i.map(e=>e.id)}}emit(e,t){this.publish?.("agent.definition.changed",{agentId:t.id,change:e,revision:t.revision,definition:t},{})}validate(e){const t=this.requireTargetInstance(e.targetInstanceId);if(this.requireFolder(t,e.cwdFolderId),!Is(t.capabilities,e.providerId))throw $_("AGENT_DEFINITION_PROVIDER_UNSUPPORTED",`Instance ${t.id} does not support provider ${e.providerId}.`,409);if(!Xu(e.executionPolicy))throw $_("AGENT_DEFINITION_POLICY_UNSUPPORTED",`Execution policy ${e.executionPolicy.workspaceMaterializer}/${e.executionPolicy.processSandbox} is not published by this Node Agent.`,409)}requireTargetInstance(e){if(!this.state.controlledInstances.get(e))throw $_("AGENT_DEFINITION_TARGET_INSTANCE_UNKNOWN",`Instance ${e} does not belong to this Node Agent.`,404);return this.state.requireInstance(e)}requireFolder(e,t){const n=U_(this.state,e,t);if("unknown-folder"===n.status)throw $_("AGENT_DEFINITION_FOLDER_UNKNOWN",`Working folder ${t} was not found on this Node Agent.`,404);if("resolved"!==n.status)throw $_("AGENT_DEFINITION_FOLDER_UNKNOWN",`Working folder ${t} cannot be resolved on instance ${e.id}.`,409)}}function $_(e,t,n){if(!ip.includes(e))throw new Error(`Unknown Agent definition error code ${e}.`);return Object.assign(new Error(t),{code:e,statusCode:n})}class H_{orchestrations;definitions;publish;constructor(e,t,n){this.orchestrations=e,this.definitions=t,this.publish=n}list(){return this.orchestrations.list()}get(e){const t=this.orchestrations.get(e);if(!t)throw B_("AGENT_ORCHESTRATION_NOT_FOUND",`Agent orchestration ${e} was not found.`,404);return t}has(e){return Boolean(this.orchestrations.get(e))}find(e){return this.orchestrations.get(e)}containsAgent(e,t){const n=this.orchestrations.get(e);return!!n&&Rp(n,t)}create(e){const t=Ap.parse(e),n=du("orchestration"),i=(new Date).toISOString(),s=this.orchestrations.transaction(()=>(this.validateGraph(t,n),this.orchestrations.insert({id:n,...t},i)));return this.orchestrations.afterCommit(()=>this.publishChange("created",s)),s}update(e,t){const n=Tp.parse(t),i=(new Date).toISOString(),s=this.orchestrations.transaction(()=>{const t=this.orchestrations.get(e);if(!t)return{status:"missing"};const s={name:n.name??t.name,agentIds:n.agentIds??t.agentIds,edges:n.edges??t.edges};return this.validateGraph(s,e,t),this.orchestrations.update(e,n.expectedRevision,s,i)});if("missing"===s.status)throw B_("AGENT_ORCHESTRATION_NOT_FOUND",`Agent orchestration ${e} was not found.`,404);if("revision-conflict"===s.status)throw Object.assign(B_("AGENT_ORCHESTRATION_REVISION_CONFLICT","Agent orchestration changed since it was read.",409),{details:vp.parse({code:"AGENT_ORCHESTRATION_REVISION_CONFLICT",expectedRevision:n.expectedRevision,actualRevision:s.orchestration.revision})});return this.orchestrations.afterCommit(()=>this.publishChange("updated",s.orchestration)),s.orchestration}delete(e){const t=this.get(e);if(Ip(e))throw B_("AGENT_ORCHESTRATION_DEFAULT_PROTECTED","The default orchestration of an Agent cannot be deleted directly; delete the Agent instead.",409);return!!this.orchestrations.delete(e)&&(this.orchestrations.afterCommit(()=>this.publishChange("deleted",t)),!0)}insertDefaultForAgent(e,t,n){return this.orchestrations.insert({id:yp(e),name:t,agentIds:[e],edges:[]},n)}deleteForAgent(e,t){const n=yp(e),i=this.orchestrations.idsReferencingAgent(e),s="delete"===t?i.filter(e=>e===n||!Ip(e)):[],r=[...new Set([n,...s])].flatMap(e=>{const t=this.orchestrations.get(e);return t?[t]:[]});return this.orchestrations.deleteMany(r.map(e=>e.id)),r}publishChange(e,t){this.publish?.("agent.orchestration.changed",{orchestrationId:t.id,change:e,revision:t.revision,orchestration:t},{})}validateGraph(e,t,n){const i=zp(e),s=new Set(i.agentIds);for(const e of i.edges){if(e.fromAgentId===e.toAgentId)throw B_("AGENT_ORCHESTRATION_INVALID_GRAPH","An Agent cannot call itself.",409,{agentId:e.fromAgentId});if(!s.has(e.fromAgentId)||!s.has(e.toAgentId))throw B_("AGENT_ORCHESTRATION_INVALID_GRAPH","Every edge must connect Agents inside the orchestration graph.",409,{fromAgentId:e.fromAgentId,toAgentId:e.toAgentId})}const r=new Set(n?.agentIds??[]);for(const e of i.agentIds)if(!this.definitions.get(e)&&!r.has(e))throw B_("AGENT_ORCHESTRATION_AGENT_UNKNOWN",`Agent definition ${e} was not found on this Node Agent.`,409,{agentId:e});const o=function(e){const t=new Map;for(const n of e.agentIds)t.set(n,[]);for(const n of e.edges)t.get(n.fromAgentId)?.push(n.toAgentId);const n=new Map,i=[],s=e=>{n.set(e,"visiting"),i.push(e);for(const r of t.get(e)??[]){if("visiting"===n.get(r))return[...i.slice(i.indexOf(r)),r];if("visited"===n.get(r))continue;const e=s(r);if(e)return e}i.pop(),n.set(e,"visited")};for(const t of e.agentIds){if(n.has(t))continue;const e=s(t);if(e)return e;i.length=0}}(i);if(o)throw Object.assign(B_("AGENT_ORCHESTRATION_CYCLE",`The orchestration graph would form a cycle: ${o.join(" -> ")}.`,409),{details:{code:"AGENT_ORCHESTRATION_CYCLE",cycle:o}});const a=Ip(t);if(a){if(!this.definitions.get(a))throw B_("AGENT_ORCHESTRATION_DEFAULT_PROTECTED",`The owning Agent ${a} of this default orchestration was not found.`,409,{agentId:a});if(!s.has(a))throw B_("AGENT_ORCHESTRATION_DEFAULT_PROTECTED","A default orchestration must keep its owning Agent in the graph.",409,{agentId:a})}}}function B_(e,t,n,i){return Object.assign(new Error(t),{code:e,statusCode:n,...i?{details:i}:{}})}class q_{state;definitions;orchestrations;runs;supportsExecution;publish;resources;coordinator;constructor(e,t,n,i,s,r,o){this.state=e,this.definitions=t,this.orchestrations=n,this.runs=i,this.supportsExecution=s,this.publish=r,this.resources=o}setCoordinator(e){this.coordinator=e}list(){return this.runs.list().map(e=>this.withSharedSpace(e))}get(e){const t=this.runs.get(e);if(!t)throw G_("AGENT_RUN_NOT_FOUND",`Agent Run ${e} was not found.`,404,{runId:e});return this.withSharedSpace(t)}withSharedSpace(e){const t=this.resources?.getSharedSpace(e.runId);return t?{...e,sharedSpace:{runtimeId:t.runtimeId,state:t.state,usageBytes:t.usageBytes,quotaBytes:t.quotaBytes,...t.expiresAt?{expiresAt:t.expiresAt}:{}}}:e}getMember(e,t){this.get(e);const n=this.runs.getMember(e,t);if(!n)throw G_("AGENT_RUN_MEMBER_NOT_FOUND",`Agent Run member ${t} was not found.`,404,{runId:e,memberId:t});return n}transitionMember(e,t,n){const i=this.get(e),s=this.runs.transitionMember(e,t,n),r=this.get(e);return r.revision!==i.revision&&this.publishMember(r,s),s}resolveMemberInvocationTools(e,t){const n=this.get(e),i=this.requireOrchestrationForRun(n.orchestrationId);return nI(i.edges.filter(e=>e.fromAgentId===t).flatMap(e=>this.definitions.has(e.toAgentId)?[{agentId:e.toAgentId,orchestrationId:i.id}]:[]))}requireOrchestrationForRun(e){const t=this.orchestrations.find(e);if(!t)throw G_("AGENT_RUN_ORCHESTRATION_UNKNOWN",`Agent orchestration ${e} was not found on this Node Agent.`,409,{orchestrationId:e});return t}create(e){const t=nm.parse(e),n=this.runs.getByClientRequestId(t.clientRequestId);if(n){const e=n.members?.find(e=>e.memberId===n.rootMemberId);if(n.orchestrationId===t.orchestrationId&&(void 0===t.entryAgentId||e?.agentId===t.entryAgentId)&&b.isDeepStrictEqual(n.input,t.input)&&b.isDeepStrictEqual(n.provenance,t.provenance)&&b.isDeepStrictEqual(n.budget,V_(t.budget)))return this.withSharedSpace(n);throw G_("AGENT_RUN_IDEMPOTENCY_CONFLICT","The client request id is already associated with a different Agent Run request.",409,{clientRequestId:t.clientRequestId,runId:n.runId})}if("control-plane"!==t.provenance.source&&!this.state.controlledInstances.get(t.provenance.initiatingInstanceId))throw G_("AGENT_RUN_INITIATING_INSTANCE_UNKNOWN",`Initiating instance ${t.provenance.initiatingInstanceId} does not belong to this Node Agent.`,404,{initiatingInstanceId:t.provenance.initiatingInstanceId});const i=this.requireOrchestrationForRun(t.orchestrationId),s=function(e,t){if(t){if(!Rp(e,t))throw G_("AGENT_RUN_ENTRY_INVALID",`Agent ${t} is not part of orchestration ${e.id}.`,409,{orchestrationId:e.id,entryAgentId:t});return t}const n=function(e){const t=new Set(e.edges.map(e=>e.toAgentId));return e.agentIds.filter(e=>!t.has(e))}(e);if(1!==n.length)throw G_("AGENT_RUN_ENTRY_REQUIRED","The orchestration has multiple entry Agents; the request must name one.",409,{orchestrationId:e.id,entryAgentIds:n});return n[0]}(i,t.entryAgentId),{definition:r,runtimeType:o}=this.definitions.resolveExecution(s);if(!this.supportsExecution({targetInstanceId:r.targetInstanceId,runtimeType:o,providerId:r.providerId,permissionMode:r.permissionMode,executionPolicy:r.executionPolicy}))throw G_("AGENT_RUN_EXECUTION_UNSUPPORTED","The target runtime, workspace materializer, process sandbox, and provider combination is not supported.",409,{agentId:r.id,runtimeType:o,providerId:r.providerId,executionPolicy:r.executionPolicy});const a=this.runs.create({clientRequestId:t.clientRequestId,orchestrationId:i.id,input:t.input,provenance:t.provenance,budget:V_(t.budget),root:{agentId:r.id,instanceId:r.targetInstanceId,executionSnapshot:{agentRevision:r.revision,targetInstanceId:r.targetInstanceId,cwdFolderId:r.cwdFolderId,appendedPrompt:r.appendedPrompt,providerId:r.providerId,modelEntityId:r.modelEntityId,modelName:r.modelName,modelUpstreamName:r.modelUpstreamName,reasoningEffort:r.reasoningEffort,permissionMode:r.permissionMode,executionPolicy:r.executionPolicy},input:t.input}});this.publishRun(a);const c=a.members?.find(e=>e.memberId===a.rootMemberId);return c&&this.publishMember(a,c),c&&this.coordinator?.accept(a.runId,c.memberId),this.withSharedSpace(a)}addMember(e){const t=Vp.parse(e.input),n=this.get(e.runId);if("running"!==n.status)throw G_("AGENT_RUN_ALREADY_TERMINAL","Only a running Agent Run can accept another member.",409,{runId:e.runId,status:n.status});const i=this.getMember(e.runId,e.parentMemberId);if("running"!==i.status)throw G_("AGENT_RUN_ALREADY_TERMINAL","Only a running Agent Run member can invoke another Agent.",409,{runId:e.runId,memberId:e.parentMemberId,status:i.status});const s=this.requireOrchestrationForRun(n.orchestrationId);if(!function(e,t,n){return e.edges.some(e=>e.fromAgentId===t&&e.toAgentId===n)}(s,i.agentId,e.agentId))throw G_("AGENT_RUN_INVOCATION_FORBIDDEN","The caller Agent is not authorized to invoke the target Agent in this orchestration.",403,{runId:e.runId,memberId:e.parentMemberId,agentId:e.agentId,orchestrationId:s.id});const{definition:r,runtimeType:o}=this.definitions.resolveExecution(e.agentId);if(!this.supportsExecution({targetInstanceId:r.targetInstanceId,runtimeType:o,providerId:r.providerId,permissionMode:r.permissionMode,executionPolicy:r.executionPolicy}))throw G_("AGENT_RUN_EXECUTION_UNSUPPORTED","The callee execution combination has not passed behavior probing.",409,{agentId:r.id,runtimeType:o,providerId:r.providerId,executionPolicy:r.executionPolicy});const a=this.runs.addMember({runId:n.runId,parentMemberId:i.memberId,clientRequestId:e.clientRequestId,agentId:r.id,instanceId:r.targetInstanceId,input:t,executionSnapshot:{agentRevision:r.revision,targetInstanceId:r.targetInstanceId,cwdFolderId:r.cwdFolderId,appendedPrompt:r.appendedPrompt,providerId:r.providerId,modelEntityId:r.modelEntityId,modelName:r.modelName,modelUpstreamName:r.modelUpstreamName,reasoningEffort:r.reasoningEffort,permissionMode:r.permissionMode,executionPolicy:r.executionPolicy}}),c=this.get(n.runId),d={permissionModeChanged:i.executionSnapshot.permissionMode!==r.permissionMode,workspaceMaterializerChanged:i.executionSnapshot.executionPolicy.workspaceMaterializer!==r.executionPolicy.workspaceMaterializer,processSandboxChanged:i.executionSnapshot.executionPolicy.processSandbox!==r.executionPolicy.processSandbox,providerChanged:i.executionSnapshot.providerId!==r.providerId};return Object.values(d).some(Boolean)&&this.appendTimeline(n.runId,"member.policy-difference",{memberId:a.memberId,data:{parentMemberId:i.memberId,...d}}),this.publishMember(c,a),"queued"===a.status&&this.coordinator?.accept(n.runId,a.memberId),a}transitionRun(e,t){const n=this.runs.transitionRun(e,t);return this.publishRun(n),this.withSharedSpace(n)}appendTimeline(e,t,n={}){const i=this.runs.appendTimeline({runId:e,kind:t,...n});return this.publishRun(this.get(e)),i}toolResult(e){const t=this.get(e);if(mm.has(t.status)){if("completed"===t.status){const n=t.result?.text??"",i=n.slice(0,jp);return Xp.parse({runId:e,status:"completed",result:{text:i,truncated:Boolean(t.result?.truncated)||i.length<n.length}})}return Xp.parse({runId:e,status:t.status,error:t.error??{code:"cancelled"===t.status?"AGENT_RUN_CANCELLED":"AGENT_RUN_FAILED",message:"cancelled"===t.status?"The Agent Run was cancelled.":"The Agent Run failed.",retryable:!1}})}}async waitForToolResult(e,t,n=18e5){const i=Date.now();for(;;){const s=this.toolResult(e);if(s)return s;if(t?.aborted)throw G_("AGENT_RUN_ALREADY_TERMINAL","Waiting for the Agent Run result was aborted.",499,{runId:e});if(Date.now()-i>=n)return Xp.parse({runId:e,status:"failed",error:{code:"AGENT_RUN_RESULT_TIMEOUT",message:"The Agent Run did not reach a terminal state before the tool timeout.",retryable:!0}});await new Promise(e=>{const n=setTimeout(e,100);n.unref?.(),t?.addEventListener("abort",()=>{clearTimeout(n),e()},{once:!0})})}}async waitForMemberToolResult(e,t,n,i=18e5){const s=Date.now();for(;;){const r=this.getMember(e,t);if(mm.has(r.status)){if("completed"===r.status){const t=r.result?.text??"",n=t.slice(0,jp);return Xp.parse({runId:e,status:"completed",result:{text:n,truncated:Boolean(r.result?.truncated)||n.length<t.length}})}return Xp.parse({runId:e,status:r.status,error:r.error??{code:"cancelled"===r.status?"AGENT_RUN_MEMBER_CANCELLED":"AGENT_RUN_MEMBER_FAILED",message:"cancelled"===r.status?"The Agent Run member was cancelled.":"The Agent Run member failed.",retryable:!1}})}if(n?.aborted)throw G_("AGENT_RUN_ALREADY_TERMINAL","Waiting for the Agent Run member was aborted.",499,{runId:e,memberId:t});if(Date.now()-s>=i)return Xp.parse({runId:e,status:"failed",error:{code:"AGENT_RUN_MEMBER_RESULT_TIMEOUT",message:"The Agent Run member did not finish before the tool timeout.",retryable:!0}});await new Promise(e=>{const t=setTimeout(e,100);t.unref?.(),n?.addEventListener("abort",()=>{clearTimeout(t),e()},{once:!0})})}}cancel(e,t){const n=im.parse(t),i=this.get(e);if(void 0!==n.expectedRevision&&n.expectedRevision!==i.revision)throw G_("AGENT_RUN_REVISION_CONFLICT","Agent Run changed since it was read.",409,{runId:e,expectedRevision:n.expectedRevision,actualRevision:i.revision});if("finalizing"===i.status)return i;if(mm.has(i.status))throw G_("AGENT_RUN_ALREADY_TERMINAL","A terminal Agent Run cannot be cancelled.",409,{runId:e,status:i.status});const s=this.runs.transitionRun(e,{status:"finalizing"});return this.coordinator?.cancel?.(e),this.publishRun(s),this.withSharedSpace(s)}publishRun(e){e=this.withSharedSpace(e),this.publish?.("agent.run.changed",{runId:e.runId,revision:e.revision,run:e},{})}publishMember(e,t){this.publish?.("agent.run.member.changed",{runId:e.runId,memberId:t.memberId,revision:e.revision,member:t},{instanceId:t.instanceId})}}function V_(e){return e?{maxMembers:Math.min(e.maxMembers,Mp.maxMembers),maxDepth:Math.min(e.maxDepth,Mp.maxDepth),maxConcurrency:Math.min(e.maxConcurrency,Mp.maxConcurrency)}:{...Mp}}function G_(e,t,n,i){if(!rm.includes(e))throw new Error(`Unknown Agent Run service error code ${e}.`);return Object.assign(new Error(t),{code:e,statusCode:n,...i?{details:i}:{}})}class W_{timers=new Map;running=new Map;queued=new Map;lastStartedAt=new Map;accepting=!0;adapter;maxQueuedPerJob;now;constructor(e,t=100,n=Date.now){this.adapter=e,this.maxQueuedPerJob=t,this.now=n}start(){this.accepting=!0}setTimer(e,t){const n=this.timers.get(e);n&&clearTimeout(n),this.timers.set(e,t)}clearTimer(e){const t=this.timers.get(e);t&&clearTimeout(t),this.timers.delete(e)}clearQueued(e,t="job-disabled"){const n=this.queued.get(e);if(n){for(const e of n)this.adapter.skipped(e.event,t);this.queued.delete(e)}}submit(e,t,n){if(!this.accepting)return this.adapter.skipped(t,"scheduler-stopped"),"skipped";const i=this.now(),s=this.lastStartedAt.get(e);if(n.cooldownMs&&void 0!==s&&i-s<n.cooldownMs)return this.adapter.skipped(t,"cooldown"),"skipped";if((this.running.get(e)??0)>=n.maxConcurrentRuns){if("skip"===n.whenBusy)return this.adapter.skipped(t,"busy"),"skipped";const i=this.queued.get(e)??[];return i.length>=this.maxQueuedPerJob?(this.adapter.skipped(t,"queue-full"),"skipped"):(i.push({event:t,policy:n}),this.queued.set(e,i),"queued")}return this.begin(e,t,n),"started"}stop(){this.accepting=!1;for(const e of this.timers.values())clearTimeout(e);this.timers.clear();for(const e of this.queued.values())for(const t of e)this.adapter.skipped(t.event,"scheduler-stopped");this.queued.clear()}begin(e,t,n){this.running.set(e,(this.running.get(e)??0)+1),this.lastStartedAt.set(e,this.now());const i=()=>{const t=(this.running.get(e)??1)-1;t>0?this.running.set(e,t):this.running.delete(e),this.drain(e)};this.adapter.execute(t).then(i,i)}drain(e){if(!this.accepting)return;const t=this.queued.get(e);if(!t?.length)return;const n=t[0];(this.running.get(e)??0)>=n.policy.maxConcurrentRuns||(t.shift(),t.length||this.queued.delete(e),this.begin(e,n.event,n.policy))}}function K_(e,t){return new Date(Date.UTC(e,t+1,0)).getUTCDate()}function Y_(e,t,n,i,s,r){return v.CronExpressionParser.parse(`0 ${i} ${n} ${e} ${t} *`,{currentDate:r,strict:!0,tz:s}).next().toDate()}function X_(e,t,n){return`sch_${d.createHash("sha256").update(`${e}\0${t}\0${n}`).digest("hex").slice(0,32)}`}const J_=/^[a-zA-Z0-9][a-zA-Z0-9_.:-]{0,119}$/;class Q_{entries=new Map;register(e,t){if(e.workspaceMaterializer!==t.kind)throw new Error(`Materializer ${t.kind} cannot be registered as ${e.workspaceMaterializer}.`);const n=this.key(e);if(this.entries.has(n))throw new Error(`Workspace materializer combination ${n} is already registered.`);this.entries.set(n,t)}require(e){const t=this.entries.get(this.key(e));if(t)return t;throw Object.assign(new Error("No workspace materializer is available for the requested execution combination."),{code:"AGENT_RUN_MATERIALIZER_UNAVAILABLE",statusCode:409,details:{...e}})}key(e){return`${e.runtimeType}\0${e.workspaceMaterializer}\0${e.processSandbox}`}}function Z_(e,t){if(!J_.test(e))throw Object.assign(new Error(`${t} is not a safe workspace path segment.`),{code:"AGENT_RUN_WORKSPACE_ID_INVALID",statusCode:400,details:{field:t}});return e}function eE(e,t,i="/run/task-handoff/agent-runs/workspaces"){const s=n.posix.resolve("/",i),r=n.posix.join(s,Z_(e,"runId")),o=n.posix.join(r,Z_(t,"memberId"));return{root:s,runRoot:r,memberRoot:o,cwd:n.posix.join(o,"merged"),markerPath:n.posix.join(o,".task-handoff-agent-run.json")}}function tE(e,t){const i=n.posix.resolve("/",e),s=n.posix.resolve("/",t);if(s===i||s.startsWith(`${i}/`))return s;throw Object.assign(new Error("Agent Run workspace path is outside its owned root."),{code:"AGENT_RUN_WORKSPACE_PATH_OUTSIDE_ROOT",statusCode:400})}function nE(e){return Z_(e.runId,"runId"),Z_(e.memberId,"memberId"),Z_(e.generationId,"generationId"),{version:1,runId:e.runId,memberId:e.memberId,generationId:e.generationId,createdAt:e.createdAt??(new Date).toISOString()}}function iE(e,t="AGENT_RUN_EXECUTION_FAILED"){const n=e&&"object"==typeof e?e:{};return{code:"string"==typeof n.code?n.code:t,message:e instanceof Error?e.message:String(e),retryable:!0===n.retryable}}class sE{runScheduler;memberScheduler;controllers=new Map;activeExecutions=new Set;completionWaiters=new Map;cleanupRetryTimers=new Map;managedRunIds=new Set;options;accepting=!0;constructor(e){this.options=e,this.memberScheduler=new W_({execute:e=>this.trackMemberExecution(e),skipped:(e,t)=>this.failQueued(e,t)}),this.runScheduler=new W_({execute:e=>this.submitRootMember(e),skipped:(e,t)=>this.failQueued(e,t)})}accept(e,t){if(!this.accepting)return this.failQueued(this.event(e,t),"scheduler-stopped");const n=this.event(e,t);if(n.root){if(this.managedRunIds.has(e))return;this.managedRunIds.add(e),this.runScheduler.submit(n.initiatorKey,n,{maxConcurrentRuns:2,whenBusy:"queue"})}else this.memberScheduler.submit(`run:${e}`,n,{maxConcurrentRuns:n.maxConcurrency,whenBusy:"queue"})}cancel(e){this.memberScheduler.clearQueued(`run:${e}`,"job-disabled");for(const[t,n]of this.controllers)t.startsWith(`${e}:`)&&n.abort()}async stop(){this.accepting=!1,this.runScheduler.stop(),this.memberScheduler.stop();for(const e of this.cleanupRetryTimers.values())clearTimeout(e);this.cleanupRetryTimers.clear();for(const e of this.controllers.values())e.abort();await Promise.allSettled([...this.activeExecutions])}async reconcile(){for(const e of this.options.runs.list()){if(mm.has(e.status)){this.managedRunIds.delete(e.runId);continue}if(this.managedRunIds.has(e.runId))continue;const t=this.options.resources.listForRun(e.runId);if("queued"===e.status&&0===t.length){const t=e.members?.find(t=>t.memberId===e.rootMemberId);"queued"===t?.status&&this.accept(e.runId,t.memberId);continue}await this.reconcileInterruptedRun(e.runId)}}async reconcileInterruptedRun(e){const t={code:"AGENT_RUN_NODE_RESTARTED",message:"The Node Agent restarted after this Agent Run began; started members are not executed again.",retryable:!1};let n=this.options.runs.get(e);"finalizing"!==n.status&&(n=this.options.runs.transitionRun(e,{status:"finalizing"}));for(const i of n.members??[])mm.has(i.status)||"finalizing"===i.status||this.options.runs.transitionMember(e,i.memberId,{status:"finalizing",error:t});const i=new Set;for(const t of this.options.resources.listForRun(e))if(t.instanceId&&i.add(t.instanceId),"provider-thread"===t.kind&&"deleted"!==t.phase&&"manual-intervention"!==t.phase)if(t.memberId&&t.instanceId)try{this.options.resources.transition(t.resourceId,"deleting"),await this.options.sessions.close(this.options.state.requireInstance(t.instanceId),e,t.memberId),this.options.resources.transition(t.resourceId,"deleted")}catch(e){this.options.resources.transition(t.resourceId,"delete-retrying",{incrementCleanupAttempts:!0,metadata:{code:"AGENT_RUN_PROVIDER_THREAD_CLOSE_FAILED",message:e instanceof Error?e.message:String(e)}})}else this.options.resources.transition(t.resourceId,"manual-intervention",{metadata:{code:"AGENT_RUN_RESOURCE_OWNERSHIP_UNPROVEN",message:"Provider thread ownership is incomplete."}});for(const e of i)await(this.options.reconcileInstanceResources?.(e).catch(()=>{}));const s=this.options.resources.listForRun(e).filter(e=>"provider-thread"===e.kind||"overlay-mount"===e.kind),r=s.some(e=>"manual-intervention"===e.phase),o=s.some(e=>"deleted"!==e.phase&&"manual-intervention"!==e.phase),a=Math.max(1,...s.map(e=>e.cleanupAttempts));if(o)this.options.runs.transitionRun(e,{status:"finalizing",error:t,cleanup:{status:"retrying",attempts:a,message:"Runtime cleanup will be retried.",updatedAt:(new Date).toISOString()}});else{for(const n of this.options.runs.get(e).members??[])mm.has(n.status)||this.options.runs.transitionMember(e,n.memberId,{status:"failed",error:t});this.options.runs.transitionRun(e,{status:"failed",error:t,cleanup:{status:r?"manual-intervention":"completed",attempts:a,...r?{message:"At least one runtime resource could not be proven to belong to this Agent Run."}:{},updatedAt:(new Date).toISOString()}})}}trackMemberExecution(e){const t=this.executeMember(e);return this.activeExecutions.add(t),t.finally(()=>this.activeExecutions.delete(t)),t}event(e,t){const n=this.options.runs.get(e);return this.options.runs.getMember(e,t),{runId:e,memberId:t,root:n.rootMemberId===t,initiatorKey:"control-plane"===n.provenance.source?`control-plane:${n.provenance.authorizationSubject?.subjectId??"system"}`:`story:${n.provenance.initiatingAiSessionId}`,maxConcurrency:n.budget.maxConcurrency}}async submitRootMember(e){await new Promise(t=>{this.completionWaiters.set(`${e.runId}:${e.memberId}`,t),this.memberScheduler.submit(`run:${e.runId}`,e,{maxConcurrentRuns:e.maxConcurrency,whenBusy:"queue"})})}async executeMember(e){const t=`${e.runId}:${e.memberId}`;if(this.controllers.has(t))return;const n=new AbortController;let i,s,r;this.controllers.set(t,n);let o,a,c,l=!1;try{let t=this.options.runs.get(e.runId),u=this.options.runs.getMember(e.runId,e.memberId);if("finalizing"===t.status)throw Object.assign(new Error("The Agent Run was cancelled before the member started."),{code:"AGENT_RUN_CANCELLED"});e.root&&this.options.runs.transitionRun(t.runId,{status:"preparing"}),u=this.options.runs.transitionMember(t.runId,u.memberId,{status:"preparing"}),this.options.runs.appendTimeline(t.runId,"member.preparing",{memberId:u.memberId}),r=this.options.state.requireInstance(u.instanceId);const p=this.options.state.requireRuntime(r.runtimeId);if("docker"!==p.type)throw Object.assign(new Error("Phase 1 Agent Run execution requires a Docker Runtime."),{code:"AGENT_RUN_RUNTIME_UNSUPPORTED"});const m=U_(this.options.state,r,u.executionSnapshot.cwdFolderId);if("resolved"!==m.status)throw Object.assign(new Error("The Agent working folder is no longer available in the target instance."),{code:"AGENT_RUN_FOLDER_UNAVAILABLE"});const h=`generation_${d.randomBytes(12).toString("hex")}`;e.root&&await this.options.sharedSpaces.ensure({runId:t.runId,runtimeId:p.id,instanceId:r.id,generationId:h}),this.options.sharedSpaces.bindingForMember(t.runId,p.id),s=this.options.materializers.require({runtimeType:p.type,workspaceMaterializer:u.executionSnapshot.executionPolicy.workspaceMaterializer,processSandbox:u.executionSnapshot.executionPolicy.processSandbox}),i=await s.prepare({runId:t.runId,memberId:u.memberId,generationId:h,runtimeId:p.id,instanceId:r.id,sourceRuntimePath:m.runtimePath,executionSnapshot:u.executionSnapshot});const g=this.options.sharedSpaces.pathPolicyForMember(t.runId,p.id,i.layout.cwd),f=this.options.runs.resolveMemberInvocationTools(t.runId,u.agentId),y=u.executionSnapshot.modelEntityId&&u.executionSnapshot.modelName?{modelEntityId:u.executionSnapshot.modelEntityId,modelName:u.executionSnapshot.modelName,modelUpstreamName:u.executionSnapshot.modelUpstreamName}:void 0;if(!u.input)throw Object.assign(new Error("The Agent Run member has no frozen input."),{code:"AGENT_RUN_MEMBER_INPUT_MISSING"});const I=await this.options.sessions.create(r,{runId:t.runId,memberId:u.memberId,clientRequestId:`agent_member_${u.memberId}`,providerId:u.executionSnapshot.providerId,cwd:{type:"runtime-path",path:g.cwd},writableRoots:{workspace:{type:"runtime-path",path:g.writableRoots[0]},shared:{type:"runtime-path",path:g.writableRoots[1]}},prompt:u.input.prompt,appendedPrompt:u.executionSnapshot.appendedPrompt,permissionMode:u.executionSnapshot.permissionMode||"auto-review",modelSelection:y,reasoningEffort:u.executionSnapshot.reasoningEffort,enabledTools:f.enabledTools});l=!0;const _=this.options.resources.register({runId:t.runId,memberId:u.memberId,instanceId:r.id,runtimeId:p.id,kind:"provider-thread",generationId:h,backendIdentity:I.providerSessionId,metadata:{aiSessionId:I.aiSessionId,providerId:u.executionSnapshot.providerId}});for(o=_.resourceId,this.options.resources.transition(_.resourceId,"ready"),this.options.runs.transitionMember(t.runId,u.memberId,{status:"running",aiSessionId:I.aiSessionId}),e.root&&this.options.runs.transitionRun(t.runId,{status:"running"}),this.options.runs.appendTimeline(t.runId,"member.running",{memberId:u.memberId});!n.signal.aborted&&(t=this.options.runs.get(t.runId),"finalizing"!==t.status);){const e=await this.options.sessions.status(r,t.runId,u.memberId);if(await this.options.sharedSpaces.refreshUsage(t.runId,r.id),"completed"===e.status){a=e.result;break}if("failed"===e.status){c=e.error;break}await new Promise(e=>setTimeout(e,this.options.pollIntervalMs??250))}a||c||(c={code:"AGENT_RUN_CANCELLED",message:"The Agent Run member was cancelled.",retryable:!1})}catch(e){c=iE(e)}finally{await this.finalizeMember(e,r,l,o,s,i,a,c),this.controllers.delete(t),this.complete(e)}}async finalizeMember(e,t,n,i,s,r,o,a){const c=`${e.runId}:${e.memberId}`;let d;this.cleanupRetryTimers.delete(c);const l=this.options.runs.getMember(e.runId,e.memberId),u=mm.has(l.status);try{if(u||"finalizing"===l.status||this.options.runs.transitionMember(e.runId,e.memberId,{status:"finalizing"}),!u&&n&&t){i&&this.options.resources.transition(i,"deleting");try{await this.options.sessions.close(t,e.runId,e.memberId),i&&this.options.resources.transition(i,"deleted")}catch(e){throw i&&this.options.resources.transition(i,"delete-retrying",{incrementCleanupAttempts:!0,metadata:{code:"AGENT_RUN_PROVIDER_THREAD_CLOSE_FAILED",message:e instanceof Error?e.message:String(e)}}),e}}!u&&r&&s&&await s.dispose(r,nE({runId:e.runId,memberId:e.memberId,generationId:r.generationId}))}catch(e){d=iE(e,"AGENT_RUN_CLEANUP_FAILED")}const p="finalizing"===this.options.runs.get(e.runId).status&&"AGENT_RUN_CANCELLED"===a?.code;if(d){if(u||this.options.runs.transitionMember(e.runId,e.memberId,{status:"finalizing",...o?{result:o}:{},...a?{error:a}:{}}),e.root){const t=this.options.runs.get(e.runId);"finalizing"!==t.status&&this.options.runs.transitionRun(e.runId,{status:"finalizing"});const n=(t.cleanup?.attempts??0)+1;this.options.runs.transitionRun(e.runId,{status:"finalizing",cleanup:{status:"retrying",attempts:n,message:d.message,updatedAt:(new Date).toISOString()}}),this.options.runs.appendTimeline(e.runId,"run.cleanup-retrying",{memberId:e.memberId,data:{code:d.code,attempts:n}})}return void this.scheduleCleanupRetry(e,t,n,i,s,r,o,a)}const m=a?p?"cancelled":"failed":"completed";if(u||(this.options.runs.transitionMember(e.runId,e.memberId,{status:m,..."completed"===m?{result:o}:{error:a}}),this.options.runs.appendTimeline(e.runId,`member.${m}`,{memberId:e.memberId})),!e.root)return;const h=this.options.runs.get(e.runId);"finalizing"!==h.status&&this.options.runs.transitionRun(e.runId,{status:"finalizing"});try{this.options.sharedSpaces.retain(e.runId)}catch(n){d=iE(n,"AGENT_RUN_SHARED_SPACE_RETAIN_FAILED");const i=(h.cleanup?.attempts??0)+1;return this.options.runs.transitionRun(e.runId,{status:"finalizing",cleanup:{status:"retrying",attempts:i,message:d.message,updatedAt:(new Date).toISOString()}}),void this.scheduleCleanupRetry(e,t,!1,void 0,void 0,void 0,o,a)}const g={status:"completed",attempts:(h.cleanup?.attempts??0)+1,updatedAt:(new Date).toISOString()},f=a?p?"cancelled":"failed":"completed";this.options.runs.transitionRun(e.runId,{status:f,..."completed"===f?{result:o}:{error:a},cleanup:g}),this.managedRunIds.delete(e.runId)}scheduleCleanupRetry(e,t,n,i,s,r,o,a){if(!this.accepting)return;const c=`${e.runId}:${e.memberId}`;if(this.cleanupRetryTimers.has(c))return;const d=this.options.runs.get(e.runId).cleanup?.attempts??1,l=Math.min((this.options.cleanupRetryBaseMs??1e3)*2**Math.min(d-1,6),6e4),u=setTimeout(()=>{this.cleanupRetryTimers.delete(c);const d=this.finalizeMember(e,t,n,i,s,r,o,a);this.activeExecutions.add(d),d.finally(()=>this.activeExecutions.delete(d))},l);u.unref?.(),this.cleanupRetryTimers.set(c,u)}failQueued(e,t){try{if("queued"!==this.options.runs.getMember(e.runId,e.memberId).status)return;this.options.runs.transitionMember(e.runId,e.memberId,{status:"finalizing"});const n={code:"AGENT_RUN_SCHEDULER_STOPPED",message:`Agent Run scheduling stopped: ${t}.`,retryable:"scheduler-stopped"===t};this.options.runs.transitionMember(e.runId,e.memberId,{status:"failed",error:n}),e.root&&("finalizing"!==this.options.runs.get(e.runId).status&&this.options.runs.transitionRun(e.runId,{status:"finalizing"}),this.options.runs.transitionRun(e.runId,{status:"failed",error:n,cleanup:{status:"completed",attempts:0,updatedAt:(new Date).toISOString()}}),this.managedRunIds.delete(e.runId))}catch{}finally{this.complete(e)}}complete(e){const t=`${e.runId}:${e.memberId}`,n=this.completionWaiters.get(t);n&&(this.completionWaiters.delete(t),n())}}const rE=c.z.union([lI,Jy]),oE=c.z.object({type:c.z.literal("runtime-path"),path:c.z.string().trim().min(1).max(4096).refine(e=>e.startsWith("/"),"Agent Run runtime paths must be absolute POSIX paths.")}).strict(),aE=c.z.object({runId:Dp,memberId:Lp,clientRequestId:Oe,providerId:Be,cwd:oE,writableRoots:c.z.object({workspace:oE,shared:oE}).strict(),prompt:c.z.string().trim().min(1).max(128e3),appendedPrompt:c.z.string().max(32e3),permissionMode:Tt.optional(),modelSelection:Dt.optional(),reasoningEffort:Lt.optional(),enabledTools:c.z.array(rE).max(100).default([])}).strict().superRefine((e,t)=>{e.cwd.path!==e.writableRoots.workspace.path&&t.addIssue({code:"custom",path:["writableRoots","workspace"],message:"The workspace writable root must be the member cwd."}),e.writableRoots.workspace.path===e.writableRoots.shared.path&&t.addIssue({code:"custom",path:["writableRoots"],message:"Workspace and shared roots must be distinct."})}),cE=c.z.object({disposition:c.z.enum(["created","already-created"]),aiSessionId:c.z.string().trim().min(1).max(120),providerSessionId:c.z.string().trim().min(1).max(240)}).strict(),dE=c.z.object({runId:Dp,memberId:Lp,aiSessionId:c.z.string().trim().min(1).max(120),status:c.z.enum(["running","completed","failed"]),result:Kp.optional(),error:Wp.optional()}).strict().superRefine((e,t)=>{"completed"!==e.status||e.result||t.addIssue({code:"custom",path:["result"],message:"Completed member status requires a result."}),"failed"!==e.status||e.error||t.addIssue({code:"custom",path:["error"],message:"Failed member status requires an error."})}),lE=c.z.object({runId:Dp,memberId:Lp,aiSessionId:c.z.string().trim().min(1).max(120),closed:c.z.boolean()}).strict(),uE=c.z.object({ordinaryAiSessionIds:c.z.array(c.z.string().trim().min(1).max(120)).max(1e4)}).strict();function pE(e,t,n,i){return Object.assign(new Error(t,void 0===i?void 0:{cause:i}),{code:e,statusCode:n})}class mE{fetchImpl;resolveInstanceWeb;constructor(e,t){this.fetchImpl=e,this.resolveInstanceWeb=t}async create(e,t){const n=aE.parse({...t,...t.modelSelection?{modelSelection:_s(e.capabilities,t.providerId,t.modelSelection)}:{}});return cE.parse(await this.request(e,"/api/internal/node-agent/agent-runs/members",{method:"POST",body:n}))}async status(e,t,n){return dE.parse(await this.request(e,`/api/internal/node-agent/agent-runs/${encodeURIComponent(t)}/members/${encodeURIComponent(n)}`,{method:"GET"}))}async close(e,t,n){return lE.parse(await this.request(e,`/api/internal/node-agent/agent-runs/${encodeURIComponent(t)}/members/${encodeURIComponent(n)}/close`,{method:"POST",body:{}}))}async probeState(e){return uE.parse(await this.request(e,"/api/internal/node-agent/agent-runs/probe-state",{method:"GET"}))}async request(e,t,n){if(!e.registrationToken)throw pE("AGENT_RUN_INSTANCE_CREDENTIAL_MISSING","Target instance has no registration credential.",503);let i;try{i=await this.fetchImpl(`${await this.resolveInstanceWeb(e)}${t}`,{method:n.method,headers:{authorization:`Bearer ${e.registrationToken}`,"content-type":"application/json"},...void 0===n.body?{}:{body:JSON.stringify(n.body)}})}catch(e){throw pE("AGENT_RUN_INSTANCE_UNAVAILABLE","Target instance is temporarily unavailable.",503,e)}const s=await i.json().catch(()=>({}));if(!i.ok)throw pE(s.error?.code||"AGENT_RUN_INSTANCE_REQUEST_FAILED",s.error?.message||`Target instance returned HTTP ${i.status}.`,i.status);return s.data}}const hE=10737418240;function gE(e,t,i){const s=Dp.parse(e),r=n.posix.resolve("/",i);return{runId:s,runtimeId:t,runtimePath:n.posix.join(r,s)}}class fE{repository;backend;root;constructor(e,t,n){this.repository=e,this.backend=t,this.root=n}async ensure(e){const t=this.repository.runtimeSharedSpaceUsage(e.runtimeId,e.runId);if(t>=hE)throw Object.assign(new Error("The Agent Run runtime shared-space quota is exhausted."),{code:"AGENT_RUN_SHARED_RUNTIME_QUOTA_EXCEEDED",statusCode:409,details:{runtimeId:e.runtimeId,usageBytes:t,quotaBytes:hE}});this.repository.ensureSharedSpace({...e,quotaBytes:1073741824});const n=gE(e.runId,e.runtimeId,this.root);try{const t=await this.backend.ensureRunDirectory({...e,runtimePath:n.runtimePath}),i=this.repository.updateSharedSpace(e.runId,{state:"active",diagnostics:t,timestamp:e.timestamp});return this.repository.register({runId:e.runId,instanceId:e.instanceId,runtimeId:e.runtimeId,kind:"shared-space-directory",generationId:e.generationId,backendIdentity:n.runtimePath,metadata:{runtimePath:n.runtimePath},timestamp:e.timestamp}),{space:i,binding:n}}catch(t){throw this.repository.updateSharedSpace(e.runId,{state:"delete-retrying",diagnostics:{code:"AGENT_RUN_SHARED_SPACE_PREPARE_FAILED",message:t instanceof Error?t.message:String(t)},timestamp:e.timestamp}),Object.assign(new Error("Could not prepare the Agent Run shared space.",{cause:t}),{code:"AGENT_RUN_SHARED_SPACE_PREPARE_FAILED",statusCode:409})}}bindingForMember(e,t){const n=this.repository.getSharedSpace(e);if(!n)throw Object.assign(new Error("The Agent Run shared space was not found."),{code:"AGENT_RUN_SHARED_SPACE_NOT_FOUND",statusCode:404});return function(e,t){if(e.runtimeId!==t)throw Object.assign(new Error("The member runtime cannot access this Agent Run shared space."),{code:"AGENT_RUN_SHARED_RUNTIME_MISMATCH",statusCode:409,details:{runId:e.runId,sharedRuntimeId:e.runtimeId,memberRuntimeId:t}})}(n,t),gE(e,t,this.root)}pathPolicyForMember(e,t,i){return function(e,t){if(!n.posix.isAbsolute(t))throw Object.assign(new Error("The Agent Run workspace cwd must be an absolute runtime path."),{code:"AGENT_RUN_WORKSPACE_PATH_INVALID",statusCode:400});return{cwd:n.posix.resolve(t),writableRoots:[n.posix.resolve(t),e.runtimePath]}}(this.bindingForMember(e,t),i)}retain(e,t=new Date){const n=new Date(t.getTime()+6048e5).toISOString();return this.repository.updateSharedSpace(e,{state:"retained",expiresAt:n,timestamp:t.toISOString()})}async refreshUsage(e,t,n=new Date){const i=this.repository.getSharedSpace(e);if(!i)throw Object.assign(new Error("The Agent Run shared space was not found."),{code:"AGENT_RUN_SHARED_SPACE_NOT_FOUND",statusCode:404});if(!this.backend.inspectRunDirectory)throw Object.assign(new Error("The shared-space backend cannot report usage."),{code:"AGENT_RUN_SHARED_USAGE_UNAVAILABLE",statusCode:409});const s=gE(e,i.runtimeId,this.root),r=await this.backend.inspectRunDirectory({runId:e,generationId:i.generationId,runtimeId:i.runtimeId,instanceId:t,runtimePath:s.runtimePath}),o=this.repository.runtimeSharedSpaceUsage(i.runtimeId,e)+r.usageBytes,a={...i.diagnostics,usageBytes:r.usageBytes,runQuotaBytes:i.quotaBytes,runtimeUsageBytes:o,runtimeQuotaBytes:hE,measuredAt:n.toISOString()};if(this.repository.updateSharedSpace(e,{usageBytes:r.usageBytes,diagnostics:a,timestamp:n.toISOString()}),r.usageBytes>i.quotaBytes)throw Object.assign(new Error("The Agent Run shared-space quota is exhausted."),{code:"AGENT_RUN_SHARED_RUN_QUOTA_EXCEEDED",statusCode:409,details:{runId:e,usageBytes:r.usageBytes,quotaBytes:i.quotaBytes}});if(o>hE)throw Object.assign(new Error("The Agent Run runtime shared-space quota is exhausted."),{code:"AGENT_RUN_SHARED_RUNTIME_QUOTA_EXCEEDED",statusCode:409,details:{runtimeId:i.runtimeId,usageBytes:o,quotaBytes:hE}});return this.repository.getSharedSpace(e)}async reconcileExpired(e=new Date){const t=this.repository.listSharedSpaces({expiredBefore:e.toISOString()}),n=[];for(const i of t){if("retained"!==i.state&&"delete-retrying"!==i.state)continue;const t=this.repository.listForRun(i.runId).find(e=>"shared-space-directory"===e.kind);if(t&&t.instanceId){this.repository.updateSharedSpace(i.runId,{state:"expiring",timestamp:e.toISOString()});try{if(!this.backend.removeRunDirectory)throw Object.assign(new Error("Shared-space backend does not support expiry cleanup."),{code:"AGENT_RUN_SHARED_SPACE_CLEANUP_UNSUPPORTED"});await this.backend.removeRunDirectory({runId:i.runId,generationId:t.generationId,runtimeId:i.runtimeId,instanceId:t.instanceId,runtimePath:String(t.metadata.runtimePath??t.backendIdentity)}),this.repository.updateSharedSpace(i.runId,{state:"expired",usageBytes:0,timestamp:e.toISOString()}),this.repository.transition(t.resourceId,"deleted",{timestamp:e.toISOString()}),n.push({runId:i.runId,status:"expired"})}catch(s){this.repository.updateSharedSpace(i.runId,{state:"delete-retrying",diagnostics:{code:"AGENT_RUN_SHARED_SPACE_CLEANUP_FAILED",message:s instanceof Error?s.message:String(s)},timestamp:e.toISOString()}),this.repository.transition(t.resourceId,"delete-retrying",{incrementCleanupAttempts:!0,timestamp:e.toISOString()}),n.push({runId:i.runId,status:"retrying"})}}else this.repository.updateSharedSpace(i.runId,{state:"manual-intervention",diagnostics:{code:"AGENT_RUN_SHARED_SPACE_OWNERSHIP_UNPROVEN"},timestamp:e.toISOString()}),n.push({runId:i.runId,status:"manual-intervention"})}return n}}const yE=["SYS_ADMIN","SYS_PTRACE","SYS_CHROOT","DAC_OVERRIDE","CHOWN"];function IE(e,t,n,i){return Object.assign(new Error(t,void 0===n?void 0:{cause:n}),{code:e,statusCode:409,...i?{details:i}:{}})}class _E{kind="overlay-copy-on-write";runCommand;resources;targetForInstance;terminateMemberThread;helperImage;constructor(e,t,n,i=async()=>{},s="ghcr.io/edgestorage/task-handoff-agent-run-overlay-helper:1"){this.runCommand=e,this.resources=t,this.targetForInstance=n,this.terminateMemberThread=i,this.helperImage=s}async prepare(e){if("overlay-copy-on-write"!==e.executionSnapshot.executionPolicy.workspaceMaterializer||"instance"!==e.executionSnapshot.executionPolicy.processSandbox)throw IE("AGENT_RUN_MATERIALIZER_UNAVAILABLE","The requested execution policy has no Docker instance materializer.");const t=this.targetForInstance(e.instanceId);if(t.runtimeId!==e.runtimeId)throw IE("AGENT_RUN_RUNTIME_MISMATCH","The target instance no longer belongs to the frozen runtime.");const i=await this.requireReadyContainer(t),s=eE(e.runId,e.memberId),r=n.posix.join(Ec,e.runId,e.memberId),o=n.posix.join(r,"upper"),a=n.posix.join(r,"work"),c=n.posix.join(Ac,e.runId);this.assertStorageBoundaries(e.sourceRuntimePath,{upperPath:o,workPath:a,sharedPath:c,mergedPath:s.cwd});const d=nE(e),l=`${String(i.Id)}:${s.cwd}`,u=this.resources.register({runId:e.runId,memberId:e.memberId,instanceId:e.instanceId,runtimeId:e.runtimeId,kind:"overlay-mount",generationId:e.generationId,backendIdentity:l,metadata:{containerId:i.Id,mergedPath:s.cwd,upperPath:o,workPath:a,sourceRuntimePath:e.sourceRuntimePath}}),p={materializer:this.kind,generationId:e.generationId,layout:s,backendIdentity:l,diagnostics:{isolation:"instance",sharesContainerUserNetworkAndCredentials:!0,sourceWritesDeniedBy:"provider-thread-write-roots",crossRunWritesDeniedBy:"provider-thread-write-roots-and-node-path-validation"},target:t,resourceId:u.resourceId,upperPath:o,workPath:a,sharedPath:c,marker:d};try{return this.appendInjectionAudit(u.resourceId,{requestedAt:(new Date).toISOString(),result:"pending",helperImage:this.helperImage,capabilities:[...yE],targetContainerId:String(i.Id)}),await this.runHelper(t,e.runId,e.memberId,e.generationId,["inject","--lower",e.sourceRuntimePath,"--upper",o,"--work",a,"--merged",s.cwd,"--shared",c,"--marker",JSON.stringify(d)]),this.finishInjectionAudit(u.resourceId,"completed"),this.resources.transition(u.resourceId,"ready"),p}catch(t){throw this.finishInjectionAudit(u.resourceId,"failed",t),await this.rollbackInjection(p,t),IE("AGENT_RUN_OVERLAY_INJECTION_FAILED","Could not inject the Agent Run overlay workspace.",t,{runId:e.runId,memberId:e.memberId})}}async ensureRunDirectory(e){const t=this.targetForInstance(e.instanceId);if(t.runtimeId!==e.runtimeId)throw IE("AGENT_RUN_SHARED_RUNTIME_MISMATCH","The target instance is outside the run runtime.");return await this.requireReadyContainer(t),await this.runHelper(t,e.runId,"shared_space",e.generationId,["shared-ensure","--path",e.runtimePath,"--generation",e.generationId]),{runtimePath:e.runtimePath,runtimeId:e.runtimeId,volumeRole:"agent-run"}}async prepareProbe(e){const t=this.targetForInstance(e.instanceId);if(t.runtimeId!==e.runtimeId)throw IE("AGENT_RUN_RUNTIME_MISMATCH","The probe target no longer belongs to the frozen runtime.");const i=await this.requireReadyContainer(t),s=eE(e.runId,e.memberId),r=n.posix.join(Ec,e.runId,e.memberId),o=n.posix.join(r,"upper"),a=n.posix.join(r,"work"),c=n.posix.join(Ac,e.runId);this.assertStorageBoundaries(e.sourceRuntimePath,{upperPath:o,workPath:a,sharedPath:c,mergedPath:s.cwd});const d=nE(e),l={materializer:this.kind,generationId:e.generationId,layout:s,backendIdentity:`${String(i.Id)}:${s.cwd}`,diagnostics:{probe:!0},target:t,resourceId:`probe:${e.generationId}`,upperPath:o,workPath:a,sharedPath:c,marker:d};return await this.runHelper(t,e.runId,e.memberId,e.generationId,["inject","--lower",e.sourceRuntimePath,"--upper",o,"--work",a,"--merged",s.cwd,"--shared",c,"--marker",JSON.stringify(d)]),l}async verifyProbe(e,t,n){const i=await this.runHelper(e.target,e.marker.runId,e.marker.memberId,e.marker.generationId,["probe-verify","--lower",t,"--merged",e.layout.cwd,"--shared",e.sharedPath,"--other-shared",n,"--generation",e.marker.generationId]),s=JSON.parse(i.stdout||"{}");if(!0!==s.workspaceWritable||!0!==s.sharedWritable||!0!==s.sourceWriteRejected||!0!==s.otherRunWriteRejected)throw IE("AGENT_RUN_BEHAVIOR_PROBE_FAILED","The Agent Run filesystem behavior probe did not prove every write boundary.",void 0,s);return s}async disposeProbe(e){await this.runHelper(e.target,e.marker.runId,e.marker.memberId,e.marker.generationId,["dispose","--merged",e.layout.cwd,"--upper",e.upperPath,"--work",e.workPath])}async removeRunDirectory(e){const t=this.targetForInstance(e.instanceId);if(t.runtimeId!==e.runtimeId)throw IE("AGENT_RUN_SHARED_RUNTIME_MISMATCH","The target instance is outside the run runtime.");return await this.requireReadyContainer(t),await this.runHelper(t,e.runId,"shared_space",e.generationId,["shared-expire","--path",e.runtimePath,"--generation",e.generationId]),{runtimePath:e.runtimePath,runtimeId:e.runtimeId,volumeRole:"agent-run"}}async inspectRunDirectory(e){const t=this.targetForInstance(e.instanceId);if(t.runtimeId!==e.runtimeId)throw IE("AGENT_RUN_SHARED_RUNTIME_MISMATCH","The target instance is outside the run runtime.");await this.requireReadyContainer(t);const n=await this.runHelper(t,e.runId,"shared_space",e.generationId,["shared-inspect","--path",e.runtimePath,"--generation",e.generationId]),i=JSON.parse(n.stdout||"{}");if(!Number.isSafeInteger(i.usageBytes)||Number(i.usageBytes)<0)throw IE("AGENT_RUN_SHARED_USAGE_INVALID","The shared-space helper returned an invalid usage measurement.");return{usageBytes:Number(i.usageBytes)}}async inspectOwnership(e,t){try{const n=await this.runCommand("docker",["inspect","--format","{{json .}}",e.target.containerName]),i=JSON.parse(n.stdout||"{}");if(!0!==i.State?.Running||e.target.expectedContainerId&&i.Id!==e.target.expectedContainerId)return"absent";const s=await this.runHelper(e.target,t.runId,t.memberId,t.generationId,["inspect","--merged",e.layout.cwd]),r=JSON.parse(s.stdout||"{}");return!0!==r.mounted?"absent":r.marker&&function(e,t){return 1===e.version&&e.runId===t.runId&&e.memberId===t.memberId&&e.generationId===t.generationId}(r.marker,t)?"owned":"foreign"}catch{return"foreign"}}async dispose(e,t){if("foreign"===await this.inspectOwnership(e,t))throw this.resources.transition(e.resourceId,"manual-intervention",{metadata:{ownership:"foreign",mergedPath:e.layout.cwd}}),IE("AGENT_RUN_RESOURCE_OWNERSHIP_UNPROVEN","Refusing to remove an Agent Run workspace with a foreign generation marker.");await this.terminateMemberThread(t.runId,t.memberId),this.resources.transition(e.resourceId,"deleting");try{await this.runHelper(e.target,t.runId,t.memberId,t.generationId,["dispose","--merged",e.layout.cwd,"--upper",e.upperPath,"--work",e.workPath]),this.resources.transition(e.resourceId,"deleted")}catch(t){throw this.resources.transition(e.resourceId,"delete-retrying",{incrementCleanupAttempts:!0,metadata:{code:"AGENT_RUN_OVERLAY_DISPOSE_FAILED",message:t instanceof Error?t.message:String(t)}}),IE("AGENT_RUN_OVERLAY_DISPOSE_FAILED","Could not dispose the Agent Run overlay workspace.",t)}}async reconcileInstance(e){const t=[];for(const n of this.resources.listActiveForInstance(e)){if("overlay-mount"!==n.kind||!n.memberId)continue;const e=this.workspaceFromResource(n),i=nE({runId:n.runId,memberId:n.memberId,generationId:n.generationId,createdAt:n.createdAt});try{await this.dispose(e,i),t.push({resourceId:n.resourceId,status:"deleted"})}catch{const e=this.resources.get(n.resourceId);t.push({resourceId:n.resourceId,status:"manual-intervention"===e?.phase?"manual-intervention":"retrying"})}}return t}async requireReadyContainer(e){let t;try{const n=await this.runCommand("docker",["inspect","--format","{{json .}}",e.containerName]);t=JSON.parse(n.stdout||"{}")}catch(e){throw IE("AGENT_RUN_INSTANCE_NOT_READY","The target Docker instance is not available.",e)}if("string"!=typeof t.Id||!0!==t.State?.Running||e.expectedContainerId&&t.Id!==e.expectedContainerId)throw IE("AGENT_RUN_INSTANCE_NOT_READY","The target Docker instance identity or running state is not ready.");if(!e.providerReady)throw IE("AGENT_RUN_PROVIDER_NOT_READY","The target instance shared provider is not ready.");const n=Array.isArray(t.Mounts)?t.Mounts:[],i=bc(e.nodeId,e.runtimeId),s=n.find(e=>e.Destination===i.mountPath);if(!s)throw IE("AGENT_RUN_RUNTIME_VOLUME_MISSING","The target instance does not have the Agent Run runtime volume.",void 0,{role:i.role});if("volume"!==s.Type||s.Name!==i.name)throw IE("AGENT_RUN_RUNTIME_VOLUME_IDENTITY_MISMATCH","The target instance has an unexpected Agent Run runtime volume.",void 0,{role:i.role});return t}assertStorageBoundaries(e,t){if(!n.posix.isAbsolute(e))throw IE("AGENT_RUN_SOURCE_PATH_INVALID","The workspace source must be an absolute runtime path.");const i=n.posix.resolve(e);for(const e of[t.upperPath,t.workPath])tE(Ec,e);if(tE(Ac,t.sharedPath),tE(n.posix.dirname(t.mergedPath),t.mergedPath),i===_c||i.startsWith(`${_c}/`)||t.upperPath===Ac||t.upperPath.startsWith(`${Ac}/`)||t.workPath===Ac||t.workPath.startsWith(`${Ac}/`)||t.sharedPath===Ec||t.sharedPath.startsWith(`${Ec}/`))throw IE("AGENT_RUN_OVERLAY_STORAGE_BOUNDARY_INVALID","The source, overlay backing subtree, and shared artifact subtree must remain disjoint.")}helperArgs(e,t,n,i,s){const r=["run","--rm","--name",`task-handoff-agent-helper-${t}-${n}`.replace(/[^a-zA-Z0-9_.-]/g,"-").slice(0,120),"--pid",`container:${e.expectedContainerId||e.containerName}`,"--network","none","--read-only","--tmpfs","/tmp:rw,nosuid,nodev,noexec,mode=1777","--cap-drop","ALL"];for(const e of yE)r.push("--cap-add",e);return r.push("--label","task-handoff.owner=task-handoff","--label","task-handoff.role=agent-run-overlay-helper","--label",`task-handoff.run-id=${t}`,"--label",`task-handoff.member-id=${n}`,"--label",`task-handoff.generation-id=${i}`,this.helperImage,...s),r}runHelper(e,t,n,i,s){return this.runCommand("docker",this.helperArgs(e,t,n,i,s),{timeoutMs:3e4})}async rollbackInjection(e,t){try{await this.runHelper(e.target,e.marker.runId,e.marker.memberId,e.marker.generationId,["rollback","--merged",e.layout.cwd,"--upper",e.upperPath,"--work",e.workPath]);const t=this.resources.get(e.resourceId);this.resources.transition(e.resourceId,"deleted",{metadata:{...t?.metadata,rolledBack:!0}})}catch(n){const i=this.resources.get(e.resourceId);this.resources.transition(e.resourceId,"delete-retrying",{incrementCleanupAttempts:!0,metadata:{...i?.metadata,code:"AGENT_RUN_OVERLAY_ROLLBACK_FAILED",prepareError:t instanceof Error?t.message:String(t),rollbackError:n instanceof Error?n.message:String(n)}})}}appendInjectionAudit(e,t){const n=this.resources.get(e);if(!n)return;const i=Array.isArray(n.metadata.injectionAttempts)?n.metadata.injectionAttempts:[];this.resources.transition(e,n.phase,{metadata:{...n.metadata,injectionAttempts:[...i,t]}})}finishInjectionAudit(e,t,n){const i=this.resources.get(e);if(!i)return;const s=Array.isArray(i.metadata.injectionAttempts)?[...i.metadata.injectionAttempts]:[],r=s.at(-1);r&&"object"==typeof r&&!Array.isArray(r)&&(s[s.length-1]={...r,result:t,finishedAt:(new Date).toISOString(),...void 0===n?{}:{error:n instanceof Error?n.message:String(n)}}),this.resources.transition(e,i.phase,{metadata:{...i.metadata,injectionAttempts:s}})}workspaceFromResource(e){if(!e.instanceId||!e.memberId)throw IE("AGENT_RUN_RESOURCE_INVALID","The overlay resource is missing instance or member ownership.");const t=eE(e.runId,e.memberId),i=n.posix.join(Ec,e.runId,e.memberId);return{materializer:this.kind,generationId:e.generationId,layout:t,backendIdentity:e.backendIdentity,diagnostics:e.metadata,target:this.targetForInstance(e.instanceId),resourceId:e.resourceId,upperPath:n.posix.join(i,"upper"),workPath:n.posix.join(i,"work"),sharedPath:n.posix.join(Ac,e.runId),marker:nE({runId:e.runId,memberId:e.memberId,generationId:e.generationId,createdAt:e.createdAt})}}}class EE{stories;definitions;orchestrations;entries;onUpdated;constructor(e,t,n,i,s){this.stories=e,this.definitions=t,this.orchestrations=n,this.entries=i,this.onUpdated=s}async get(e){if(!await this.stories.exists(e))throw TE("STORY_AGENT_ENTRY_STORY_NOT_FOUND",`Story ${e} was not found.`,404,{storyId:e});return this.project(this.entries.get(e))}async update(e,t){const n=R_.parse(t);if(!await this.stories.exists(e))throw TE("STORY_AGENT_ENTRY_STORY_NOT_FOUND",`Story ${e} was not found.`,404,{storyId:e});const i=this.entries.get(e);if(i.revision!==n.expectedRevision)throw TE("STORY_AGENT_ENTRY_REVISION_CONFLICT","Story Agent entries changed since they were read.",409,{storyId:e,expectedRevision:n.expectedRevision,actualRevision:i.revision});const s=new Set(i.entries.map(AE)),r=n.entries.map(e=>({agentId:e.agentId,orchestrationId:e.orchestrationId??yp(e.agentId)}));for(const t of r)if(!s.has(AE(t))){if(!this.definitions.has(t.agentId))throw TE("STORY_AGENT_ENTRY_AGENT_NOT_FOUND",`Agent definition ${t.agentId} was not found on this Node Agent.`,409,{storyId:e,agentId:t.agentId});if(!this.orchestrations.has(t.orchestrationId))throw TE("STORY_AGENT_ENTRY_ORCHESTRATION_NOT_FOUND",`Agent orchestration ${t.orchestrationId} was not found on this Node Agent.`,409,{storyId:e,orchestrationId:t.orchestrationId});if(!this.orchestrations.containsAgent(t.orchestrationId,t.agentId))throw TE("STORY_AGENT_ENTRY_ORCHESTRATION_MISMATCH",`Agent ${t.agentId} is not part of orchestration ${t.orchestrationId}.`,409,{storyId:e,agentId:t.agentId,orchestrationId:t.orchestrationId})}const o=this.project(this.entries.replace(e,r));return await(this.onUpdated?.(o)),o}project(e){return{storyId:e.storyId,revision:e.revision,entries:e.entries.map(e=>({agentId:e.agentId,orchestrationId:e.orchestrationId,status:this.referenceAvailable(e)?"available":"missing-reference"}))}}referenceAvailable(e){return this.definitions.has(e.agentId)&&this.orchestrations.containsAgent(e.orchestrationId,e.agentId)}}function AE(e){return`${e.agentId}${e.orchestrationId}`}function TE(e,t,n,i){if(!z_.includes(e))throw new Error(`Unknown Story Agent authorization error code ${e}.`);return Object.assign(new Error(t),{code:e,statusCode:n,...i?{details:i}:{}})}class bE{tails=new Map;accepting=!0;async acquire(e){if(!this.accepting)throw Object.assign(new Error("Story storage is shutting down."),{code:"STORY_STORAGE_QUIESCING",statusCode:503});const t=this.tails.get(e)??Promise.resolve();let n;const i=new Promise(e=>{n=e}),s=t.catch(()=>{}).then(()=>i);this.tails.set(e,s),await t.catch(()=>{});let r=!1;return()=>{r||(r=!0,n(),s.finally(()=>{this.tails.get(e)===s&&this.tails.delete(e)}))}}async run(e,t){const n=await this.acquire(e);try{return await t()}finally{n()}}stopAccepting(){this.accepting=!1}async drain(){await Promise.all([...this.tails.values()])}pendingStoryIds(){return[...this.tails.keys()]}}class wE{coordinator;paths;ownerNodeId;repository;maxFileBytes;onChange;constructor(e,t,n,i=33554432,s){this.paths=e,this.ownerNodeId=t,this.repository=n,this.maxFileBytes=i,this.onChange=s,this.coordinator=new bE}async init(){t.mkdirSync(this.paths.storyMutationsDir,{recursive:!0,mode:448}),t.mkdirSync(this.paths.storyTrashDir,{recursive:!0,mode:448}),t.chmodSync(this.paths.storyMutationsDir,448),t.chmodSync(this.paths.storyTrashDir,448),await this.recoverFileMutations()}setOnChange(e){this.onChange=e}async list(){const e=await this.repository.stories.list();return Promise.all(e.map(e=>this.project(e)))}async get(e){const t=await this.repository.stories.get(e);return t?this.project(t):void 0}async require(e){const t=await this.repository.stories.get(e);if(!t)throw SE("STORY_NOT_FOUND","Story was not found.",404);return t}async exists(e){return Boolean(await this.repository.stories.get(e))}async automationContext(e){const t=await this.repository.stories.get(e);if(!t)return;if(await this.repository.deletionIntents.get(e))throw SE("STORY_DELETING","Story is being deleted.",409);const n=(await this.repository.actions.list(e)).map(({storyId:e,displayOrder:t,sessionPreset:n,...i})=>dy.parse({...i,sessionPreset:n||void 0}));return{id:t.id,archivedAt:t.archivedAt||void 0,actions:n}}async create(e){const t=My.parse(e),n=(new Date).toISOString(),i=await this.repository.transaction(async e=>{const i=await e.stories.insert({id:du("story"),title:t.title,description:t.description,createdAt:n,updatedAt:n,maxIdleAiSessions:t.maxIdleAiSessions??5,nextDocumentSequence:1,agentToolsContent:rI.content,agentToolsActions:rI.actions,agentToolsAutomations:rI.automations,agentToolsAiSessions:rI.aiSessions,agentToolsDecisions:rI.decisions}),s=(t.actions||[]).map((e,t)=>({storyId:i.id,id:du("story_action"),title:e.title,promptTemplate:e.promptTemplate,targetInstanceId:e.targetInstanceId,sessionPreset:e.sessionPreset,displayOrder:t}));return await e.actions.replace(i.id,s),i}),s=await this.project(i);return this.onChange?.("created",s),s}async retentionSettings(e){return sy.parse({maxIdleAiSessions:(await this.require(e)).maxIdleAiSessions})}async update(e,t,n=!0){const i=jy.parse(t),s=(new Date).toISOString(),r=await this.repository.transaction(async t=>{if(!await t.stories.get(e))throw SE("STORY_NOT_FOUND","Story was not found.",404);if(await t.deletionIntents.get(e))throw SE("STORY_DELETING","Story is being deleted.",409);if(void 0!==i.actions){const n=await t.actions.list(e),s=new Set(i.actions.flatMap(e=>e.id?[e.id]:[])),r=n.map(e=>e.id).filter(e=>!s.has(e)),o=await t.automations.referencingActions(e,r);if(o.length)throw SE("STORY_ACTION_AUTOMATION_IN_USE","Story Action is referenced by an Automation.",409,{automationIds:o.map(e=>e.id)});await t.actions.replace(e,i.actions.map((t,n)=>({storyId:e,id:t.id||du("story_action"),title:t.title,promptTemplate:t.promptTemplate,targetInstanceId:t.targetInstanceId,sessionPreset:t.sessionPreset,displayOrder:n})))}return t.stories.update(e,{...void 0!==i.title?{title:i.title}:{},...void 0!==i.description?{description:i.description||null}:{},...void 0!==i.maxIdleAiSessions?{maxIdleAiSessions:i.maxIdleAiSessions}:{},updatedAt:s})}),o=await this.project(r);return n&&this.onChange?.("updated",o),o}async archive(e){return this.setArchived(e,!0)}async restore(e){return this.setArchived(e,!1)}async setArchived(e,t){await this.require(e);const n=(new Date).toISOString(),i=await this.repository.stories.update(e,{archivedAt:t?n:null,updatedAt:n}),s=await this.project(i);return this.onChange?.(t?"archived":"restored",s),s}async deleteRecord(e){const t=await this.get(e);if(!t)return!1;const n=await this.repository.stories.delete(e);return n&&this.onChange?.("deleted",t),n}notifyDeleted(e){this.onChange?.("deleted",e)}notifyUpdated(e){this.onChange?.("updated",e)}async listContent(e){const t=await this.require(e);return(await this.project(t)).documents}async pageContent(e,t,n){const i=await this.require(e),{items:s,totalItems:r}=await this.repository.documents.page(e,t,n),o=Math.ceil(r/n);return{storyCreatedAt:i.createdAt,documents:s,pagination:{page:t,pageSize:n,totalItems:r,totalPages:o,hasMore:t*n<r}}}async readContent(e,n){const i=await this.coordinator.acquire(e);try{await this.require(e);const s=ry.parse(n);if(!await this.repository.documents.get(e,s))throw SE("STORY_CONTENT_NOT_INDEXED","Story content is not indexed.",404);const r=this.openRegularFileWithinRoot(e,s),o=t.createReadStream("",{fd:r.fd,autoClose:!0});let a=!1;const c=()=>{a||(a=!0,i())};return o.once("close",c),o.once("error",c),{stream:o,size:r.size,revision:r.revision}}catch(t){if(i(),"ENOENT"===t.code)throw await this.removeMissingDocument(e,n),SE("STORY_CONTENT_NOT_FOUND","Story content file was not found.",404);throw t}}async writeContent(e,i){return this.coordinator.run(e,async()=>{if((await this.require(e)).archivedAt)throw SE("STORY_ARCHIVED","Archived Story content is read-only.",409);const s=ry.parse(i.storyPath),r=await this.repository.documents.get(e,s);if(r){if(!i.expectedRevision)throw SE("STORY_REVISION_REQUIRED","expectedRevision is required when replacing Story content.",409);const n=this.openRegularFileWithinRoot(e,s);if(t.closeSync(n.fd),n.revision!==i.expectedRevision)throw SE("STORY_REVISION_CONFLICT","Story content changed since it was read.",409)}else if(!i.title?.trim())throw SE("STORY_CONTENT_TITLE_REQUIRED","A title is required for new Story content.",400);this.ensureStoryParent(e,s);const o=du("story_file_mutation"),a=this.filePath(e,s),c=`${a}.${o}.tmp`,d=`${a}.${o}.bak`,l=(new Date).toISOString();if(!r&&t.existsSync(a))throw SE("STORY_PATH_CONFLICT","Story path already exists on disk.",409);await this.repository.fileMutations.insert({id:o,storyId:e,operation:"write",storyPath:s,title:i.title?.trim(),temporaryName:c,backupName:d,phase:"receiving",createdAt:l,updatedAt:l});let u=0,p=!1;try{const l=new f.Transform({transform:(e,t,n)=>{u+=e.byteLength,n(u>this.maxFileBytes?SE("STORY_FILE_TOO_LARGE","Story content exceeds the node limit.",413):null,e)}});await I.pipeline(i.stream,l,t.createWriteStream(c,{flags:"wx",mode:384})),this.fsyncFile(c),await this.repository.fileMutations.update(o,{phase:"prepared",updatedAt:(new Date).toISOString()}),r&&t.renameSync(a,d),t.renameSync(c,a),this.fsyncDirectory(n.dirname(a)),await this.repository.fileMutations.update(o,{phase:"files-staged",updatedAt:(new Date).toISOString()}),await this.repository.transaction(async t=>{const n=await t.stories.get(e);if(!n)throw SE("STORY_NOT_FOUND","Story was not found.",404);if(r)await t.documents.update(e,s,{title:i.title?.trim()||r.title});else{const r=await t.documents.list(e);await t.documents.insert({storyId:e,storyPath:s,title:i.title.trim(),indexedSequence:n.nextDocumentSequence,displayOrder:r.length}),await t.stories.update(e,{nextDocumentSequence:n.nextDocumentSequence+1,updatedAt:(new Date).toISOString()})}r&&await t.stories.update(e,{updatedAt:(new Date).toISOString()}),await t.fileMutations.update(o,{phase:"database-committed",updatedAt:(new Date).toISOString()})}),p=!0,t.rmSync(d,{force:!0}),await this.repository.fileMutations.update(o,{phase:"cleanup",updatedAt:(new Date).toISOString()}),await this.repository.fileMutations.delete(o);const m=this.openRegularFileWithinRoot(e,s);t.closeSync(m.fd);const h=await this.get(e);h&&this.onChange?.("content.written",h);const g=await this.repository.documents.get(e,s);if(!g)throw SE("STORY_CONTENT_NOT_INDEXED","Story content is not indexed.",500);return{title:g.title,storyPath:s,revision:m.revision,size:u}}catch(e){throw p||await this.rollbackFileMutation(o,a,c,d,Boolean(r)),e}})}async updateDocument(e,i,s){return this.coordinator.run(e,async()=>{if((await this.require(e)).archivedAt)throw SE("STORY_ARCHIVED","Archived Story content is read-only.",409);const r=ry.parse(i),o=await this.repository.documents.get(e,r);if(!o)throw SE("STORY_CONTENT_NOT_INDEXED","Story content is not indexed.",404);const a=s.storyPath?ry.parse(s.storyPath):r;if(a!==r&&await this.repository.documents.get(e,a))throw SE("STORY_PATH_CONFLICT","Story path is already indexed.",409);if(a===r)await this.repository.transaction(async t=>{await t.documents.update(e,r,{title:s.title?.trim()||o.title}),await t.stories.update(e,{updatedAt:(new Date).toISOString()})});else{this.openAndClose(e,r),this.ensureStoryParent(e,a);const i=this.filePath(e,r),c=this.filePath(e,a);if(t.existsSync(c))throw SE("STORY_PATH_CONFLICT","Story path already exists on disk.",409);const d=du("story_file_mutation"),l=(new Date).toISOString();await this.repository.fileMutations.insert({id:d,storyId:e,operation:"rename",storyPath:r,nextStoryPath:a,title:s.title?.trim(),temporaryName:i,backupName:c,phase:"prepared",createdAt:l,updatedAt:l});let u=!1;try{t.renameSync(i,c),this.fsyncDirectory(n.dirname(i)),n.dirname(i)!==n.dirname(c)&&this.fsyncDirectory(n.dirname(c)),await this.repository.fileMutations.update(d,{phase:"files-staged",updatedAt:(new Date).toISOString()}),await this.repository.transaction(async t=>{await t.documents.replacePath(e,r,{...o,storyPath:a,title:s.title?.trim()||o.title}),await t.stories.update(e,{updatedAt:(new Date).toISOString()}),await t.fileMutations.update(d,{phase:"database-committed",updatedAt:(new Date).toISOString()})}),u=!0,await this.repository.fileMutations.update(d,{phase:"cleanup",updatedAt:(new Date).toISOString()}),await this.repository.fileMutations.delete(d)}catch(e){throw u||(t.existsSync(c)&&!t.existsSync(i)&&t.renameSync(c,i),await this.repository.fileMutations.delete(d)),e}}const c=await this.get(e);return this.onChange?.("document.updated",c),c})}async reorderDocuments(e,t){const{storyPaths:n}=Fy.parse(t),i=(await this.repository.documents.list(e)).map(e=>e.storyPath);if(n.length!==i.length||new Set(n).size!==n.length||i.some(e=>!n.includes(e)))throw SE("STORY_DOCUMENT_ORDER_INVALID","Document order must contain every indexed storyPath exactly once.",400);await this.repository.transaction(async t=>{await t.documents.reorder(e,n),await t.stories.update(e,{updatedAt:(new Date).toISOString()})});const s=await this.get(e);return this.onChange?.("document.reordered",s),s}async deleteDocument(e,i){return this.coordinator.run(e,async()=>{if((await this.require(e)).archivedAt)throw SE("STORY_ARCHIVED","Archived Story content is read-only.",409);const s=ry.parse(i);if(!await this.repository.documents.get(e,s))return!1;const r=this.filePath(e,s),o=`${r}.${du("story_file_mutation")}.deleted`,a=du("story_file_mutation"),c=(new Date).toISOString();await this.repository.fileMutations.insert({id:a,storyId:e,operation:"delete",storyPath:s,backupName:o,phase:"prepared",createdAt:c,updatedAt:c});let d=!1;try{this.openAndClose(e,s),t.renameSync(r,o),this.fsyncDirectory(n.dirname(r)),await this.repository.fileMutations.update(a,{phase:"files-staged",updatedAt:(new Date).toISOString()}),await this.repository.transaction(async t=>{await t.documents.delete(e,s),await t.stories.update(e,{updatedAt:(new Date).toISOString()}),await t.fileMutations.update(a,{phase:"database-committed",updatedAt:(new Date).toISOString()})}),d=!0,t.rmSync(o,{force:!0}),await this.repository.fileMutations.update(a,{phase:"cleanup",updatedAt:(new Date).toISOString()}),await this.repository.fileMutations.delete(a)}catch(e){throw d||(t.existsSync(o)&&!t.existsSync(r)&&t.renameSync(o,r),await this.repository.fileMutations.delete(a)),e}const l=await this.get(e);return l&&this.onChange?.("document.deleted",l),!0})}stopAccepting(){this.coordinator.stopAccepting()}drain(){return this.coordinator.drain()}async project(e){const n=(await this.repository.actions.list(e.id)).map(({storyId:e,displayOrder:t,sessionPreset:n,...i})=>dy.parse({...i,sessionPreset:n||void 0})),i=await this.repository.documents.list(e.id),s=[];for(const n of i)try{const i=this.openRegularFileWithinRoot(e.id,n.storyPath);t.closeSync(i.fd),s.push({title:n.title,storyPath:n.storyPath,revision:i.revision})}catch(t){if("ENOENT"!==t.code)throw t;await this.removeMissingDocument(e.id,n.storyPath)}return Py.parse({id:e.id,ownerNodeId:this.ownerNodeId,title:e.title,description:e.description||void 0,actions:n,documents:s,createdAt:e.createdAt,updatedAt:e.updatedAt,archivedAt:e.archivedAt||void 0})}storyRoot(e){return n.resolve(this.paths.storyContentDir,Py.shape.id.parse(e))}filePath(e,t){const i=this.storyRoot(e),s=n.resolve(i,...ry.parse(t).split("/"));if(s===i||!s.startsWith(`${i}${n.sep}`))throw SE("STORY_PATH_OUTSIDE_ROOT","Story path is outside the Story directory.",400);return s}ensureStoryParent(e,i){const s=this.filePath(e,i);try{const e=t.lstatSync(this.paths.storyContentDir);if(e.isSymbolicLink()||!e.isDirectory())throw SE("STORY_PATH_UNSAFE","Story content root must be a real directory.",409)}catch(e){if("ENOENT"!==e.code)throw e;t.mkdirSync(this.paths.storyContentDir,{recursive:!0,mode:448})}t.chmodSync(this.paths.storyContentDir,448);let r=this.paths.storyContentDir;for(const e of n.relative(this.paths.storyContentDir,n.dirname(s)).split(n.sep).filter(Boolean)){r=n.join(r,e);try{const e=t.lstatSync(r);if(e.isSymbolicLink()||!e.isDirectory())throw SE("STORY_PATH_UNSAFE","Story path parent must be a real directory.",409)}catch(e){if("ENOENT"!==e.code)throw e;t.mkdirSync(r,{mode:448})}t.chmodSync(r,448)}}openRegularFileWithinRoot(e,i){const s=this.filePath(e,i);this.assertExistingParentsSafe(this.storyRoot(e),n.dirname(s));const r="number"==typeof t.constants.O_NOFOLLOW?t.constants.O_NOFOLLOW:0;if(!r)throw SE("STORY_NOFOLLOW_UNAVAILABLE","Safe no-follow file access is unavailable on this platform.",500);const o=t.openSync(s,t.constants.O_RDONLY|r);try{const e=t.fstatSync(o);if(!e.isFile())throw SE("STORY_CONTENT_NOT_FILE","Story content must be a regular file.",409);if(e.size>this.maxFileBytes)throw SE("STORY_FILE_TOO_LARGE","Story content exceeds the node limit.",413);const n=d.createHash("sha256"),i=Buffer.allocUnsafe(65536);let s=0;for(;s<e.size;){const r=t.readSync(o,i,0,Math.min(i.length,e.size-s),s);if(!r)break;n.update(i.subarray(0,r)),s+=r}return{fd:o,size:e.size,revision:n.digest("hex")}}catch(e){throw t.closeSync(o),e}}assertExistingParentsSafe(e,i){const s=n.relative(this.paths.storyContentDir,i);let r=this.paths.storyContentDir;for(const e of s.split(n.sep).filter(Boolean)){r=n.join(r,e);const i=t.lstatSync(r);if(i.isSymbolicLink()||!i.isDirectory())throw SE("STORY_PATH_UNSAFE","Story path parent must be a real directory.",409)}if(!i.startsWith(e))throw SE("STORY_PATH_OUTSIDE_ROOT","Story path is outside the Story directory.",400)}openAndClose(e,n){const i=this.openRegularFileWithinRoot(e,n);t.closeSync(i.fd)}fsyncFile(e){const n=t.openSync(e,"r");try{t.fsyncSync(n)}finally{t.closeSync(n)}}fsyncDirectory(e){if("win32"===process.platform)return;const n=t.openSync(e,"r");try{t.fsyncSync(n)}finally{t.closeSync(n)}}async removeMissingDocument(e,t){if(!await this.repository.documents.get(e,t))return;await this.repository.transaction(async n=>{await n.documents.delete(e,t),await n.stories.update(e,{updatedAt:(new Date).toISOString()})});const n=await this.get(e);n&&this.onChange?.("document.deleted",n)}async rollbackFileMutation(e,n,i,s,r){t.rmSync(i,{force:!0}),r&&t.existsSync(s)?(t.rmSync(n,{force:!0}),t.renameSync(s,n)):r||t.rmSync(n,{force:!0}),await this.repository.fileMutations.delete(e)}async recoverFileMutations(){for(const e of await this.repository.fileMutations.list())await this.coordinator.run(e.storyId,async()=>{const n=this.filePath(e.storyId,e.nextStoryPath||e.storyPath);if("database-committed"===e.phase||"cleanup"===e.phase)"write"===e.operation?(e.temporaryName&&t.rmSync(e.temporaryName,{force:!0}),e.backupName&&t.rmSync(e.backupName,{force:!0})):"delete"===e.operation&&e.backupName&&t.rmSync(e.backupName,{force:!0});else if("write"===e.operation){const i=Boolean(e.temporaryName&&t.existsSync(e.temporaryName)),s=Boolean(await this.repository.documents.get(e.storyId,e.storyPath));e.backupName&&t.existsSync(e.backupName)?(t.rmSync(n,{force:!0}),t.renameSync(e.backupName,n)):s||"files-staged"!==e.phase&&("prepared"!==e.phase||i)||t.rmSync(n,{force:!0}),e.temporaryName&&t.rmSync(e.temporaryName,{force:!0})}else"rename"===e.operation&&e.temporaryName&&t.existsSync(n)&&!t.existsSync(e.temporaryName)?t.renameSync(n,e.temporaryName):"delete"===e.operation&&e.backupName&&t.existsSync(e.backupName)&&!t.existsSync(n)&&t.renameSync(e.backupName,n);await this.repository.fileMutations.delete(e.id)})}}function SE(e,t,n,i){return Object.assign(new Error(t),{code:e,statusCode:n,...void 0===i?{}:{details:i}})}const NE=c.z.object({storyId:c.z.string().trim().min(1).max(120),actionId:c.z.string().trim().min(1).max(120),targetInstanceId:c.z.string().trim().min(1).max(120),prompt:c.z.string().trim().min(1).max(32e3),sessionPreset:cy.optional(),cwd:c.z.string().trim().min(1).max(4096)}).strict(),vE=my,OE=hy,RE=_y,zE=Ay.extend({executionKey:c.z.string().trim().min(1).max(160),requestFingerprint:c.z.string().regex(/^[a-f0-9]{64}$/),executionInput:NE}).strict(),xE=new Set(["completed","failed","skipped"]),CE={queued:["dispatching","skipped"],dispatching:["running","failed"],running:["completed","failed"],completed:[],failed:[],skipped:[]};class kE{repository;now;constructor(e,t=()=>new Date){this.repository=e,this.now=t}async init(){}async list(e){return(await this.repository.automations.list(e)).map(DE)}async stored(e){const t=await this.repository.automations.get(e);return t?function(e){return{...DE(e),scheduleAnchorAt:e.scheduleAnchorAt}}(t):void 0}async get(e){const t=await this.repository.automations.get(e);return t?DE(t):void 0}async create(e){const t=fy.parse(e),n=this.now().toISOString();return DE(await this.repository.automations.insert({id:du("story_automation"),storyId:t.storyId,actionId:t.actionId,schedule:vE.parse(t.schedule),enabled:t.enabled,policy:OE.parse(t.policy),scheduleAnchorAt:n,createdAt:n,updatedAt:n}))}async update(e,t,n){const i=Iy.parse(t);return this.repository.transaction(async t=>{const s=await t.automations.get(e);if(!s)return;jE(s.updatedAt,n);const r=function(e,t){return new Date(Math.max(e.getTime(),Date.parse(t)+1)).toISOString()}(this.now(),s.updatedAt),o=void 0!==i.schedule||!0===i.enabled&&!s.enabled,a=await t.automations.update(e,{...i,...o?{scheduleAnchorAt:r}:{},updatedAt:r});return a?DE(a):void 0})}referencingActions(e,t){return this.repository.automations.referencingActions(e,[...t])}async hasActiveRuns(e){return(await this.repository.runs.list(e)).some(e=>!xE.has(e.status))}activeRunsForStory(e){return this.repository.runs.activeForStory(e).then(e=>e.map(LE))}async delete(e,t){return this.repository.transaction(async n=>{const i=await n.automations.get(e);if(!i)return!1;if(jE(i.updatedAt,t),(await n.runs.list(e)).some(e=>!xE.has(e.status)))throw ME("STORY_AUTOMATION_RUN_ACTIVE","Automation has a non-terminal run.",409);return n.automations.delete(e)})}async deleteForStory(e){if((await this.activeRunsForStory(e)).length)throw ME("STORY_AUTOMATION_RUN_ACTIVE","Story has a non-terminal Automation run.",409);await this.repository.automations.deleteForStory(e)}async createRun(e){const t=NE.parse(e.executionInput);return this.repository.transaction(async n=>{const i=await n.runs.byExecutionKey(e.executionKey);if(i)return LE(i);const s=await n.runs.insert({...e,executionInput:t,id:du("story_automation_run"),status:"queued",targetInstanceId:t.targetInstanceId,queuedAt:this.now().toISOString()});return await n.runs.trimTerminal(e.automationId,100),LE(s)})}async transition(e,t,n={}){return this.repository.transaction(async i=>{const s=await i.runs.get(e);if(!s)throw ME("STORY_AUTOMATION_RUN_NOT_FOUND","Automation run was not found.",404);const r=LE(s);if(r.status===t)return r;if(!CE[r.status].includes(t))throw ME("STORY_AUTOMATION_RUN_TRANSITION_INVALID",`Cannot transition run from ${r.status} to ${t}.`,409);const o=this.now().toISOString(),a=await i.runs.update(e,{...n,status:t,..."dispatching"===t?{startedAt:o}:{},...xE.has(t)?{completedAt:o}:{}});return await i.runs.trimTerminal(r.automationId,100),LE(a)})}async runsFor(e){return(await this.repository.runs.list(e)).map(PE)}async run(e){const t=await this.repository.runs.get(e);return t?PE(t):void 0}async runByExecutionKey(e){const t=await this.repository.runs.byExecutionKey(e);return t?LE(t):void 0}async pendingRuns(){return(await this.repository.runs.pending()).map(LE)}}function DE(e){return gy.parse({id:e.id,storyId:e.storyId,actionId:e.actionId,schedule:vE.parse(e.schedule),enabled:e.enabled,policy:OE.parse(e.policy),createdAt:e.createdAt,updatedAt:e.updatedAt})}function LE(e){return zE.parse({...e,aiSessionId:e.aiSessionId||void 0,startedAt:e.startedAt||void 0,completedAt:e.completedAt||void 0,error:e.error?RE.parse(e.error):void 0,executionInput:NE.parse(e.executionInput)})}function PE(e){const{executionKey:t,requestFingerprint:n,executionInput:i,...s}=LE(e);return Ay.parse(s)}function ME(e,t,n){return Object.assign(new Error(t),{code:e,statusCode:n})}function jE(e,t){if(void 0!==t&&e!==t)throw ME("STORY_AUTOMATION_CONFLICT","Automation was changed by another request.",409)}class UE{state;stories;automations;scheduler;repository;aiSessionCloser;decisions;constructor(e,t,n,i,s,r,o){this.state=e,this.stories=t,this.automations=n,this.scheduler=i,this.repository=s,this.aiSessionCloser=r,this.decisions=o}async init(){t.mkdirSync(this.state.paths.storyTrashDir,{recursive:!0,mode:448});for(const e of await this.repository.deletionIntents.list()){const i=await this.repository.stories.get(e.storyId),s=this.storyRoot(e.storyId),r=e.trashName?n.join(this.state.paths.storyTrashDir,e.trashName):void 0;i?r&&t.existsSync(r)&&!t.existsSync(s)&&t.renameSync(r,s):r&&t.rmSync(r,{recursive:!0,force:!0}),await this.repository.deletionIntents.delete(e.storyId)}}async update(e,t){const n=jy.parse(t);n.actions&&this.assertActionTargets(n.actions);const i=await this.stories.update(e,n);return await this.scheduler.refresh(),i}async create(e){const t=My.parse(e);return this.assertActionTargets(t.actions||[]),this.stories.create(t)}async createAutomationWithAction(e,t){const n=yy.parse(t);this.assertActionTargets([n.action]);const i=await this.stories.automationContext(e);if(!i)throw FE("STORY_NOT_FOUND","Story was not found.",404);if(i.archivedAt)throw FE("STORY_ARCHIVED","Archived Story cannot create an Automation.",409);if(i.actions.some(e=>e.id===n.action.id))throw FE("STORY_ACTION_ID_CONFLICT","Story Action id already exists.",409);const s={storyId:e,actionId:n.action.id,...n.automation};await this.scheduler.validateCreate(s,{...i,actions:[...i.actions,n.action]});let r="";await this.repository.transaction(async t=>{await t.actions.replace(e,[...i.actions,n.action].map((t,n)=>({storyId:e,id:t.id,title:t.title,promptTemplate:t.promptTemplate,targetInstanceId:t.targetInstanceId,sessionPreset:t.sessionPreset,displayOrder:n}))),await t.stories.update(e,{updatedAt:(new Date).toISOString()}),r=(await this.automations.create(s)).id});const o=await this.stories.get(e);return o&&this.stories.notifyUpdated(o),this.scheduler.activateCreated(r)}async archive(e){const t=await this.stories.archive(e);return await this.scheduler.refresh(),t}async restore(e){const t=await this.stories.restore(e);return await this.scheduler.refresh(),t}async delete(e){return this.stories.coordinator.run(e,async()=>{const t=await this.stories.get(e);return!!t&&(await this.prepareStoryDeletion(e),this.deleteCoordinated(t))})}async prepareStoryDeletion(e){const t=await this.automations.activeRunsForStory(e);if(t.length)throw FE("STORY_AUTOMATION_RUN_ACTIVE","Story has a non-terminal Automation run.",409,{runIds:t.map(e=>e.id)});const n=this.state.listInstances().flatMap(t=>t.aiSessions.sessions.filter(t=>t.storyId===e).map(n=>({instance:t,sessionId:n.id,storyId:e})));if(!n.length)return;if(!this.aiSessionCloser)throw FE("STORY_AI_SESSION_CLOSE_UNAVAILABLE","AI Sessions cannot be closed for Story deletion.",503);const i=await Promise.allSettled(n.map(e=>this.aiSessionCloser.close(e))),s={code:"STORY_DELETED",message:"The Story owning the decision was deleted."};await Promise.all(i.flatMap((e,t)=>"fulfilled"===e.status?[this.decisions?.expireForSession(n[t].sessionId,s)]:[])),await(this.decisions?.expireForStory(e,s));const r=i.flatMap((e,t)=>"rejected"===e.status?[{instanceId:n[t].instance.id,aiSessionId:n[t].sessionId,message:e.reason instanceof Error?e.reason.message:String(e.reason)}]:[]);if(r.length)throw FE("STORY_AI_SESSION_CLOSE_FAILED","One or more AI Sessions could not be closed.",409,{sessions:r})}async deleteCoordinated(e){const i=e.id;await this.scheduler.clearStory(i);const s=this.storyRoot(i),r=`${i}-${Date.now()}-${Math.random().toString(16).slice(2)}`,o=n.join(this.state.paths.storyTrashDir,r),a=(new Date).toISOString();await this.repository.deletionIntents.put({storyId:i,phase:"prepared",trashName:null,createdAt:a,updatedAt:a});try{let c=!1;return t.existsSync(s)&&(t.renameSync(s,o),this.fsyncDirectory(n.dirname(s)),this.fsyncDirectory(n.dirname(o)),c=!0),await this.repository.deletionIntents.put({storyId:i,phase:"files-staged",trashName:c?r:null,createdAt:a,updatedAt:(new Date).toISOString()}),await this.repository.transaction(async e=>{const t=await e.runs.activeForStory(i);if(t.length)throw FE("STORY_AUTOMATION_RUN_ACTIVE","Story has a non-terminal Automation run.",409,{runIds:t.map(e=>e.id)});await e.automations.deleteForStory(i),await e.stories.delete(i),await e.deletionIntents.put({storyId:i,phase:"database-committed",trashName:c?r:null,createdAt:a,updatedAt:(new Date).toISOString()})}),c&&t.rmSync(o,{recursive:!0,force:!0}),await this.repository.deletionIntents.put({storyId:i,phase:"cleanup",trashName:c?r:null,createdAt:a,updatedAt:(new Date).toISOString()}),await this.repository.deletionIntents.delete(i),this.stories.notifyDeleted(e),!0}catch(e){throw await this.repository.stories.get(i)&&(t.existsSync(o)&&!t.existsSync(s)&&t.renameSync(o,s),await this.repository.deletionIntents.delete(i)),e}}storyRoot(e){return n.join(this.state.paths.storyContentDir,ze.parse(e))}assertActionTargets(e){for(const t of e)if(this.state.requireInstance(t.targetInstanceId).nodeId!==this.state.node.id)throw FE("STORY_NODE_MISMATCH","Story Action target belongs to another node.",409)}fsyncDirectory(e){if("win32"===process.platform)return;const n=t.openSync(e,"r");try{t.fsyncSync(n)}finally{t.closeSync(n)}}}function FE(e,t,n,i){return Object.assign(new Error(t),{code:e,statusCode:n,details:i})}const $E=c.z.object({agent:Be,cwd:kt,cwdFolderId:c.z.string().trim().min(1).max(120).optional(),gitSelection:Mt.optional(),workspaceSelection:Pt.optional(),message:c.z.string().trim().min(1).max(32e3),permissionMode:Tt.optional(),clientRequestId:Oe,modelSelection:Dt.optional(),reasoningEffort:Lt.optional(),storyId:ze}).strict().refine(e=>!(e.gitSelection&&e.workspaceSelection),{message:"gitSelection and workspaceSelection are mutually exclusive.",path:["workspaceSelection"]}),HE=c.z.object({disposition:c.z.enum(["created","already-created"]),aiSessionId:c.z.string().trim().min(1).max(120)}).strict();class BE{state;stories;fetchImpl;resolveInstanceWeb;constructor(e,t,n,i){this.state=e,this.stories=t,this.fetchImpl=n,this.resolveInstanceWeb=i}async resolve(e,t,n){const i=n?.id===e?n:await this.stories.automationContext(e);if(!i)throw qE("STORY_NOT_FOUND","Story was not found.",404);if(i.archivedAt)throw qE("STORY_ARCHIVED","Archived Story Action cannot run.",409);const s=i.actions.find(e=>e.id===t);if(!s)throw qE("STORY_ACTION_NOT_FOUND","Story Action was not found.",404);if(!s.targetInstanceId)throw qE("STORY_ACTION_TARGET_REQUIRED","Story Action requires a target instance.",409);const r=this.state.requireInstance(s.targetInstanceId);if(r.nodeId!==this.state.node.id)throw qE("STORY_NODE_MISMATCH","Story Action target belongs to another node.",409);return{storyId:i.id,actionId:s.id,targetInstanceId:r.id,prompt:s.promptTemplate,sessionPreset:s.sessionPreset,cwd:this.runtimeCwd(r,s.sessionPreset?.cwdFolderId)}}request(e,t){const n=e.sessionPreset;return $E.parse({agent:n?.agent||"codex",cwd:{type:"runtime-path",path:e.cwd},cwdFolderId:n?.cwdFolderId,gitSelection:n?.gitSelection,workspaceSelection:n?.workspaceSelection,message:e.prompt,permissionMode:n?.permissionMode||"ask",clientRequestId:t,modelSelection:n?.modelSelection,reasoningEffort:n?.reasoningEffort,storyId:e.storyId})}async dispatch(e,t){const n=this.state.requireInstance(e.targetInstanceId);if(!n.registrationToken)throw qE("STORY_ACTION_INSTANCE_CREDENTIAL_MISSING","Target instance has no registration credential.",503);const i=this.request(e,t),s=i.modelSelection?{...i,modelSelection:_s(n.capabilities,i.agent,i.modelSelection)}:i;let r;try{r=await this.fetchImpl(`${await this.resolveInstanceWeb(n)}/api/internal/node-agent/story-automation/ai-sessions`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${n.registrationToken}`},body:JSON.stringify(s)})}catch(e){throw qE("STORY_ACTION_DISPATCH_UNAVAILABLE","Target instance is temporarily unavailable.",503,e,!0)}const o=await r.json().catch(()=>({}));if(!r.ok)throw qE(o.error?.code||"STORY_ACTION_DISPATCH_FAILED",o.error?.message||`Target instance returned HTTP ${r.status}.`,r.status);return HE.parse(o.data)}async run(e,t,n){const i=await this.resolve(e,t),s=await this.dispatch(i,n);return{targetInstanceId:i.targetInstanceId,aiSessionId:s.aiSessionId}}runtimeCwd(e,t){if(!t)return e.runtime.workspacePath||e.workspace.path||"/workspace";const n=U_(this.state,e,t);if("unknown-folder"===n.status)throw qE("NODE_LOCAL_FOLDER_NOT_FOUND","Story Action working folder was not found.",404);if("unsupported-source"===n.status)throw qE("AI_SESSION_CWD_UNAVAILABLE","Working folder is unavailable for this instance source.",409);if("outside-workspace"===n.status)throw qE("AI_SESSION_CWD_OUTSIDE_WORKSPACE","Working folder is outside the instance workspace.",409);return n.runtimePath}}function qE(e,t,n,i,s=!1){return Object.assign(new Error(t),{code:e,statusCode:n,retryable:s,...void 0===i?{}:{cause:i}})}class VE{runtime;nextRunAt=new Map;completion=new Map;registeredAutomationIds=new Set;backgroundMutations=new Set;state;stories;automations;publish;now;actionExecution;constructor(e,t,n,i,s,r,o=()=>new Date,a){this.state=e,this.stories=t,this.automations=n,this.publish=r,this.now=o,this.actionExecution=a||new BE(e,t,i,s),this.runtime=new W_({execute:({runId:e})=>this.executeRun(e),skipped:({runId:e},t)=>this.trackMutation(this.skipRun(e,t))})}async start(){this.runtime.stop(),this.runtime.start(),this.nextRunAt.clear(),this.registeredAutomationIds.clear();for(const e of await this.automations.list())await this.register(e);for(const e of await this.automations.pendingRuns())await this.resume(e);await this.reconcileInstances()}async stop(){this.runtime.stop(),this.nextRunAt.clear(),await Promise.allSettled([...this.backgroundMutations])}async refresh(){for(const e of this.registeredAutomationIds)this.runtime.clearTimer(e);this.registeredAutomationIds.clear(),this.nextRunAt.clear();for(const e of await this.automations.list())e.enabled&&!await this.blockedReason(e)||this.runtime.clearQueued(e.id),await this.register(e)}async clearStory(e){for(const t of await this.automations.list(e))this.runtime.clearTimer(t.id),this.runtime.clearQueued(t.id),this.registeredAutomationIds.delete(t.id),this.nextRunAt.delete(t.id)}async status(e){const t=await this.requireAutomation(e),n=await this.automations.runsFor(e),i=n.filter(e=>!GE(e.status)),s=await this.blockedReason(t),r=n.find(e=>GE(e.status)),o=t.enabled?s?"blocked":i.length?"running":"failed"===r?.status?"error":"scheduled":"disabled";return by.parse({automation:t,effectiveStatus:o,blockedReason:s,nextRunAt:this.nextRunAt.get(e),currentRuns:i.slice(0,20),lastRun:r})}async list(e){return Promise.all((await this.automations.list(e)).map(e=>this.status(e.id)))}async create(e){const t=await this.validateInput(e),n=await this.automations.create(t);return await this.register(n),await this.publishStatus(n.id,"created"),this.status(n.id)}async validateCreate(e,t){const n=fy.parse(e);return await this.validateReferences({...n,id:"validation",createdAt:this.now().toISOString(),updatedAt:this.now().toISOString()},t),n}async activateCreated(e){const t=await this.requireAutomation(e);return await this.register(t),await this.publishStatus(e,"created"),this.status(e)}async update(e,t,n){const i={...await this.requireAutomation(e),...t};if(await this.validateReferences(i),await this.automations.update(e,t,n))return await this.refresh(),await this.publishStatus(e,"updated"),this.status(e)}setEnabled(e,t){return this.update(e,{enabled:t})}async delete(e,t){const n=await this.requireAutomation(e),i=await this.automations.delete(e,t);return i&&(this.runtime.clearTimer(e),this.nextRunAt.delete(e),this.publish?.(vy,{storyId:n.storyId,automationId:e,change:"deleted"},{nodeId:this.state.node.id})),i}async manualRun(e,t){const n=await this.requireAutomation(e),i=this.now().toISOString(),s=X_(e,"manual",t.clientRequestId),r=await this.automations.runByExecutionKey(s);if(r)return this.automations.run(r.id);const o=await this.prepareRun(n,"manual",i,s);return this.runtime.submit(e,{runId:o.id},n.policy),this.automations.run(o.id)}async runs(e){return await this.requireAutomation(e),this.automations.runsFor(e)}async reconcileInstances(e){for(const t of(await this.automations.pendingRuns()).filter(e=>"running"===e.status&&e.aiSessionId)){if(e&&t.targetInstanceId!==e)continue;const n=this.state.listInstances().find(e=>e.id===t.targetInstanceId),i=n?.aiSessions.sessions.find(e=>e.id===t.aiSessionId);if(!i&&e!==t.targetInstanceId)continue;if(i&&"idle"!==i.status&&"failed"!==i.status)continue;const s="failed"===i?.status?"failed":"completed",r="failed"===s?{code:"AI_SESSION_FAILED",message:"The automated AI Session failed."}:void 0,o=await this.automations.transition(t.id,s,r?{error:r}:{});this.resolveCompletion(t.id),await this.publishRun(o),await this.publishStatus(t.automationId,"status")}}async register(e){if(!e.enabled||await this.blockedReason(e))return;const t=await this.automations.stored(e.id);if(!t)return;const n=function(e){const t=e.schedule;if("interval"===t.scheduleKind)return{type:"interval",intervalMs:t.intervalMs};if("daily"===t.scheduleKind)return{type:"daily",timeOfDay:t.timeOfDay,timezone:t.timezone};if("weekly"===t.scheduleKind)return{type:"weekly",weekdays:t.weekdays,timeOfDay:t.timeOfDay,timezone:t.timezone};if("monthly"===t.scheduleKind)return{type:"monthly",dayOfMonth:t.dayOfMonth,timeOfDay:t.timeOfDay,timezone:t.timezone};throw new Error(`Unsupported Story automation schedule kind: ${t.schedule.scheduleKind}`)}(e),i=function(e,t,n=t){if("interval"===e.type){const i=Math.max(0,t.getTime()-n.getTime()),s=Math.floor(i/e.intervalMs)+1;return new Date(n.getTime()+s*e.intervalMs)}const[i,s]=e.timeOfDay.split(":").map(Number);if("monthly"===e.type&&e.dayOfMonth<0)return function(e,t,n,i,s){const r=function(e,t){const n=new Intl.DateTimeFormat("en-US",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(e),i=e=>Number(n.find(t=>t.type===e)?.value);return{year:i("year"),month:i("month")-1,day:i("day")}}(s,i),o=[];for(let a=0;a<12;a+=1){const c=new Date(Date.UTC(r.year,r.month+a,1)),d=c.getUTCFullYear(),l=c.getUTCMonth(),u=K_(d,l)+e+1;o.push(Y_(u,l+1,t,n,i,s))}return o.sort((e,t)=>e.getTime()-t.getTime()),o[0]}(e.dayOfMonth,i,s,e.timezone,t);const r="weekly"===e.type?[...new Set(e.weekdays)].sort((e,t)=>e-t).join(","):"*",o="monthly"===e.type?String(e.dayOfMonth):"*";return v.CronExpressionParser.parse(`0 ${s} ${i} ${o} * ${r}`,{currentDate:t,strict:!0,tz:e.timezone}).next().toDate()}(n,this.now(),new Date(t.scheduleAnchorAt));this.nextRunAt.set(e.id,i.toISOString()),this.registeredAutomationIds.add(e.id);const s=setTimeout(()=>{this.trackMutation(this.handleTimer(e.id,i))},Math.max(1,i.getTime()-this.now().getTime()));s.unref?.(),this.runtime.setTimer(e.id,s)}async handleTimer(e,t){const n=await this.automations.get(e);if(!n?.enabled||await this.blockedReason(n))return;const i=t.toISOString();try{const e=await this.prepareRun(n,"schedule",i,X_(n.id,"schedule",i));this.runtime.submit(n.id,{runId:e.id},n.policy)}catch{await this.publishStatus(n.id,"status")}await this.register(n),await this.publishStatus(n.id,"status")}async prepareRun(e,t,n,i){const s=await this.executionInput(e),r=this.actionExecution.request(s,i);return this.automations.createRun({automationId:e.id,eventType:t,scheduledFor:n,executionKey:i,requestFingerprint:(o=r,d.createHash("sha256").update(JSON.stringify(o)).digest("hex")),executionInput:s});var o}async resume(e){const t=await this.automations.get(e.automationId);t&&(e.status,this.runtime.submit(t.id,{runId:e.id},t.policy))}async executeRun(e){let t=(await this.automations.pendingRuns()).find(t=>t.id===e);if(t){if("queued"===t.status&&(t=await this.automations.transition(t.id,"dispatching")),"dispatching"===t.status)try{try{const e=await this.actionExecution.dispatch(t.executionInput,t.executionKey);t=await this.automations.transition(t.id,"running",{aiSessionId:e.aiSessionId}),await this.publishRun(t)}catch(e){if(e&&"object"==typeof e&&"retryable"in e&&!0===e.retryable)return void await this.publishStatus(t.automationId,"status");throw e}}catch(e){const n=await this.automations.transition(t.id,"failed",{error:WE(e)});return await this.publishRun(n),void await this.publishStatus(t.automationId,"status")}await this.completionFor(t.id).promise}}async skipRun(e,t){const n=await this.automations.run(e);if(!n||"queued"!==n.status)return;const i=await this.automations.transition(e,"skipped",{error:{code:`STORY_AUTOMATION_${t.replaceAll("-","_").toUpperCase()}`,message:KE(t)}});await this.publishRun(i)}async executionInput(e,t){return this.actionExecution.resolve(e.storyId,e.actionId,t)}async validateInput(e){const t=fy.parse(e);return await this.validateReferences({...t,id:"validation",createdAt:this.now().toISOString(),updatedAt:this.now().toISOString()}),t}async validateReferences(e,t){await this.executionInput(e,t)}async blockedReason(e){try{return void await this.executionInput(e)}catch(e){const t=WE(e);return["STORY_ARCHIVED","STORY_DELETING","STORY_NOT_FOUND","STORY_ACTION_NOT_FOUND","STORY_ACTION_TARGET_REQUIRED","NODE_INSTANCE_NOT_FOUND","STORY_NODE_MISMATCH"].includes(t.code)?t:void 0}}async requireAutomation(e){const t=await this.automations.get(e);if(!t)throw Object.assign(new Error("Story Automation was not found."),{code:"STORY_AUTOMATION_NOT_FOUND",statusCode:404});return t}completionFor(e){const t=this.completion.get(e);if(t)return t;let n;const i={promise:new Promise(e=>{n=e}),resolve:n};return this.completion.set(e,i),i}resolveCompletion(e){this.completion.get(e)?.resolve(),this.completion.delete(e)}trackMutation(e){return this.backgroundMutations.add(e),e.finally(()=>this.backgroundMutations.delete(e)),e}async publishRun(e){const t=await this.automations.run(e.id),n=await this.automations.get(e.automationId);t&&n&&this.publish?.(vy,{storyId:n.storyId,automationId:n.id,change:"run",run:t},{nodeId:this.state.node.id,instanceId:e.targetInstanceId})}async publishStatus(e,t){const n=await this.status(e);this.publish?.(vy,{storyId:n.automation.storyId,automationId:e,change:t,status:n},{nodeId:this.state.node.id})}}function GE(e){return"completed"===e||"failed"===e||"skipped"===e}function WE(e){const t=e&&"object"==typeof e?e:void 0;return{code:"string"==typeof t?.code?t.code:"STORY_AUTOMATION_FAILED",message:"string"==typeof t?.message?t.message:String(e)}}function KE(e){return{cooldown:"Skipped by cooldown policy.",busy:"Skipped because the concurrency limit was reached.","queue-full":"Skipped because the queue is full.","scheduler-stopped":"Skipped because the scheduler stopped.","job-disabled":"Skipped because the Automation was disabled or blocked."}[e]}class YE{repository;constructor(e){this.repository=e}async settings(e){const t=await this.requireStory(e);return this.settingsFor(t)}async update(e,t){const n=sI.parse(t),i=await this.repository.transaction(async t=>{if(!await t.stories.get(e))throw XE("STORY_NOT_FOUND","Story was not found.",404);return t.stories.update(e,{agentToolsContent:n.content,agentToolsActions:n.actions,agentToolsAutomations:n.automations,agentToolsAiSessions:n.aiSessions,agentToolsDecisions:n.decisions,updatedAt:(new Date).toISOString()})});return this.settingsFor(i)}async resolve(e){const t=await this.requireStory(e),n=this.settingsFor(t),i=this.repository.agents.storyEntries.get(e),s=nI(t.archivedAt?[]:i.entries.filter(e=>{if(!this.repository.agents.definitions.get(e.agentId))return!1;const t=this.repository.agents.orchestrations.get(e.orchestrationId);return Boolean(t)&&Rp(t,e.agentId)})),r=d.createHash("sha256").update(JSON.stringify([cI(n.policy),Boolean(t.archivedAt),iI(i.revision,s)])).digest("hex");return fI.parse({storyId:e,policy:n.policy,revision:r,enabledTools:mI(n.policy,{archived:Boolean(t.archivedAt)}),agentInvocation:s})}async assertEnabled(e,t){const n=lI.safeParse(t),i=await this.resolve(e);if(!n.success||!i.enabledTools.includes(n.data))throw XE("STORY_AGENT_TOOL_DISABLED","The Story Agent tool is disabled.",403);return i}async assertAgentInvocation(e,t,n){const i=await this.resolve(e);if(!i.agentInvocation.enabledTools.includes("agent_run"))throw XE("STORY_AGENT_INVOCATION_FORBIDDEN","The Agent is not authorized as an entry Agent for this Story.",403);const s=i.agentInvocation.allowedTargets.filter(e=>e.agentId===t);if(n){const e=s.find(e=>e.orchestrationId===n);if(!e)throw XE("STORY_AGENT_INVOCATION_FORBIDDEN","The Agent is not authorized as an entry Agent for this Story.",403);return e}if(1===s.length)return s[0];if(!s.length)throw XE("STORY_AGENT_INVOCATION_FORBIDDEN","The Agent is not authorized as an entry Agent for this Story.",403);throw XE("STORY_AGENT_INVOCATION_AMBIGUOUS","The Agent is bound to multiple orchestrations in this Story; the call must name one.",409)}async requireStory(e){const t=await this.repository.stories.get(e);if(!t)throw XE("STORY_NOT_FOUND","Story was not found.",404);return t}settingsFor(e){const t=function(e){const t=aI.safeParse(e);return sI.parse({...oI,...t.success?t.data:{}})}({content:e.agentToolsContent,actions:e.agentToolsActions,automations:e.agentToolsAutomations,aiSessions:e.agentToolsAiSessions,decisions:e.agentToolsDecisions}),n=d.createHash("sha256").update(cI(t)).digest("hex");return hI.parse({policy:t,revision:n})}}function XE(e,t,n){return Object.assign(new Error(t),{code:e,statusCode:n})}class JE{state;fetchImpl;resolveInstanceWeb;warn;constructor(e,t,n,i){this.state=e,this.fetchImpl=t,this.resolveInstanceWeb=n,this.warn=i}async notify(e){const t=yI.parse(e),n=this.state.listInstances().filter(e=>e.registrationToken&&e.aiSessions.sessions.some(e=>e.storyId===t.storyId));await Promise.all(n.map(e=>this.notifyInstance(e,t)))}async notifyInstance(e,t){try{const n=await this.fetchImpl(`${await this.resolveInstanceWeb(e)}/api/internal/node-agent/story-agent-tools/invalidate`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.registrationToken}`},body:JSON.stringify(t)});if(!n.ok)throw new Error(`HTTP ${n.status}`)}catch(n){this.warn({storyId:t.storyId,revision:t.revision,instanceId:e.id,error:n instanceof Error?n.message:String(n)},"Story Agent Tool policy invalidation failed")}}}class QE{state;fetchImpl;resolveInstanceWeb;constructor(e,t,n){this.state=e,this.fetchImpl=t,this.resolveInstanceWeb=n}list(e,t,n){const i=this.candidates(e),s=(t-1)*n;return qI.parse({sessions:i.slice(s,s+n).map(({instance:e,session:t})=>({instanceId:e.id,sessionId:t.id,title:t.title,agent:t.agent,status:t.status,updatedAt:t.updatedAt})),pagination:EI(i.length,t,n)})}async get(e,t,n,i,s){const r=this.requireTarget(e,t,n),o=(a=await this.request(r.instance,`/api/internal/node-agent/story-ai-sessions/${encodeURIComponent(n)}`),GI.parse(o_.parse(a)));var a;const c=function(e){return e.map((e,t)=>({turn:e,index:t})).sort((e,t)=>{const n=[e.turn.startedAt,e.turn.updatedAt,e.turn.completedAt].filter(Boolean).sort().at(-1)||"";return([t.turn.startedAt,t.turn.updatedAt,t.turn.completedAt].filter(Boolean).sort().at(-1)||"").localeCompare(n)||t.index-e.index}).map(({turn:e})=>e)}(o.turnIndex.turns),d=(i-1)*s;return XI.parse({ref:{instanceId:t,sessionId:n},session:{cwd:o.detail.cwd,error:o.detail.error,modelName:o.detail.modelSelection?.modelName,reasoningEffort:o.detail.reasoningEffort},turns:c.slice(d,d+s).map(e=>({id:e.id,status:e.status,phase:e.phase,updatedAt:e.updatedAt,completedAt:e.completedAt})),pagination:EI(c.length,i,s)})}async turn(e,t,n,i,s,r,o){const a=this.requireTarget(e,t,n),c=(d=await this.request(a.instance,`/api/internal/node-agent/story-ai-sessions/${encodeURIComponent(n)}/turns/${encodeURIComponent(i)}`),r_.parse(a_.parse(d)));var d;const l=c.body.turn,u=(s-1)*r;return s_.parse({ref:{instanceId:t,sessionId:n},turn:{id:l.id,status:l.status,phase:l.phase,contextCompactions:l.contextCompactions,startedAt:l.startedAt,updatedAt:l.updatedAt,completedAt:l.completedAt},items:c.timeline.items.slice(u,u+r).map(e=>function(e,t){const n=[],i=(e,i)=>{if(void 0!==i)return i.length<=t?i:(n.push(e),i.slice(0,t))};if("user-message"===e.type)return{id:e.id,type:e.type,text:i("text",e.text),attachments:e.attachments,...n.length?{truncatedFields:n}:{}};if("ai-message"===e.type)return{id:e.id,type:e.type,text:i("text",e.text),...n.length?{truncatedFields:n}:{}};const s=e.paths?.slice(0,100);return e.paths&&e.paths.length>100&&n.push("paths"),{id:e.id,type:e.type,activityKind:e.activityKind,title:e.title,status:e.status,summary:i("summary",e.summary),input:i("input",e.input),output:i("output",e.output),paths:s,exitCode:e.exitCode,durationMs:e.durationMs,...n.length?{truncatedFields:n}:{}}}(e,o)),pagination:EI(c.timeline.items.length,s,r)})}candidates(e){return this.state.listInstances().flatMap(t=>t.aiSessions.sessions.flatMap(n=>this.inScope(e,t.id,n)?[{instance:t,session:n}]:[])).sort((e,t)=>t.session.updatedAt.localeCompare(e.session.updatedAt)||e.instance.id.localeCompare(t.instance.id)||e.session.id.localeCompare(t.session.id))}requireTarget(e,t,n){const i=this.candidates(e).find(({instance:e,session:i})=>e.id===t&&i.id===n);if(!i)throw ZE("AI_SESSION_NOT_FOUND","AI Session was not found.",404);return i}inScope(e,t,n){return n.storyId===e.storyId&&"subagent"!==n.lineage?.kind&&"failed"!==n.status&&(t!==e.instanceId||n.id!==e.sessionId)}async request(e,t){if(!e.registrationToken)throw ZE("AI_SESSION_UNAVAILABLE","AI Session instance is unavailable.",503);let n;try{n=await this.fetchImpl(`${await this.resolveInstanceWeb(e)}${t}`,{headers:{authorization:`Bearer ${e.registrationToken}`}})}catch(e){throw ZE("AI_SESSION_UNAVAILABLE","AI Session instance is unavailable.",503,e)}const i=await n.json().catch(()=>({}));if(!n.ok){if(404===n.status)throw ZE("AI_SESSION_NOT_FOUND","AI Session was not found.",404);throw ZE("AI_SESSION_READ_FAILED","AI Session could not be read.",n.status)}return i.data}}function ZE(e,t,n,i){return Object.assign(new Error(t),{code:e,statusCode:n,...void 0===i?{}:{cause:i}})}class eA{fetchImpl;resolveInstanceWeb;constructor(e,t){this.fetchImpl=e,this.resolveInstanceWeb=t}async close(e){if(!e.instance.registrationToken)throw new Error("AI Session instance is unavailable.");const t=await this.fetchImpl(`${await this.resolveInstanceWeb(e.instance)}/api/internal/node-agent/ai-sessions/${encodeURIComponent(e.sessionId)}/close-for-story-deletion`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.instance.registrationToken}`},body:JSON.stringify({clientRequestId:d.randomUUID(),storyId:e.storyId})});if(!t.ok)throw new Error(`AI Session close failed with HTTP ${t.status}.`)}}const tA=c.z.object({turnId:c.z.string().trim().min(1).max(240).optional()}).strip();class nA{state;repository;fetchImpl;resolveInstanceWeb;publish;constructor(e,t,n,i,s){this.state=e,this.repository=t,this.fetchImpl=n,this.resolveInstanceWeb=i,this.publish=s}async list(e){await this.requireStory(e);const t=await this.repository.decisions.list(e);return Ly.parse({decisions:t.map(iA)})}async get(e,t){return await this.requireStory(e),iA(await this.requireDecision(e,t))}async register(e,t){const n=Cy.parse(t);if((await this.requireStory(e.storyId)).archivedAt)throw sA("STORY_ARCHIVED","Archived Story cannot accept new decisions.",409);if(!this.findSessionInstance(e.storyId,e.sessionId))throw sA("STORY_DECISION_SESSION_SCOPE_MISMATCH","The AI Session does not belong to the requested Story.",409);if(!e.turnId)throw sA("STORY_DECISION_TURN_REQUIRED","The active AI Session turn could not be determined for the decision.",409);const i=await this.repository.decisions.bySessionTurn(e.storyId,e.sessionId,e.turnId);if(i){if("pending"===i.status)return iA(i);throw sA("STORY_DECISION_CONFLICT","A decision already exists for this AI Session turn.",409)}const s=(new Date).toISOString(),r=iA(await this.repository.decisions.insert({id:`story_decision_${d.randomUUID().replace(/-/g,"").slice(0,24)}`,storyId:e.storyId,sessionId:e.sessionId,turnId:e.turnId,question:n.question,options:n.options||[],allowFreeText:n.allowFreeText??!0,context:n.context,status:"pending",revision:1,createdAt:s,updatedAt:s}));return this.emit("created",r),r}async decide(e,t,n){const i=ky.parse(n);await this.assertStoryMutable(e);const s=await this.requireDecision(e,t),r=s.options||[];if("decided"===s.status&&function(e,t){return(e.selectedOptionId||void 0)===(t.optionId||void 0)&&(e.response||void 0)===(t.response||void 0)}(s,i))return iA(s);if("pending"!==s.status)throw sA("STORY_DECISION_TERMINAL","The decision is no longer pending.",409);if(s.revision!==i.expectedRevision)throw sA("STORY_DECISION_REVISION_CONFLICT","The decision was modified by another request.",409);if(i.optionId&&!r.some(e=>e.id===i.optionId))throw sA("STORY_DECISION_OPTION_UNKNOWN","The selected decision option does not exist.",400);if(!i.optionId&&i.response&&!1===s.allowFreeText)throw sA("STORY_DECISION_FREE_TEXT_FORBIDDEN","This decision does not accept a free-text response.",400);const o=this.findSessionInstance(s.storyId,s.sessionId);if(!o)throw sA("STORY_DECISION_SESSION_UNAVAILABLE","The AI Session that raised the decision is unavailable.",409);if(!o.registrationToken)throw sA("STORY_DECISION_SESSION_UNAVAILABLE","The AI Session instance is unavailable.",503);const a=function(e,t){const n=[];if(t.optionId){const i=(e.options||[]).find(e=>e.id===t.optionId);n.push(`Selected decision option: ${i?.label||t.optionId}`)}return t.response&&n.push(t.response),n.join("\n\n")}(s,i),c=hs(o.capabilities).features.aiSessionSendIdempotency?await this.dispatchResponse(o,s,a,s.id):await this.dispatchWithResumingLedger(o,s,a,!0===i.retry),d=(new Date).toISOString(),l=await this.repository.transaction(async e=>{const n=await e.decisions.get(t);if(!n||"pending"!==n.status||n.revision!==i.expectedRevision)throw sA("STORY_DECISION_REVISION_CONFLICT","The decision was modified by another request.",409);return e.decisions.updateIfRevision(t,i.expectedRevision,{status:"decided",revision:i.expectedRevision+1,response:i.response,selectedOptionId:i.optionId,decidedTurnId:c,decidedAt:d,updatedAt:d,resumeState:null,resumeAttemptedAt:null})});if(!l)throw sA("STORY_DECISION_REVISION_CONFLICT","The decision was modified by another request.",409);const u=iA(l);return this.emit("decided",u),u}async dispatchWithResumingLedger(e,t,n,i){if("resuming"===t.resumeState&&!i)throw Object.assign(sA("STORY_DECISION_RESUME_PENDING","A previous decision reply may already have reached the AI Session. Confirm an explicit retry to send it again.",409),{retryable:!0,details:{targetTag:"v0.0.33",reason:"TARGET_INSTANCE_WITHOUT_SEND_IDEMPOTENCY",resumeAttemptedAt:t.resumeAttemptedAt||void 0}});const s=(new Date).toISOString();await this.repository.decisions.update(t.id,{resumeState:"resuming",resumeAttemptedAt:s});try{return await this.dispatchResponse(e,t,n)}catch(e){throw"STORY_DECISION_DISPATCH_UNAVAILABLE"!==e.code&&await this.repository.decisions.update(t.id,{resumeState:null,resumeAttemptedAt:null}),e}}async cancel(e,t,n){const i=Dy.parse(n);if(await this.assertStoryMutable(e),"pending"!==(await this.requireDecision(e,t)).status)throw sA("STORY_DECISION_TERMINAL","The decision is no longer pending.",409);const s=(new Date).toISOString(),r=await this.repository.transaction(async e=>e.decisions.updateIfRevision(t,i.expectedRevision,{status:"cancelled",revision:i.expectedRevision+1,updatedAt:s}));if(!r)throw sA("STORY_DECISION_REVISION_CONFLICT","The decision was modified by another request.",409);const o=iA(r);return this.emit("cancelled",o),o}async expireForSession(e,t){const n=(new Date).toISOString(),i=(await this.repository.decisions.expirePendingForSession(e,t,n)).map(iA);for(const e of i)this.emit("expired",e);return i}async expireForStory(e,t){if(!await this.repository.stories.get(e))return[];const n=(await this.repository.decisions.list(e)).filter(e=>"pending"===e.status),i=[];for(const e of n){const n=await this.repository.decisions.updateIfRevision(e.id,e.revision,{status:"expired",revision:e.revision+1,expiredReason:t,updatedAt:(new Date).toISOString()});if(n){const e=iA(n);this.emit("expired",e),i.push(e)}}return i}async dispatchResponse(e,t,n,i){if(!e.registrationToken)throw sA("STORY_DECISION_SESSION_UNAVAILABLE","The AI Session instance is unavailable.",503);let s;try{s=await this.fetchImpl(`${await this.resolveInstanceWeb(e)}/api/internal/node-agent/ai-sessions/${encodeURIComponent(t.sessionId)}/messages`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.registrationToken}`},body:JSON.stringify(i?{message:n,clientRequestId:i}:{message:n})})}catch(e){throw sA("STORY_DECISION_DISPATCH_UNAVAILABLE","The AI Session instance is temporarily unavailable.",503,e)}const r=await s.json().catch(()=>({}));if(!s.ok)throw sA(r.error?.code||"STORY_DECISION_DISPATCH_FAILED",r.error?.message||`AI Session send failed with HTTP ${s.status}.`,s.status);return tA.parse(r.data||{}).turnId}findSessionInstance(e,t){return this.state.listInstances().find(n=>Boolean(n.registrationToken)&&n.aiSessions.sessions.some(n=>n.id===t&&n.storyId===e))}async requireStory(e){const t=await this.repository.stories.get(e);if(!t)throw sA("STORY_NOT_FOUND","Story was not found.",404);return t}async assertStoryMutable(e){const t=await this.requireStory(e);if(t.archivedAt)throw sA("STORY_DECISION_STORY_ARCHIVED","Archived Story decisions are read-only.",409);return t}async requireDecision(e,t){const n=await this.repository.decisions.get(t);if(!n||n.storyId!==e)throw sA("STORY_DECISION_NOT_FOUND","Story decision was not found.",404);return n}emit(e,t){this.publish?.({storyId:t.storyId,decisionId:t.id,revision:t.revision,change:e,decision:t})}}function iA(e){return xy.parse({id:e.id,storyId:e.storyId,sessionId:e.sessionId,turnId:e.turnId||void 0,question:e.question,options:e.options||[],allowFreeText:e.allowFreeText,context:e.context||void 0,status:e.status,revision:e.revision,response:e.response||void 0,selectedOptionId:e.selectedOptionId||void 0,decidedTurnId:e.decidedTurnId||void 0,expiredReason:e.expiredReason||void 0,createdAt:e.createdAt,updatedAt:e.updatedAt,decidedAt:e.decidedAt||void 0})}function sA(e,t,n,i){return Object.assign(new Error(t),{code:e,statusCode:n,...void 0===i?{}:{cause:i}})}class rA{closed=new Set;pending=new Set;reconciliation;state;stories;fetchImpl;resolveInstanceWeb;warn;onSessionClosed;constructor(e,t,n,i,s){this.state=e,this.stories=t,this.fetchImpl=n,this.resolveInstanceWeb=i,this.warn=s}setSessionClosedHandler(e){this.onSessionClosed=e}reconcile(){if(this.reconciliation)return this.reconciliation;const e=this.reconcileOnce().finally(()=>{this.reconciliation===e&&(this.reconciliation=void 0)});return this.reconciliation=e,e}async reconcileOnce(){const e=new Map,t=new Set,n=[];for(const n of this.state.listInstances()){if(!n.registrationToken)continue;let i;try{i=await this.fetchImpl(`${await this.resolveInstanceWeb(n)}/api/internal/node-agent/ai-sessions/idle-retention`,{headers:{authorization:`Bearer ${n.registrationToken}`}})}catch(e){this.warn({instanceId:n.id,error:e instanceof Error?e.message:String(e)},"could not inspect Story idle sessions");continue}if(!i.ok)continue;const s=await i.json().catch(()=>({}));if(Array.isArray(s.data))for(const i of s.data){if(!i||"object"!=typeof i)continue;const s=i;if("string"!=typeof s.sessionId||"string"!=typeof s.storyId||"idle"!==s.status)continue;if(void 0===aA(s))continue;if(!await this.stories.exists(s.storyId))continue;const r=`${n.id}:${s.sessionId}`;if(t.add(r),this.closed.has(r))continue;const o=e.get(s.storyId)||[];o.push({instance:n,sessionId:s.sessionId,storyId:s.storyId,status:"idle",completedAt:s.completedAt,updatedAt:s.updatedAt}),e.set(s.storyId,o)}}for(const[t,i]of e){const e=(await this.stories.retentionSettings(t)).maxIdleAiSessions;for(;i.length>e;){i.sort((e,t)=>aA(e)-aA(t)||`${e.instance.id}:${e.sessionId}`.localeCompare(`${t.instance.id}:${t.sessionId}`));const e=i.shift(),s=`${e.instance.id}:${e.sessionId}`;this.pending.has(s)||(this.pending.add(s),n.push(this.close(e,s).catch(n=>{this.warn({storyId:t,instanceId:e.instance.id,sessionId:e.sessionId,error:n instanceof Error?n.message:String(n)},"Story idle Session retention close failed"),setTimeout(()=>{this.reconcile()},5e3).unref?.()})))}}await Promise.all(n);for(const e of this.closed)t.has(e)||this.closed.delete(e)}async close(e,t){try{if(!await this.isUnchangedCandidate(e))return;const n=await this.fetchImpl(`${await this.resolveInstanceWeb(e.instance)}/api/internal/node-agent/ai-sessions/${encodeURIComponent(e.sessionId)}/close`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.instance.registrationToken}`},body:JSON.stringify({clientRequestId:d.randomUUID()})});if(204===n.status)return;if(!n.ok)throw new Error(`HTTP ${n.status}`);this.closed.add(t),await(this.onSessionClosed?.(e.sessionId))}finally{this.pending.delete(t)}}async isUnchangedCandidate(e){const t=await this.fetchImpl(`${await this.resolveInstanceWeb(e.instance)}/api/internal/node-agent/ai-sessions/idle-retention`,{headers:{authorization:`Bearer ${e.instance.registrationToken}`}});if(!t.ok)throw new Error(`HTTP ${t.status}`);const n=await t.json().catch(()=>({}));if(!Array.isArray(n.data))return!1;const i=n.data.find(t=>{if(!t||"object"!=typeof t)return!1;const n=t;return n.sessionId===e.sessionId&&n.storyId===e.storyId&&"idle"===n.status});return void 0!==i&&aA(i)===aA(e)}}class oA{closed=new Set;pending=new Set;reconciliation;state;fetchImpl;resolveInstanceWeb;warn;constructor(e,t,n,i){this.state=e,this.fetchImpl=t,this.resolveInstanceWeb=n,this.warn=i}reconcile(){if(this.reconciliation)return this.reconciliation;const e=this.reconcileOnce().finally(()=>{this.reconciliation===e&&(this.reconciliation=void 0)});return this.reconciliation=e,e}async reconcileOnce(){const e=new Map,t=new Set,n=[];for(const n of this.state.listInstances()){if(!n.registrationToken)continue;let i;try{i=await this.fetchImpl(`${await this.resolveInstanceWeb(n)}/api/internal/node-agent/ai-sessions/instance-idle-retention`,{headers:{authorization:`Bearer ${n.registrationToken}`}})}catch(e){this.warn({instanceId:n.id,error:e instanceof Error?e.message:String(e)},"could not inspect instance idle sessions");continue}if(!i.ok)continue;const s=await i.json().catch(()=>({}));if(Array.isArray(s.data))for(const i of s.data){if(!i||"object"!=typeof i)continue;const s=i;if("string"!=typeof s.sessionId||"idle"!==s.status)continue;if(void 0===aA(s))continue;const r=`${n.id}:${s.sessionId}`;if(t.add(r),this.closed.has(r))continue;const o=e.get(n.id)||[];o.push({instance:n,sessionId:s.sessionId,status:"idle",completedAt:s.completedAt,updatedAt:s.updatedAt}),e.set(n.id,o)}}for(const[t,i]of e)for(;i.length>100;){i.sort((e,t)=>aA(e)-aA(t)||`${e.instance.id}:${e.sessionId}`.localeCompare(`${t.instance.id}:${t.sessionId}`));const e=i.shift(),s=`${e.instance.id}:${e.sessionId}`;this.pending.has(s)||(this.pending.add(s),n.push(this.close(e,s).catch(n=>{this.warn({instanceId:t,sessionId:e.sessionId,error:n instanceof Error?n.message:String(n)},"Instance idle Session retention close failed"),setTimeout(()=>{this.reconcile()},5e3).unref?.()})))}await Promise.all(n);for(const e of this.closed)t.has(e)||this.closed.delete(e)}async close(e,t){try{const n=await this.fetchImpl(`${await this.resolveInstanceWeb(e.instance)}/api/internal/node-agent/ai-sessions/${encodeURIComponent(e.sessionId)}/close`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.instance.registrationToken}`},body:JSON.stringify({clientRequestId:d.randomUUID()})});if(204===n.status)return;if(!n.ok)throw new Error(`HTTP ${n.status}`);this.closed.add(t)}finally{this.pending.delete(t)}}}function aA(e){return cA(e.completedAt)??cA(e.updatedAt)}function cA(e){const t=e?Date.parse(e):Number.NEGATIVE_INFINITY;return Number.isFinite(t)?t:void 0}const dA=c.z.object({path:c.z.string().trim().min(1).max(2048),method:c.z.string().trim().min(1).max(20).default("GET"),headers:c.z.record(c.z.string(),c.z.string()).default({}),body:c.z.string().optional(),bodyBase64:c.z.string().optional()}).strict(),lA=c.z.object({id:c.z.string().trim().min(1).max(120).optional(),name:c.z.string().trim().max(160),path:c.z.string().trim().min(1).max(4096),defaultImageSelection:Ds.optional(),labels:c.z.record(c.z.string(),c.z.string()).default({})}).strict(),uA=c.z.object({name:c.z.string().trim().max(160)}).strict(),pA=c.z.object({path:c.z.string().trim().min(1).max(4096).optional(),depth:c.z.coerce.number().int().min(0).max(1).default(0)}).strict(),mA=c.z.object({id:c.z.string().trim().min(1).max(120).optional(),name:c.z.string().trim().min(1).max(160).optional(),runtimeId:c.z.string().trim().min(1).max(120),imageSelection:Ds.optional(),environmentSource:Ls.optional(),projectId:c.z.string().trim().min(1).max(120).optional(),image:Co.optional(),source:Dr,sourceSnapshot:c.z.record(c.z.string(),c.z.unknown()).default({}),config:c.z.object({autoImportAgentConfigs:c.z.boolean().optional(),codexConfigEnabled:c.z.boolean().optional(),codexHomeMode:c.z.enum(["default","taskhandoff"]).optional(),defaultCodexPermissionMode:Tt.optional(),codexSettings:rs.optional(),aiSessionHistoryLimit:c.z.number().int().min(1).max(en).optional(),aiSessionAttachmentRetentionDays:c.z.number().int().min(0).max(tn).optional(),aiSessionMaxFileAttachmentBytes:c.z.number().int().positive().max(De).optional()}).strict().optional(),modelSelection:Ia.shape.modelSelection,gitWorkspaceProvisioning:vi.optional()}).strict().superRefine((e,t)=>{e.environmentSource&&e.imageSelection&&t.addIssue({code:"custom",path:["environmentSource"],message:"environmentSource and imageSelection are mutually exclusive."}),"template"===e.environmentSource?.type&&e.image&&t.addIssue({code:"custom",path:["image"],message:"Template environment source is resolved by the node-agent and cannot include an image snapshot."}),e.gitWorkspaceProvisioning&&"local-folder"===e.source.type&&t.addIssue({code:"custom",path:["gitWorkspaceProvisioning"],message:"Git provisioning requires a Git source."})}),hA=c.z.object({name:c.z.string().trim().min(1).max(160).optional(),config:c.z.object({autoImportAgentConfigs:c.z.boolean().optional(),codexConfigEnabled:c.z.boolean().optional(),codexHomeMode:c.z.enum(["default","taskhandoff"]).optional(),defaultCodexPermissionMode:Tt.optional(),codexSettings:rs.optional(),aiSessionHistoryLimit:c.z.number().int().min(1).max(en).optional(),aiSessionAttachmentRetentionDays:c.z.number().int().min(0).max(tn).optional(),aiSessionMaxFileAttachmentBytes:c.z.number().int().positive().max(De).optional()}).strict().optional(),modelSelection:Ia.shape.modelSelection.optional()}).strict(),gA=c.z.object({id:c.z.string().trim().min(1).max(120).optional(),name:c.z.string().trim().min(1).max(160),type:c.z.enum(["docker","kubernetes","local"]),status:c.z.enum(["unknown","online","offline","degraded"]).default("unknown"),accessStrategy:c.z.enum(["node-proxy","direct-port","kubernetes-ingress","kubernetes-port-forward"]).optional(),capabilities:c.z.record(c.z.string(),c.z.unknown()).default({}),labels:c.z.record(c.z.string(),c.z.string()).default({})}).strict(),fA=gA.omit({id:!0}).partial().strict();function yA(e){const t=e.authorization;return"string"==typeof t&&t.startsWith("Bearer ")?t.slice(7).trim():void 0}class IA{operations=new Map;intents=new Map;intent(e){const t=this.intents.get(e);if(t)return t;const n={controller:new AbortController};return this.intents.set(e,n),n}invalidate(e){this.intents.get(e)?.controller.abort();const t={controller:new AbortController};return this.intents.set(e,t),t}isIntentCurrent(e,t){return this.intents.get(e)===t}signal(e,t){const n=this.intents.get(e);return n===t?n.controller.signal:AbortSignal.abort()}clearIntent(e){this.intents.delete(e)}async run(e,t){const n=this.operations.get(e)||Promise.resolve();let i;const s=new Promise(e=>{i=e});this.operations.set(e,s),await n;try{return await t()}finally{i(),this.operations.get(e)===s&&this.operations.delete(e)}}}const _A=c.z.object({gitWorkspaceProvisioning:vi.optional()}).strict().default({});class EA{state;images;options;inFlight=new Map;abortController=new AbortController;stopped=!1;constructor(e,t,n){this.state=e,this.images=t,this.options=n}retry(e){const t=this.state.requireInstance(e);if("docker"!==this.state.requireRuntime(t.runtimeId).type||!t.imageSnapshot)throw Object.assign(new Error(`Instance ${e} does not use a Docker image.`),{statusCode:400,code:"INSTANCE_IMAGE_PROVISIONING_UNSUPPORTED"});if("failed"!==t.status||"failed"!==t.imageProvisioning?.phase)throw Object.assign(new Error(`Instance ${e} does not have failed image provisioning to retry.`),{statusCode:409,code:"INSTANCE_IMAGE_PROVISIONING_NOT_FAILED"});const n=de();return this.state.controlledInstances.put(Ia.parse({...t,status:"provisioning",health:"unknown",imageProvisioning:{phase:"checking-image",requestedReference:t.imageSnapshot.requestedReference,generation:(t.imageProvisioning?.generation||0)+1,startedAt:n,updatedAt:n},updatedAt:n}))}provision(e,t){if(this.stopped)return Promise.resolve();const n=e.imageProvisioning?.generation;if(void 0===n)return Promise.resolve();const i=`${e.id}:${n}`,s=this.inFlight.get(i);if(s)return s;const r=this.provisionGeneration(e,n,t).finally(()=>{this.inFlight.get(i)===r&&this.inFlight.delete(i)});return this.inFlight.set(i,r),r}async stop(){this.stopped=!0,this.abortController.abort(),await Promise.allSettled([...this.inFlight.values()])}async provisionGeneration(e,t,n){const i=this.currentGeneration(e.id,t,!0,e.createdAt);if(!i)return;let s,r=0,o=!1,a=Promise.resolve();try{const c=await this.images.ensure(i.imageSnapshot.requestedReference,n=>{a=a.then(async()=>{if(!s)try{await this.updatePhase(e.id,t,n,e.createdAt)}catch(e){s={error:e}}})},n=>{this.stopped||(o=!0,r=n.sequence,this.publishTerminalOutput(e,t,n))},this.abortController.signal);if(await a,s)throw s.error;if(this.stopped)return;o&&this.publishFinished(e,t,r+1,"succeeded");const d=async()=>{if(this.stopped)return;const i=this.currentGeneration(e.id,t,!0,e.createdAt);if(!i)return;const s=this.state.controlledInstances.put(Ia.parse({...i,status:"provisioning"===i.status?"created":i.status,health:"unknown",imageSnapshot:{...i.imageSnapshot,requestedReference:c.requestedReference,resolvedDigest:c.resolvedDigest,resolvedReference:c.resolvedReference},imageProvisioning:{...i.imageProvisioning,phase:"ready",error:void 0,updatedAt:de()},updatedAt:de()}));this.options.sync(),this.options.diagnostic({instanceId:e.id,action:"image.provision",reference:c.requestedReference,digest:c.resolvedDigest,pulled:c.pulled},"node instance image provisioning completed"),"starting"===s.status&&await(n?.())};await(this.options.runInstanceOperation?.(e.id,d)??d())}catch(n){if(await a,s&&(n=s.error),this.stopped)return;o&&this.publishFinished(e,t,r+1,"failed");const i=n instanceof Error?n.message:String(n),c=async()=>{if(this.stopped)return;const n=this.currentGeneration(e.id,t,!1,e.createdAt);n?.imageProvisioning&&["provisioning","starting"].includes(n.status)&&(this.state.controlledInstances.put(Ia.parse({...n,status:"failed",health:"failed",imageProvisioning:{...n.imageProvisioning,phase:"failed",error:i,updatedAt:de()},updatedAt:de()})),this.options.sync(),this.options.warn({instanceId:e.id,action:"image.provision",reference:n.imageProvisioning.requestedReference,error:i},"node instance image provisioning failed"))};await(this.options.runInstanceOperation?.(e.id,c)??c())}}currentGeneration(e,t,n=!0,i){const s=this.state.controlledInstances.get(e);if(!(!s||i&&s.createdAt!==i||s.imageProvisioning?.generation!==t||n&&!s.imageSnapshot))return s}async updatePhase(e,t,n,i){if(this.stopped)return;const s=async()=>{if(this.stopped)return;const s=this.currentGeneration(e,t,!0,i);s&&["provisioning","starting"].includes(s.status)&&(this.state.controlledInstances.put(Ia.parse({...s,status:"starting"===s.status?"starting":"provisioning",imageProvisioning:{...s.imageProvisioning,phase:n,error:void 0,updatedAt:de()},updatedAt:de()})),this.options.sync())};await(this.options.runInstanceOperation?.(e,s)??s())}eventBase(e,t){return{instanceId:e.id,generation:t,requestedReference:e.imageProvisioning.requestedReference,observedAt:de()}}publishTerminalOutput(e,t,n){for(const[i,s]of function(e,t=6e4){const n=[];for(let i=0;i<e.length;i+=t)n.push(e.slice(i,i+t));return n}(n.data).entries())this.options.publish(Do,{...this.eventBase(e,t),sequence:1e3*n.sequence+i,data:s,...n.replay?{replay:!0}:{}},e.id)}publishFinished(e,t,n,i){this.options.publish(Lo,{...this.eventBase(e,t),sequence:1e3*n,outcome:i},e.id)}}const AA={GIT_WORKSPACE_PROVISIONING_TIMEOUT:"Git workspace provisioning timed out",GIT_WORKSPACE_PROVISIONING_CANCELLED:"Git workspace provisioning was cancelled",GIT_WORKSPACE_PROVISIONING_CLONE_FAILED:"Git clone failed",GIT_WORKSPACE_PROVISIONING_AUTHENTICATION_REJECTED:"Git authentication rejected",GIT_WORKSPACE_PROVISIONING_CREDENTIAL_AMBIGUOUS:"Git credential is ambiguous",GIT_WORKSPACE_PROVISIONING_CREDENTIAL_MISSING:"Git credential is missing",GIT_WORKSPACE_PROVISIONING_HOST_KEY_REQUIRED:"Git host key is not pinned",GIT_WORKSPACE_PROVISIONING_LFS_FAILED:"Git LFS pull failed",GIT_WORKSPACE_PROVISIONING_REF_NOT_FOUND:"Git ref was not found",GIT_WORKSPACE_PROVISIONING_REMOTE_UNSUPPORTED:"Git remote is not supported",GIT_WORKSPACE_PROVISIONING_SSH_AGENT_UNAVAILABLE:"Git SSH agent is unavailable",GIT_WORKSPACE_PROVISIONING_SUBDIRECTORY_NOT_FOUND:"Git subdirectory was not found",GIT_WORKSPACE_PROVISIONING_WORKSPACE_NOT_EMPTY:"Workspace is not empty",GIT_WORKSPACE_PROVISIONING_WORKSPACE_OWNERSHIP_MISMATCH:"Workspace belongs to another instance",GIT_CREDENTIAL_MISSING:"Git credential is missing",GIT_CREDENTIAL_AMBIGUOUS:"Git credential is ambiguous",GIT_CREDENTIAL_MISSING_HOST_KEY:"Git host key is not pinned"};class TA{state;options;inFlight=new Map;abortController=new AbortController;stopped=!1;constructor(e,t){this.state=e,this.options=t}provision(e,t){if(this.stopped)return Promise.resolve();const n=e.workspace.gitProvisioning?.generation;if(void 0===n)return Promise.resolve();const i=`${e.id}:${n}`,s=this.inFlight.get(i);if(s)return s;const r=this.provisionGeneration(e,n,t).finally(()=>{this.inFlight.get(i)===r&&this.inFlight.delete(i)});return this.inFlight.set(i,r),r}retry(e){const t=this.state.get(e);if(!t)throw Object.assign(new Error(`Instance ${e} was not found.`),{statusCode:404,code:"NODE_INSTANCE_NOT_FOUND"});const n=t.workspace.gitProvisioning;if(!n||"failed"!==n.phase)throw Object.assign(new Error(`Instance ${e} does not have failed Git provisioning to retry.`),{statusCode:409,code:"INSTANCE_GIT_PROVISIONING_NOT_FAILED"});const i=de();return this.state.put(Ia.parse({...t,status:"starting",health:"unknown",ready:!1,workspace:{...t.workspace,status:"pending",error:void 0,gitProvisioning:{...n,phase:"pending",error:void 0,generation:n.generation+1,updatedAt:i}},updatedAt:i}))}async stop(){this.stopped=!0,this.abortController.abort(),await Promise.allSettled([...this.inFlight.values()])}async provisionGeneration(e,t,n){const i=this.currentGeneration(e.id,t);if(!i)return;const s=new sc;let r,o=0,a=Promise.resolve();const c=e=>{a=a.then(()=>this.updatePhase(i.id,t,e))},d=e=>{if(e)for(const[n,s]of function(e,t=6e4){const n=[];for(let i=0;i<e.length;i+=t)n.push(e.slice(i,i+t));return n}(e).entries())this.options.publish($o,{...this.eventBase(i,t),sequence:1e3*(o+=1)+n,data:s},i.id)};try{await this.updatePhase(i.id,t,"cloning");const e=this.options.context(i);if(await this.options.run(e,{signal:this.abortController.signal,onOutput:e=>{const t=s.push(e);t.stage&&c(t.stage),t.commit&&(r=t.commit),d(e)}}),await a,this.stopped)return;this.publishFinished(i,t,++o,"succeeded"),await this.commitReady(i,t,r,n)}catch(e){if(s.flush(),await a,this.stopped)return;const n=function(e){const t=function(e){const t=e&&"object"==typeof e?e.code:void 0;return"string"==typeof t?t:void 0}(e);return t?.startsWith("GIT_WORKSPACE_PROVISIONING_")||t?.startsWith("GIT_CREDENTIAL_")?t:Uc(e)}(e),r=function(e,t){const n=AA[e]||"Git workspace provisioning failed",i=t?(s=t,s.replace(/(\b[a-z][a-z0-9+.-]*:\/\/)([^/@\s]+)@/gi,"$1***@")).slice(0,500):void 0;var s;return i?`${n}: ${i}`:n}(n,s.failureDetail()??(e instanceof Error?e.message:void 0));this.publishFinished(i,t,++o,"failed"),await this.commitFailure(i.id,t,r,n)}}currentGeneration(e,t){const n=this.state.get(e);if(n&&n.workspace.gitProvisioning?.generation===t)return n}async updatePhase(e,t,n){this.stopped||await this.runOperation(e,async()=>{if(this.stopped)return;const i=this.currentGeneration(e,t);if(!i||!["provisioning","starting"].includes(i.status))return;const s=i.workspace.gitProvisioning;s.phase!==n&&(this.state.put(Ia.parse({...i,workspace:{...i.workspace,gitProvisioning:{...s,phase:n,updatedAt:de()}},updatedAt:de()})),this.options.sync())})}async commitReady(e,t,n,i){const s=await this.runOperation(e.id,async()=>{if(this.stopped)return;const i=this.currentGeneration(e.id,t);if(!i)return;const s=i.workspace.gitProvisioning;return this.state.put(Ia.parse({...i,workspace:{...i.workspace,mode:"git-clone",status:"ready",error:void 0,resolvedCommit:n||i.workspace.resolvedCommit,gitProvisioning:{...s,phase:"ready",error:void 0,updatedAt:de()}},updatedAt:de()}))});s&&(this.options.sync(),this.options.diagnostic({instanceId:e.id,action:"git.provision",remoteUrl:s.workspace.gitProvisioning?.remoteUrl,resolvedCommit:s.workspace.resolvedCommit},"node instance git workspace provisioning completed"),"starting"===s.status&&await(i?.()))}async commitFailure(e,t,n,i){await this.runOperation(e,async()=>{if(this.stopped)return;const s=this.currentGeneration(e,t);if(!s||!["provisioning","starting"].includes(s.status))return;const r=s.workspace.gitProvisioning;this.state.put(Ia.parse({...s,status:"failed",health:"failed",ready:!1,workspace:{...s.workspace,status:"failed",error:n,gitProvisioning:{...r,phase:"failed",error:n,updatedAt:de()}},updatedAt:de()})),this.options.sync(),this.options.warn({instanceId:e,action:"git.provision",remoteUrl:r.remoteUrl,error:n,code:i},"node instance git workspace provisioning failed")})}runOperation(e,t){return this.options.runInstanceOperation?.(e,t)??t()}eventBase(e,t){return{instanceId:e.id,generation:t,remoteUrl:e.workspace.gitProvisioning.remoteUrl,observedAt:de()}}publishFinished(e,t,n,i){this.options.publish(Ho,{...this.eventBase(e,t),sequence:1e3*n,outcome:i},e.id)}}const bA=c.z.object({name:c.z.string().trim().min(1).max(160)}).strict();function wA(e,t,n){return{code:"object"==typeof e&&e&&"code"in e&&"string"==typeof e.code?e.code:t,message:e instanceof Error?e.message:String(e),phase:n}}class SA{templateOperations=new IA;store;docker;requireInstanceValue;requireRuntimeValue;runInstanceOperationValue;privateSecretValues;isImageReferencedValue;constructor(e,t,n,i,s,r,o=()=>!1){this.store=e,this.docker=t,this.requireInstanceValue=n,this.requireRuntimeValue=i,this.runInstanceOperationValue=s,this.privateSecretValues=r,this.isImageReferencedValue=o}list(){return this.store.list()}require(e){const t=this.store.get(e);if(!t)throw Object.assign(new Error(`Environment template ${e} was not found.`),{statusCode:404,code:"ENVIRONMENT_TEMPLATE_NOT_FOUND"});return t}runTemplateOperation(e,t){return this.templateOperations.run(e,async()=>t())}async create(e,t){const n=bA.parse(t),i=this.requireInstanceValue(e),s=this.requireRuntimeValue(i.runtimeId);if("docker"!==s.type)throw Object.assign(new Error(`Runtime ${s.name} does not support environment templates.`),{statusCode:409,code:"ENVIRONMENT_TEMPLATE_RUNTIME_UNSUPPORTED"});if(!i.runtime.containerName)throw Object.assign(new Error(`Instance ${i.id} does not have a Docker container.`),{statusCode:409,code:"ENVIRONMENT_TEMPLATE_CONTAINER_NOT_FOUND"});const r=de(),o=du("envtpl"),a=`task-handoff/environment-template:${o.toLowerCase().replace(/[^a-z0-9_.-]/g,"-")}`;return this.store.put(Js.parse({id:o,name:n.name,sourceInstanceId:i.id,nodeId:i.nodeId,internalTag:a,status:"creating",createdAt:r,updatedAt:r})),this.runInstanceOperationValue(i.id,async()=>{let e,t=!1;try{const n=this.requireInstanceValue(i.id);if("docker"!==this.requireRuntimeValue(n.runtimeId).type||!n.runtime.containerName)throw Object.assign(new Error(`Instance ${i.id} is no longer a valid Docker template source.`),{code:"ENVIRONMENT_TEMPLATE_SOURCE_CHANGED"});const s=this.privateSecretValues(n);await this.docker.inspectContainerConfigSecurity(n.runtime.containerName,s),e=await this.docker.commitEnvironmentTemplate(n.runtime.containerName,n.runtime.containerId,a),t=!0;const r=await this.docker.inspectEnvironmentTemplateImage(a);return await this.docker.inspectImageConfigSecurity(a,s),this.store.put(Js.parse({...this.require(o),...r,status:"ready",error:void 0,updatedAt:de()}))}catch(n){return t&&(await this.docker.untagEnvironmentTemplate(a,e).catch(()=>!1),e&&await this.docker.garbageCollectEnvironmentTemplateImage(e).catch(()=>!1)),this.store.put(Js.parse({...this.require(o),status:"failed",error:wA(n,"ENVIRONMENT_TEMPLATE_CREATE_FAILED","commit"),updatedAt:de()}))}})}async delete(e){return this.runTemplateOperation(e,async()=>{const t=this.require(e);this.store.put(Js.parse({...t,status:"deleting",error:void 0,updatedAt:de()}));try{const n=t.internalTag?await this.docker.untagEnvironmentTemplate(t.internalTag,t.imageId):void 0,i=t.imageId||n;return i&&!this.isImageReferencedValue(i)&&await this.docker.garbageCollectEnvironmentTemplateImage(i),this.store.delete(e),{deleted:!0,templateId:e}}catch(e){throw this.store.put(Js.parse({...t,status:"failed",error:wA(e,"ENVIRONMENT_TEMPLATE_DELETE_FAILED","delete"),updatedAt:de()})),e}})}async releaseUnusedImage(e){return!this.store.list().some(t=>t.imageId===e)&&!this.isImageReferencedValue(e)&&this.docker.garbageCollectEnvironmentTemplateImage(e)}}const NA=new Set(["content-encoding","content-length","transfer-encoding"]),vA=67108864;function OA(e){return Object.fromEntries([...e.entries()].filter(([e])=>!NA.has(e.toLowerCase())))}function RA(e){return e.bodyBase64?Buffer.from(e.bodyBase64,"base64"):e.body}function zA(){const e=Number(process.env.TASK_HANDOFF_INSTANCE_PROXY_MAX_RESPONSE_BYTES);return Number.isSafeInteger(e)&&e>0?e:67108864}const xA="x-task-handoff-trace-id";function CA(e){return e.startsWith("/")?e:`/${e}`}function kA(e,t){return e.code(502).send({error:{code:"INSTANCE_PROXY_RESPONSE_TOO_LARGE",message:`Instance response exceeds ${t} bytes.`}})}async function DA(e,t,n,i){try{return await e(t,n)}catch(e){if(n.signal?.aborted)throw e;throw i.diagnostic({instanceId:i.instanceId,action:"proxy.upstream.failed",method:i.method,path:i.path,error:e instanceof Error?e.message:String(e)},"node instance proxy upstream unavailable"),Object.assign(new Error(`Instance ${i.instanceId} web endpoint is not reachable.`),{statusCode:502,code:"INSTANCE_PROXY_UPSTREAM_UNREACHABLE",retryable:!0,cause:e})}}function LA(e,t){return Object.assign(new Error(`Instance ${e.id} has an invalid node-owned web endpoint: ${t}`),{statusCode:409,code:"NODE_INSTANCE_WEB_ENDPOINT_INVALID"})}function PA(e,t){return function(e,t={}){const n=t.fallbackWeb||(t.fallbackKind&&e.runtime?.kind===t.fallbackKind&&e.runtime.port?`http://127.0.0.1:${e.runtime.port}`:void 0),i=t.authoritativeWeb||n;if(!i){const t=new Error(`Instance ${e.id} does not have a web endpoint.`);throw Object.assign(t,{statusCode:409,code:"NODE_INSTANCE_WEB_ENDPOINT_MISSING"}),t}let s;try{s=new URL(i)}catch{throw LA(e,"endpoint is not a URL")}if("http:"!==s.protocol||"127.0.0.1"!==s.hostname||!s.port||s.username||s.password||"/"!==s.pathname&&""!==s.pathname||s.search||s.hash)throw LA(e,"endpoint must be an origin-only http://127.0.0.1:<port> URL");return s.origin}(e,{authoritativeWeb:t,fallbackKind:"local"})}async function MA(e){const t=xg(e.bindScope);return!await new Promise(t=>{const n=g.createConnection({host:"127.0.0.1",port:e.port}),i=e=>{n.removeAllListeners(),n.destroy(),t(e)};n.once("connect",()=>i(!0)),n.once("error",()=>i(!1)),n.setTimeout(250,()=>i(!1))})&&new Promise(n=>{const i=g.createServer();i.once("error",()=>n(!1)),i.listen({host:t,port:e.port,exclusive:!0},()=>i.close(()=>n(!0)))})}class jA{app;state;settings;sockets=new Set;config;source;status="error";error;onActiveListener;validateUpdate;synchronizeUpdate;updateQueue=Promise.resolve();constructor(e){this.app=e.app,this.state=e.state,this.settings=e.settings,this.config=e.config,this.source=e.source,this.onActiveListener=e.onActiveListener,this.validateUpdate=e.validateUpdate,this.synchronizeUpdate=e.synchronizeUpdate,this.app.server.on("connection",e=>{this.sockets.add(e),e.once("close",()=>this.sockets.delete(e))})}current(){return oa.parse({...this.config,host:xg(this.config.bindScope),status:this.status,source:this.source,...this.error?{error:this.error}:{}})}async start(){try{await this.listen(this.config),this.status="listening",this.error=void 0,this.state.setListenerPort(this.config.port)}catch(e){throw this.status="error",this.error=e instanceof Error?e.message:String(e),this.app.log.error({host:xg(this.config.bindScope),port:this.config.port,error:this.error},"node agent TCP listener failed to start"),Object.assign(new Error(`Failed to bind node agent TCP listener at ${xg(this.config.bindScope)}:${this.config.port}: ${this.error}`),{statusCode:409,code:"NODE_AGENT_LISTENER_BIND_FAILED"})}const e=this.current();return this.onActiveListener?.(e),e}update(e){const t=this.updateQueue.then(()=>this.updateOnce(e));return this.updateQueue=t.then(()=>{},()=>{}),t}async updateOnce(e){const t=aa.parse(e);if(t.bindScope===this.config.bindScope&&t.port===this.config.port)return this.current();if(t.port!==this.config.port){const e=this.state.runningInstanceCount();if(e>0&&!this.synchronizeUpdate)throw Object.assign(new Error(`Cannot change the node agent port while ${e} controlled instance(s) are running.`),{statusCode:409,code:"NODE_AGENT_LISTENER_PORT_IN_USE_BY_INSTANCES",blockingInstanceCount:e});await(this.validateUpdate?.(t))}const n=this.snapshot();await this.stop();try{await this.listen(t)}catch(e){throw await this.restore(n),Object.assign(new Error(`Failed to bind node agent TCP listener at ${xg(t.bindScope)}:${t.port}: ${e instanceof Error?e.message:String(e)}`),{statusCode:409,code:"NODE_AGENT_LISTENER_BIND_FAILED"})}this.state.setListenerPort(t.port);try{await(this.synchronizeUpdate?.(t))}catch(e){throw await this.stop(),await this.restore(n),await Promise.resolve(this.synchronizeUpdate?.(n.config)).catch(e=>{this.app.log.error({error:e instanceof Error?e.message:String(e)},"node agent listener instance endpoint rollback failed")}),Object.assign(new Error(`Failed to switch controlled instances to node agent port ${t.port}: ${e instanceof Error?e.message:String(e)}`),{statusCode:409,code:"NODE_AGENT_LISTENER_INSTANCE_SYNC_FAILED"})}try{this.settings.put({...this.settings.get(),version:1,externalListener:t})}catch(e){throw await this.stop(),await this.restore(n),await Promise.resolve(this.synchronizeUpdate?.(n.config)).catch(e=>{this.app.log.error({error:e instanceof Error?e.message:String(e)},"node agent listener persistence rollback failed")}),Object.assign(new Error(`Failed to persist node agent TCP listener: ${e instanceof Error?e.message:String(e)}`),{statusCode:500,code:"NODE_AGENT_LISTENER_PERSIST_FAILED"})}this.config=t,this.source="persisted",this.status="listening",this.error=void 0;const i=this.current();return this.onActiveListener?.(i),i}async shutdown(){await this.updateQueue,await this.stop()}snapshot(){return{config:this.config,source:this.source,status:this.status,error:this.error}}async restore(e){if(this.config=e.config,this.source=e.source,this.status=e.status,this.error=e.error,"listening"===e.status)try{await this.listen(e.config)}catch(e){this.status="error",this.error=`Failed to restore previous listener: ${e instanceof Error?e.message:String(e)}`,this.app.log.error({error:this.error},"node agent TCP listener rollback failed")}this.state.setListenerPort(e.config.port),"listening"===this.status&&this.onActiveListener?.(this.current())}async listen(e){await new Promise((t,n)=>{const i=e=>{this.app.server.off("listening",s),n(e)},s=()=>{this.app.server.off("error",i),t()};this.app.server.once("error",i),this.app.server.once("listening",s),this.app.server.listen({host:xg(e.bindScope),port:e.port})})}async stop(){this.app.server.listening&&await new Promise((e,t)=>{this.app.server.close(n=>n?t(n):e());for(const e of this.sockets)e.destroy()})}}const UA="TASK_HANDOFF_NODE_AGENT_V1",FA="/api/node-tunnel";function $A(e=""){return d.createHash("sha256").update(e).digest("hex")}function HA(e,t){return d.createHmac("sha256",e).update(function(e){return[UA,e.keyId,e.method.toUpperCase(),e.pathWithQuery,e.timestamp,e.nonce,e.bodySha256].join("\n")}(t)).digest("hex")}function BA(e){const t=e.timestamp||(new Date).toISOString(),n=e.nonce||d.randomBytes(18).toString("base64url"),i=$A(e.body||""),s=HA(e.secret,{keyId:e.keyId,method:e.method,pathWithQuery:e.pathWithQuery,timestamp:t,nonce:n,bodySha256:i});return{"x-taskhandoff-node-id":e.nodeId,"x-taskhandoff-key-id":e.keyId,"x-taskhandoff-timestamp":t,"x-taskhandoff-nonce":n,"x-taskhandoff-body-sha256":i,"x-taskhandoff-signature":s}}class qA{usedNonces=new Map;identity;nodeId;overrideSecret;overrideKeyId;nowMs;constructor(e,t,n,i,s=Date.now){this.identity=e,this.nodeId=t,this.overrideSecret=n,this.overrideKeyId=i,this.nowMs=s}hasRemoteSecrets(){return this.identity.remoteSecrets(this.overrideSecret,this.overrideKeyId).length>0}verify(e){const t=function(e){const t=new Map;for(const[n,i]of Object.entries(e)){const e=Array.isArray(i)?i.join(","):"string"==typeof i?i:void 0===i?"":String(i);t.set(n.toLowerCase(),e)}return{nodeId:t.get("x-taskhandoff-node-id")||"",keyId:t.get("x-taskhandoff-key-id")||"",timestamp:t.get("x-taskhandoff-timestamp")||"",nonce:t.get("x-taskhandoff-nonce")||"",bodySha256:t.get("x-taskhandoff-body-sha256")||"",signature:t.get("x-taskhandoff-signature")||""}}(e.headers);if(!t.nodeId&&!t.signature)return!1;const n="DELETE"===e.method&&"/api/node-agent/pairing/current"===e.url.split("?")[0],i=this.identity.remoteSecrets(this.overrideSecret,this.overrideKeyId,n);if(!i.length)return!1;if(t.nodeId!==this.nodeId)throw Object.assign(new Error("Invalid node agent HMAC node id."),{statusCode:401,code:"NODE_AGENT_HMAC_NODE_MISMATCH"});if(!t.keyId)throw Object.assign(new Error("Node agent HMAC key id is missing."),{statusCode:401,code:"NODE_AGENT_HMAC_KEY_MISSING"});const s=i.filter(e=>t.keyId===e.keyId);if(!s.length)throw Object.assign(new Error("Invalid node agent HMAC key id."),{statusCode:401,code:"NODE_AGENT_HMAC_KEY_INVALID"});const r=Date.parse(t.timestamp);if(!Number.isFinite(r)||Math.abs(this.nowMs()-r)>6e4)throw Object.assign(new Error("Node agent HMAC timestamp is outside the allowed window."),{statusCode:401,code:"NODE_AGENT_HMAC_TIMESTAMP_INVALID"});if(!t.nonce)throw Object.assign(new Error("Node agent HMAC nonce is missing."),{statusCode:401,code:"NODE_AGENT_HMAC_NONCE_MISSING"});this.pruneNonces();const o=`${t.nodeId}:${t.keyId}:${t.nonce}`;if(this.usedNonces.has(o))throw Object.assign(new Error("Node agent HMAC nonce was already used."),{statusCode:401,code:"NODE_AGENT_HMAC_NONCE_REPLAY"});const a=$A(null==(c=e.body)?"":"string"==typeof c||Buffer.isBuffer(c)?c:JSON.stringify(c));var c;if(t.bodySha256!==a)throw Object.assign(new Error("Node agent HMAC body hash mismatch."),{statusCode:401,code:"NODE_AGENT_HMAC_BODY_HASH_INVALID"});if(!s.some(n=>function(e,t){const n=Buffer.from(e,"hex"),i=Buffer.from(t,"hex");return n.length===i.length&&d.timingSafeEqual(n,i)}(t.signature,HA(n.secret,{keyId:t.keyId,method:e.method,pathWithQuery:e.url,timestamp:t.timestamp,nonce:t.nonce,bodySha256:a}))))throw Object.assign(new Error("Invalid node agent HMAC signature."),{statusCode:401,code:"NODE_AGENT_HMAC_SIGNATURE_INVALID"});return this.usedNonces.set(o,r+6e4+1),t.keyId}pruneNonces(){const e=this.nowMs();for(const[t,n]of this.usedNonces)n<=e&&this.usedNonces.delete(t)}}function VA(e,t){console.warn(JSON.stringify({message:e,...t}))}class GA{repository;logger;constructor(e,t,n={}){const i=t&&"readIdentity"in t?t:void 0,s=i?n:t||n;this.repository=i||Km(Jh(e)).access,this.logger=s.logger||VA}read(){const e=this.repository.readIdentity();return e?bh(e,this.logger):void 0}init(){}write(e){const t=bh({...e,updatedAt:de()},this.logger);return this.repository.writeIdentity(t)}}class WA{values=new Map;put(e,t,n=Date.now()){this.prune(n),this.values.set(e,t)}take(e,t=Date.now()){this.prune(t);const n=this.values.get(e);return n&&this.values.delete(e),n}peek(e,t=Date.now()){return this.prune(t),this.values.get(e)}delete(e,t=Date.now()){this.prune(t);const n=this.values.get(e);return n&&this.values.delete(e),n}list(e=Date.now()){return this.prune(e),[...this.values.values()]}prune(e=Date.now()){for(const[t,n]of this.values)Date.parse(n.expiresAt)<=e&&this.values.delete(t)}}class KA{store;repository;pairingInvites=new WA;controlPlaneConnectionOperations=new Map;constructor(e,t){this.repository=t||Km(Jh(e)).access,this.store=new GA(e,this.repository),this.store.init(),this.recoverControlPlaneConnectionOperations()}async runControlPlaneConnectionOperation(e,t){const n=e.replace(/\/$/,""),i=this.controlPlaneConnectionOperations.get(n)||Promise.resolve();let s;const r=new Promise(e=>{s=e});this.controlPlaneConnectionOperations.set(n,r),await i;try{return await t()}finally{s(),this.controlPlaneConnectionOperations.get(n)===r&&this.controlPlaneConnectionOperations.delete(n)}}resolveNodeId(e){if(e?.trim())return this.writeNodeId(e.trim()),e.trim();const t=this.store.read();if(t?.nodeId)return t.nodeId;const n=du("node");return this.writeNodeId(n),n}createPairingInvite(e){const t=de(),n=new Date(Date.now()+(e.expiresInMs||6e5)).toISOString(),i=lu(),s={tokenHash:$A(i),createdAt:t,expiresAt:n,...e.controlPlaneName?{controlPlaneName:e.controlPlaneName}:{}};return this.pairingInvites.put(s.tokenHash,s),{...s,token:i}}completePairingInvite(e){const t=this.store.read()||this.newIdentity(),n=$A(e.joinToken),i=this.pairingInvites.take(n);if(!i){const e=new Error("Node agent pairing invite is invalid or expired.");throw Object.assign(e,{statusCode:401,code:"NODE_AGENT_PAIRING_INVITE_INVALID"}),e}const s=de(),r={id:e.controlPlaneId||du("cp"),keyId:du("key"),...e.controlPlaneName||i.controlPlaneName?{name:e.controlPlaneName||i.controlPlaneName}:{},secret:lu(),pairedAt:s,updatedAt:s};return this.store.write({...t,controlPlanePairings:[...(t.controlPlanePairings||[]).filter(e=>e.id!==r.id),r]}),r}stageControlPlaneConnection(e){const{pairing:t,connection:n}=this.createControlPlaneConnection(e),i=this.store.read()||this.newIdentity(),s=n.url.replace(/\/$/,""),r=(i.controlPlaneConnections||[]).filter(e=>e.id===n.id||e.url.replace(/\/$/,"")===s),o={operationId:du("connection_operation"),pairing:t,connection:n,replacedConnections:r},a=de();return this.repository.transaction(()=>{this.store.write({...i,controlPlanePairings:[...(i.controlPlanePairings||[]).filter(e=>e.keyId!==t.keyId),t],controlPlaneConnections:[...(i.controlPlaneConnections||[]).filter(e=>e.id!==n.id&&e.url.replace(/\/$/,"")!==s),n]}),this.repository.putOperation({id:o.operationId,kind:"create-connection",phase:"prepared",requested:o,pairingKeyId:t.keyId,connectionId:n.id,replacedConnections:r,createdAt:a,updatedAt:a})}),o}markControlPlaneConnectionRemoteAccepted(e){const t=this.repository.listOperations().find(t=>t.id===e.operationId);if(!t)throw Object.assign(new Error("Control-plane connection operation was not found."),{code:"NODE_AGENT_CONNECTION_OPERATION_NOT_FOUND",statusCode:409});this.repository.putOperation({...t,phase:"remote-accepted",updatedAt:de()})}commitControlPlaneConnection(e,t={}){const n=this.store.read()||this.newIdentity(),i={...e.pairing,...t.name?{name:t.name}:{}},s={...e.connection,...t.name?{name:t.name}:{}},r=new Set((n.controlPlaneConnections||[]).map(e=>e.pairingKeyId)),o=new Set(e.replacedConnections.map(e=>e.pairingKeyId));return this.repository.transaction(()=>{this.store.write({...n,controlPlanePairings:[...(n.controlPlanePairings||[]).filter(e=>e.keyId!==i.keyId&&(!o.has(e.keyId)||r.has(e.keyId))),i],controlPlaneConnections:[...(n.controlPlaneConnections||[]).filter(e=>e.id!==s.id),s]});const t=this.repository.listOperations().find(t=>t.id===e.operationId);t&&this.repository.putOperation({...t,phase:"committed",updatedAt:de()}),this.repository.deleteOperation(e.operationId)}),{pairing:i,connection:s}}rollbackControlPlaneConnection(e){const t=this.store.read();if(!t)return;const n=new Set(e.replacedConnections.map(e=>e.id));this.repository.transaction(()=>{this.store.write({...t,controlPlanePairings:(t.controlPlanePairings||[]).filter(t=>t.keyId!==e.pairing.keyId),controlPlaneConnections:[...(t.controlPlaneConnections||[]).filter(t=>t.id!==e.connection.id&&!n.has(t.id)),...e.replacedConnections]}),this.repository.deleteOperation(e.operationId)})}recoverControlPlaneConnectionOperations(){for(const e of this.repository.listOperations(["prepared","remote-accepted"])){const t=e.requested;t?.pairing?.keyId&&t?.connection?.id?"remote-accepted"===e.phase?(this.repository.putOperation({...e,phase:"committed",updatedAt:de()}),this.repository.deleteOperation(e.id)):this.rollbackControlPlaneConnection(t):this.repository.putOperation({...e,phase:"failed",error:{code:"NODE_AGENT_CONNECTION_OPERATION_INVALID"},updatedAt:de()})}}createControlPlaneConnection(e){const t=de(),n={id:du("cp"),keyId:du("key"),...e.name?{name:e.name}:{},secret:lu(),pairedAt:t,updatedAt:t};return{pairing:n,connection:{id:du("connection"),pairingKeyId:n.keyId,...e.name?{name:e.name}:{},url:e.url,enabled:!1!==e.enabled,createdAt:t,updatedAt:t}}}resolvedControlPlaneAccess(){const e=this.store.read(),t=new Map((e?.controlPlanePairings||[]).filter(e=>!e.revokedAt).map(e=>[e.keyId,e])),n=e?.controlPlaneConnections||[];return{hasPersistedAccess:n.length>0||t.size>0,connections:n.map(e=>({connection:e,pairing:t.get(e.pairingKeyId)}))}}listControlPlanePairings(e=""){return(this.store.read()?.controlPlanePairings||[]).filter(e=>!e.revokedAt).map(({secret:t,...n})=>({...n,current:Boolean(e&&n.keyId===e)})).sort((e,t)=>Number(t.current)-Number(e.current)||t.updatedAt.localeCompare(e.updatedAt))}listControlPlaneConnections(){return[...this.store.read()?.controlPlaneConnections||[]].sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))}deleteControlPlanePairing(e,t=""){if(t&&e===t){const e=new Error("Cannot delete the pairing used to authenticate the current request.");throw Object.assign(e,{statusCode:409,code:"NODE_AGENT_PAIRING_CURRENT_REQUEST"}),e}const n=this.store.read();if(!n)return!1;if((n.controlPlaneConnections||[]).some(t=>t.pairingKeyId===e))throw Object.assign(new Error("Cannot delete a pairing used by a configured control-plane connection."),{statusCode:409,code:"NODE_AGENT_PAIRING_IN_USE"});const i=(n.controlPlanePairings||[]).filter(t=>t.keyId!==e);return i.length!==(n.controlPlanePairings||[]).length&&(this.store.write({...n,controlPlanePairings:i}),!0)}revokeCurrentControlPlanePairing(e){if(!e)throw Object.assign(new Error("Current paired-HMAC authentication is required to revoke this pairing."),{statusCode:403,code:"NODE_AGENT_PAIRING_SELF_REVOKE_HMAC_REQUIRED"});const t=this.store.read(),n=t?.controlPlanePairings?.find(t=>t.keyId===e);if(!t||!n)throw Object.assign(new Error("The current control-plane pairing no longer exists."),{statusCode:404,code:"NODE_AGENT_PAIRING_NOT_FOUND"});if(n.revokedAt)return{keyId:e,revoked:!0,revokedAt:n.revokedAt};if((t.controlPlaneConnections||[]).some(t=>t.pairingKeyId===e))throw Object.assign(new Error("Cannot revoke a pairing used by a configured control-plane connection."),{statusCode:409,code:"NODE_AGENT_PAIRING_IN_USE"});const i=de();return this.store.write({...t,controlPlanePairings:t.controlPlanePairings.map(t=>t.keyId===e?{...t,revokedAt:i,updatedAt:i}:t)}),{keyId:e,revoked:!0,revokedAt:i}}deleteControlPlaneConnection(e){const t=this.store.read();if(!t)return!1;const n=(t.controlPlaneConnections||[]).filter(t=>t.id!==e);return n.length!==(t.controlPlaneConnections||[]).length&&(this.store.write({...t,controlPlaneConnections:n}),!0)}remoteSecrets(e,t,n=!1){return[...(this.store.read()?.controlPlanePairings||[]).filter(e=>n||!e.revokedAt).map(e=>({keyId:e.keyId,secret:e.secret})),...e&&t?[{keyId:t,secret:e}]:[]]}isRevokedPairing(e){return Boolean(this.store.read()?.controlPlanePairings?.some(t=>t.keyId===e&&t.revokedAt))}reverseTunnelSecret(e,t,n){if(t&&n)return{keyId:n,secret:t};const i=this.store.read(),s=(i?.controlPlanePairings||[]).filter(e=>!e.revokedAt);if(!s.length)return;if(e){const t=e.replace(/\/$/,""),n=(i?.controlPlaneConnections||[]).find(e=>e.url.replace(/\/$/,"")===t),r=n&&s.find(e=>e.keyId===n.pairingKeyId);if(r)return{keyId:r.keyId,secret:r.secret}}const r=[...s].sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))[0];return r?{keyId:r.keyId,secret:r.secret}:void 0}newIdentity(){return{nodeId:this.resolveNodeId(),createdAt:de(),updatedAt:de(),controlPlanePairings:[],controlPlaneConnections:[]}}writeNodeId(e){const t=this.store.read();this.store.write({...t||{createdAt:de()},nodeId:e,updatedAt:de(),controlPlanePairings:t?.controlPlanePairings||[],controlPlaneConnections:t?.controlPlaneConnections||[]})}}const YA=c.z.string().trim().min(1).max(160);const XA=Sr.strict();function JA(e){const t=e.filter(e=>!["created","stopped","failed"].includes(e.status)),n=new Set(t.map(e=>e.id)),i=t.filter(e=>e.apps.runningCount>0||e.aiSessions.runningCount>0);return{runningInstanceCount:t.length,stoppedInstanceCount:e.length-t.length,activeInstanceCount:i.length,restartInstanceCount:t.length,runningInstanceIds:t.map(e=>e.id).sort(),stoppedInstanceIds:e.filter(e=>!n.has(e.id)).map(e=>e.id).sort(),activeInstanceIds:i.map(e=>e.id).sort()}}class QA{preflights=new Map;options;applying=!1;constructor(e){this.options=e}async check(e){const t=Tr.parse(e),n=JA(this.options.listInstances()),i=await hg(this.options.runCommand,this.options.moduleDir),s=this.options.currentRuntimeVersion(),r=this.options.managedUpdateSupport?.(i)||{supported:!0};if(!r.supported)return br.parse({source:"npm",channel:t.channel,currentVersion:i.currentVersion||s,availableVersion:i.currentVersion||s||"unavailable",impact:n,updateAvailable:!1,supported:!1,reason:r.reason||"Managed updates are unavailable on this node.",checkedAt:(new Date).toISOString()});const o="@task-handoff/server"===i.packageName?[...new Set([...i.relatedCurrentVersions,s])]:i.relatedCurrentVersions,a=await async function(e){const t=e.packageName||"@task-handoff/node-agent",n=await async function(e,t,n){const i=function(e){return"stable"===e?"latest":e}(n),s=await e(pg(),["view",`${t}@${i}`,"version","--json"]).catch(e=>{if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e,n=[t.message,t.details?.stdout,t.details?.stderr].filter(e=>"string"==typeof e).join("\n");return/\bE404\b/i.test(n)}(e))throw e});if(!s)return;const r=JSON.parse(s.stdout);if("string"!=typeof r)throw new Error(`npm did not resolve ${t}@${i} to one version.`);return r}(e.runCommand,t,e.channel);if(!n)return function(e){return br.parse({source:"npm",channel:e.channel,currentVersion:e.currentVersion,availableVersion:e.currentVersion||"unavailable",impact:e.impact||{runningInstanceCount:0,stoppedInstanceCount:0,activeInstanceCount:0,restartInstanceCount:0,runningInstanceIds:[],stoppedInstanceIds:[],activeInstanceIds:[]},updateAvailable:!1,reason:`No ${e.channel} release is currently published.`,checkedAt:de()})}({channel:e.channel,currentVersion:e.currentVersion,impact:e.impact});const i=ug(e.currentVersion,n)||(e.relatedCurrentVersions||[]).some(e=>ug(e,n)),s=i?await async function(e,t,n){const i=await e(pg(),["view",`${t}@${n}`,"dist.integrity","--json"]),s=JSON.parse(i.stdout);if("string"!=typeof s||!/^sha(?:256|384|512)-[A-Za-z0-9+/=]+$/.test(s))throw Object.assign(new Error(`npm did not return immutable integrity metadata for ${t}@${n}.`),{statusCode:502,code:"NODE_UPDATE_PREFLIGHT_FAILED",retryable:!0});return s}(e.runCommand,t,n):void 0;return br.parse({source:"npm",channel:e.channel,currentVersion:e.currentVersion,availableVersion:n,...s?{artifactRef:`npm:${t}@${n}#${s}`}:{},runtimeArtifacts:e.runtimeArtifacts||[],impact:e.impact||{runningInstanceCount:0,stoppedInstanceCount:0,activeInstanceCount:0,restartInstanceCount:0,runningInstanceIds:[],stoppedInstanceIds:[],activeInstanceIds:[]},updateAvailable:i,checkedAt:de()})}({channel:t.channel,currentVersion:i.currentVersion||s,runCommand:this.options.runCommand,packageName:i.packageName,relatedCurrentVersions:o,impact:n});if(!a.updateAvailable)return a;const c={...a,runtimeArtifacts:[],preflightToken:lu()};return this.preflights.set(c.preflightToken,{result:c,expiresAt:Date.now()+6e5}),c}async apply(e){const i=XA.parse(e),s=this.preflights.get(i.preflightToken);(!s||s.expiresAt<=Date.now())&&await this.consumePreflight(i),this.applying&&this.throwAlreadyRunning(),this.applying=!0;try{const{check:e,selection:s}=await this.consumePreflight(i);if(this.options.jobs.list().some(e=>!["succeeded","degraded","failed"].includes(e.status))&&this.throwAlreadyRunning(),!e.supported)throw Object.assign(new Error(e.reason||"The requested update is not supported."),{statusCode:400,code:"UPDATE_UNSUPPORTED"});if(!e.updateAvailable)throw Object.assign(new Error(e.reason||"No update is available for the selected channel."),{statusCode:409,code:"UPDATE_NOT_AVAILABLE"});const r=this.options.jobs.create(this.options.nodeId,e),{worker:o,packaged:a,expectedWorker:c}=function(e,i=t.existsSync){const s=[n.resolve(e,"..","bin","task-handoff-node-update-worker"),n.resolve(e,"..","..","bin","task-handoff-node-update-worker")],r=s.find(i),o=n.resolve(e,"..","..","..","..","scripts","node-update-worker.cts");return r?{worker:r,packaged:!0,expectedWorker:s[0]}:i(o)?{worker:o,packaged:!1,expectedWorker:s[0]}:{worker:void 0,packaged:!1,expectedWorker:s[0]}}(this.options.moduleDir);if(!o)throw this.options.jobs.patch(r.id,{status:"failed",rollout:{...r.rollout,phase:"failed"},error:{code:"NODE_UPDATE_FAILED",message:`Update worker was not found: ${c}`,retryable:!1},completedAt:(new Date).toISOString()}),Object.assign(new Error(`Node agent update worker was not found: ${c}`),{statusCode:500,code:"UPDATE_WORKER_NOT_FOUND"});const d=process.env.TASK_HANDOFF_CONTROL_PLANE_HEALTH_URL?.trim();try{await this.options.runCommand("systemd-run",["--unit",`task-handoff-update-${r.id}`,"--collect","--property=Type=exec",...a?[o]:[process.execPath,o],"--job-file",this.options.jobs.records.filePath(r.id),"--target-version",r.toVersion,"--npm-command",pg(),"--install-prefix",s.installPrefix,...process.env.TASK_HANDOFF_NODE_AGENT_IPC_PATH?.trim()?["--node-agent-ipc-path",process.env.TASK_HANDOFF_NODE_AGENT_IPC_PATH.trim()]:[],...d?["--control-plane-health-url",d]:[]])}catch(e){const t=e instanceof Error?e.message:String(e);throw this.options.jobs.patch(r.id,{status:"failed",rollout:{...r.rollout,phase:"failed"},error:{code:"NODE_UPDATE_FAILED",message:`Failed to launch the node update worker: ${t}`,retryable:!0},completedAt:(new Date).toISOString()}),Object.assign(new Error(`Failed to launch the node update worker: ${t}`),{statusCode:500,code:"NODE_UPDATE_WORKER_LAUNCH_FAILED",cause:e})}return await this.waitForWorkerClaim(r)}finally{this.applying=!1}}async consumePreflight(e){const t=this.preflights.get(e.preflightToken);if(this.preflights.delete(e.preflightToken),!t||t.expiresAt<=Date.now())throw Object.assign(new Error("The update preflight is missing or expired. Check for updates again."),{statusCode:409,code:"UPDATE_PREFLIGHT_EXPIRED"});const n=t.result,i=await hg(this.options.runCommand,this.options.moduleDir);return n.channel===e.channel&&n.availableVersion===e.targetVersion&&n.currentVersion===(i.currentVersion||this.options.currentRuntimeVersion())&&!0===n.artifactRef?.startsWith(`npm:${i.packageName}@`)&&JSON.stringify(n.impact)===JSON.stringify(JA(this.options.listInstances()))||this.throwStale(),{check:n,selection:i}}throwStale(){throw Object.assign(new Error("The update target or affected instances changed after preflight. Check for updates again."),{statusCode:409,code:"UPDATE_PREFLIGHT_STALE"})}throwAlreadyRunning(){throw Object.assign(new Error("Another server update is already running on this node."),{statusCode:409,code:"SERVER_UPDATE_ALREADY_RUNNING"})}async waitForWorkerClaim(e){const t=this.options.workerClaimTimeoutMs??5e3,n=this.options.workerClaimPollMs??50,i=Date.now()+t;for(;Date.now()<=i;){const t=this.options.jobs.records.get(e.id);if(!t)throw Object.assign(new Error(`Update job ${e.id} disappeared before the worker claimed it.`),{statusCode:500,code:"UPDATE_JOB_NOT_FOUND"});if("queued"!==t.status)return t;if(Date.now()>=i)break;await new Promise(e=>setTimeout(e,Math.max(1,Math.min(n,i-Date.now()))))}const s=this.options.jobs.records.get(e.id);if("queued"!==s?.status)return s||e;throw this.options.jobs.patch(e.id,{status:"failed",rollout:{...s.rollout,phase:"failed"},error:{code:"NODE_UPDATE_FAILED",message:"The node update worker did not claim the queued job after systemd accepted it.",retryable:!0},completedAt:(new Date).toISOString()}),Object.assign(new Error("The node update worker did not start after systemd accepted the update job."),{statusCode:500,code:"NODE_UPDATE_WORKER_START_TIMEOUT"})}}const ZA=new Set(["provisioning","starting","registering","registered","running"]);function eT(e,t){return"offline"!==t.status&&ZA.has(e.status)&&!Xl(e)&&!Jl(e)}function tT(e){return"offline"===e.status}function nT(e){return Ia.parse({...e,health:"unknown",connectionStatus:"offline",agentStatus:"offline",targetStatus:"unknown",uiAccessStatus:"unknown",target:{...e.target,status:"unknown"},updatedAt:de()})}class iT{options;restoredInstances=new Set;restoreErrors=new Map;unexpectedExitRetries=new Map;suppressedInstances=new Set;pendingUnexpectedExits=new Map;activeRestores=new Map;timer;activeCycle;cycleRequested=!1;cycleRequestDelayMs;started=!1;stopped=!1;constructor(e){this.options=e}markRestored(e){const t=this.options.state.requireInstance(e);return!(["failed","stopping","stopped"].includes(t.status)||Xl(t)||Jl(t)||(this.restoredInstances.add(e),this.restoreErrors.delete(e),0))}allowRecovery(e){this.suppressedInstances.delete(e);const t=this.pendingUnexpectedExits.get(e);void 0!==t&&(this.pendingUnexpectedExits.delete(e),this.applyUnexpectedLocalExit(e,t))}completeSuppressedOperation(e){this.pendingUnexpectedExits.delete(e),this.restoredInstances.delete(e),this.restoreErrors.delete(e),this.unexpectedExitRetries.delete(e)}forgetInstance(e){this.restoredInstances.delete(e),this.restoreErrors.delete(e),this.unexpectedExitRetries.delete(e),this.suppressedInstances.delete(e),this.activeRestores.delete(e),this.pendingUnexpectedExits.delete(e)}async suppressRecovery(e){this.suppressedInstances.add(e),await(this.activeRestores.get(e)?.catch(()=>{}))}handleUnexpectedLocalExit(e,t){this.stopped||(this.suppressedInstances.has(e)?this.pendingUnexpectedExits.set(e,t):this.applyUnexpectedLocalExit(e,t))}applyUnexpectedLocalExit(e,t){const n=this.options.state.requireInstance(e);if("local"!==this.options.state.requireRuntime(n.runtimeId).type)return;this.restoredInstances.delete(e);const i=this.options.nowMs?.()??Date.now(),s=this.unexpectedExitRetries.get(e),r=this.options.crashStableWindowMs??3e4,o=s&&i-s.lastExitAt<r?s.attempt+1:1;this.unexpectedExitRetries.set(e,{attempt:o,lastExitAt:i});const a=this.options.retryBaseDelayMs??1e3,c=1===o?0:Math.min(this.options.retryMaxDelayMs??3e4,a*2**Math.min(o-2,10)),d=t instanceof Error?t.message:String(t);this.restoreErrors.set(e,{message:d,attempt:o,nextAttemptAt:i+c}),this.options.state.applyInstanceLifecycle(e,{type:"runtime-exited",error:t}),this.requestCycle(c)}async restoreManagedInstances(){if(this.stopped)return;const{state:e}=this.options;for(const t of e.listInstances()){if(this.stopped)return;const n=e.requireRuntime(t.runtimeId);"docker"===n.type&&!tT(n)&&["provisioning","starting"].includes(t.status)&&"ready"!==t.imageProvisioning?.phase&&this.options.provisionImage(t),"docker"===n.type&&!tT(n)&&["provisioning","starting"].includes(t.status)&&Jl(t)&&!Xl(t)&&this.options.provisionGit?.(t)}const t=e.listInstances().filter(t=>{if(this.restoredInstances.has(t.id))return!1;if(this.suppressedInstances.has(t.id))return!1;const n=e.requireRuntime(t.runtimeId);if("local"===n.type){const e=this.restoreErrors.get(t.id);return(ZA.has(t.status)||"failed"===t.status)&&(!e||e.nextAttemptAt<=(this.options.nowMs?.()??Date.now()))}return("docker"===n.type||"wsl"===n.type)&&eT(t,n)});await Promise.all(t.map(async t=>{if(this.stopped)return;const n=async()=>{if(this.stopped)return;const n=e.listInstances().find(e=>e.id===t.id);if(!n)return;if(!this.isRestoreCandidate(n))return;const i=this.restoreErrors.get(n.id);try{const t=this.options.restoreInstance(n.id);this.activeRestores.set(n.id,t);try{await t}finally{this.activeRestores.get(n.id)===t&&this.activeRestores.delete(n.id)}if(this.stopped||this.suppressedInstances.has(n.id))return;if(await this.options.autoImport(e.requireInstance(n.id)),this.stopped||this.suppressedInstances.has(n.id))return;if(this.restoreErrors.get(n.id)!==i)return;if(!this.markRestored(n.id))throw new Error(`Restored instance ${n.id} did not reach a recoverable running state.`)}catch(t){if(this.stopped||this.suppressedInstances.has(n.id))return;"local"===e.requireRuntime(n.runtimeId).type&&e.applyInstanceLifecycle(n.id,{type:"start-failed",error:t});const i=t instanceof Error?t.message:String(t),s=this.restoreErrors.get(n.id),r=(s?.attempt??0)+1,o=this.options.retryBaseDelayMs??1e3,a=Math.min(this.options.retryMaxDelayMs??3e4,o*2**Math.min(r-1,10)),c=(this.options.nowMs?.()??Date.now())+a;this.restoreErrors.set(n.id,{message:i,attempt:r,nextAttemptAt:c}),s?.message===i&&s.attempt===r||this.options.warn({instanceId:n.id,action:"restore",runtimeId:n.runtimeId,error:i,attempt:r,nextAttemptAt:new Date(c).toISOString()},"node instance restore failed; recovery will retry")}};await(this.options.runInstanceOperation?.(t.id,n)??n())}))}isRestoreCandidate(e){if(this.restoredInstances.has(e.id)||this.suppressedInstances.has(e.id))return!1;const t=this.options.state.requireRuntime(e.runtimeId);if("local"===t.type){const t=this.restoreErrors.get(e.id);return(ZA.has(e.status)||"failed"===e.status)&&(!t||t.nextAttemptAt<=(this.options.nowMs?.()??Date.now()))}return("docker"===t.type||"wsl"===t.type)&&eT(e,t)}async recoverManagedInstances(){if(this.stopped)return;const{state:e,convergence:t}=this.options,n=e.listInstances().filter(n=>this.options.usesManagedArtifact(n)&&!t.isRunning(n.id)&&(this.restoredInstances.has(n.id)||"unknown"!==n.target.status)&&(!n.ready||"matched"!==n.runtimeVersion?.phase)&&!Xl(n)&&!tT(e.requireRuntime(n.runtimeId))&&!["created","stopped","failed","provisioning","stopping"].includes(n.status));await Promise.all(n.map(async e=>{if(!this.stopped)try{await t.schedule(e.id)}catch(t){this.options.error({instanceId:e.id,error:t},"runtime convergence recovery failed")}}))}start(){this.started||this.stopped||(this.started=!0,this.runAndContinue())}notifyRuntimeAvailable(){this.requestCycle(0)}async stop(){this.stopped=!0,this.timer&&clearTimeout(this.timer),this.timer=void 0;const e=this.options.stopImageProvisioning(),t=this.options.stopGitProvisioning?.()??Promise.resolve(),n=this.options.state.listInstances().map(e=>this.options.convergence.cancel(e.id));await Promise.all(n),await this.activeCycle,await e,await t,await this.options.runtimeAdapters.stopAll();for(const e of this.options.state.listInstances())"local"===this.options.state.requireRuntime(e.runtimeId).type&&this.options.state.controlledInstances.put(nT(e))}async runCycle(){await this.restoreManagedInstances(),this.stopped||await this.recoverManagedInstances()}runAndContinue(){if(this.stopped)return;const e=this.runCycle().catch(e=>this.options.error({error:e},"node agent startup recovery cycle failed"));this.activeCycle=e,e.finally(()=>{this.activeCycle===e&&(this.activeCycle=void 0),this.cycleRequested?(this.cycleRequested=!1,this.cycleRequestDelayMs=void 0,this.scheduleNext()):this.scheduleNext()})}scheduleNext(){if(this.stopped)return;const e=this.options.nowMs?.()??Date.now(),t=new Map(this.options.state.listInstances().map(e=>[e.id,e])),n=[...this.restoreErrors.entries()].reduce((e,[n,i])=>{const s=t.get(n);return!s||this.restoredInstances.has(n)||this.suppressedInstances.has(n)||"local"!==this.options.state.requireRuntime(s.runtimeId).type?e:ZA.has(s.status)||"failed"===s.status?Math.min(e,i.nextAttemptAt):e},Number.POSITIVE_INFINITY),i=Math.min(this.options.intervalMs??1e4,Math.max(0,n-e));this.timer=setTimeout(()=>{this.timer=void 0,this.runAndContinue()},i),this.timer.unref?.()}requestCycle(e=0){if(this.started&&!this.stopped){if(this.activeCycle)return this.cycleRequested=!0,void(this.cycleRequestDelayMs=void 0===this.cycleRequestDelayMs?e:Math.min(this.cycleRequestDelayMs,e));this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>{this.timer=void 0,this.runAndContinue()},e),this.timer.unref?.()}}}function sT(e){if(null==e||"string"==typeof e&&!e.trim())return 15e3;const t="number"==typeof e?e:Number(e);return!Number.isFinite(t)||t<=0?15e3:Math.max(1e3,Math.trunc(t))}function rT(e,t){return JSON.stringify({status:t.status??e.status,capabilities:t.capabilities??e.capabilities})}class oT{hooks;intervalMs;timer;probing=!1;stopped=!1;constructor(e,t={}){this.hooks=e,this.intervalMs=sT(t.intervalMs)}start(){this.stopped||this.timer||this.runCycle()}async checkNow(){this.stopped||(this.timer&&clearTimeout(this.timer),this.timer=void 0,await this.runCycle())}async checkRuntime(e){const t=this.hooks.listTargets().find(t=>t.runtime.id===e);return!!t&&(await this.probeTarget(t),!0)}stop(){this.stopped=!0,this.timer&&clearTimeout(this.timer),this.timer=void 0}async runCycle(){if(!this.stopped){try{await this.probeAll()}catch(e){this.hooks.onCycleError?.(e)}this.schedule(this.intervalMs)}}schedule(e){this.stopped||this.timer||(this.timer=setTimeout(()=>{this.timer=void 0,this.runCycle()},e),this.timer.unref?.())}async probeAll(){if(!this.stopped&&!this.probing){this.probing=!0;try{for(const e of this.hooks.listTargets()){if(this.stopped)return;await this.probeTarget(e)}}finally{this.probing=!1}}}async probeTarget(e){const t=e.runtime;let n;try{n=await e.probe()}catch(e){return void this.hooks.onProbeError?.(t,e)}if(!n)return;rT(t,n)!==rT(t,{})&&await this.hooks.apply(t,n);const i=n.status??t.status;if(i===t.status)return;const s={...t,...n,status:i};"online"===i?this.hooks.onAvailable?.(s,t):"offline"!==i&&"degraded"!==i||this.hooks.onUnavailable?.(s,t)}}const aT=new Set(["DELETE","GET","HEAD","PATCH","POST","PUT","OPTIONS"]);function cT(e){return"string"==typeof e&&aT.has(e.toUpperCase())?e.toUpperCase():"GET"}function dT(e){const t=function(e){if(null==e)return;const t=ws.parse(e);return"utf8"===t.encoding?t.data:Vi(t.data)}(e);return Buffer.isBuffer(t)?t:t instanceof Uint8Array?Buffer.from(t):t}function lT(e,t){const n=new URL(t.tunnelUrl);n.searchParams.set("nodeId",t.nodeId);const i=t.secret?BA({nodeId:t.nodeId,keyId:t.keyId,secret:t.secret,method:"GET",pathWithQuery:`${n.pathname}${n.search}`}):{},s=new h(n,{headers:i}),r=new Map,o=new Map,a=new Map;let c;s.on("error",i=>{e.log.warn({nodeId:t.nodeId,tunnelUrl:`${n.origin}${n.pathname}`,error:i instanceof Error?i.message:String(i)},"node agent reverse tunnel connection failed")});const d=e=>{const n=e.startsWith("/")?e:`/${e}`,i="function"==typeof t.port?t.port():t.port,s=new URL(`/api/node-agent${n}`,`http://127.0.0.1:${i}`);return s.protocol="ws:",s},l=(e,n,i,s={})=>{const r=e.startsWith("/")?e:`/${e}`;return{...s,...t.secret&&t.keyId?BA({nodeId:t.nodeId,keyId:t.keyId,secret:t.secret,method:n,pathWithQuery:`/api/node-agent${r}`,body:i}):t.token?{authorization:`Bearer ${t.token}`}:{}}},u=e=>t.secret?BA({nodeId:t.nodeId,keyId:t.keyId,secret:t.secret,method:"GET",pathWithQuery:`${e.pathname}${e.search}`}):{},p=(e,t,n)=>{const i=r.get(e);r.delete(e),i?.upstream&&j(i.upstream,t,n),i?.tunnel&&j(i.tunnel,t,n)},m=(e,t,n=!1)=>new Promise((i,s)=>{e.send(t,{binary:n,compress:!1},e=>e?s(e):i())});s.on("open",()=>{s.send(JSON.stringify({type:"node-agent.identify",nodeId:t.nodeId,serverTime:(new Date).toISOString()})),c=e.nodeAgentEventForwarder?.addOutput(s,{legacyFallbackMs:1e3})}),s.on("close",()=>{for(const e of r.keys())p(e,1001,"Reverse tunnel disconnected.");for(const[e,t]of o)o.delete(e),t.controller.abort(),j(t.tunnel,1001,"Reverse tunnel disconnected.");for(const[e,t]of a)a.delete(e),t.abort();c?.(),c=void 0});return s.on("message",i=>{(async i=>{let c;try{c=JSON.parse(String(i))}catch{return void s.send(JSON.stringify({type:"node-agent.error",code:"INVALID_JSON"}))}const g=c&&"object"==typeof c?c:{};if("control-plane.event-subscribe"!==g.type){if("control-plane.http.open"===g.type){const i="string"==typeof g.streamId?g.streamId:"",r="string"==typeof g.route&&g.route.startsWith("/")?g.route:"/health",a=g.init&&"object"==typeof g.init?g.init:{},c=a.headers&&"object"==typeof a.headers?a.headers:{},d=cT(a.method);let p;try{p=dT(a.body)}catch(n){return e.log.warn({nodeId:t.nodeId,messageType:g.type,streamId:i,error:n instanceof Error?n.message:String(n)},"node agent reverse tunnel request body rejected"),void s.send(JSON.stringify({type:"node-agent.error",code:"NODE_TUNNEL_REQUEST_BODY_INVALID",streamId:i}))}const f=new AbortController,y=(e=>{const t=new URL(n);return t.pathname=`${t.pathname.replace(/\/$/,"")}/http-streams/${encodeURIComponent(e)}`,t})(i),I=new h(y,{headers:u(y)});return o.set(i,{tunnel:I,controller:f}),I.on("open",async()=>{try{const e=await fetch((e=>{const n=e.startsWith("/")?e:`/${e}`,i="function"==typeof t.port?t.port():t.port;return new URL(`/api/node-agent${n}`,`http://127.0.0.1:${i}`)})(r),{method:d,headers:l(r,d,p,c),body:Buffer.isBuffer(p)?new Uint8Array(p):p,signal:f.signal});if(await m(I,JSON.stringify({type:"node-agent.http.head",streamId:i,status:e.status,headers:Object.fromEntries(e.headers.entries())})),e.body){const t=e.body.getReader();for(;;){const{done:e,value:n}=await t.read();if(e)break;await m(I,Buffer.from(n),!0)}}await m(I,JSON.stringify({type:"node-agent.http.end",streamId:i})),I.close(1e3,"HTTP stream completed.")}catch(e){I.readyState===h.OPEN&&(await m(I,JSON.stringify({type:"node-agent.http.error",streamId:i,message:e instanceof Error?e.message:String(e)})).catch(()=>{}),I.close(1011,"HTTP stream failed."))}finally{o.delete(i)}}),I.on("close",()=>{f.abort(),o.delete(i)}),void I.on("error",()=>f.abort())}if("control-plane.http.cancel"===g.type){const e="string"==typeof g.streamId?g.streamId:"",t=o.get(e);if(!t)return;return o.delete(e),t.controller.abort(),void j(t.tunnel,1e3,"string"==typeof g.reason?g.reason:"HTTP stream canceled.")}if("control-plane.websocket.open"===g.type){const e="string"==typeof g.streamId?g.streamId:"",t="string"==typeof g.route?g.route:"",i=Array.isArray(g.protocols)?g.protocols.filter(e=>"string"==typeof e):void 0;try{const o=l(t,"GET",void 0),a=i?.length?new h(d(t),i,{headers:o}):new h(d(t),{headers:o}),c=(e=>{const t=new URL(n);return t.pathname=`${t.pathname.replace(/\/$/,"")}/streams/${encodeURIComponent(e)}`,t})(e),p=new h(c,{headers:u(c)});r.set(e,{upstream:a,tunnel:p,close:(e=1e3,t="")=>{j(a,e,t),j(p,e,t)}}),a.on("open",()=>{s.send(JSON.stringify({type:"node-agent.websocket.open",streamId:e,protocol:a.protocol}))}),F(p,a,{pendingFrameLimit:256,upstreamOpenTimeoutMs:1e4,onClientClose:()=>{r.delete(e)},onClientError:t=>{r.delete(e),s.send(JSON.stringify({type:"node-agent.websocket.error",streamId:e,message:t instanceof Error?t.message:String(t)}))},onUpstreamClose:(t,n)=>{r.delete(e);const i=M(t),o=P(n);s.send(JSON.stringify({type:"node-agent.websocket.close",streamId:e,...void 0===i?{}:{code:i},...o?{reason:o}:{}}))},onUpstreamError:t=>{r.delete(e),s.send(JSON.stringify({type:"node-agent.websocket.error",streamId:e,message:t instanceof Error?t.message:String(t)}))}})}catch(t){s.send(JSON.stringify({type:"node-agent.websocket.error",streamId:e,message:t instanceof Error?t.message:String(t)}))}return}if("control-plane.websocket.close"===g.type){const e="string"==typeof g.streamId?g.streamId:"";return void p(e,"number"==typeof g.code?g.code:1e3,"string"==typeof g.reason?g.reason:"")}if("control-plane.request.cancel"===g.type){const e="string"==typeof g.requestId?g.requestId:"";return a.get(e)?.abort(),void a.delete(e)}if("control-plane.request"===g.type){const n="string"==typeof g.requestId?g.requestId:"",i=g.init&&"object"==typeof g.init?g.init:{},r="string"==typeof g.route&&g.route.startsWith("/")?g.route:"/health",o=i.headers&&"object"==typeof i.headers?i.headers:{},c=cT(i.method);let d;try{d=dT(i.body)}catch(i){return e.log.warn({nodeId:t.nodeId,messageType:g.type,requestId:n,error:i instanceof Error?i.message:String(i)},"node agent reverse tunnel request body rejected"),void s.send(JSON.stringify({type:"node-agent.response",requestId:n,status:400,error:{code:"NODE_TUNNEL_REQUEST_BODY_INVALID",message:"Reverse tunnel request body does not match the negotiated protocol."}}))}const u=new AbortController;a.set(n,u);try{const t=await e.inject({method:c,url:`/api/node-agent${r}`,headers:l(r,c,d,o),payload:d,signal:u.signal});if(u.signal.aborted)return;s.send(JSON.stringify({type:"node-agent.response",requestId:n,status:t.statusCode,headers:t.headers,body:t.body}))}catch(e){if(u.signal.aborted)return;s.send(JSON.stringify({type:"node-agent.response",requestId:n,status:502,error:{code:"NODE_AGENT_REVERSE_INJECT_FAILED",message:e instanceof Error?e.message:String(e)}}))}finally{a.delete(n)}}}else e.nodeAgentEventForwarder?.setOutputSubscription?.(s,g.aiSessionTransient,g.eventEnvelopeVersion,g.aiSessionHierarchy)})(i).catch(n=>{e.log.warn({nodeId:t.nodeId,error:n instanceof Error?n.message:String(n)},"node agent reverse tunnel message rejected");try{s.send(JSON.stringify({type:"node-agent.error",code:"INVALID_TUNNEL_MESSAGE"}))}catch{}})}),s}function uT(e,t){return Number.isFinite(e)&&Number(e)>0?Number(e):t}function pT(e){if(!e.length)return;const t=[...e].sort((e,t)=>e-t);return t[Math.ceil(.95*t.length)-1]}function mT(e){return e.unref?.(),e}class hT{connectTimeoutMs;handshakeTimeoutMs;heartbeatIntervalMs;heartbeatTimeoutMs;heartbeatMissThreshold;stableThresholdMs;now;setTimeoutFn;clearTimeoutFn;ping;onTimeout;onStable;onPhase;connectTimer;handshakeTimer;heartbeatTimer;stableTimer;awaitingPongSince;consecutiveHeartbeatMisses=0;stable=!1;stopped=!1;currentPhase="connecting";lastActivityAt;lastPongAt;pingRttMs;recentPingRttMs=[];constructor(e){this.connectTimeoutMs=uT(e.connectTimeoutMs,1e4),this.handshakeTimeoutMs=uT(e.handshakeTimeoutMs,1e4),this.heartbeatIntervalMs=uT(e.heartbeatIntervalMs,25e3),this.heartbeatTimeoutMs=uT(e.heartbeatTimeoutMs,15e3),this.heartbeatMissThreshold=Math.max(1,Math.floor(uT(e.heartbeatMissThreshold,2))),this.stableThresholdMs=uT(e.stableThresholdMs,6e4),this.now=e.now||Date.now,this.setTimeoutFn=e.setTimeoutFn||setTimeout,this.clearTimeoutFn=e.clearTimeoutFn||clearTimeout,this.ping=e.ping,this.onTimeout=e.onTimeout,this.onStable=e.onStable,this.onPhase=e.onPhase}get phase(){return this.currentPhase}start(){this.stopped=!1,this.setPhase("connecting"),this.clearTimer("connectTimer"),this.connectTimer=mT(this.setTimeoutFn(()=>this.timeout("connect"),this.connectTimeoutMs))}opened(){this.stopped||(this.clearTimer("connectTimer"),this.setPhase("handshaking"),this.handshakeTimer=mT(this.setTimeoutFn(()=>this.timeout("handshake"),this.handshakeTimeoutMs)),this.scheduleHeartbeat(this.heartbeatIntervalMs))}healthy(){this.stopped||(this.clearTimer("handshakeTimer"),this.activity(),this.setPhase("healthy"),this.stable||this.stableTimer||(this.stableTimer=mT(this.setTimeoutFn(()=>{this.stableTimer=void 0,this.stopped||"healthy"!==this.currentPhase||(this.stable=!0,this.onStable?.())},this.stableThresholdMs))))}activity(){this.stopped||(this.lastActivityAt=this.now(),this.awaitingPongSince=void 0,this.consecutiveHeartbeatMisses=0,"handshaking"!==this.currentPhase&&"healthy"!==this.currentPhase||this.scheduleHeartbeat(this.heartbeatIntervalMs))}pong(){if(this.stopped)return;const e=this.now();void 0!==this.awaitingPongSince&&(this.pingRttMs=Math.max(0,e-this.awaitingPongSince),this.recentPingRttMs.push(this.pingRttMs),this.recentPingRttMs.length>20&&this.recentPingRttMs.shift()),this.awaitingPongSince=void 0,this.consecutiveHeartbeatMisses=0,this.lastPongAt=e,this.lastActivityAt=e,this.scheduleHeartbeat(this.heartbeatIntervalMs)}close(){this.stopped||(this.stopped=!0,this.clearTimers(),this.awaitingPongSince=void 0,this.setPhase("closed"))}diagnostics(){return{phase:this.currentPhase,stable:this.stable,...void 0===this.pingRttMs?{}:{pingRttMs:this.pingRttMs},...this.recentPingRttMs.length?{pingRttP95Ms:pT(this.recentPingRttMs)}:{},...void 0===this.lastActivityAt?{}:{lastActivityAt:new Date(this.lastActivityAt).toISOString()},...void 0===this.lastPongAt?{}:{lastPongAt:new Date(this.lastPongAt).toISOString()},...this.consecutiveHeartbeatMisses?{consecutiveHeartbeatMisses:this.consecutiveHeartbeatMisses}:{}}}scheduleHeartbeat(e){this.stopped||(this.clearTimer("heartbeatTimer"),this.heartbeatTimer=mT(this.setTimeoutFn(()=>{if(this.heartbeatTimer=void 0,!this.stopped){if(void 0!==this.awaitingPongSince){const e=Math.max(0,this.now()-this.awaitingPongSince);return e>=this.heartbeatTimeoutMs?(this.consecutiveHeartbeatMisses+=1,this.awaitingPongSince=void 0,this.consecutiveHeartbeatMisses>=this.heartbeatMissThreshold?void this.timeout("heartbeat"):void this.sendHeartbeatProbe()):void this.scheduleHeartbeat(this.heartbeatTimeoutMs-e)}this.sendHeartbeatProbe()}},e)))}sendHeartbeatProbe(){this.awaitingPongSince=this.now();try{this.ping()}catch{if(this.consecutiveHeartbeatMisses+=1,this.awaitingPongSince=void 0,this.consecutiveHeartbeatMisses>=this.heartbeatMissThreshold)return void this.timeout("heartbeat")}this.scheduleHeartbeat(this.heartbeatTimeoutMs)}timeout(e){this.stopped||(this.clearTimers(),this.setPhase("failed"),this.onTimeout(e))}setPhase(e){this.currentPhase!==e&&(this.currentPhase=e,this.onPhase?.(e))}clearTimers(){this.clearTimer("connectTimer"),this.clearTimer("handshakeTimer"),this.clearTimer("heartbeatTimer"),this.clearTimer("stableTimer")}clearTimer(e){const t=this[e];t&&this.clearTimeoutFn(t),this[e]=void 0}}function gT(e){const t=new URL(FA,e);return t.protocol="https:"===t.protocol?"wss:":"ws:",t.toString()}const fT=new Set(["linux","darwin","win32","freebsd","openbsd","aix","sunos"]);function yT(e){return fT.has(e)?e:"unknown"}function IT(e){return!0===e.managedArtifacts}class _T{managedArtifacts=!0;executor;runCommand;platform;arch;constructor(e,t,n,i){this.executor=e,this.runCommand=t,this.platform=n,this.arch=i}artifactTarget(e){return this.executor.inspectRuntimeTarget(e?.instance.runtime.containerName)}resolveInstanceWeb(e){return this.executor.resolveInstanceWeb(e)}resolveNodeAgentUrl(e){return this.executor.resolveNodeAgentUrl(e)}runtimeState(e){const t=e.instance.runtime.containerName;return t?this.executor.runtimeState(t):Promise.resolve("absent")}async installRuntime(e,t){const n=e.instance.runtime.containerName;if(!n)throw Object.assign(new Error(`Instance ${e.instance.id} does not have a Docker container.`),{code:"INSTANCE_RUNTIME_INSTALL_FAILED"});await this.executor.installRuntimeReleaseWithRecovery({containerName:n,expectedContainerId:e.instance.runtime.containerId,artifactPath:t.archivePath,identity:t.identity})}async inspectRuntime(e,t){const n=e.instance.runtime.containerName;return!!n&&function(e,t){return e.packageName===t.packageName&&e.version===t.version&&e.platform===t.platform&&e.arch===t.arch&&e.formatVersion===t.formatVersion&&e.launcherAbi===t.launcherAbi&&e.entrypoint===t.entrypoint&&e.sha256===t.sha256}(await this.executor.inspectRuntimeVersion(n),t)}start(e){return this.executor.start(e)}stop(e){return this.executor.stop(e)}restart(e){return this.executor.restart(e,e.instance.runtime.containerId)}delete(e,t){return this.executor.delete(e,t)}async check(e){try{const t=(await this.runCommand("docker",["version","--format","{{.Server.Version}}"],{timeoutMs:5e3})).stdout.trim();return{status:"online",capabilities:{...Og("docker",e.capabilities),daemon:{status:"online",hostPlatform:yT(this.platform),...t?{serverVersion:t}:{}}}}}catch(t){return{status:"offline",capabilities:{...Og("docker",e.capabilities),daemon:{status:"offline",hostPlatform:yT(this.platform),error:t instanceof Error?t.message:String(t)}}}}}}class ET{members=new Map;constructor(e=[]){for(const t of e)this.register(t.type,t.adapter)}register(e,t){return this.members.set(e,t),this}has(e){return this.members.has(e)}types(){return[...this.members.keys()]}forRuntime(e){const t=this.members.get(e.type);if(!t)throw Object.assign(new Error(`Runtime type ${e.type} is not supported by this node agent.`),{statusCode:400,code:"NODE_RUNTIME_TYPE_UNSUPPORTED"});return t}managedAdapters(){return[...this.members.values()].filter(IT)}async stopAll(){for(const e of this.members.values())!0===e.stopOnShutdown&&await(e.stopAll?.())}}function AT(e,i,s){const r="win32"===i?[...new Set((s.PATHEXT||".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean).flatMap(e=>[e,e.toLowerCase()]))]:[""];for(const s of r){const r="win32"!==i||n.extname(e)?e:`${e}${s}`;try{if(t.accessSync(r,t.constants.X_OK),t.statSync(r).isFile())return r}catch{}}}function TT(e,t,i,s={}){const r=AT(n.join(t,i.command),i.platform,i.env);if(!r)return;const o=i.env.PATH||"";return{executable:r,resolver:e,env:{PATH:o?`${t}${n.delimiter}${o}`:t,...s}}}function bT(e,t){const n=e=>e.replace(/^v/,"").split(/[.-]/).map(e=>/^\d+$/.test(e)?Number(e):e),i=n(e),s=n(t);for(let e=0;e<Math.max(i.length,s.length);e+=1){const t=i[e]??0,n=s[e]??0;if(t!==n)return"number"==typeof t&&"number"==typeof n?n-t:String(n).localeCompare(String(t))}return 0}function wT(e,i){if(!i||n.isAbsolute(i)||i.split("/").some(e=>!e||"."===e||".."===e))return;const s=n.join(e,"alias",...i.split("/"));try{return t.readFileSync(s,"utf8").trim().split(/\s+/)[0]}catch{return}}const ST=[{id:"path",resolve(e){if(n.isAbsolute(e.command)){const t=AT(e.command,e.platform,e.env);return t?{executable:t,resolver:this.id}:void 0}if(e.explicitPath){const t=AT(n.resolve(e.cwd,e.command),e.platform,e.env);return t?{executable:t,resolver:this.id}:void 0}for(const t of(e.env.PATH||"").split(n.delimiter).filter(Boolean)){const i=AT(n.join(t,e.command),e.platform,e.env);if(i)return{executable:i,resolver:this.id}}}},{id:"nvm",resolve(e){if(e.explicitPath||"win32"===e.platform)return;const i=[];e.env.NVM_BIN&&i.push(e.env.NVM_BIN);const s=function(e){const i=n.join(e,"versions","node");try{return t.readdirSync(i,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name).sort(bT)}catch{return[]}}(e.nvmDir),r=function(e,t){let n="default";const i=new Set;for(let s=0;s<8&&n&&!i.has(n);s+=1){i.add(n);const s=wT(e,n);if(!s)break;const r=t.find(e=>e===s||e===`v${s}`);if(r)return r;if(/^(?:node|stable)$/.test(s))return t[0];if(/^v?\d+(?:\.\d+){0,2}$/.test(s)){const e=s.startsWith("v")?s:`v${s}`,n=t.find(t=>t===e||t.startsWith(`${e}.`));if(n)return n}n=s}}(e.nvmDir,s);r&&i.push(n.join(e.nvmDir,"versions","node",r,"bin"));for(const t of s)i.push(n.join(e.nvmDir,"versions","node",t,"bin"));for(const t of[...new Set(i)]){const n=TT(this.id,t,e,{NVM_BIN:t,NVM_DIR:e.nvmDir});if(n)return n}}},{id:"homebrew",resolve(e){if(!e.explicitPath&&"win32"!==e.platform)for(const t of e.homebrewBinDirectories){const n=TT(this.id,t,e);if(n)return n}}},{id:"npm-global",resolve(e){if(!e.explicitPath)for(const t of e.npmGlobalBinDirectories){const n=TT(this.id,t,e);if(n)return n}}}];function NT(e,t){const i=t.HOMEBREW_PREFIX?[n.join(t.HOMEBREW_PREFIX,"bin")]:[];return"darwin"===e&&i.push("/opt/homebrew/bin","/usr/local/bin"),"linux"===e&&i.push("/home/linuxbrew/.linuxbrew/bin"),[...new Set(i)]}function vT(e,t,i){const s=[],r=t.NPM_CONFIG_PREFIX||t.npm_config_prefix;if(r&&s.push("win32"===e?r:n.join(r,"bin")),"win32"===e){const e=t.APPDATA||(i?n.join(i,"AppData","Roaming"):void 0);e&&s.push(n.join(e,"npm"))}return[...new Set(s)]}function OT(e,t={}){const i=t.platform||process.platform;if("win32"!==i)return e;const r=e.PATHEXT?e:{...e,PATHEXT:".COM;.EXE;.BAT;.CMD"};if(function(e,t){for(const i of(e.PATH||"").split(n.delimiter).filter(Boolean))if(AT(n.join(i,"node"),t,e))return!0;return!1}(r,i))return r;const o=function(e,t={}){const i=t.platform||process.platform;if("win32"!==i)return;const r=t.homeDir||s.homedir(),o=t.nodeRuntimeDirectories||function(e,t,i){if("win32"!==e)return[];const s=t.LOCALAPPDATA||(i?n.join(i,"AppData","Local"):void 0),r=t.APPDATA||(i?n.join(i,"AppData","Roaming"):void 0),o="node.exe"===n.basename(process.execPath).toLowerCase()?n.dirname(process.execPath):void 0,a=[t.NVM_SYMLINK,t.NVM_HOME,t.TASK_HANDOFF_NODE?n.dirname(t.TASK_HANDOFF_NODE):void 0,o,t.ProgramFiles?n.join(t.ProgramFiles,"nodejs"):void 0,t["ProgramFiles(x86)"]?n.join(t["ProgramFiles(x86)"],"nodejs"):void 0,s?n.join(s,"Programs","nodejs"):void 0,s?n.join(s,"Volta","bin"):void 0,s?n.join(s,"Microsoft","WinGet","Links"):void 0,i?n.join(i,"scoop","shims"):void 0,r?n.join(r,"nvm"):void 0];return[...new Set(a.filter(e=>Boolean(e)))]}(i,e,r);for(const t of o)if(AT(n.join(t,"node"),i,e))return t}(r,{...t,platform:i});return o?{...r,PATH:r.PATH?`${o}${n.delimiter}${r.PATH}`:o}:r}function RT(e,t){return Object.assign(new Error(t),{code:e})}function zT(e,t=process.platform){return"win32"===t&&/\.(?:cmd|bat)$/i.test(e)}const xT=/[\s"&|<>^()[\]]/;const CT="task-handoff.local-process-nonce",kT=1e3,DT=1e4,LT=2e3;function PT(e,t){try{e?.(t)}catch{}}function MT(e){return e.runtime.port?`http://127.0.0.1:${e.runtime.port}`:void 0}async function jT(e,t){try{const n=await fetch(`${e}/api/internal/node-agent/process-identity`,{headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(kT)});if(!n.ok)return;const i=(await n.json()).data;if("string"!=typeof i?.instanceId||"number"!=typeof i.pid||"string"!=typeof i.processNonce)return;return{instanceId:i.instanceId,pid:i.pid,processNonce:i.processNonce,startIdentity:"string"==typeof i.startIdentity?i.startIdentity:void 0}}catch{return}}async function UT(e,t){if(B.processStartIdentity(e)!==t)return!1;try{process.kill(e,"SIGTERM")}catch{return!0}const n=Date.now()+DT;for(;Date.now()<n;){try{process.kill(e,0)}catch{return!0}await new Promise(e=>setTimeout(e,50))}try{process.kill(e,"SIGKILL")}catch{}const i=Date.now()+LT;for(;Date.now()<i;){try{process.kill(e,0)}catch{return!0}await new Promise(e=>setTimeout(e,50))}return!1}function FT(e,t){return Object.assign(new Error(t),{statusCode:503,code:"LOCAL_INSTANCE_STOP_UNCONFIRMED",instanceId:e.id})}async function $T(){const e=Number(process.env.TASK_HANDOFF_LOCAL_INSTANCE_PORT_START||19e3),t=Number.isInteger(e)&&e>0?e:19e3;for(let e=t;e<t+1e3&&e<=65535;e+=1)if(await BT(e))return e;throw Object.assign(new Error(`No free localhost port found in range ${t}-${Math.min(t+999,65535)}.`),{statusCode:503,code:"LOCAL_INSTANCE_PORT_UNAVAILABLE"})}async function HT(e){return!await function(e){return new Promise(t=>{const n=g.createConnection({host:"127.0.0.1",port:e}),i=e=>{n.removeAllListeners(),n.destroy(),t(e)};n.once("connect",()=>i(!0)),n.once("error",()=>i(!1)),n.setTimeout(250,()=>i(!1))})}(e)&&new Promise(t=>{const n=g.createServer();n.once("error",()=>t(!1)),n.listen({host:"127.0.0.1",port:e,exclusive:!0},()=>n.close(()=>t(!0)))})}const BT=HT;function qT(e,t){return null!==e.exitCode||null!==e.signalCode?Promise.resolve(!0):new Promise(n=>{const i=setTimeout(()=>{e.off("exit",s),n(null!==e.exitCode||null!==e.signalCode)},t);i.unref();const s=()=>{clearTimeout(i),n(!0)};e.once("exit",s)})}async function VT(e,t=1e4,n=2e3,i){if(await qT(e,t))return;PT(i,{stage:"graceful-timeout",pid:e.pid,timeoutMs:t});let s=!1;if(null===e.exitCode&&null===e.signalCode&&(e.kill("SIGKILL"),s=!0,PT(i,{stage:"force-signal-sent",pid:e.pid,signal:"SIGKILL"})),!await qT(e,n))throw PT(i,{stage:"force-exit-unconfirmed",pid:e.pid,signal:"SIGKILL",timeoutMs:n}),Object.assign(new Error(`Controlled instance process pid=${e.pid??"unknown"} did not exit after SIGKILL.`),{statusCode:503,code:"LOCAL_INSTANCE_PROCESS_EXIT_UNCONFIRMED",pid:e.pid});s&&PT(i,{stage:"force-exit-confirmed",pid:e.pid,signal:"SIGKILL"})}class GT{children=new Map;readyChildren=new WeakSet;expectedExits=new WeakSet;lifecycleReporters=new WeakMap;lockPath;onUnexpectedExit;onUnexpectedExitError;constructor(e,t,n){this.lockPath=e,this.onUnexpectedExit=t,this.onUnexpectedExitError=n}track(e,t,n){this.children.set(e,t),n&&this.lifecycleReporters.set(t,n),t.once("exit",(n,i)=>{if(this.release(e,t),this.readyChildren.has(t)&&!this.expectedExits.has(t)){const s={instanceId:e,pid:t.pid,code:n,signal:i},r=e=>{try{this.onUnexpectedExitError?.(e,s)}catch{}};try{Promise.resolve(this.onUnexpectedExit?.(s)).catch(r)}catch(e){r(e)}}}),t.unref()}markReady(e,t){return this.children.get(e)===t&&null===t.exitCode&&null===t.signalCode&&(this.readyChildren.add(t),!0)}release(e,t){this.children.get(e)===t&&this.children.delete(e)}async stop(e){const t=this.children.get(e.id);if(t){this.expectedExits.add(t);const n=this.lifecycleReporters.get(t);return t.killed||(t.kill("SIGTERM"),PT(n,{stage:"graceful-signal-sent",pid:t.pid,signal:"SIGTERM"})),this.children.delete(e.id),void await VT(t,DT,LT,n)}const i=await async function(e){const t=MT(e),n=e.runtime.labels?.[CT];if(!t||!n||!e.registrationToken)return;const i=await jT(t,e.registrationToken);if(i&&i.instanceId===e.id&&i.processNonce===n)try{return(await fetch(`${t}/api/internal/node-agent/shutdown`,{method:"POST",headers:{authorization:`Bearer ${e.registrationToken}`},signal:AbortSignal.timeout(kT)})).ok?i:void 0}catch{return}}(e);if(i){const t=MT(e),n=Date.now()+DT;for(;t&&Date.now()<n;){if(!await jT(t,e.registrationToken))return;await new Promise(e=>setTimeout(e,50))}const s=t?await jT(t,e.registrationToken):void 0;if(s&&s.instanceId===i.instanceId&&s.pid===i.pid&&s.processNonce===i.processNonce&&s.startIdentity===i.startIdentity&&s.startIdentity&&await UT(s.pid,s.startIdentity))return;throw FT(e,`Controlled instance ${e.id} accepted shutdown but its exit could not be confirmed.`)}const r=function(e=function(){const e="win32"===process.platform?s.tmpdir():"/tmp";return n.join(e,`task-handoff-local-controlled-instance-${function(){const e=process.getuid?.();return void 0!==e?String(e):s.userInfo().username.replace(/[^a-zA-Z0-9_.-]/g,"_")}()}.lock`)}()){return Y(e)}(this.lockPath),o=await async function(e){const t=MT(e);if(t)try{const[n,i]=await Promise.all([fetch(`${t}/api/instance/status`,{signal:AbortSignal.timeout(kT)}),fetch(`${t}/api/diagnostics`,{signal:AbortSignal.timeout(kT)})]);if(!n.ok||!i.ok)return;const s=await n.json(),r=await i.json(),o=r.data?.runtime?.pid;if(s.data?.id!==e.id||"controlled"!==s.data.controlMode||"number"!=typeof o||!Number.isInteger(o)||o<=0)return;const a=B.processStartIdentity(o);return a?{pid:o,startIdentity:a}:void 0}catch{return}}(e);if(o){if(await UT(o.pid,o.startIdentity))return;throw FT(e,`Legacy controlled instance ${e.id} did not exit after termination.`)}if(r?.instanceId===e.id&&Q(r))throw FT(e,`Local controlled instance ${e.id} is still owned by pid ${r.pid}, but its process identity could not be verified.`)}async waitUntilHealthy(e,t,n,i,s=function(e=process.env.TASK_HANDOFF_LOCAL_PROCESS_READY_TIMEOUT_MS){const t=Number(e);return Number.isFinite(t)&&t>0?t:3e4}()){const r=Date.now()+s;for(;Date.now()<r;){if(null!==n.exitCode||null!==n.signalCode)return!1;const s=await jT(e,i);if(s&&s.instanceId===t.instanceId&&s.pid===t.pid&&s.processNonce===t.processNonce&&s.startIdentity===t.startIdentity)return!0;await new Promise(e=>setTimeout(e,100))}return!1}async isRunning(e){const t=this.children.get(e.id);if(t&&null===t.exitCode&&null===t.signalCode)return!0;const n=MT(e);return!(!n||!e.registrationToken)&&Boolean(await jT(n,e.registrationToken))}async stopAll(){const e=Array.from(this.children.values());for(const t of e){this.expectedExits.add(t);const e=this.lifecycleReporters.get(t);t.killed||(t.kill("SIGTERM"),PT(e,{stage:"graceful-signal-sent",pid:t.pid,signal:"SIGTERM"}))}this.children.clear(),await Promise.all(e.map(e=>VT(e,DT,LT,this.lifecycleReporters.get(e))))}}function WT(){const e=process.env.TASK_HANDOFF_LOCAL_CONTROLLED_COMMAND_ARGV?.trim();if(!e){const e=process.env.TASK_HANDOFF_LOCAL_CONTROLLED_COMMAND?.trim();return e?e.split(/\s+/):void 0}let t;try{t=JSON.parse(e)}catch{throw Object.assign(new Error("TASK_HANDOFF_LOCAL_CONTROLLED_COMMAND_ARGV must be valid JSON."),{code:"LOCAL_CONTROLLED_COMMAND_INVALID"})}if(!Array.isArray(t)||!t.length||t.some(e=>"string"!=typeof e||!e))throw Object.assign(new Error("TASK_HANDOFF_LOCAL_CONTROLLED_COMMAND_ARGV must be a non-empty string array."),{code:"LOCAL_CONTROLLED_COMMAND_INVALID"});return t}async function KT(e,t){try{const i=function(e,t=[],i={}){const r=i.env||process.env,o=i.platform||process.platform,a=function(e,t={}){const i=t.env||process.env,r=t.platform||process.platform,o=t.homeDir||s.homedir(),a={command:e,env:i,cwd:t.cwd||process.cwd(),platform:r,homeDir:o,nvmDir:t.nvmDir||i.NVM_DIR||n.join(o,".nvm"),homebrewBinDirectories:t.homebrewBinDirectories||NT(r,i),npmGlobalBinDirectories:t.npmGlobalBinDirectories||vT(r,i,o),explicitPath:n.isAbsolute(e)||e.includes("/")||e.includes("\\")};for(const e of t.resolvers||ST){const t=e.resolve(a);if(t)return t}}(e,i),c=!a&&!0===i.win32ShimWhenUnresolved&&"win32"===o&&!zT(e,o)&&""===n.win32.extname(e),d=a?.executable||(c?`${e}.cmd`:e),l={...r,...a?.env||{}};if(!zT(d,o))return{executable:d,args:[...t],env:l,interpreterWrapped:!1};const u=OT(l,{...i,env:l,platform:o});return{executable:u.ComSpec||"cmd.exe",args:["/d","/s","/c","call",d,...t.map(e=>function(e){if(/[\0\r\n]/.test(e))throw RT("COMMAND_ARGUMENT_INVALID","Command arguments must not contain NUL or line breaks.");if(e.includes("%"))throw RT("COMMAND_ARGUMENT_UNSUPPORTED","cmd.exe expands '%' even inside quotes, so this argument cannot be passed through a .cmd/.bat shim safely.");return""===e?'""':xT.test(e)?`"${e.replace(/"/g,'\\"')}"`:e}(e))],env:u,interpreterWrapped:!0}}(t,["--version"]),r=i.interpreterWrapped?await e(i.executable,i.args,{env:i.env}):await e(t,["--version"]);return{available:!0,command:t,version:(r.stdout||r.stderr).split(/\r?\n/)[0]?.trim()||void 0}}catch{return{available:!1}}}class YT{stopOnShutdown=!0;runCommand;paths;nodeAgentUrl;processSupervisor;async resolveInstanceWeb(e){const t=e.instance.runtime.port;if(!t)throw Object.assign(new Error(`Instance ${e.instance.id} does not have a node-owned local runtime port.`),{statusCode:409,code:"INSTANCE_RUNTIME_ENDPOINT_UNAVAILABLE"});return`http://127.0.0.1:${t}`}async runtimeState(e){try{return await this.processSupervisor.isRunning(e.instance)?"running":"stopped"}catch{return"unknown"}}commandOverride;lockPath;constructor(e,t,n,i,s,r,o){this.runCommand=e,this.paths=t,this.nodeAgentUrl=n,this.commandOverride=i,this.lockPath=s,this.processSupervisor=new GT(s,r,o)}async start(e){await this.processSupervisor.stop(e.instance);const i=function(e){if("local-folder"!==e.source.type){const e=new Error("Localhost runtime currently supports local folder sources only.");throw Object.assign(e,{statusCode:400,code:"LOCAL_RUNTIME_REQUIRES_LOCAL_FOLDER"}),e}return n.resolve(e.source.path)}(e.instance),s=e.instance.runtime.port,r=!!s&&await HT(s),o="allocate"===process.env.TASK_HANDOFF_LOCAL_INSTANCE_PORT_CONFLICT;if(s&&!r&&!o)throw Object.assign(new Error(`Local controlled instance port 127.0.0.1:${s} is already in use.`),{statusCode:409,code:"LOCAL_INSTANCE_PORT_IN_USE"});const a=s&&r?s:await $T(),c=n.join(this.paths.dataDir,"local-instances",e.instance.id),u=n.join(c,"logs"),p=(e.instance.config?.codexConfigEnabled??1)&&"taskhandoff"===(e.instance.config?.codexHomeMode??"taskhandoff")?n.join(c,"configs","codex"):void 0;t.mkdirSync(u,{recursive:!0,mode:448}),p&&t.mkdirSync(p,{recursive:!0,mode:448}),Yf(c,448),Yf(u,448),p&&Yf(p,448);const[m,...h]=function(e){if(e)return e;const i=n.resolve(process.cwd(),"bin","task-handoff.js");if(t.existsSync(i))return[process.execPath,i,"web"];throw Object.assign(new Error("The bundled controlled-instance command is unavailable."),{statusCode:500,code:"LOCAL_CONTROLLED_COMMAND_MISSING"})}(this.commandOverride),g=[...h,"--host","127.0.0.1","--port",String(a)],f=d.randomUUID(),y=n.join(u,"controlled-instance.out.log"),I=n.join(u,"controlled-instance.err.log");Cl(y),Cl(I);const _=function(e){const i=e.platform??process.platform,s=e.kind??"host-ipc",r=e.directoryName??Kf(e.scope,e.key??d.randomUUID(),e.keyHashLength??12),o=Vf(s,i);if("named-pipe"===o)return{endpoint:{path:`\\\\.\\pipe\\${r}-${d.randomBytes(6).toString("hex")}`,transport:o,kind:s,platform:i,filesystemBacked:!1}};const a=e.rootDir||Wf(i,e.temporaryDirectory),c=t.mkdtempSync(n.join(a,`${r}-`));return{endpoint:{path:n.join(c,e.fileName??"ipc.sock"),transport:o,kind:s,platform:i,filesystemBacked:!0},directory:c}}({scope:"th-git",key:e.instance.id,keyHashLength:12,fileName:"broker.sock"});_.directory&&Yf(_.directory,448);const E=()=>{var e;(e=_.endpoint).filesystemBacked&&function(e){try{t.unlinkSync(e)}catch(e){if("ENOENT"!==e.code)throw e}}(e.path),_.directory&&t.rmSync(_.directory,{recursive:!0,force:!0})},A=t.openSync(y,"a",384),T=t.openSync(I,"a",384),b=l.spawn(m,g,{cwd:i,detached:!1,stdio:["ignore",A,T],env:{...process.env,TASK_HANDOFF_CONTROL_MODE:"controlled",TASK_HANDOFF_RUNTIME_KIND:"local",TASK_HANDOFF_CONTROLLED_INSTANCE_VERSION:Tg(),...this.lockPath?{TASK_HANDOFF_LOCAL_CONTROLLED_INSTANCE_LOCK_PATH:this.lockPath}:{},TASK_HANDOFF_NODE_AGENT_URL:this.nodeAgentUrl(),TASK_HANDOFF_INSTANCE_ID:e.instance.id,TASK_HANDOFF_INSTANCE_NAME:e.instance.name,TASK_HANDOFF_REGISTRATION_TOKEN:e.instance.registrationToken||"",TASK_HANDOFF_PROJECT_ID:e.project.id,TASK_HANDOFF_NODE_ID:e.node.id,TASK_HANDOFF_RUNTIME_ID:e.runtime.id,TASK_HANDOFF_LOCAL_PROCESS_NONCE:f,TASK_HANDOFF_WORKSPACE:i,TASK_HANDOFF_WORKSPACE_MODE:"local-bind",TASK_HANDOFF_DATA_DIR:c,TASK_HANDOFF_INSTANCE_PRIVATE_CONFIG_PATH:e.privateConfigPath||"",TASK_HANDOFF_LOG_DIR:u,TASK_HANDOFF_APP_SESSION_PERSIST:"1",TASK_HANDOFF_CODEX_APP_SERVER:process.env.TASK_HANDOFF_CODEX_APP_SERVER||"1",TASK_HANDOFF_WEB_PORT:String(a),TASK_HANDOFF_WEB_HOST:"127.0.0.1",TASK_HANDOFF_GIT_CREDENTIAL_SOCKET:_.endpoint.path,...e.modelEnv||{},CODEX_HOME:p}});t.closeSync(A),t.closeSync(T);try{await function(e){return new Promise((t,n)=>{const i=()=>{e.off("error",s),t()},s=t=>{e.off("spawn",i),n(t)};e.once("spawn",i),e.once("error",s)})}(b)}catch(e){E();const s=e instanceof Error?e.message:String(e);try{t.appendFileSync(n.join(u,"controlled-instance.lifecycle.log"),`[${(new Date).toISOString()}] spawn failed command=${m} cwd=${i} error=${s}\n`)}catch{}throw Object.assign(new Error(`Controlled instance process could not start with command ${m} in ${i}: ${s}`),{statusCode:500,code:"LOCAL_INSTANCE_PROCESS_SPAWN_FAILED"})}const w=n.join(u,"controlled-instance.lifecycle.log");this.processSupervisor.track(e.instance.id,b,e=>{t.appendFileSync(w,`[${(new Date).toISOString()}] shutdown stage=${e.stage} pid=${e.pid??""} signal=${e.signal??""} timeoutMs=${e.timeoutMs??""}\n`)}),b.on("error",e=>{try{t.appendFileSync(w,`[${(new Date).toISOString()}] process error pid=${b.pid??""} error=${e.message}\n`)}catch{}}),b.once("exit",(e,n)=>{E();try{t.appendFileSync(w,`[${(new Date).toISOString()}] exited pid=${b.pid??""} code=${e??""} signal=${n??""}\n`)}catch{}});const S=`http://127.0.0.1:${a}`,N=b.pid?B.processStartIdentity(b.pid):void 0;if(!(b.pid&&e.instance.registrationToken&&await this.processSupervisor.waitUntilHealthy(S,{instanceId:e.instance.id,pid:b.pid,processNonce:f,startIdentity:N},b,e.instance.registrationToken)&&this.processSupervisor.markReady(e.instance.id,b)))throw this.processSupervisor.release(e.instance.id,b),null===b.exitCode&&null===b.signalCode&&b.kill("SIGTERM"),await VT(b),Object.assign(new Error(`Controlled instance process did not become ready for instance ${e.instance.id} on ${S}.`),{statusCode:503,code:"LOCAL_INSTANCE_PROCESS_NOT_READY"});return{status:"registering",health:"unknown",connectionStatus:"online",agentStatus:"unknown",targetStatus:"unknown",uiAccessStatus:"unknown",target:{strategy:"direct-port",status:"unknown",web:S,api:`${S}/api`},workspace:{mode:"local-bind",status:"pending",path:i},runtime:{kind:"local",workspacePath:i,pid:b.pid,port:a,labels:{...e.instance.runtime.labels,"task-handoff.runtime-kind":"local",[CT]:f}}}}async stop(e){return await this.processSupervisor.stop(e.instance),{status:"stopped",health:"unknown",connectionStatus:"offline",agentStatus:"offline",targetStatus:"unknown",uiAccessStatus:"unknown",target:{...e.instance.target,status:"unknown"},runtime:e.instance.runtime}}async restart(e){return this.start(e)}async delete(e,t){return await this.stop(e),qs.parse({instanceId:e.instance.id,containerDeleted:!0,completed:!0,deletedVolumes:[],retainedVolumes:[],volumeResults:[]})}async check(e){const[t,n]=await Promise.all([KT(this.runCommand,"codex"),KT(this.runCommand,"claude")]);return{status:"online",capabilities:Bg({...e.capabilities,apps:{terminal:!0,codex:t,claude:n}})}}async stopAll(){await this.processSupervisor.stopAll()}}const XT="th-wsl-",JT=["sh","-c","while true; do sleep 30; done"],QT="WSL_COMMAND_FAILED",ZT="WSL_RUNTIME_UNSUPPORTED_PLATFORM";function eb(e,t,n){return Object.assign(new Error(t),{code:e,...n?{details:n}:{}})}function tb(e){return`'${e.replace(/'/g,"'\\''")}'`}function nb(e){const t=e.trim();if(!t)throw eb("WSL_INSTANCE_ID_INVALID","Instance id is required to derive a WSL distro name.");const n=d.createHash("sha256").update(t).digest("hex").slice(0,8),i=`-${n}`,s=function(e){return e.trim().toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}(t).slice(0,121-i.length);return`${XT}${s?`${s}${i}`:n}`}function ib(e,t){return"utf8"===t?e.toString("utf8"):"utf16le"===t?(e.length>=2&&255===e[0]&&254===e[1]?e.subarray(2):e).toString("utf16le"):function(e){if(e.length>=2&&255===e[0]&&254===e[1])return e.subarray(2).toString("utf16le");const t=e.subarray(0,Math.min(e.length,1024));let n=0,i=0;for(let e=0;e<t.length;e+=1)0===t[e]&&(e%2==1?n+=1:i+=1);return 0===n&&0===i?e.toString("utf8"):n>i?e.toString("utf16le"):e.toString("utf8")}(e)}class sb{wslPath;runner;spawnSession;platform;commandTimeoutMs;sessionCommand;sessions=new Map;constructor(e={}){this.wslPath=e.wslPath??function(e=process.env){const t=e.SystemRoot?.trim()||e.windir?.trim()||"C:\\Windows";return n.win32.join(t,"System32","wsl.exe")}(),this.runner=e.runner??function(e,n=l.spawn){return(i,s={})=>new Promise((r,o)=>{if(s.signal?.aborted)return void o(eb(QT,`${e} ${i.join(" ")} was aborted.`));const a=n(e,i,{stdio:[s.stdinFile?"pipe":"ignore","pipe","pipe"],windowsHide:!0}),c=[],d=[];let l=!1,u=!1;const p=s.timeoutMs??3e4,m=setTimeout(()=>{l=!0,a.kill("SIGKILL")},p),h=()=>{u=!0,a.kill("SIGKILL")};s.signal?.addEventListener("abort",h,{once:!0});const g=()=>{clearTimeout(m),s.signal?.removeEventListener("abort",h)};if(m.unref?.(),a.stdout?.on("data",e=>c.push(Buffer.from(e))),a.stderr?.on("data",e=>d.push(Buffer.from(e))),s.stdinFile&&a.stdin){const n=t.createReadStream(s.stdinFile);n.on("error",t=>{a.stdin?.destroy(),g(),o(eb(QT,`${e} could not read stdin file ${s.stdinFile}: ${t.message}`,{args:i}))}),n.pipe(a.stdin)}a.on("error",t=>{g(),o(eb(QT,`${e} could not be started: ${t.message}`,{args:i}))}),a.on("close",t=>{g();const n={stdout:ib(Buffer.concat(c),s.decode??"auto").trim(),stderr:ib(Buffer.concat(d),s.decode??"auto").trim(),exitCode:t??-1};l?o(eb(QT,`${e} ${i.join(" ")} timed out after ${p}ms`,{...n,args:i,timeoutMs:p})):u?o(eb(QT,`${e} ${i.join(" ")} was aborted.`,{...n,args:i})):r(n)})})}(this.wslPath),this.spawnSession=e.sessionSpawner??function(e,t=l.spawn){return(n,i)=>{const s=t(e,n,{stdio:["ignore","pipe","pipe"],windowsHide:!0});let r=!1;return s.stdout?.on("data",()=>{}),s.stderr?.on("data",()=>{}),s.on("error",()=>{r=!0}),s.unref?.(),{name:i,pid:s.pid,alive:()=>!r&&null===s.exitCode&&!s.killed,stop:()=>new Promise(e=>{if(r=!0,null!==s.exitCode)return void e();const t=()=>e();s.once("close",t),s.kill();const n=setTimeout(t,5e3);n.unref?.()})}}}(this.wslPath),this.platform=e.platform??process.platform,this.commandTimeoutMs=e.commandTimeoutMs??3e4,this.sessionCommand=e.sessionCommand??JT}get executablePath(){return this.wslPath}async run(e,t={}){if("win32"!==this.platform)throw eb(ZT,"The WSL runtime is available only on Windows nodes.",{platform:this.platform,args:e});return this.runner(e,{timeoutMs:this.commandTimeoutMs,...t})}async runOrThrow(e,t={},n){const i=await this.run(e,t);if(0!==i.exitCode)throw eb(QT,n??`wsl.exe ${e.join(" ")} failed with exit code ${i.exitCode}.`,{args:e,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr});return i}async version(){return(await this.runOrThrow(["--version"])).stdout}async available(){try{return await this.version(),!0}catch{return!1}}async listDistros(){return function(e){const t=[];for(const n of e.split(/\r?\n/)){const e=n.replace(/\0/g,"").trimEnd();if(!e.trim())continue;const i=/^(\*?)\s*(.+?)\s+(Running|Stopped|Installing|Uninstalling)\s+(\d+)\s*$/i.exec(e);i&&t.push({isDefault:"*"===i[1],name:i[2].trim(),state:`${i[3][0].toUpperCase()}${i[3].slice(1).toLowerCase()}`,version:Number(i[4])})}return t}((await this.runOrThrow(["--list","--verbose"],{decode:"auto"})).stdout)}async findDistro(e){return(await this.listDistros()).find(t=>t.name===e)}async distroState(e){const t=await this.findDistro(e);return t?"Running"===t.state?"running":"Stopped"===t.state?"stopped":"unknown":"absent"}async importDistro(e){return await this.runOrThrow(["--import",e.name,e.installDir,e.tarballPath,"--version",String(e.version??2)]),this.findDistro(e.name)}async terminate(e){await this.runOrThrow(["--terminate",e])}async unregister(e){await this.runOrThrow(["--unregister",e])}async exec(e,t,n={}){if(!t.length)throw eb(QT,"A command is required to exec inside a WSL distro.",{name:e});return this.run(["-d",e,"-u","root","--",...t],{decode:"utf8",...n})}async execOrThrow(e,t,n={}){const i=await this.exec(e,t,n);if(0!==i.exitCode)throw eb(QT,`wsl.exe -d ${e} -- ${t.join(" ")} failed with exit code ${i.exitCode}.`,{args:["-d",e,"-u","root","--",...t],exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr});return i}async execStream(e,t,n={}){if("win32"!==this.platform)throw eb(ZT,"The WSL runtime is available only on Windows nodes.",{platform:this.platform,args:t});if(!t.length)throw eb(QT,"A command is required to exec inside a WSL distro.",{name:e});const i=["-d",e,"-u","root","--",...t],s=l.spawn(this.wslPath,i,{stdio:["ignore","pipe","pipe"],windowsHide:!0}),r=[],o=[],a=n.timeoutMs??this.commandTimeoutMs;let c=!1;const d=setTimeout(()=>{c=!0,s.kill("SIGKILL")},a);d.unref?.();const u=()=>s.kill("SIGKILL");n.signal?.addEventListener("abort",u,{once:!0}),s.stdout?.on("data",e=>{r.push(Buffer.from(e)),n.onData?.(e.toString("utf8"))}),s.stderr?.on("data",e=>{o.push(Buffer.from(e)),n.onData?.(e.toString("utf8"))});const p=await new Promise((e,t)=>{s.on("error",e=>t(eb(QT,`${this.wslPath} could not be started: ${e.message}`,{args:i}))),s.on("close",t=>e(t??-1))}).finally(()=>{clearTimeout(d),n.signal?.removeEventListener("abort",u)}),m={stdout:Buffer.concat(r).toString("utf8").trim(),stderr:Buffer.concat(o).toString("utf8").trim(),exitCode:p};if(c)throw eb(QT,`${this.wslPath} ${i.join(" ")} timed out after ${a}ms`,{...m,args:i,timeoutMs:a});return m}async systemctl(e,t){return this.execOrThrow(e,["systemctl",...t])}static windowsPathToDrvfs(e){const t=/^([a-zA-Z]):[\\/](.*)$/.exec(e.trim());if(t)return`/mnt/${t[1].toLowerCase()}/${t[2].replace(/\\/g,"/")}`}async copyIntoDistro(e,t,i,s={}){const r=n.posix.dirname(i);await this.execOrThrow(e,["sh","-c",`mkdir -p ${tb(r)} && cat > ${tb(i)}`],{...s,stdinFile:t})}async defaultGateway(e){return function(e){for(const t of e.split("\n").slice(1)){const e=t.trim().split(/\s+/);if(e.length<3||"00000000"!==e[1]||!/^[0-9a-fA-F]{8}$/.test(e[2]))continue;const n=e[2];return[n.slice(6,8),n.slice(4,6),n.slice(2,4),n.slice(0,2)].map(e=>parseInt(e,16)).join(".")}}((await this.exec(e,["cat","/proc/net/route"])).stdout)}async unitActive(e,t){return(await this.exec(e,["systemctl","is-active",t])).stdout.split(/\s+/)[0]||"unknown"}async ensureDistroRunning(e,t={}){const n=Date.now()+(t.timeoutMs??6e4),i=await this.distroState(e);if("absent"===i)throw eb("WSL_DISTRO_MISSING",`WSL distro ${e} does not exist on this node.`,{name:e});if("running"===i)return"running";await this.exec(e,["true"]);const s=t.intervalMs??500;for(;Date.now()<n;){if("running"===await this.distroState(e))return"running";await new Promise(e=>setTimeout(e,s))}throw eb(QT,`WSL distro ${e} did not reach Running within the timeout.`,{name:e})}sessionAlive(e){const t=this.sessions.get(e);return!(!t||!t.alive()&&(this.sessions.delete(e),1))}async holdSession(e){if(this.sessionAlive(e))return this.sessions.get(e);const t=this.spawnSession(["-d",e,"-u","root","--",...this.sessionCommand],e);this.sessions.set(e,t);try{await this.ensureDistroRunning(e)}catch(t){throw await this.releaseSession(e).catch(()=>{}),eb("WSL_SESSION_FAILED",`Could not hold a keep-alive session for WSL distro ${e}.`,{name:e,cause:t instanceof Error?t.message:String(t)})}return t}async releaseSession(e){const t=this.sessions.get(e);this.sessions.delete(e),t&&await t.stop()}async releaseAllSessions(){const e=[...this.sessions.keys()];await Promise.all(e.map(e=>this.releaseSession(e).catch(()=>{})))}}function rb(e,t){const n=e.trim();if(!n)throw new Error("A node agent URL is required.");if(/^https?:\/\//i.test(n))return new URL(n).origin;const i=/^([^:/]+)(?::(\d+))?$/.exec(n);if(!i)throw new Error(`Node agent address ${e} is not a valid host[:port] or URL.`);const s=i[2]?Number(i[2]):t;return`http://${i[1]}:${s}`}const ob="/opt/task-handoff/instance-runtime",ab="/opt/task-handoff/bootstrap/runtime-installer.mjs",cb="/run/task-handoff/runtime-artifact.tar.gz";function db(e){return`'${e.replace(/'/g,"'\\''")}'`}const lb="/opt/task-handoff/bootstrap",ub=`${lb}/entrypoint.sh`,pb="/run/task-handoff/private",mb=`${pb}/${dc}`,hb="task-handoff-instance.service",gb=`/etc/systemd/system/${hb}`,fb="/workspace",yb="/var/lib/task-handoff/bootstrap-revision",Ib=["const url = process.argv[1];","const controller = new AbortController();","const timer = setTimeout(() => controller.abort(), 2000);","fetch(`${url}/api/node-agent/health`, { signal: controller.signal }).then(async (response) => {"," const body = await response.json().catch(() => undefined);"," clearTimeout(timer);"," const health = response.ok && body && body.data && body.data.role === 'node-agent';"," const code = body && body.error && typeof body.error.code === 'string' ? body.error.code : '';"," process.exit(health || code.startsWith('NODE_AGENT_') ? 0 : 2);","}).catch((error) => { clearTimeout(timer); console.error(String(error && error.message || error)); process.exit(1); });"].join(" "),_b="WSL_LIFECYCLE_FAILED",Eb="WSL_WORKSPACE_UNSUPPORTED";function Ab(e,t,n){return Object.assign(new Error(t),{code:e,...n?{details:n}:{}})}function Tb(e){return d.createHash("sha256").update(t.readFileSync(e)).digest("hex")}class bb{provisioner;executor;options;constructor(e){this.options=e,this.provisioner=e.provisioner,this.executor=e.executor}distroNameFor(e){return this.provisioner.distroNameForInstance({id:e.id,containerName:e.runtime.containerName})}async provision(e){return this.provisioner.provision({id:e.id,runtimeId:e.runtimeId,containerName:e.runtime.containerName})}sessionAlive(e){const t=this.executor;return"function"==typeof t.sessionAlive&&t.sessionAlive(e)}async nodeAgentUrlCandidates(e,t){const n=this.options.hostAddress?.trim()||process.env.TASK_HANDOFF_WSL_NODE_AGENT_URL?.trim();if(n)return[{url:rb(n,this.options.listenerPort),source:"explicit"}];const i=[{url:`http://127.0.0.1:${this.options.listenerPort}`,source:"loopback"}],s=await this.executor.defaultGateway(t).catch(()=>{});return s&&i.push({url:`http://${s}:${this.options.listenerPort}`,source:"gateway"}),this.options.fallbackNodeAgentUrl&&i.push({url:this.options.fallbackNodeAgentUrl,source:"fallback"}),i}async nodeAgentUrl(e,t){const n=await this.nodeAgentUrlCandidates(e,t),i=this.options.probeNodeAgent??((e,t)=>this.probeNodeAgentUrl(e,t)),s=Math.max(1,this.options.probeAttempts??2),r=[];for(const o of n)for(let n=0;n<s;n+=1){n>0&&await new Promise(e=>setTimeout(e,250));const s=await i(t,o.url).catch(e=>({reachable:!1,detail:e instanceof Error?e.message:String(e)}));if(s.reachable)return this.options.logger?.("wsl node agent url resolved",{instanceId:e.instance.id,distroName:t,url:o.url,source:o.source,attempt:n}),o.url;r.push({url:o.url,source:o.source,reason:s.detail??"unreachable"})}const o=this.options.listenerHost?.()??"127.0.0.1";throw Ab("WSL_NODE_AGENT_UNREACHABLE",`No node agent address is reachable from WSL distro ${t} for instance ${e.instance.id}.`,{distroName:t,instanceId:e.instance.id,listenerHost:o,listenerPort:this.options.listenerPort,candidates:r,remediation:[`Windows blocks the distro-to-host direction by default: the vEthernet (WSL) adapter is an unidentified network (Public profile, inbound dropped) and the WSL Hyper-V firewall filters WSL traffic too, so binding the listener beyond loopback is not enough on its own. Enable WSL2 mirrored networking so the distro shares the host loopback (no administrator rights needed), or allow inbound TCP ${this.options.listenerPort} from the WSL subnet in Windows Firewall and set the node agent external listener bind scope to "all-ipv4" (currently ${o}).`,"Alternatively set TASK_HANDOFF_WSL_NODE_AGENT_URL to an address the distro can already reach.","See docs/wsl-runtime.md, section Node agent reachability, for the measured setup steps."]})}async probeNodeAgentUrl(e,t){const n=await this.executor.exec(e,["node","-e",Ib,t],{timeoutMs:5e3});if(0===n.exitCode)return{reachable:!0};const i=n.stderr.trim();return 127===n.exitCode?{reachable:!1,detail:`the distro could not run node for the reachability probe: ${i||"command not found"}`}:{reachable:!1,detail:i.split("\n").map(e=>e.trim()).filter(Boolean).pop()||n.stdout.trim()||`probe exited with code ${n.exitCode}`}}async syncBootstrapAssets(e){const i=this.options.bootstrapDir;if(!i||!t.existsSync(i))return;const s=function(e){const i=d.createHash("sha256"),s=t.existsSync(e)?t.readdirSync(e,{withFileTypes:!0}).filter(e=>e.isFile()).sort((e,t)=>e.name.localeCompare(t.name)):[];for(const t of s){const s=n.join(e,t.name);i.update(t.name),i.update("\0"),i.update(Tb(s)),i.update("\0")}return i.digest("hex")}(i),r=await this.executor.exec(e,["cat",yb]);if(0!==r.exitCode||r.stdout.trim()!==s){await this.executor.execOrThrow(e,["sh","-c",`mkdir -p ${lb}`]);for(const s of t.readdirSync(i,{withFileTypes:!0}))s.isFile()&&await this.executor.copyIntoDistro(e,n.join(i,s.name),`${lb}/${s.name}`);await this.executor.execOrThrow(e,["sh","-c",`chmod 0755 ${lb}/*.sh ${lb}/*.mjs 2>/dev/null || true`]),await this.executor.execOrThrow(e,["sh","-c",`mkdir -p ${n.posix.dirname(yb)} && printf '%s' ${wb(s)} > ${yb}`]),this.options.logger?.("wsl bootstrap assets synchronized",{distroName:e,revision:s,bootstrapDir:i})}}async syncPrivateConfig(e,n){e.privateConfigPath&&t.existsSync(e.privateConfigPath)&&(await this.executor.execOrThrow(n,["sh","-c",`mkdir -p ${pb} && chmod 0700 ${pb}`]),await this.executor.copyIntoDistro(n,e.privateConfigPath,mb),await this.executor.execOrThrow(n,["sh","-c",`chmod 0600 ${mb}`]))}async installRuntime(e,t){await async function(e,t,n){await e.copyIntoDistro(t,n.archivePath,cb),await e.execOrThrow(t,["sh","-c",`install -d -m 0755 ${ob} ${ob}/releases ${ob}/staging ${ob}/incoming && node ${ab} install --artifact ${cb} --version ${db(n.identity.version)} --sha256 ${db(n.identity.sha256)} --platform ${db(n.identity.platform)} --arch ${db(n.identity.arch)} --launcher-abi ${String(n.identity.launcherAbi)}`])}(this.executor,e,t)}async inspectRuntime(e,t){return async function(e,t,n){const i=await e.exec(t,["node",ab,"verify-active"]);if(0!==i.exitCode)return!1;let s;try{s=JSON.parse(i.stdout)}catch{return!1}return function(e,t){return e.packageName===t.packageName&&e.version===t.version&&e.platform===t.platform&&e.arch===t.arch&&e.formatVersion===t.formatVersion&&e.launcherAbi===t.launcherAbi&&e.entrypoint===t.entrypoint&&e.sha256===t.sha256}(s,n)}(this.executor,e,t)}artifactTarget(){return{platform:"linux",arch:this.options.hostArch??process.arch,launcherAbi:1}}async allocatePort(){return this.options.allocatePort?this.options.allocatePort():$T()}async writeUnit(e,t,n,i){const s=function(e,t){const n=Object.entries(e).filter(([,e])=>"string"==typeof e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`Environment="${e}=${function(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/%/g,"%%")}(t)}"`);return["[Unit]",`Description=${t.description}`,"After=network-online.target","Wants=network-online.target","","[Service]","Type=simple",`WorkingDirectory=${t.workspace}`,...n,`ExecStart=/bin/bash ${ub} task-handoff web`,"Restart=no","KillMode=mixed","TimeoutStopSec=20","","[Install]","WantedBy=multi-user.target",""].join("\n")}(t,{workspace:n,description:`Task Handoff controlled instance ${i}`}),r=Buffer.from(s,"utf8").toString("base64");await this.executor.execOrThrow(e,["sh","-c",`printf '%s' ${wb(r)} | base64 -d > ${gb}`])}async waitForUnitActive(e){const t=Date.now()+(this.options.unitReadyTimeoutMs??3e4),n=this.options.pollIntervalMs??500;for(;Date.now()<t;){const t=await this.executor.unitActive(e,hb).catch(()=>"unknown");if("active"===t)return"active";if("failed"===t)throw Ab(_b,`systemd unit ${hb} failed to start in WSL distro ${e}.`,{distroName:e});await new Promise(e=>setTimeout(e,n))}const i=await this.executor.unitActive(e,hb).catch(()=>"unknown");if("active"===i)return"active";throw Ab(_b,`systemd unit ${hb} did not become active in WSL distro ${e} within the timeout.`,{distroName:e,state:i})}async start(e){const t=this.distroNameFor(e.instance),n=await this.provisioner.provision({id:e.instance.id,runtimeId:e.instance.runtimeId,containerName:e.instance.runtime.containerName}),i=await this.prepareWorkspace(e,t);await this.syncBootstrapAssets(t),await this.syncPrivateConfig(e,t),await this.executor.holdSession(t);const s=e.instance.runtime.port??await this.allocatePort(),r=await this.nodeAgentUrl(e,t),o=function(e,t){const n=e.instance.imageSelection,i={TASK_HANDOFF_CONTROL_MODE:"controlled",TASK_HANDOFF_NODE_AGENT_URL:t.nodeAgentUrl,TASK_HANDOFF_INSTANCE_ID:e.instance.id,TASK_HANDOFF_INSTANCE_NAME:e.instance.name,TASK_HANDOFF_PROJECT_ID:e.project.id,TASK_HANDOFF_NODE_ID:e.node?.id||"node_unset",TASK_HANDOFF_RUNTIME_ID:e.runtime?.id||"runtime_wsl_host",TASK_HANDOFF_RUNTIME_KIND:"wsl",...n?{TASK_HANDOFF_IMAGE_ID:n.imageId}:{},TASK_HANDOFF_INSTANCE_LAUNCHER:`${lb}/instance-launcher.sh`,TASK_HANDOFF_CHAT_BRIDGES:"none",TASK_HANDOFF_WEB_PORT:String(t.port),TASK_HANDOFF_WEB_HOST:"127.0.0.1",TASK_HANDOFF_WORKSPACE:t.workspace,TASK_HANDOFF_WORKSPACE_MODE:e.project.workspacePolicy.mode,TASK_HANDOFF_INSTANCE_PRIVATE_CONFIG_PATH:mb,...n?.tag?{TASK_HANDOFF_IMAGE_TAG:n.tag}:{},..."local-folder"===e.project.source.type?{}:{TASK_HANDOFF_SKIP_WORKSPACE_BOOTSTRAP:"true"}};if("local-folder"!==e.project.source.type){i.TASK_HANDOFF_PROJECT_SOURCE=JSON.stringify(e.project.source),i.TASK_HANDOFF_WORKSPACE_POLICY=JSON.stringify(e.project.workspacePolicy);for(const[t,n]of Gc({url:e.project.source.url,ref:e.project.source.ref,clone:e.project.source.clone},{legacy:!0}))i[t]=n;e.project.source.clone?.subdirectory&&(i.TASK_HANDOFF_WORKSPACE_SUBDIRECTORY=e.project.source.clone.subdirectory)}return i}(e,{nodeAgentUrl:r,workspace:i,port:s});await this.writeUnit(t,o,i,e.instance.id),await this.executor.systemctl(t,["daemon-reload"]),await this.executor.systemctl(t,["enable",hb]),await this.executor.systemctl(t,["restart",hb]);const a=await this.waitForUnitActive(t).catch(n=>(this.options.logger?.("wsl unit not active after start",{instanceId:e.instance.id,distroName:t,error:n instanceof Error?n.message:String(n)}),"unknown")),c=`http://127.0.0.1:${s}`;return this.options.logger?.("wsl instance started",{instanceId:e.instance.id,distroName:t,port:s,nodeAgentUrl:r,created:n.created,unitState:a}),{status:"registering",health:"unknown",connectionStatus:"online",agentStatus:"unknown",targetStatus:"unknown",uiAccessStatus:"unknown",target:{strategy:"node-proxy",status:"unknown",web:c,api:`${c}/api`},workspace:{mode:e.project.workspacePolicy.mode,status:"ready",path:i},runtime:{kind:"wsl",containerName:t,workspacePath:i,port:s,labels:{...e.instance.runtime.labels,...n.labels}}}}async stop(e){const t=this.distroNameFor(e.instance);return"absent"===await this.executor.distroState(t).catch(()=>"unknown")?(await this.executor.releaseSession(t).catch(()=>{}),this.stoppedResult(e)):(await this.executor.systemctl(t,["stop",hb]).catch(()=>{}),await this.executor.releaseSession(t).catch(()=>{}),await this.executor.terminate(t).catch(()=>{}),this.options.logger?.("wsl instance stopped",{instanceId:e.instance.id,distroName:t}),this.stoppedResult(e))}stoppedResult(e){return{status:"stopped",health:"unknown",connectionStatus:"offline",agentStatus:"offline",targetStatus:"unknown",uiAccessStatus:"unknown",target:{...e.instance.target,status:"unknown"},runtime:e.instance.runtime}}async restart(e){const t=this.distroNameFor(e.instance);return await this.executor.systemctl(t,["stop",hb]).catch(()=>{}),await this.executor.releaseSession(t).catch(()=>{}),this.start(e)}async delete(e,t){const n=this.distroNameFor(e.instance);if("absent"===await this.executor.distroState(n).catch(()=>"unknown"))return await this.executor.releaseSession(n).catch(()=>{}),this.provisioner.forgetDistro(n),qs.parse({instanceId:e.instance.id,containerDeleted:!0,completed:!0,deletedVolumes:[],retainedVolumes:this.distroVolumeDispositions(n,"missing",t),volumeResults:this.distroVolumeDispositions(n,"missing",t)});let i,s=!1;try{await this.executor.systemctl(n,["stop",hb]).catch(()=>{}),await this.executor.releaseSession(n).catch(()=>{}),await this.executor.unregister(n),this.provisioner.forgetDistro(n),s=!0}catch(e){i={code:"object"==typeof e&&e&&"code"in e&&"string"==typeof e.code?String(e.code):_b,message:e instanceof Error?e.message:String(e)}}const r=s?"deleted":t.deleteVolumes?"failed":"retained",o=this.distroVolumeDispositions(n,r,t,i);return this.options.logger?.(s?"wsl instance deleted":"wsl instance delete incomplete",{instanceId:e.instance.id,distroName:n,status:r,...i?{error:i.message}:{}}),qs.parse({instanceId:e.instance.id,containerDeleted:s,completed:s,deletedVolumes:o.filter(e=>"deleted"===e.status||"missing"===e.status),retainedVolumes:o.filter(e=>"retained"===e.status),volumeResults:o})}distroVolumeDispositions(e,t,n,i){const s="failed"!==t||n.deleteVolumes?t:"retained";return[{role:"data",mountPath:"/data"},{role:"agent-home",mountPath:"/home/agent"},{role:"workspace",mountPath:fb}].map(({role:t,mountPath:n})=>({role:t,name:`${e}:${t}`,mountPath:n,status:s,..."failed"===s?{error:i??{code:_b,message:`Could not remove WSL distro ${e}.`}}:{}}))}async prepareWorkspace(e,t){const n=e.project.workspacePolicy.path||fb;return"local-folder"===e.project.source.type?this.prepareLocalFolderWorkspace(e,t,n):(await this.executor.execOrThrow(t,["sh","-c",`mkdir -p ${wb(n)}`]),n)}async prepareLocalFolderWorkspace(e,t,i){if("local-folder"!==e.project.source.type)throw Ab(Eb,"Local folder workspace preparation requires a local-folder source.");const s=function(e){const t=/^([a-zA-Z]):[\\/](.*)$/.exec(e.trim());return t?`/mnt/${t[1].toLowerCase()}/${t[2].replace(/\\/g,"/")}`:void 0}(e.project.source.path);if(!s)throw Ab(Eb,`Local folder ${e.project.source.path} is not a Windows absolute path mapable into WSL.`,{instanceId:e.instance.id,path:e.project.source.path});if(0!==(await this.executor.exec(t,["test","-d",s])).exitCode)throw Ab("WSL_WORKSPACE_PREPARATION_FAILED",`Mapped local folder ${s} is not accessible inside WSL distro ${t}.`,{instanceId:e.instance.id,mapped:s});return await this.executor.execOrThrow(t,["sh","-c",`mkdir -p ${wb(n.posix.dirname(i))} && ln -sfn ${wb(s)} ${wb(i)}`]),i}}function wb(e){return`'${e.replace(/'/g,"'\\''")}'`}function Sb(e){return e.runtime.containerName?.trim()||nb(e.id)}class Nb{managedArtifacts=!0;executor;platform;lifecycle;constructor(e,t={}){this.executor=e,this.platform=t.platform??process.platform,this.lifecycle=t.lifecycle??(t.provisioner&&t.listenerPort?new bb({provisioner:t.provisioner,executor:e,listenerPort:t.listenerPort,hostAddress:t.hostAddress,fallbackNodeAgentUrl:t.fallbackNodeAgentUrl,listenerHost:t.listenerHost,bootstrapDir:t.bootstrapDir,hostArch:t.hostArch??process.arch,allocatePort:t.allocatePort,logger:t.logger}):void 0)}requireLifecycle(e){if(this.lifecycle)return this.lifecycle;throw Object.assign(new Error(`The WSL runtime lifecycle is not configured; cannot ${e}.`),{statusCode:503,code:"WSL_RUNTIME_LIFECYCLE_UNAVAILABLE",details:{operation:e}})}async resolveInstanceWeb(e){const t=e.instance.runtime.port;if(!t)throw Object.assign(new Error(`Instance ${e.instance.id} does not have a node-owned WSL runtime port.`),{statusCode:409,code:"INSTANCE_RUNTIME_ENDPOINT_UNAVAILABLE"});return`http://127.0.0.1:${t}`}async resolveNodeAgentUrl(e){if(!this.lifecycle)return e.nodeAgentUrl||"";const t=Sb(e.instance);return this.lifecycle.nodeAgentUrl(e,t)}async runtimeState(e){const t=Sb(e.instance);if(!t)return"absent";try{return await this.executor.distroState(t)}catch{return"unknown"}}async start(e){return this.requireLifecycle("start").start(e)}async stop(e){return this.requireLifecycle("stop").stop(e)}async restart(e){return this.requireLifecycle("restart").restart(e)}async delete(e,t){return this.requireLifecycle("delete").delete(e,t)}async artifactTarget(e){return this.lifecycle?this.lifecycle.artifactTarget():{platform:"linux",arch:process.arch,launcherAbi:1}}async installRuntime(e,t){const n=this.requireLifecycle("installRuntime"),i=Sb(e.instance);await n.installRuntime(i,t)}async inspectRuntime(e,t){if(!this.lifecycle)return!1;const n=Sb(e.instance);return this.lifecycle.inspectRuntime(n,t)}async check(e){const t=function(e={}){return na(e)}(e.capabilities),n=yT(this.platform);try{const e=await this.executor.version();return{status:"online",capabilities:{...t,wsl:{status:"online",hostPlatform:n,executablePath:this.executor.executablePath,version:e}}}}catch(e){return{status:"offline",capabilities:{...t,wsl:{status:"offline",hostPlatform:n,executablePath:this.executor.executablePath,error:e instanceof Error?e.message:String(e)}}}}}}const vb="WSL_BASE_TEMPLATE_MISSING",Ob="WSL_BASE_TEMPLATE_INVALID",Rb="WSL_BASE_TEMPLATE_UNAVAILABLE",zb="WSL_DISTRO_OWNERSHIP_CONFLICT",xb="/var/lib/task-handoff/distro.json",Cb="wsl-base",kb="/var/lib/task-handoff/owner-baseline",Db=["/workspace","/data","/home/agent"],Lb="agent";function Pb(){const e=Db.join(" "),t=`chown -R ${Lb}:${Lb}`;return`[ -f ${kb} ] || { mkdir -p ${e} && ${t} ${e} && { [ ! -d /app ] || ${t} /app; } && mkdir -p ${n.posix.dirname(kb)} && : > ${kb}; }`}const Mb="task-handoff.runtime-kind",jb="wsl",Ub="task-handoff.instance-id",Fb="task-handoff.runtime-id",$b="task-handoff.owner-node-id",Hb="task-handoff.base-template";function Bb(e,t,n,i=500){return Object.assign(new Error(t),{statusCode:i,code:e,...n?{details:n}:{}})}const qb=c.z.object({id:c.z.string().min(1),version:c.z.string().min(1),platform:c.z.literal("linux"),arch:c.z.string().min(1),formatVersion:c.z.literal(1),sha256:c.z.string().regex(/^[a-f0-9]{64}$/),sizeBytes:c.z.number().int().nonnegative().optional(),createdAt:c.z.string().optional(),tools:c.z.record(c.z.string(),c.z.string()).optional()}).strict(),Vb=c.z.object({runtimeKind:c.z.literal(jb),distroName:c.z.string().min(1),instanceId:c.z.string().min(1),runtimeId:c.z.string().min(1),nodeId:c.z.string().min(1),baseTemplateId:c.z.string().min(1),baseTemplateVersion:c.z.string().min(1),createdAt:c.z.string().min(1)}).strict(),Gb=c.z.object({version:c.z.literal(1),distros:c.z.record(c.z.string(),Vb)}).strict();function Wb(e=process.env){const t=[],i=e.TASK_HANDOFF_WSL_BASE_TEMPLATE_DIR?.trim();i&&t.push(n.resolve(i));const s=e.TASK_HANDOFF_BUNDLED_RUNTIME_DIR?.trim(),r=s?n.resolve(s):n.resolve(n.dirname(process.argv[1]||process.cwd()),"..","runtime-artifacts");return t.push(n.join(r,"wsl-base"),r),t}async function Kb(e){const n=d.createHash("sha256"),i=t.createReadStream(e);for await(const e of i)n.update(e);return n.digest("hex")}function Yb(e,t){return`${Cb}-${e}-${t}`}async function Xb(e){let t;try{t=JSON.parse(await y.readFile(e,"utf8"))}catch(t){throw Bb(Ob,`WSL base template manifest ${e} could not be read.`,{manifestPath:e,cause:t instanceof Error?t.message:String(t)})}const n=qb.safeParse(t);if(!n.success)throw Bb(Ob,`WSL base template manifest ${e} is invalid.`,{manifestPath:e,issues:n.error.issues});return n.data}function Jb(e,t){if(t.expectedVersion&&e.version!==t.expectedVersion)throw Bb(Ob,`WSL base template version ${e.version} does not match expected ${t.expectedVersion}.`,{actualVersion:e.version,expectedVersion:t.expectedVersion});if(t.expectedArch&&e.arch!==t.expectedArch)throw Bb(Ob,`WSL base template arch ${e.arch} does not match expected ${t.expectedArch}.`,{actualArch:e.arch,expectedArch:t.expectedArch})}async function Qb(e,i){let s;try{s=await y.readdir(e)}catch{return}const r=[];for(const o of s){const s=n.join(e,o),a=n.join(s,"manifest.json"),c=n.join(s,".ready");if(!t.existsSync(c)||!t.existsSync(a))continue;const d=await Xb(a).catch(()=>{});if(!d)continue;if(i.expectedVersion&&d.version!==i.expectedVersion)continue;if(i.expectedArch&&d.arch!==i.expectedArch)continue;const l=n.join(s,`${Yb(d.version,d.arch)}.tar.gz`);t.existsSync(l)&&r.push({identity:d,archivePath:l,manifestPath:a,cacheHit:!0})}return r.sort((e,t)=>t.identity.version.localeCompare(e.identity.version)),r[0]}async function Zb(e){if(e.archivePath){const i=n.resolve(e.archivePath),s=e.manifestPath?n.resolve(e.manifestPath):i.endsWith(".tar.gz")?`${i.slice(0,-7)}.manifest.json`:`${i}.manifest.json`;if(!t.existsSync(i))throw Bb(vb,`WSL base template archive ${i} does not exist.`,{archivePath:i});if(!t.existsSync(s))throw Bb(vb,`WSL base template manifest ${s} does not exist.`,{manifestPath:s});return{archivePath:i,manifestPath:s}}for(const i of e.sourceDirs??[]){let s;try{s=await y.readdir(i)}catch{continue}const r=s.filter(e=>e.startsWith(`${Cb}-`)&&e.endsWith(".manifest.json")).map(e=>n.join(i,e)).sort().reverse();for(const s of r){const r=await Xb(s).catch(()=>{});if(!r)continue;if(e.expectedVersion&&r.version!==e.expectedVersion)continue;if(e.expectedArch&&r.arch!==e.expectedArch)continue;const o=n.join(i,`${Yb(r.version,r.arch)}.tar.gz`);if(t.existsSync(o))return{archivePath:o,manifestPath:s}}}throw Bb(vb,"No cached or bundled WSL base template was found. Build/package one or set TASK_HANDOFF_WSL_BASE_TEMPLATE.",{sourceDirs:e.sourceDirs??[]})}function ew(e){return"string"==typeof e?.code?String(e.code):void 0}function tw(e){return e instanceof Error?e.message:String(e)}async function nw(e,t){const i=await Xb(e.manifestPath);Jb(i,t);const s=await Qb(t.cacheDir,{...t,expectedVersion:i.version,expectedArch:i.arch});if(s)return s;const r=await Kb(e.archivePath);if(r!==i.sha256)throw Bb(Ob,`WSL base template ${i.id}@${i.version} failed SHA-256 verification.`,{archivePath:e.archivePath,expectedSha256:i.sha256,actualSha256:r});const o=Yb(i.version,i.arch),a=n.join(t.cacheDir,o);await y.mkdir(a,{recursive:!0});const c=n.join(a,`.${o}.${process.pid}.part`);try{await y.copyFile(e.archivePath,c);const n=await iw(i,c,t);return t.logger?.("wsl base template cached",{version:i.version,arch:i.arch,sourceArchivePath:e.archivePath,cacheArchivePath:n.archivePath,sizeBytes:i.sizeBytes}),n}finally{await y.rm(c,{force:!0})}}async function iw(e,t,i){const s=Yb(e.version,e.arch),r=n.join(i.cacheDir,s);await y.mkdir(r,{recursive:!0});const o=n.join(r,`${s}.tar.gz`);await y.rename(t,o);const a=n.join(r,"manifest.json");return m.sync(a,`${JSON.stringify(e,null,2)}\n`,{encoding:"utf8"}),m.sync(n.join(r,".ready"),"",{encoding:"utf8"}),{identity:e,archivePath:o,manifestPath:a,cacheHit:!1}}class sw{filePath;constructor(e){this.filePath=e}file(){return new pu(this.filePath,()=>({version:1,distros:{}}),{schema:Gb})}get(e){return this.file().get().distros[e]}list(){return this.file().get().distros}put(e){const t=this.file().get();return this.file().put({version:1,distros:{...t.distros,[e.distroName]:e}})}delete(e){const t=this.file().get(),{[e]:n,...i}=t.distros;return this.file().put({version:1,distros:i})}}class rw{executor;nodeId;distroRoot;index;options;constructor(e){this.options=e,this.executor=e.executor,this.nodeId=e.nodeId,this.distroRoot=e.distroRoot,this.index=e.index}distroNameForInstance(e){const t=e.containerName?.trim();return t||nb(e.id)}async prefetchBaseTemplate(){await this.ensureBaseTemplate()}forgetDistro(e){this.index.delete(e)}labelsFor(e,t){return n={instanceId:e.id,runtimeId:e.runtimeId,nodeId:this.nodeId,baseTemplateId:t.baseTemplateId},{[Mb]:jb,[Ub]:n.instanceId,[Fb]:n.runtimeId,[$b]:n.nodeId,...n.baseTemplateId?{[Hb]:n.baseTemplateId}:{}};var n}async ensureBaseTemplate(){return async function(e){const t=await Zb(e).catch(t=>{if(e.archivePath||t?.code!==vb)throw t});if(t)return await nw(t,e);const i=await Qb(e.cacheDir,e);if(i)return i;let s;const r=await async function(e){const t=e.expectedVersion,i=e.expectedArch;if(!t||!i)return;const s=e.fetchImpl??fetch,r=(e.releaseBaseUrl?.trim().replaceAll("{version}",t)||Vl(t)).replace(/\/+$/,""),o=Yb(t,i),a=`${r}/${o}.manifest.json`,c=`${r}/${o}.tar.gz`,l=(e,t,n)=>Bb(Rb,e,{...t,...void 0===n?{}:{cause:tw(n)}},503);let u,p;try{u=await s(a)}catch(e){throw l(`Could not reach the WSL base template release manifest ${a}.`,{manifestUrl:a,retryable:!0},e)}if(!u.ok)throw l(`WSL base template release manifest ${a} returned HTTP ${u.status}.`,{manifestUrl:a,status:u.status,retryable:404===u.status||u.status>=500});try{p=await u.json()}catch(e){throw Bb(Ob,`WSL base template release manifest ${a} is not valid JSON.`,{manifestUrl:a,cause:tw(e)})}const m=qb.safeParse(p);if(!m.success)throw Bb(Ob,`WSL base template release manifest ${a} is invalid.`,{manifestUrl:a,issues:m.error.issues});const h=m.data;Jb(h,e);const g=n.join(e.cacheDir,o);await y.mkdir(g,{recursive:!0});const f=n.join(g,`.${o}.${d.randomUUID()}.part`);try{const t=await y.open(f,"wx");let n;try{n=await s(c)}catch(e){throw await t.close(),l(`Could not download the WSL base template archive ${c}.`,{archiveUrl:c,retryable:!0},e)}if(!n.ok||!n.body)throw await t.close(),l(`WSL base template archive ${c} returned HTTP ${n.status}.`,{archiveUrl:c,status:n.status,retryable:404===n.status||n.status>=500});await I.pipeline(n.body,t.createWriteStream());const i=await Kb(f);if(i!==h.sha256)throw Bb(Ob,`Downloaded WSL base template ${h.id}@${h.version} failed SHA-256 verification.`,{archiveUrl:c,expectedSha256:h.sha256,actualSha256:i});const r=await iw(h,f,e);return e.logger?.("wsl base template downloaded",{version:h.version,arch:h.arch,manifestUrl:a,archiveUrl:c,cacheArchivePath:r.archivePath,sizeBytes:h.sizeBytes}),r}catch(e){if(ew(e)?.startsWith("WSL_"))throw e;throw l(`Could not download the WSL base template archive ${c}.`,{archiveUrl:c,retryable:!0},e)}finally{await y.rm(f,{force:!0})}}(e).catch(t=>{if(ew(t)!==Rb)throw t;s={code:Rb,message:t instanceof Error?t.message:String(t),...t&&"object"==typeof t&&"details"in t?{details:t.details}:{}},e.logger?.("wsl base template pull failed",{version:e.expectedVersion,arch:e.expectedArch,code:s.code,error:s.message})});if(r)return r;const o=await async function(e){const t={...e,expectedVersion:void 0},n=await Qb(e.cacheDir,t);if(n)return n;if(e.archivePath)return;const i=await Zb(t).catch(()=>{});return i?await nw(i,t):void 0}(e);if(o)return e.logger?.("wsl base template fell back to a locally available version",{version:o.identity.version,expectedVersion:e.expectedVersion,cacheHit:o.cacheHit}),o;throw Bb(vb,"No locally available WSL base template was found and the release channel did not provide one. Build/package one, set TASK_HANDOFF_WSL_BASE_TEMPLATE_DIR, or restore the node's access to the runtime release channel.",{sourceDirs:e.sourceDirs??[],expectedVersion:e.expectedVersion,expectedArch:e.expectedArch,...s?{pullError:s}:{}})}({cacheDir:this.options.baseTemplateCacheDir,sourceDirs:this.options.baseTemplateSourceDirs??Wb(),expectedVersion:this.options.expectedBaseTemplateVersion,expectedArch:this.options.expectedArch,fetchImpl:this.options.fetchImpl,logger:this.options.logger})}async provision(e){const t=this.distroNameForInstance(e),i=await this.executor.findDistro(t);if(i){const n=await this.assertOwnership(t,e);return await this.ensureMarker(t,n),await this.ensureAgentOwnershipBaseline(t),{distroName:t,created:!1,ownership:n,labels:this.labelsFor(e,n),state:i.state}}const s=await this.ensureBaseTemplate(),r=n.join(this.distroRoot,t);await y.mkdir(r,{recursive:!0});const o=await this.executor.importDistro({name:t,installDir:r,tarballPath:s.archivePath}),a={runtimeKind:jb,distroName:t,instanceId:e.id,runtimeId:e.runtimeId,nodeId:this.nodeId,baseTemplateId:s.identity.id,baseTemplateVersion:s.identity.version,createdAt:(this.options.now?.()??new Date).toISOString()};return this.index.put(a),await this.writeMarker(t,a),await this.ensureAgentOwnershipBaseline(t),this.options.logger?.("wsl distro provisioned",{distroName:t,instanceId:e.id,installDir:r,baseTemplateVersion:s.identity.version,cacheHit:s.cacheHit}),{distroName:t,created:!0,ownership:a,labels:this.labelsFor(e,a),state:o?.state??"Stopped"}}async assertOwnership(e,t){const n=this.index.get(e);if(n)return this.assertOwnershipMatches(n,e,t),n;const i=await this.readMarker(e);if(i)return this.assertOwnershipMatches(i,e,t),this.index.put(i),i;throw Bb(zb,`WSL distro ${e} already exists but carries no ownership record for instance ${t.id}.`,{distroName:e,instanceId:t.id},409)}assertOwnershipMatches(e,t,n){if(e.nodeId!==this.nodeId||e.distroName!==t||e.instanceId!==n.id||e.runtimeId!==n.runtimeId)throw Bb(zb,`WSL distro ${t} is owned by node ${e.nodeId} instance ${e.instanceId}, not ${this.nodeId}/${n.id}.`,{distroName:t,ownerNodeId:e.nodeId,ownerInstanceId:e.instanceId,expectedNodeId:this.nodeId,expectedInstanceId:n.id},409)}async readMarker(e){const t=await this.executor.exec(e,["cat",xb]);if(0===t.exitCode)try{const e=Vb.safeParse(JSON.parse(t.stdout));return e.success?e.data:void 0}catch{return}}async ensureAgentOwnershipBaseline(e){await this.executor.execOrThrow(e,["sh","-c",Pb()])}async writeMarker(e,t){const i=Buffer.from(`${JSON.stringify(t,null,2)}\n`,"utf8").toString("base64"),s=n.posix.dirname(xb);await this.executor.execOrThrow(e,["sh","-c",`mkdir -p ${s} && printf '%s' ${i} | base64 -d > ${xb}`])}async ensureMarker(e,t){await this.readMarker(e)||await this.writeMarker(e,t)}async reconcileOrphans(e){const t=new Set(e.instanceIds),n=e.now?.()??Date.now(),i=e.retentionMs??6048e5,s={diagnostics:[],reclaimable:[],reclaimed:[]},r=(await this.executor.listDistros()).filter(e=>e.name.startsWith(XT));for(const o of r){let r=this.index.get(o.name);if(!r){if(!e.inspectUnindexedMarkers){s.diagnostics.push({code:"WSL_DISTRO_UNOWNED",distroName:o.name,action:"skipped",message:`WSL distro ${o.name} has no node-agent ownership record and was left untouched.`});continue}if(r=await this.readMarker(o.name).catch(()=>{}),!r){s.diagnostics.push({code:"WSL_DISTRO_UNOWNED",distroName:o.name,action:"skipped",message:`WSL distro ${o.name} has no readable ownership record and was left untouched.`});continue}this.index.put(r)}if(r.nodeId!==this.nodeId){s.diagnostics.push({code:"WSL_DISTRO_FOREIGN_NODE",distroName:o.name,instanceId:r.instanceId,action:"skipped",message:`WSL distro ${o.name} belongs to node ${r.nodeId} and was left untouched.`});continue}if(t.has(r.instanceId))continue;s.reclaimable.push(o.name);const a=Date.parse(r.createdAt),c=e.force||Number.isFinite(a)&&n-a>=i;e.reclaim&&c?(await this.executor.unregister(o.name),this.index.delete(o.name),s.reclaimed.push(o.name),s.diagnostics.push({code:"WSL_DISTRO_RECLAIMED",distroName:o.name,instanceId:r.instanceId,action:"reclaimed",message:`Reclaimed orphaned WSL distro ${o.name} for deleted instance ${r.instanceId}.`})):s.diagnostics.push({code:"WSL_DISTRO_ORPHANED",distroName:o.name,instanceId:r.instanceId,action:"retained",message:`WSL distro ${o.name} has no live instance record and is retained${c?" (eligible for reclaim)":""}.`})}return s}}const ow="WSL_SESSION_RECOVERY_FAILED";class aw{options;recovering=new Map;timer;active;started=!1;stopped=!1;constructor(e){this.options=e}start(){this.started||this.stopped||(this.started=!0,this.schedule(0))}notify(){this.started&&!this.stopped&&this.schedule(0)}async stop(){this.stopped=!0,this.timer&&clearTimeout(this.timer),this.timer=void 0,await this.active}schedule(e){this.stopped||(this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>{this.timer=void 0,this.runCycle()},e),this.timer.unref?.())}runCycle(){const e=this.checkOnce().catch(e=>this.options.onDiagnostic({code:ow,instanceId:"node",distroName:"node",classification:"recovered",message:"WSL session supervision cycle failed.",error:e instanceof Error?e.message:String(e)})).finally(()=>{this.active===e&&(this.active=void 0),this.schedule(this.options.intervalMs??Math.max(1e3,Math.floor(5e3)))});this.active=e}async checkOnce(){let e=0;for(const t of this.options.listRunningInstances()){const{id:n,distroName:i}=t;this.options.sessionAlive(i)||(await this.recover(t),e+=1)}return e}recover(e){const t=this.recovering.get(e.id);if(t)return t;const n=this.recoverInstance(e).finally(()=>this.recovering.delete(e.id));return this.recovering.set(e.id,n),n}async recoverInstance(e){const{id:t,distroName:n}=e,i=this.options.recoveryBudgetMs??6e4,s=this.options.nowMs??(()=>Date.now()),r=this.options.delay??(e=>new Promise(t=>setTimeout(t,e))),o=s()+i;let a=await this.options.distroState(n).catch(()=>"unknown");const c="running"===a?"instance-crash":"session-lost";this.options.onDiagnostic({code:"WSL_SESSION_LOST",instanceId:t,distroName:n,classification:c,message:"session-lost"===c?`WSL keep-alive session for ${n} was lost and the distro may have been reclaimed; rebuilding.`:`WSL distro ${n} is running but its keep-alive session was lost; rebuilding without treating it as an instance crash.`}),await(this.options.onSessionLost?.(t,n));try{for("running"!==a&&(await this.options.ensureDistroRunning(n),a="running"),await this.options.holdSession(n);s()<o;){if("active"===await this.options.unitActive(n).catch(()=>"unknown")&&(!this.options.waitForEndpointHealthy||await this.options.waitForEndpointHealthy(t).catch(()=>!1)))return void this.options.onDiagnostic({code:"WSL_SESSION_RECOVERED",instanceId:t,distroName:n,classification:"recovered",message:`WSL keep-alive session for ${n} was rebuilt and the instance is healthy.`});await r(500)}throw new Error(`WSL distro ${n} did not reach unit ${hb} active with a healthy endpoint within ${i}ms.`)}catch(e){this.options.onDiagnostic({code:ow,instanceId:t,distroName:n,classification:c,message:`WSL keep-alive session for ${n} could not be rebuilt.`,error:e instanceof Error?e.message:String(e)})}}async releaseFor(e,t){this.recovering.delete(e),await this.options.releaseSession(t).catch(()=>{})}}const cw="/run/task-handoff/git-auth",dw="/run/task-handoff/git-runtime",lw=`${lb}/git-wsl-provision.sh`,uw=`${lb}/git-wsl-credential-helper.mjs`,pw="TASK_HANDOFF_GIT_PROVISIONING_STAGE=",mw="TASK_HANDOFF_GIT_PROVISIONING_ERROR=",hw="TASK_HANDOFF_GIT_PROVISIONING_COMMIT=";function gw(e,t){return e.split(/\r?\n/).filter(e=>e.startsWith(t)).map(e=>e.slice(t.length).trim()).filter(Boolean).pop()}class fw{executor;logger;constructor(e){this.executor=e.executor,this.logger=e.logger}async ensureScripts(e){const i=t.mkdtempSync(n.join(s.tmpdir(),"task-handoff-wsl-git-"));try{const s=n.join(i,"git-wsl-provision.sh"),r=n.join(i,"git-wsl-credential-helper.mjs");t.writeFileSync(s,`#!/usr/bin/env bash\nset -euo pipefail\n\n# Cross-filesystem normalization (6.4): drvfs mounts and the distro ext4 root can disagree on\n# default modes, so pin the provisioning umask and hand the materialized workspace to the template's\n# \`agent\` user when it exists.\numask 022\n\nworkspace="\${TASK_HANDOFF_WORKSPACE:-${fb}}"\nstaging="\${workspace}/.task-handoff-git-provisioning"\ncheckout="\${staging}/checkout"\nruntime_dir="${dw}"\n\nfail() {\n printf '${mw}%s\\n' "$1" >&2\n exit "\${2:-1}"\n}\nstage() {\n printf '${pw}%s\\n' "$1"\n}\n\nmkdir -p "\${workspace}" "\${staging}" "\${runtime_dir}"\nexisting="$(find "\${workspace}" -mindepth 1 -maxdepth 1 ! -name .task-handoff-git-provisioning -print -quit 2>/dev/null)"\nif [ -n "\${existing}" ]; then\n if [ -e "\${workspace}/.git" ]; then\n echo "Workspace is already materialized; skipping provisioning."\n exit 0\n fi\n fail WORKSPACE_NOT_EMPTY 73\nfi\nrm -rf -- "\${staging}"\nmkdir -p "\${staging}"\n\nif [ -d "${cw}" ]; then\n cp -a "${cw}/." "\${runtime_dir}/"\nfi\nchmod 0700 "\${runtime_dir}"\n\nexport TASK_HANDOFF_WSL_GIT_RUNTIME_DIR="\${runtime_dir}"\nexport GIT_TERMINAL_PROMPT=0\ngit_config=(-c credential.helper= -c credential.helper="!node ${uw} credential" -c credential.useHttpPath=true)\n\nssh_command=""\nfor credential_dir in "\${runtime_dir}"/credential-*; do\n [ -d "\${credential_dir}" ] || continue\n if [ -f "\${credential_dir}/private-key" ]; then\n chmod 0600 "\${credential_dir}/private-key"\n known_hosts="\${credential_dir}/known_hosts"\n [ -f "\${known_hosts}" ] || : > "\${known_hosts}"\n ssh_command="ssh -i \${credential_dir}/private-key -o IdentitiesOnly=yes -o UserKnownHostsFile=\${known_hosts} -o StrictHostKeyChecking=yes"\n fi\ndone\nexport GIT_SSH_COMMAND="\${ssh_command}"\n\nclone_args=(clone --progress)\nif [ -n "\${TASK_HANDOFF_WORKSPACE_GIT_DEPTH:-}" ] && [ -z "\${TASK_HANDOFF_WORKSPACE_GIT_COMMIT:-}" ]; then clone_args+=(--depth "\${TASK_HANDOFF_WORKSPACE_GIT_DEPTH}"); fi\nif [ -n "\${TASK_HANDOFF_WORKSPACE_GIT_REF:-}" ]; then clone_args+=(--branch "\${TASK_HANDOFF_WORKSPACE_GIT_REF}"); fi\nclone_args+=(-- "\${TASK_HANDOFF_WORKSPACE_GIT_URL}" "\${checkout}")\n\nstage cloning\nif ! git "\${git_config[@]}" "\${clone_args[@]}"; then fail CLONE_FAILED 74; fi\n\nif [ -n "\${TASK_HANDOFF_WORKSPACE_GIT_COMMIT:-}" ]; then\n stage checking-out\n if ! git -C "\${checkout}" checkout --detach "\${TASK_HANDOFF_WORKSPACE_GIT_COMMIT}"; then fail REF_NOT_FOUND 75; fi\nfi\nif [ "\${TASK_HANDOFF_WORKSPACE_GIT_SUBMODULES:-false}" = "true" ]; then\n stage submodules\n if ! git "\${git_config[@]}" -C "\${checkout}" submodule update --init --recursive --progress; then fail CLONE_FAILED 74; fi\nfi\nif [ "\${TASK_HANDOFF_WORKSPACE_GIT_LFS:-false}" = "true" ]; then\n stage lfs\n if ! git "\${git_config[@]}" -C "\${checkout}" lfs pull; then fail LFS_FAILED 76; fi\nfi\nif [ -n "\${TASK_HANDOFF_WORKSPACE_SUBDIRECTORY:-}" ] && [ ! -d "\${checkout}/\${TASK_HANDOFF_WORKSPACE_SUBDIRECTORY}" ]; then\n fail SUBDIRECTORY_NOT_FOUND 75\nfi\nstage finalizing\nprintf '${hw}%s\\n' "$(git -C "\${checkout}" rev-parse HEAD 2>/dev/null || true)"\nshopt -s dotglob nullglob\nmv -- "\${checkout}"/* "\${workspace}/"\nrm -rf -- "\${staging}"\nif id agent >/dev/null 2>&1; then chown -R agent:agent "\${workspace}" 2>/dev/null || true; fi\n`,{mode:493}),t.writeFileSync(r,`#!/usr/bin/env node\n// Generated by the Task Handoff node agent. Reads bridged managed credentials and\n// implements the git credential helper contract for HTTPS remotes only. SSH is\n// handled by GIT_SSH_COMMAND with the bridged private key, so this helper never\n// emits secrets on stdout except the username/password git itself requires.\nimport fs from "node:fs";\nimport path from "node:path";\nconst runtimeDir = process.env.TASK_HANDOFF_WSL_GIT_RUNTIME_DIR || ${JSON.stringify(dw)};\nconst mode = process.argv[2];\nif (mode !== "credential") process.exit(0);\nlet input = "";\nprocess.stdin.setEncoding("utf8");\nprocess.stdin.on("data", (chunk) => { input += chunk; });\nprocess.stdin.on("end", () => {\n const fields = {};\n for (const line of input.split(/\\r?\\n/)) {\n const index = line.indexOf("=");\n if (index > 0) fields[line.slice(0, index)] = line.slice(index + 1);\n }\n if (fields.protocol && fields.protocol !== "https") process.exit(0);\n let entries = [];\n try { entries = fs.readdirSync(runtimeDir).filter((name) => name.startsWith("credential-")); } catch { process.exit(0); }\n for (const name of entries.sort()) {\n const dir = path.join(runtimeDir, name);\n let scope = {};\n try { scope = JSON.parse(fs.readFileSync(path.join(dir, "scope.json"), "utf8")); } catch {}\n if (scope.scheme && scope.scheme !== "https") continue;\n if (fields.host && scope.host && scope.host !== fields.host) continue;\n let username = "";\n let token = "";\n try { username = fs.readFileSync(path.join(dir, "username"), "utf8").trim(); } catch {}\n try { token = fs.readFileSync(path.join(dir, "token"), "utf8").trim(); } catch {}\n if (!token) continue;\n process.stdout.write("username=" + username + "\\npassword=" + token + "\\n");\n process.exit(0);\n }\n process.exit(1);\n});\n`,{mode:384}),await this.executor.execOrThrow(e,["sh","-c",`mkdir -p ${lb}`]),await this.executor.copyIntoDistro(e,s,lw),await this.executor.copyIntoDistro(e,r,uw),await this.executor.execOrThrow(e,["sh","-c",`chmod 0755 ${lw} && chmod 0600 ${uw}`])}finally{t.rmSync(i,{recursive:!0,force:!0})}}async provision(e,i,r={}){const o=e.gitWorkspaceProvisioning;if(!o||"local-folder"===e.project.source.type)throw Object.assign(new Error("Git provisioning requires a Git source and operation input."),{code:"GIT_WORKSPACE_PROVISIONING_INVALID",statusCode:400});await this.ensureScripts(i);const a=t.mkdtempSync(n.join(s.tmpdir(),"task-handoff-wsl-git-auth-"));t.chmodSync(a,448);try{this.materializeGitProvisioningAuth(a,o),await this.bridgeAuth(i,a);const t=this.gitEnvironment(e),n=[...Object.entries(t).map(([e,t])=>`${e}=${function(e){return`'${e.replace(/'/g,"'\\''")}'`}(t)}`),`bash ${lw}`].join(" "),s=await this.executor.execStream(i,["sh","-c",n],{onData:r.onOutput,signal:r.signal,timeoutMs:r.timeoutMs??9e5});if(0!==s.exitCode){const t=gw(s.stdout+"\n"+s.stderr,mw)??"CLONE_FAILED";throw Object.assign(new Error(`WSL Git workspace provisioning failed for ${e.instance.id}: ${t}.`),{code:"GIT_WORKSPACE_PROVISIONING_FAILED",statusCode:502,details:{code:t,distroName:i,instanceId:e.instance.id}})}e.completeGitWorkspaceProvisioning?.();const c=`${s.stdout}\n${s.stderr}`,d=c.split(/\r?\n/).filter(e=>e.startsWith(pw)).map(e=>e.slice(36).trim()),l=gw(c,hw);return this.logger?.("wsl git workspace provisioned",{instanceId:e.instance.id,distroName:i,stages:d,...l?{commit:l}:{}}),{...l?{commit:l}:{},stages:d}}finally{await this.executor.execOrThrow(i,["sh","-c",`rm -rf ${cw}`]).catch(()=>{}),t.rmSync(a,{recursive:!0,force:!0})}}gitEnvironment(e){const t=e.gitWorkspaceProvisioning,n={TASK_HANDOFF_INSTANCE_ID:e.instance.id,TASK_HANDOFF_WORKSPACE:e.project.workspacePolicy.path||fb};for(const[e,i]of Gc({url:t.remoteUrl,ref:t.ref,clone:t.clone},{legacy:!1}))n[e]=i;return t.clone.subdirectory&&(n.TASK_HANDOFF_WORKSPACE_SUBDIRECTORY=t.clone.subdirectory),n}materializeGitProvisioningAuth(e,i){const s=(e,i,s)=>{const r=n.join(e,i);t.writeFileSync(r,s,{encoding:"utf8",mode:384}),t.chmodSync(r,384)};i.credentials.forEach((i,r)=>{const o=n.join(e,`credential-${r}`);if(t.mkdirSync(o,{recursive:!0,mode:448}),t.chmodSync(o,448),s(o,"scope.json",JSON.stringify(i.payload.credential.scope)),"https-token"===i.payload.secret.kind)return s(o,"username",i.payload.secret.username),void s(o,"token",i.payload.secret.token);s(o,"private-key",i.payload.secret.privateKey),s(o,"known_hosts",i.payload.secret.pinnedKnownHosts),i.payload.secret.passphrase&&s(o,"passphrase",i.payload.secret.passphrase)})}async bridgeAuth(e,i){await this.executor.execOrThrow(e,["sh","-c",`rm -rf ${cw} && mkdir -p ${cw} && chmod 0700 ${cw}`]);for(const s of t.readdirSync(i,{withFileTypes:!0}))if(s.isDirectory()){await this.executor.execOrThrow(e,["sh","-c",`mkdir -p ${cw}/${s.name} && chmod 0700 ${cw}/${s.name}`]);for(const r of t.readdirSync(n.join(i,s.name)))await this.executor.copyIntoDistro(e,n.join(i,s.name,r),`${cw}/${s.name}/${r}`)}else await this.executor.copyIntoDistro(e,n.join(i,s.name),`${cw}/${s.name}`);await this.executor.execOrThrow(e,["sh","-c",`find ${cw} -type f -exec chmod 0600 {} +`])}}const yw=["codex","claude"],Iw=5e3,_w=B.processStartIdentity(process.pid),Ew=new WeakSet;function Aw(e){const t=process.env[e]?.trim();return t||void 0}function Tw(e){const t=e.authorization;return"string"==typeof t&&t.startsWith("Bearer ")?t.slice(7).trim():void 0}function bw(e){if("string"!=typeof e)return!1;const t=e.trim().toLowerCase();return"localhost"===t||"127.0.0.1"===t||"::1"===t||"::ffff:127.0.0.1"===t}function ww(e){return!e.ip&&!e.socket.remoteAddress&&!e.socket.remoteFamily}function Sw(e){const t=e.split("?")[0];return/^\/api\/node-agent\/instances\/[^/]+\/(register|heartbeat)$/.test(t)||/^\/api\/node-agent\/instances\/[^/]+\/git-credentials\//.test(t)||/^\/api\/node-agent\/instances\/[^/]+\/story-agent-tools$/.test(t)||/^\/api\/node-agent\/instances\/[^/]+\/ai-sessions\/[^/]+\/story-agent-tools$/.test(t)||/^\/api\/node-agent\/instances\/[^/]+\/ai-sessions\/[^/]+\/story-agent-tools\/[^/]+$/.test(t)||/^\/api\/node-agent\/instances\/[^/]+\/ai-sessions\/[^/]+\/story-content(?:\/|$)/.test(t)}function Nw(e){const t=e.capabilities;for(const e of["daemon","wsl"]){const n=t?.[e];if(!n||"object"!=typeof n)continue;const i=n.error;if("string"==typeof i&&i.trim())return i}}async function vw(e,t,n){const i=new AbortController,s=setTimeout(()=>i.abort(),2e3);try{return(await e(`${await n(t)}/api/health`,{signal:i.signal})).ok?"reachable":"endpoint-unreachable"}catch{return"endpoint-unreachable"}finally{clearTimeout(s)}}async function Ow(e,t,n,i){const s=new AbortController,r=setTimeout(()=>s.abort(),i);try{return await e(t,{...n,signal:s.signal})}finally{clearTimeout(r)}}async function Rw(e,t,n,i=async e=>PA(e)){if(!t.registrationToken)return"unavailable";const s=ms.parse({nodeAgentUrl:n}),r=await Ow(e,`${await i(t)}/api/internal/node-agent-connection`,{method:"PUT",headers:{"content-type":"application/json",authorization:`Bearer ${t.registrationToken}`},body:JSON.stringify(s)},5e3);if(404===r.status)return"unsupported";if(!r.ok)throw Object.assign(new Error(`Controlled instance rejected the node-agent connection update (HTTP ${r.status}).`),{code:"NODE_AGENT_CONNECTION_UPDATE_FAILED",statusCode:r.status});return"applied"}async function zw(e,t,n,i,s){if(!t.config.autoImportAgentConfigs)return void i.diagnostic({instanceId:t.id,action:n},"node instance config auto-import skipped");if("reachable"!==t.targetStatus)return;const r=await s(t),o=Number(process.env.TASK_HANDOFF_CONFIG_AUTO_IMPORT_TIMEOUT_MS||Iw);for(const s of yw)try{const a=await Ow(e,`${r}/api/config-sync/import/${encodeURIComponent(s)}`,{method:"POST"},Number.isFinite(o)&&o>0?o:Iw);if(!a.ok){i.warn({instanceId:t.id,action:n,preset:s,statusCode:a.status},"node instance config auto-import failed");continue}i.diagnostic({instanceId:t.id,action:n,preset:s},"node instance config auto-import completed")}catch(e){i.warn({instanceId:t.id,action:n,preset:s,error:e instanceof Error?e.message:String(e)},"node instance config auto-import failed")}}async function xw(e,t,n,i,s=async e=>PA(e)){const r=t.requireInstance(n),o=t.resolvedAssignedModelEnvironment(n),a=t.modelRegistry.privateCatalog(n);t.instancePrivateConfigs.materialize(r.id,r.registrationToken,o,a,r.config.codexSettings);const c=r.aiSessions?.sessions?.length??0,d=r.aiSessions?.runningCount??0;if(c>0||d>0)return i?.({instanceId:n,reason:"sessions-bound",boundSessionCount:c,runningSessionCount:d},"node instance model environment live sync deferred"),!1;let l,u;try{l=await s(r)}catch(e){return i?.({instanceId:n,error:e instanceof Error?e.message:String(e)},"node instance model environment live sync deferred"),!1}try{u=await Ow(e,`${l}/api/internal/model-environment`,{method:"PUT",headers:{"content-type":"application/json",authorization:`Bearer ${r.registrationToken}`},body:JSON.stringify(o)},Iw)}catch(e){return i?.({instanceId:n,targetWeb:r.target.web,error:e instanceof Error?e.message:String(e)},"node instance model environment live sync deferred"),!1}return u.ok?await async function(e,t,n,i,s){let r;try{r=await Ow(e,`${t}/api/internal/model-catalog`,{method:"PUT",headers:{"content-type":"application/json",authorization:`Bearer ${n.registrationToken}`},body:JSON.stringify(i)},Iw)}catch(e){return s?.({instanceId:n.id,error:e instanceof Error?e.message:String(e)},"node instance model catalog live sync deferred"),!1}if(r.ok)return!0;const o=await async function(e,t,n){try{const i=await Ow(e,`${t}/api/internal/model-catalog`,{headers:{authorization:`Bearer ${n}`}},Iw);if(!i.ok)return;const s=await i.json(),r=s.data?.catalog?.entities;return{source:"string"==typeof s.data?.source?s.data.source:void 0,loadedAt:"string"==typeof s.data?.loadedAt?s.data.loadedAt:void 0,modelEntityIds:Array.isArray(r)?r.map(e=>"string"==typeof e?.id?e.id:"unknown"):void 0}}catch{return}}(e,t,n.registrationToken);return s?.({instanceId:n.id,statusCode:r.status,assignedModelEntityIds:i.entities.map(e=>e.id),instanceModelEntityIds:o?.modelEntityIds,instanceModelCatalogSource:o?.source,instanceModelCatalogLoadedAt:o?.loadedAt},"node instance model catalog live sync deferred"),!1}(e,l,r,a,i):(i?.({instanceId:n,targetWeb:r.target.web,statusCode:u.status},"node instance model environment live sync deferred"),!1)}async function Cw(e,t,n,i,s,r,o="request",a){const c=e.requireInstance(i);if(c.imageProvisioning&&"ready"!==c.imageProvisioning.phase&&"docker"===e.requireRuntime(c.runtimeId).type)return s.diagnostic({instanceId:i,action:"start",reason:o,runtimeId:c.runtimeId,imageId:c.imageSelection?.imageId,imagePhase:c.imageProvisioning.phase},"node instance start queued until image provisioning completes"),e.controlledInstances.put(Ia.parse({...c,status:"starting",updatedAt:de()}));if("local-folder"!==c.source.type&&Jl(c)&&"docker"===e.requireRuntime(c.runtimeId).type)return s.diagnostic({instanceId:i,action:"start",reason:o,runtimeId:c.runtimeId,gitPhase:c.workspace.gitProvisioning?.phase},"node instance start queued until git workspace provisioning completes"),e.controlledInstances.put(Ia.parse({...c,status:"starting",updatedAt:de()}));s.diagnostic({instanceId:i,action:"start",reason:o,runtimeId:c.runtimeId,imageId:c.imageSelection?.imageId},"node instance start requested");const d=e.applyInstanceLifecycle(i,{type:"start-requested"}),l=t.forRuntime(e.requireRuntime(d.runtimeId)),u=await l.start({...e.context(d),signal:a}),p=Ia.parse({...d,...u,target:{...d.target,...u.target},workspace:u.workspace?{...d.workspace,error:void 0,...u.workspace}:d.workspace,runtime:u.runtime?{...d.runtime,...u.runtime}:d.runtime,updatedAt:de()}),m=u.target?.web?await vw(n,p,r):"unknown";if("docker"===e.requireRuntime(d.runtimeId).type&&"reachable"===m){const t=await(l.resolveNodeAgentUrl?.(e.context(p)))||e.containerUrl;Rw(n,p,t,r).then(e=>{s.diagnostic({instanceId:i,action:"node-agent-connection.sync",reason:o,syncStatus:e,nodeAgentUrl:t},"node instance connection endpoint synchronized")}).catch(e=>{s.warn({instanceId:i,action:"node-agent-connection.sync",reason:o,error:e instanceof Error?e.message:String(e)},"node instance connection endpoint sync deferred")})}const h=e.applyInstanceLifecycle(i,{type:"runtime-lifecycle-completed",baseline:d,observation:{...u,target:u.target?{...u.target,status:m}:void 0,workspace:u.workspace?{error:void 0,...u.workspace}:void 0,targetStatus:m,uiAccessStatus:m}});return s.diagnostic({instanceId:i,action:"start",reason:o,status:h.status,connectionStatus:h.connectionStatus,targetStatus:h.targetStatus,targetWeb:h.target.web,containerName:h.runtime.containerName},"node instance start completed"),h}async function kw(e={}){const i=e.token||process.env.TASK_HANDOFF_NODE_AGENT_TOKEN,d=Number(e.port||process.env.TASK_HANDOFF_NODE_AGENT_PORT||"8091"),l=`http://127.0.0.1:${d}`,u=e.containerUrl||process.env.TASK_HANDOFF_NODE_AGENT_CONTAINER_URL,p=zl(e.dataDir),g=await async function(e){return Jh(e)}(p);try{const _=Km(g),E=e.remoteSecret||process.env.TASK_HANDOFF_NODE_AGENT_REMOTE_SECRET,A=e.remoteKeyId||process.env.TASK_HANDOFF_NODE_AGENT_REMOTE_KEY_ID,T=new KA(p,_.access),b=T.resolveNodeId(e.nodeId||process.env.TASK_HANDOFF_NODE_ID),w=e.connectionMode||("local-ipc"===process.env.TASK_HANDOFF_NODE_AGENT_CONNECTION_MODE?"local-ipc":"local-loopback"),S=e.ipcPath||process.env.TASK_HANDOFF_NODE_AGENT_IPC_PATH||Dl(p.dataDir),N="local-ipc"===w?`ipc://${encodeURIComponent(S)}`:l,v=e.platform||process.platform,O=e.arch||process.arch,R=new Vg(p,b,l,u,d,v,_);R.node.connectionMode=w,R.node.controlEndpoint=N,R.node.endpoint=N,R.init();const x=new wE(p,b,_);await x.init();const C=new YE(_),k=new kE(_);await k.init();const L=e.dockerCommandRunner||Ba,P=new Ya(L,e.dockerTerminalCommandRunner),M=function(e,i=oc()){const s=t.readdirSync(i,{withFileTypes:!0}),r=new Map(s.flatMap(e=>{if(!e.isFile())return[];const s=n.join(i,e.name);return[[e.name,{source:s,mode:511&t.statSync(s).mode}]]})),o=[...rc].filter(e=>!r.has(e));if(o.length)throw new Error(`Node agent bootstrap assets are incomplete: missing ${o.sort().join(", ")} in ${i}.`);t.mkdirSync(e,{recursive:!0,mode:493}),t.chmodSync(e,493);for(const[i,s]of r){const r=n.join(e,i);m.sync(r,t.readFileSync(s.source),{mode:s.mode}),t.chmodSync(r,s.mode)}for(const i of t.readdirSync(e,{withFileTypes:!0}))r.has(i.name)||t.rmSync(n.join(e,i.name),{recursive:!0,force:!0});return n.resolve(e)}(p.dockerBootstrapDir),j=new Rc(L,{publishHost:"127.0.0.1",imageService:P,terminalCommandRunner:e.dockerTerminalCommandRunner,launcherAssetsDir:M,nodeAgentContainerIpcPath:e.containerIpcPath});let U;const $=new ET([{type:"docker",adapter:new _T(j,L,v,O)},{type:"local",adapter:new YT(e.dockerCommandRunner||Ba,p,()=>R.localNodeAgentUrl,WT(),e.localControlledInstanceLockPath||process.env.TASK_HANDOFF_LOCAL_CONTROLLED_INSTANCE_LOCK_PATH,e=>U.handleUnexpectedLocalExit(e.instanceId,new Error(`Local controlled instance exited unexpectedly (pid=${e.pid??"unknown"}, code=${e.code??"none"}, signal=${e.signal??"none"}).`)),(e,t)=>me.log.error({error:e,instanceId:t.instanceId,pid:t.pid},"local controlled instance exit recovery failed"))}]),H=R.nodeRuntimes.get("runtime_wsl_host")?new sb({platform:v}):void 0,B=new sw(p.wslDistroIndexPath),q=H?new rw({executor:H,nodeId:b,distroRoot:p.wslDistrosDir,baseTemplateCacheDir:p.wslBaseTemplateCacheDir,index:B,baseTemplateSourceDirs:Wb(),expectedBaseTemplateVersion:Tg(),expectedArch:O,fetchImpl:e.fetchImpl||fetch,logger:(e,t)=>me.log.info(t,e)}):void 0;H&&q&&$.register("wsl",new Nb(H,{platform:v,hostArch:O,provisioner:q,listenerPort:d,bootstrapDir:M,fallbackNodeAgentUrl:R.containerUrl,listenerHost:()=>me.nodeAgentListenerManager?.current().host,logger:(e,t)=>me.log.info(t,e)}));const V=async e=>PA(e,await $.forRuntime(R.requireRuntime(e.runtimeId)).resolveInstanceWeb(R.context(e))),G=e.updateCommandRunner||e.dockerCommandRunner||Ba,W=e.fetchImpl||fetch,K=new rA(R,x,W,V,(e,t)=>me.log.warn(e,t)),Y=new oA(R,W,V,(e,t)=>me.log.warn(e,t)),X=new JE(R,W,V,(e,t)=>me.log.warn(e,t)),J=new Map,Q=new Map,Z=e=>{if("endpoint-unreachable"!==e.targetStatus||"online"!==e.connectionStatus||"online"!==e.agentStatus||!e.target.web||Q.has(e.id))return;const t=e.processIncarnationId,n=(async()=>{if("reachable"!==await vw(W,e,V))return;const n=R.requireInstance(e.id);n.processIncarnationId===t&&"online"===n.connectionStatus&&"online"===n.agentStatus&&(R.controlledInstances.put(Ia.parse({...n,target:{...n.target,status:"reachable"},targetStatus:"reachable",uiAccessStatus:"reachable",updatedAt:de()})),Ae.syncNow())})().catch(t=>{me.log.debug({instanceId:e.id,error:t},"node instance endpoint reconciliation probe failed")}).finally(()=>{Q.delete(e.id)});Q.set(e.id,n)},ee=async e=>{const t=R.requireInstance(e);if("reachable"!==t.targetStatus||!t.registrationToken)return!1;const n=`${t.processIncarnationId||"unknown"}:${t.config.aiSessionHistoryLimit}:${t.config.aiSessionAttachmentRetentionDays}:${t.config.aiSessionMaxFileAttachmentBytes}`;if(J.get(e)===n)return!0;let i;try{i=await Ow(W,`${await V(t)}/api/internal/ai-session-persistence-settings`,{method:"PUT",headers:{"content-type":"application/json",authorization:`Bearer ${t.registrationToken}`},body:JSON.stringify({historyLimit:t.config.aiSessionHistoryLimit,attachmentRetentionDays:t.config.aiSessionAttachmentRetentionDays,maxFileAttachmentBytes:t.config.aiSessionMaxFileAttachmentBytes})},Iw)}catch(t){return Ge.warn({instanceId:e,error:t instanceof Error?t.message:String(t)},"node instance AI session persistence settings live sync deferred"),!1}return i.ok?(J.set(e,n),!0):(Ge.warn({instanceId:e,statusCode:i.status},"node instance AI session persistence settings live sync deferred"),!1)},te=async e=>{const t=R.requireInstance(e);if(R.instancePrivateConfigs.materialize(t.id,t.registrationToken,R.resolvedAssignedModelEnvironment(e),R.modelRegistry.privateCatalog(e),t.config.codexSettings),!t.config.codexSettings)return!0;if("reachable"!==t.targetStatus||!t.registrationToken)return!1;try{const n=await Ow(W,`${await V(t)}/api/internal/codex-settings`,{method:"PUT",headers:{"content-type":"application/json",authorization:`Bearer ${t.registrationToken}`},body:JSON.stringify(t.config.codexSettings||{})},Iw);return!!n.ok||(Ge.warn({instanceId:e,statusCode:n.status},"node instance Codex settings live sync deferred"),!1)}catch(t){return Ge.warn({instanceId:e,error:t instanceof Error?t.message:String(t)},"node instance Codex settings live sync deferred"),!1}},ne=function(e,t){const n=new Map,i=e=>e.aiSessions?.sessions?.length??0,s=e=>e.aiSessions?.runningCount??0;return{arm(e){n.set(e.id,e.processIncarnationId||"")},async converge(r,o){const a=n.get(r.id);if(void 0!==a)if((r.processIncarnationId||"")!==a){if("heartbeat"===o){if(i(r)>0||s(r)>0)return n.delete(r.id),void t({instanceId:r.id,reason:"sessions-bound",boundSessionCount:i(r),runningSessionCount:s(r)},"node instance model environment convergence abandoned");try{await e(r.id)&&n.delete(r.id)}catch(e){t({instanceId:r.id,error:e instanceof Error?e.message:String(e)},"node instance model environment convergence deferred")}}}else n.delete(r.id)}}}(e=>xw(W,R,e,Ge.warn,V),(e,t)=>Ge.warn(e,t)),ie=new ql({cacheDir:n.join(p.dataDir,"runtime-artifacts"),fetchImpl:W}),se=e.resolveRuntimeArtifactRelease||((e,t,i)=>async function(e,t,i,s=fetch){if("linux"!==t||!["x64","arm64"].includes(i))throw new jl("INSTANCE_BASE_RUNTIME_INCOMPATIBLE",`Managed controlled-instance updates require a Linux x64 or arm64 target, received ${t}/${i}.`);const r=await async function(e){const t=`controlled-instance-runtime-${e}-linux-universal`,i=function(){const e=process.env.TASK_HANDOFF_BUNDLED_RUNTIME_DIR?.trim();return n.resolve(e||n.join(n.dirname(process.argv[1]||process.cwd()),"..","runtime-artifacts"))}();try{const[s,r]=await Promise.all([y.readFile(n.join(i,`${t}.manifest.json`),"utf8"),y.readFile(n.join(i,`${t}.tar.gz.sha256`),"utf8")]),o=ja(yr,JSON.parse(s));if(!o.success||o.data.version!==e||"linux"!==o.data.platform||"universal"!==o.data.arch)throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`Bundled controlled-instance ${e} has an invalid Linux manifest.`);const a=r.trim().split(/\s+/)[0]?.toLowerCase();if(!a||!/^[a-f0-9]{64}$/.test(a))throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`Bundled controlled-instance ${e} has an invalid archive checksum.`);return{identity:o.data,source:{archivePath:n.join(i,`${t}.tar.gz`),archiveSha256:a}}}catch(t){if("ENOENT"===t.code)return;if(t instanceof jl)throw t;throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`Could not read bundled controlled-instance ${e}.`,{cause:t})}}(e);if(r)return r;const o=`controlled-instance-runtime-${e}-linux-universal`,a=Vl(e),c=`${a}/${o}.manifest.json`,d=`${a}/${o}.tar.gz`,l=`${a}/${o}.tar.gz.sha256`,[u,p]=await Promise.all([s(c),s(l)]).catch(t=>{throw new jl("INSTANCE_RUNTIME_ARTIFACT_UNAVAILABLE",`Could not read release metadata for controlled-instance ${e}.`,{cause:t,retryable:!0})});if(!u.ok||!p.ok)throw new jl("INSTANCE_RUNTIME_ARTIFACT_UNAVAILABLE",`Release metadata for controlled-instance ${e} is unavailable (manifest HTTP ${u.status}, checksum HTTP ${p.status}).`,{retryable:u.status>=500||p.status>=500});let m;try{m=await u.json()}catch(t){throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`Release manifest for controlled-instance ${e} is not valid JSON.`,{cause:t})}const h=ja(yr,m);if(!h.success)throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`Release manifest for controlled-instance ${e} is invalid: ${h.error.message}`);if(h.data.version!==e||"linux"!==h.data.platform||"universal"!==h.data.arch)throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`Release identity mismatch: requested ${e}-linux-universal, received ${h.data.version}-${h.data.platform}-${h.data.arch}.`);const g=(await p.text()).trim().split(/\s+/)[0]?.toLowerCase();if(!g||!/^[a-f0-9]{64}$/.test(g))throw new jl("INSTANCE_RUNTIME_ARTIFACT_INVALID",`Release checksum for controlled-instance ${e} is invalid.`);return{identity:h.data,source:{archiveUrl:d,archiveSha256:g}}}(e,t,i,W)),re=async(t,n,i)=>{const s=await n.artifactTarget(i);if(e.resolveRuntimeArtifact)return e.resolveRuntimeArtifact(t,s.platform,s.arch);const r=await se(t,s.platform,s.arch);if(r.identity.launcherAbi>s.launcherAbi)throw Object.assign(new Error(`Runtime requires launcher ABI ${r.identity.launcherAbi}, but ${s.platform}-${s.arch} provides ABI ${s.launcherAbi}.`),{code:"INSTANCE_BASE_RUNTIME_INCOMPATIBLE",retryable:!1});return ie.resolve(r.identity,r.source)},oe=e=>$.forRuntime(R.requireRuntime(e.runtimeId)),ae=async e=>{const t=oe(e),n=await(t.resolveNodeAgentUrl?.(R.context(e)));return n||("docker"===R.requireRuntime(e.runtimeId).type?R.containerUrl:R.localNodeAgentUrl)},ce=e=>{const t=oe(e);return IT(t)?t:void 0},le=e=>{const t=ce(e);if(t)return t;throw Object.assign(new Error(`Runtime for instance ${e.id} does not use managed artifacts.`),{code:"INSTANCE_RUNTIME_ARTIFACT_UNMANAGED",retryable:!1})},ue=e=>Boolean(ce(e)),pe=(e,t)=>{const n=R.context(e);return re(t,le(e),n)},me=o({logger:e.logger??!0});_.agents.definitions.setDiagnostic((e,t)=>me.log.warn(t,e)),_.agents.storyEntries.setDiagnostic((e,t)=>me.log.warn(t,e)),_.agents.orchestrations.setDiagnostic((e,t)=>me.log.warn(t,e));const he=new kl(p,{logger:(e,t)=>me.log.warn(t,e)}),ge=()=>R.listInstances().map(e=>e.id),fe=()=>{try{he.run(ge())}catch(e){me.log.warn({error:e},"node-agent persistence maintenance failed")}},ye=()=>{try{he.capNodeAgentLogs(),he.capActiveInstanceLogs(ge())}catch(e){me.log.warn({error:e},"node-agent open log maintenance failed")}};fe();const Ie=setInterval(()=>{fe()},216e5);Ie.unref();const _e=setInterval(()=>{ye()},6e4);_e.unref();const Ee={requests:0,active:0,completed:0,aborted:0,limitRejected:0,responseBytes:0,totalDurationMs:0,maxResponseBytes:zA()};me.decorate("nodeAgentState",R),me.decorate("nodeAgentIdentityService",T),me.decorate("nodeAgentResolveInstanceNodeAgentUrl",ae),await me.register(a,{options:D});const Ae=new sl(R,i,{logger:me.log,safetyIntervalMs:Number(process.env.TASK_HANDOFF_EVENT_CONNECTION_SAFETY_INTERVAL_MS)||void 0}),Te=new Gl(R.controlledInstances,Tg,{isInstalled:async(e,t)=>{const n=await pe(e,t);return await le(e).inspectRuntime(R.context(e),n.identity)},isRuntimeRunning:async e=>{const t=oe(e);if(!t.runtimeState)return!0;const n=await t.runtimeState(R.context(e));return"stopped"!==n&&"absent"!==n},onDrainSkipped:e=>me.log.warn({instanceId:e.id},"runtime is not running; skipping app session drain before runtime convergence"),beginDrain:async e=>{try{const t=await async function(e,t,n=async e=>PA(e)){const i=await n(t);if(t.registrationToken&&(await Ow(e,`${i}/api/internal/node-agent/drain`,{method:"POST",headers:{authorization:`Bearer ${t.registrationToken}`}},1e4)).ok)return{requested:t.apps.runningCount,failures:[]};const s=await Ow(e,`${i}/api/apps/sessions`,{method:"GET",headers:{"cache-control":"no-cache"}},5e3);if(!s.ok)throw new Error(`Could not list app sessions for runtime drain (HTTP ${s.status}).`);const r=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return[];const t=e.data;if(Array.isArray(t))return t;if(!t||"object"!=typeof t||Array.isArray(t))return[];const n=t.snapshot,i=(n&&"object"==typeof n&&!Array.isArray(n)?n:t).sessions;return Array.isArray(i)?i:[]}(await s.json()).flatMap(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return[];const t=e;return"running"===t.status&&"string"==typeof t.id&&t.id?[t.id]:[]}),o=await Promise.all(r.map(async t=>{try{const n=await Ow(e,`${i}/api/apps/sessions/${encodeURIComponent(t)}/stop`,{method:"POST"},5e3);return n.ok?void 0:{sessionId:t,error:`HTTP ${n.status}`}}catch(e){return{sessionId:t,error:e instanceof Error?e.message:String(e)}}}));return{requested:r.length,failures:o.filter(e=>Boolean(e))}}(W,e,V);return t.failures.length?me.log.warn({instanceId:e.id,requested:t.requested,failures:t.failures},"runtime convergence could not stop every app session"):me.log.info({instanceId:e.id,requested:t.requested},"runtime convergence requested app session drain"),!0}catch(t){return me.log.warn({instanceId:e.id,error:t instanceof Error?t.message:String(t)},"runtime convergence could not request app session drain"),!1}},endDrain:async e=>{try{await async function(e,t,n=async e=>PA(e)){return!!t.registrationToken&&(await Ow(e,`${await n(t)}/api/internal/node-agent/resume`,{method:"POST",headers:{authorization:`Bearer ${t.registrationToken}`}},5e3)).ok}(W,e,V)&&me.log.info({instanceId:e.id},"runtime convergence released app session drain")}catch(t){me.log.warn({instanceId:e.id,error:t instanceof Error?t.message:String(t)},"runtime convergence could not release app session drain")}},install:async(e,t)=>{const n=le(e);await n.installRuntime(R.context(e),await pe(e,t))},restart:async e=>{const t=oe(e),n=R.applyInstanceLifecycle(e.id,{type:"convergence-restart-requested"}),i=await t.restart(R.context(n)),s=Ia.parse({...n,...i,target:i.target?{...n.target,...i.target}:n.target,runtime:i.runtime?{...n.runtime,...i.runtime}:n.runtime,updatedAt:de()}),r=await vw(W,s,V);R.applyInstanceLifecycle(e.id,{type:"runtime-lifecycle-completed",baseline:n,observation:{...i,target:i.target?{...i.target,status:r}:void 0,targetStatus:r,uiAccessStatus:r}})},onForcedDrain:e=>me.log.warn({instanceId:e.id},"runtime convergence drain deadline reached; restarting instance")},{drainTimeoutMs:Number(process.env.TASK_HANDOFF_RUNTIME_DRAIN_TIMEOUT_MS)||void 0,verificationTimeoutMs:Number(process.env.TASK_HANDOFF_RUNTIME_VERIFY_TIMEOUT_MS)||void 0,maxAttempts:Number(process.env.TASK_HANDOFF_RUNTIME_MAX_ATTEMPTS)||void 0});R.controlledInstances.setOnStored(e=>{Ae.publishInstanceLifecycle(e)}),Ae.start(),me.decorate("nodeAgentEventForwarder",Ae);const be=new H_(_.agents.orchestrations,_.agents.definitions,(e,t,n)=>Ae.publish(e,t,n)),we=new F_(R,_.agents.definitions,be,(e,t,n)=>Ae.publish(e,t,n)),Ne={runtime:"docker",workspaceMaterializer:"overlay-copy-on-write",processSandbox:"instance",providerId:"codex"},ve=new q_(R,we,be,_.agents.runs,e=>e.runtimeType===Ne.runtime&&e.providerId===Ne.providerId&&e.executionPolicy.workspaceMaterializer===Ne.workspaceMaterializer&&e.executionPolicy.processSandbox===Ne.processSandbox&&"full-access"!==e.permissionMode,(e,t,n)=>Ae.publish(e,t,n),_.agents.resources),Oe=new mE(W,V),Re=new _E(L,_.agents.resources,e=>{const t=R.requireInstance(e);return{nodeId:R.node.id,runtimeId:t.runtimeId,instanceId:e,containerName:t.runtime.containerName||qc(e),expectedContainerId:t.runtime.containerId,providerReady:t.ready&&"running"===t.status&&"online"===t.connectionStatus&&"online"===t.agentStatus&&"reachable"===t.targetStatus}},async(e,t)=>{const n=ve.getMember(e,t);await Oe.close(R.requireInstance(n.instanceId),e,t)}),xe=new Q_;xe.register({runtimeType:"docker",workspaceMaterializer:"overlay-copy-on-write",processSandbox:"instance"},Re);const Ce=new fE(_.agents.resources,Re,Ac),ke=new sE({state:R,runs:ve,materializers:xe,sharedSpaces:Ce,resources:_.agents.resources,sessions:Oe,reconcileInstanceResources:e=>Re.reconcileInstance(e)});ve.setCoordinator(ke),ke.reconcile().catch(e=>me.log.warn({error:e},"Agent Run startup reconciliation failed")),Ce.reconcileExpired().catch(e=>me.log.warn({error:e},"Agent Run startup shared-space expiry reconciliation failed"));const De=setInterval(()=>{ke.reconcile().catch(e=>me.log.warn({error:e},"Agent Run reconciliation retry failed")),Ce.reconcileExpired().catch(e=>me.log.warn({error:e},"Agent Run shared-space expiry reconciliation failed"))},5e3);De.unref();const Le=new EE(x,we,be,_.agents.storyEntries,async({storyId:e})=>{const t=await C.resolve(e);await X.notify({storyId:e,revision:t.revision})}),Pe=new BE(R,x,W,V),Me=new QE(R,W,V),je=new eA(W,V),Ue=new nA(R,_,W,V,e=>Ae.publish("story.decision.changed",e,{nodeId:R.node.id}));K.setSessionClosedHandler(async e=>{await Ue.expireForSession(e,{code:"AI_SESSION_CLOSED",message:"The AI Session that raised the decision was closed."})});const Fe=new VE(R,x,k,W,V,(e,t,n)=>Ae.publish(e,t,n),void 0,Pe),$e=new UE(R,x,k,Fe,_,je,Ue);await $e.init(),await Fe.start(),x.setOnChange((e,t)=>{Ae.publish("story.changed",{storyId:t.id,nodeId:t.ownerNodeId,change:e},{nodeId:t.ownerNodeId}),K.reconcile()});const He=new ml(L,()=>R.listInstances().filter(e=>"docker"===R.requireRuntime(e.runtimeId).type),e=>Ae.publish("instance.metrics.snapshot",e,{instanceId:e.instanceId}));He.start(),me.decorate("nodeAgentRuntimeMetrics",He);const Be=(I=process.env.TASK_HANDOFF_DIAGNOSTIC_LOGS,["1","true","yes","on"].includes(String(I||"").trim().toLowerCase())),qe=new qA(T,b,E,A),Ve=(e,t)=>{Be&&me.log.info(e,t)},Ge={diagnostic:Ve,warn:(e,t)=>me.log.warn(e,t)},We=new IA,Ke=new SA(R.environmentTemplates,j,e=>R.requireInstance(e),e=>R.requireRuntime(e),(e,t)=>We.run(e,t),e=>[e.registrationToken,...R.modelRegistry.privateSecretValues(e.id)].filter(e=>Boolean(e)),e=>R.listInstances().some(t=>t.environmentTemplateOrigin?.imageId===e)),Ye=(e,t,n)=>{const i=n&&"object"==typeof n&&!Array.isArray(n)?n.protocolVersion:void 0;if("string"!=typeof i||i===Qi)return n;const s=({field:n,action:s})=>me.log.warn({instanceId:e,report:t,protocolVersion:i,expectedProtocolVersion:Qi,field:n,action:s},"cross-version controlled instance report sanitized");return"register"===t?function(e,t){if(!e||"object"!=typeof e||Array.isArray(e))return e;const n=e,i=["instanceId","projectId","source","nodeId","runtimeId","imageSelection","instanceVersion","protocolVersion","build","controlMode","capabilities","appInventory","target","workspace","registrationToken","processIncarnationId"],s=new Set([...i,"imageId"]);for(const e of Object.keys(n))s.has(e)||t?.({field:e,action:"ignored"});return Object.prototype.hasOwnProperty.call(n,"imageId")&&t?.({field:"imageId",action:"migrated"}),{...Oa(n,i),imageSelection:Gs(n.imageSelection,n.imageId)}}(n,s):function(e,t){if(!e||"object"!=typeof e||Array.isArray(e))return e;const n=["status","health","protocolVersion","build","capabilities","appInventory","apps","aiSessions","triggers","workspace","target","processIncarnationId"],i=new Set(n);for(const n of Object.keys(e))i.has(n)||t?.({field:n,action:"ignored"});return Oa(e,n)}(n,s)},Xe=e=>"local-folder"!==e.source.type&&Jl(e),Je=async(e,t,n=()=>!0,i)=>{try{if(!n())return R.requireInstance(e);let s=R.requireInstance(e);ne.arm(s),"failed"===s.runtimeVersion?.phase&&ue(s)&&(s=R.controlledInstances.put(Ia.parse({...s,ready:!1,runtimeVersion:wg(Wl(s)),updatedAt:de()})));const r=R.requireRuntime(s.runtimeId);Xe(s)&&"docker"===r.type&&!Xl(s)&&nt(s),await Cw(R,$,W,e,Ge,V,t,i);const o=R.requireInstance(e);if("docker"===r.type&&o.imageProvisioning&&"ready"!==o.imageProvisioning.phase)return Ae.syncNow(),o;if("docker"===r.type&&Xe(o))return Ae.syncNow(),o;if(!n())return R.requireInstance(e);U.markRestored(e);let a=R.requireInstance(e);if(ue(a)){try{a=await Te.schedule(e,{startRequested:!0})}catch(n){a=R.requireInstance(e),Ge.warn({instanceId:e,action:"runtime.converge",reason:t,error:n instanceof Error?n.message:String(n)},"node instance runtime convergence failed after start")}"matched"!==a.runtimeVersion?.phase&&a.runtimeVersion?.error&&Ge.warn({instanceId:e,action:"runtime.converge",reason:t,error:a.runtimeVersion.error},"node instance started with pending runtime convergence")}if("docker"===r.type&&"reachable"===a.targetStatus){const n=await($.forRuntime(r).resolveNodeAgentUrl?.(R.context(a)))||R.containerUrl;Rw(W,a,n,V).then(i=>{Ge.diagnostic({instanceId:e,action:"node-agent-connection.sync",reason:t,syncStatus:i,nodeAgentUrl:n},"node instance connection endpoint synchronized after runtime convergence")}).catch(n=>{Ge.warn({instanceId:e,action:"node-agent-connection.sync",reason:t,error:n instanceof Error?n.message:String(n)},"node instance connection endpoint sync after runtime convergence deferred")})}return n()?(await zw(W,a,"start",Ge,V),Ae.syncNow(),a):R.requireInstance(e)}catch(n){throw R.applyInstanceLifecycle(e,{type:"start-failed",error:n}),Ae.syncNow(),Ge.warn({instanceId:e,action:"start",reason:t,error:n instanceof Error?n.message:String(n)},"node instance start failed"),n}},Qe=new EA(R,P,{sync:()=>Ae.syncNow(),diagnostic:Ge.diagnostic,warn:Ge.warn,publish:(e,t,n)=>Ae.publish(e,t,{instanceId:n}),runInstanceOperation:(e,t)=>We.run(e,t)}),Ze=e=>{const t=We.intent(e.id);Qe.provision(e,async()=>{await Je(e.id,"image-ready",()=>We.isIntentCurrent(e.id,t),We.signal(e.id,t)).catch(()=>{})})},et=H?new fw({executor:H,logger:(e,t)=>me.log.debug(t,e)}):void 0,tt=new TA(R.controlledInstances,{context:e=>R.context(e),run:(e,t)=>{if("wsl"===R.requireRuntime(e.instance.runtimeId).type){if(!et||!q)throw Object.assign(new Error(`The WSL runtime is not configured on this node; cannot provision the Git workspace for ${e.instance.id}.`),{statusCode:503,code:"GIT_WORKSPACE_PROVISIONING_UNSUPPORTED"});const n=q.distroNameForInstance({id:e.instance.id,containerName:e.instance.runtime.containerName});return et.provision(e,n,{onOutput:t.onOutput,signal:t.signal})}return j.provisionGitWorkspaceStreaming(e,{onOutput:t.onOutput,signal:t.signal})},sync:()=>Ae.syncNow(),diagnostic:Ge.diagnostic,warn:Ge.warn,publish:(e,t,n)=>Ae.publish(e,t,{instanceId:n}),runInstanceOperation:(e,t)=>We.run(e,t)}),nt=e=>{const t=We.intent(e.id);tt.provision(e,async()=>{await Je(e.id,"git-ready",()=>We.isIntentCurrent(e.id,t),We.signal(e.id,t)).catch(()=>{})})},it=function(e,i){const s=i??id();try{const i=function(e=id()){if(!t.existsSync(e))return[];const i=[];for(const s of t.readdirSync(e,{withFileTypes:!0}).sort((e,t)=>e.name.localeCompare(t.name))){if(!s.isDirectory())continue;const r=n.join(e,s.name);if(!t.existsSync(n.join(r,Kc)))continue;const o=ad(r),a=n.join(r,"content");if(!t.existsSync(a))throw nd("BUILTIN_PROJECT_CONTENT_INVALID",`Built-in project ${o.id} has no content directory.`,{root:r});const c=rd(a),d=od(c);if(d!==o.contentDigest)throw nd("BUILTIN_PROJECT_CONTENT_INVALID",`Built-in project ${o.id} content does not match its manifest digest.`,{root:r,expected:o.contentDigest,actual:d});i.push({id:o.id,name:o.name,...o.localizedNames?{localizedNames:o.localizedNames}:{},runtimes:o.runtimes,contentDigest:o.contentDigest,root:r,contentDir:a,files:c})}return i}(s);if(i.length)return i;e.diagnostic({sourceDir:s},"node agent built-in project catalog is empty")}catch(t){e.diagnostic({sourceDir:s,error:t instanceof Error?t.message:String(t)},"node agent built-in project catalog unavailable")}}(Ge,e.builtinProjectsDir);if(it){const e=gd({definitions:it,targetsDir:p.builtinProjectTargetsDir,nodeId:b});if(R.attachBuiltinProjectFolders(e),R.nodeRuntimes.list().some(e=>"local"===e.type))for(const t of e.prepare())"failed"!==t.status?me.log.info({projectId:t.projectId,status:t.status},"builtin project ready"):Ge.diagnostic({projectId:t.projectId,targetDir:t.targetDir,errorCode:t.code,error:t.message},"builtin project initialization failed")}U=new iT({state:R,runtimeAdapters:$,convergence:Te,restoreInstance:e=>Cw(R,$,W,e,Ge,V,"restore"),autoImport:e=>zw(W,e,"start",Ge,V),provisionImage:Ze,provisionGit:nt,stopImageProvisioning:()=>Qe.stop(),stopGitProvisioning:()=>tt.stop(),usesManagedArtifact:ue,warn:Ge.warn,error:(e,t)=>me.log.error(e,t),runInstanceOperation:(e,t)=>We.run(e,t)});const st=H&&q&&$.has("wsl")?new aw({listRunningInstances:()=>R.listInstances().filter(e=>"wsl"===R.requireRuntime(e.runtimeId).type).filter(e=>["registering","registered","running","unhealthy"].includes(e.status)).map(e=>({id:e.id,distroName:q.distroNameForInstance({id:e.id,containerName:e.runtime.containerName})})),holdSession:e=>H.holdSession(e),sessionAlive:e=>H.sessionAlive(e),releaseSession:e=>H.releaseSession(e),distroState:e=>H.distroState(e),ensureDistroRunning:async e=>{await H.ensureDistroRunning(e)},unitActive:e=>H.unitActive(e,hb),waitForEndpointHealthy:async e=>"reachable"===await vw(W,R.requireInstance(e),V),onDiagnostic:e=>{"WSL_SESSION_RECOVERED"===e.code?me.log.info(e,e.message):me.log.warn(e,e.message),Ae.syncNow()},onSessionLost:(e,t)=>{U.allowRecovery(e),Ge.warn({instanceId:e,distroName:t},"wsl keep-alive session lost; the supervisor will rebuild it"),Ae.syncNow()}}):void 0,rt=new oT({listTargets:()=>R.nodeRuntimes.list().flatMap(e=>{let t;try{const n=$.forRuntime(e);t=n.check?.bind(n)}catch{return[]}return t?[{runtime:e,probe:()=>t(R.requireRuntime(e.id))}]:[]}),apply:(e,t)=>{R.recordRuntimeProbe(e.id,t)},onAvailable:(e,t)=>{me.log.info({runtimeId:e.id,runtimeType:e.type,previousStatus:t.status},"node runtime became available; resuming instance recovery"),U.notifyRuntimeAvailable()},onUnavailable:(e,t)=>{me.log.warn({runtimeId:e.id,runtimeType:e.type,previousStatus:t.status,error:Nw(e)},"node runtime is unavailable; instance recovery is paused until it returns")},onProbeError:(e,t)=>{me.log.warn({runtimeId:e.id,runtimeType:e.type,error:t},"node runtime availability probe failed")},onCycleError:e=>{me.log.warn({error:e},"node runtime availability cycle failed")}},{intervalMs:sT(process.env.TASK_HANDOFF_RUNTIME_AVAILABILITY_INTERVAL_MS)}),ot=new QA({nodeId:b,jobs:R.updateJobs,runCommand:G,currentRuntimeVersion:Tg,listInstances:()=>R.listInstances(),moduleDir:("undefined"==typeof document?require("url").pathToFileURL(__filename).href:z&&"SCRIPT"===z.tagName.toUpperCase()&&z.src||new URL("cli.js",document.baseURI).href)?n.dirname(r.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(__filename).href:z&&"SCRIPT"===z.tagName.toUpperCase()&&z.src||new URL("cli.js",document.baseURI).href)):__dirname,managedUpdateSupport:e.managedUpdateSupport||(n=>"linux"!==(e.platform||process.platform)?{supported:!1,reason:"Managed server updates require Linux and systemd."}:"function"==typeof process.getuid&&0!==process.getuid()?{supported:!1,reason:"Managed server updates require the node agent to run as root."}:t.existsSync("/run/systemd/system")?"@task-handoff/server"!==n.packageName||process.env.TASK_HANDOFF_CONTROL_PLANE_HEALTH_URL?.trim()?process.env.TASK_HANDOFF_NODE_AGENT_IPC_PATH?.trim()?{supported:!0}:{supported:!1,reason:"Managed server updates require the node-agent IPC readiness endpoint."}:{supported:!1,reason:"Managed server updates require a local control-plane health URL."}:{supported:!1,reason:"Managed server updates require an active systemd host."})});me.setErrorHandler((e,t,n)=>{const i=function(e){if(e instanceof c.z.ZodError)return{statusCode:400,code:"VALIDATION_ERROR",message:e.issues.map(e=>`${e.path.join(".")||"body"}: ${e.message}`).join("; "),details:{issues:e.issues.map(e=>({path:e.path.map(String),code:e.code,message:e.message}))}};const t=e&&"object"==typeof e?e:{};return{statusCode:"number"==typeof t.statusCode?t.statusCode:500,code:"string"==typeof t.code?t.code:"NODE_AGENT_ERROR",message:e instanceof Error?e.message:String(e),...t.details&&"object"==typeof t.details&&!Array.isArray(t.details)?{details:t.details}:{},..."boolean"==typeof t.retryable?{retryable:t.retryable}:{}}}(e);(Be||i.statusCode>=500)&&(i.statusCode>=500?me.log.error.bind(me.log):me.log.warn.bind(me.log))({method:t.method,url:t.url,statusCode:i.statusCode,errorCode:i.code,error:i.message},"node agent request failed"),n.code(i.statusCode).send({error:{code:i.code,message:i.message,...i.details?{details:i.details}:{},...e&&"object"==typeof e&&"string"==typeof e.expectedVersion?{expectedVersion:e.expectedVersion}:{},...e&&"object"==typeof e&&"string"==typeof e.actualVersion?{actualVersion:e.actualVersion}:{},...e&&"object"==typeof e&&"string"==typeof e.phase?{phase:e.phase}:{},...e&&"object"==typeof e&&"boolean"==typeof e.retryable?{retryable:e.retryable}:{},...e&&"object"==typeof e&&"number"==typeof e.blockingInstanceCount?{blockingInstanceCount:e.blockingInstanceCount}:{}}})}),me.addHook("preHandler",async e=>{if(Ew.has(e.raw)){if(Sw(e.url))return;const t=new Error("Container IPC only accepts instance-scoped node agent requests.");throw Object.assign(t,{statusCode:401,code:"NODE_AGENT_CONTAINER_IPC_ROUTE_FORBIDDEN"}),t}if(tg(e.url.split("?")[0]))return;const t=qe.verify(e);if(t){if(T.isRevokedPairing(t)&&"/api/node-agent/pairing/current"!==e.url.split("?")[0]){const e=new Error("The node agent pairing used for this request has been revoked.");throw Object.assign(e,{statusCode:401,code:"NODE_AGENT_HMAC_KEY_REVOKED"}),e}e.nodeAgentAuthKeyId=t}else if(ww(e)){if(i&&Tw(e.headers)!==i){const e=new Error("Invalid node agent token.");throw Object.assign(e,{statusCode:401,code:"NODE_AGENT_UNAUTHORIZED"}),e}}else if("/api/node-agent/pairing/complete"!==e.url.split("?")[0]&&!Sw(e.url)){if(qe.hasRemoteSecrets()){const e=new Error("Node agent HMAC signature is required.");throw Object.assign(e,{statusCode:401,code:"NODE_AGENT_HMAC_SIGNATURE_REQUIRED"}),e}if(!function(e){return bw(e.ip)||bw(e.socket.remoteAddress)||!e.ip&&!e.socket.remoteAddress&&!e.socket.remoteFamily}(e)){const e=new Error("Local node agent access is only accepted from loopback or local IPC connections.");throw Object.assign(e,{statusCode:401,code:"NODE_AGENT_LOCAL_TOKEN_REQUIRES_LOOPBACK"}),e}if(i&&Tw(e.headers)!==i){const e=new Error("Invalid node agent token.");throw Object.assign(e,{statusCode:401,code:"NODE_AGENT_UNAUTHORIZED"}),e}}}),me.addHook("onClose",async()=>{x.stopAccepting(),_.stopAccepting();const e=Number(process.env.TASK_HANDOFF_STORY_DRAIN_DIAGNOSTIC_MS)||3e4,t=setTimeout(()=>{me.log.warn({pendingStoryIds:x.coordinator.pendingStoryIds()},"Story storage drain deadline reached; waiting for accepted operations and preserving recovery intents")},e);t.unref();try{clearInterval(De),await ke.stop(),await Fe.stop(),clearInterval(Ie),clearInterval(_e),He.stop(),rt.stop(),Ae.stop(),await(st?.stop()),await U.stop(),await x.drain(),await _.close()}finally{clearTimeout(t)}}),me.decorate("nodeAgentRestoreManagedInstances",()=>U.restoreManagedInstances()),me.decorate("nodeAgentRecoverManagedInstances",()=>U.recoverManagedInstances()),me.decorate("nodeAgentStartRecoverySupervisor",()=>U.start()),me.decorate("nodeAgentStartRuntimeAvailabilityMonitor",()=>rt.start()),me.decorate("nodeAgentStartWslSessionSupervisor",()=>st?.start()),me.decorate("nodeAgentPrefetchWslBaseTemplate",async()=>{await(q?.prefetchBaseTemplate())}),me.get("/api/node-agent/health",async()=>{const e=s.hostname().trim();return{data:{ok:!0,role:"node-agent",...e?{hostname:e}:{},process:{pid:process.pid,..._w?{startIdentity:_w}:{}},listener:{host:"127.0.0.1",port:R.currentListenerPort},nodeId:b,platform:yT(v),arch:process.arch,protocolVersion:Qi,capabilities:{modelEndpointProbe:!0,managedModels:{multiEntityAssignment:!0,privateModelCatalog:!0,stableModelIdentity:!0,requestMappings:!0,modelRelay:(()=>{const e=at.protocolCapabilities();return{protocols:e,streaming:e.length>0,unknownModelPolicy:!0}})()},aiSessionHistoryLimit:!0,aiSessionAttachmentRetention:!0,aiSessionFileAttachmentLimit:!0,codexManagedSettings:!0,folderPlaces:!0,localFolderNameUpdate:!0,managedGitCredentials:{registry:!0,runtimeBroker:!0,workspaceProvisioning:{docker:!0,kubernetes:!1,local:!1,wsl:$.has("wsl")}},stories:{enabled:!0,agentTools:!0,agentToolCapabilities:{policy:!0,actions:!0,automations:!0,aiSessionRead:!0,decisions:!0},sessionRetention:!0,maxFileBytes:33554432,maxBatchPaths:20},agentExecution:{definitions:!0,runs:!0,orchestration:{storyEntryAuthorization:!0,orchestrations:!0,runMembers:!0,manualRuns:!0},sharedSpace:{enabled:!0,runtimes:["docker"]},combinations:[Ne]}},build:(t="node-agent",{component:t,packageName:"@task-handoff/node-agent",packageVersion:Tg(),protocolVersion:Qi,buildId:Aw("TASK_HANDOFF_BUILD_ID"),builtAt:Aw("TASK_HANDOFF_BUILT_AT"),gitCommit:Aw("TASK_HANDOFF_GIT_COMMIT"),imageRef:Aw("TASK_HANDOFF_IMAGE_REF"),imageDigest:Aw("TASK_HANDOFF_IMAGE_DIGEST")}),instanceProxy:{...Ee},eventTransport:Ae.eventTransportHealth(),serverTime:(new Date).toISOString()}};var t}),!function(e,t){e.get("/api/node-agent/settings/external-listener",async e=>({data:t(e).current()})),e.patch("/api/node-agent/settings/external-listener",async e=>({data:await t(e).update(e.body)}))}(me,e=>{if(!ww(e)){const e=new Error("Node agent TCP listener settings are available only over local Unix IPC.");throw Object.assign(e,{statusCode:403,code:"NODE_AGENT_LISTENER_LOCAL_IPC_ONLY"}),e}if(!me.nodeAgentListenerManager){const e=new Error("Node agent TCP listener manager is not initialized.");throw Object.assign(e,{statusCode:503,code:"NODE_AGENT_LISTENER_UNAVAILABLE"}),e}return me.nodeAgentListenerManager}),function(e,t,n){e.get("/api/node-agent/updates/jobs",async()=>({data:n.list()})),e.post("/api/node-agent/updates/check",async e=>({data:await t.check(e.body)})),e.post("/api/node-agent/updates/apply",async(e,n)=>n.code(202).send({data:await t.apply(e.body)}))}(me,ot,R.updateJobs),function(e,t){const{identity:n,nodeId:i,fetchImpl:s}=t;e.post("/api/node-agent/pairing/invites",async(e,t)=>{const s=n.createPairingInvite(ph.parse(e.body||{}));return t.code(201).send({data:{nodeId:i,joinToken:s.token,expiresAt:s.expiresAt}})}),e.post("/api/node-agent/pairing/complete",async(e,t)=>{const s=n.completePairingInvite(mh.parse(e.body));return t.code(201).send({data:{nodeId:i,keyId:s.keyId,secret:s.secret,pairedAt:s.pairedAt}})}),e.get("/api/node-agent/control-plane-pairings",async e=>({data:n.listControlPlanePairings(e.nodeAgentAuthKeyId)})),e.delete("/api/node-agent/control-plane-pairings/:keyId",async e=>{const t=YA.parse(e.params.keyId);return{data:{deleted:n.deleteControlPlanePairing(t,e.nodeAgentAuthKeyId)}}}),e.delete("/api/node-agent/pairing/current",async e=>({data:n.revokeCurrentControlPlanePairing(e.nodeAgentAuthKeyId||"")})),e.get("/api/node-agent/control-plane-connections",async()=>({data:n.listControlPlaneConnections().map(e=>({...e,...t.reverseTunnels()?.state(e.id)||{status:e.enabled?"connecting":"disabled"}}))})),e.delete("/api/node-agent/control-plane-connections/:connectionId",async e=>{const i=YA.parse(e.params.connectionId),s=n.deleteControlPlaneConnection(i);return s&&t.reverseTunnels()?.connectConfigured(),{data:{deleted:s}}}),e.post("/api/node-agent/control-plane-connections",async(e,r)=>{const o=hh.parse(e.body),a=function(e){const t=new URL(e);if("http:"!==t.protocol&&"https:"!==t.protocol){const e=new Error("Control-plane URL must use http or https.");throw Object.assign(e,{statusCode:400,code:"NODE_AGENT_REMOTE_CONTROL_PLANE_URL_INVALID"}),e}return t.toString().replace(/\/$/,"")}(o.controlPlaneUrl);return n.runControlPlaneConnectionOperation(a,async()=>{const e=n.stageControlPlaneConnection({url:a,...o.controlPlaneName?{name:o.controlPlaneName}:{},enabled:!1!==o.activate});let c;try{c=await async function(e,t,n){const i=await e(new URL("/api/node-join/complete",t).toString(),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n)}),s=await i.json().catch(()=>({}));if(!i.ok){const e=new Error(s.error?.message||`Control-plane node join failed with HTTP ${i.status}.`);throw Object.assign(e,{statusCode:i.status,code:s.error?.code||"NODE_AGENT_REMOTE_JOIN_FAILED"}),e}return s.data||{}}(s,a,{joinToken:o.joinToken,nodeId:i,nodeName:t.nodeName(),keyId:e.pairing.keyId,secret:e.pairing.secret,pairedAt:e.pairing.pairedAt})}catch(t){throw n.rollbackControlPlaneConnection(e),t}n.markControlPlaneConnectionRemoteAccepted(e);const d=n.commitControlPlaneConnection(e,{name:o.controlPlaneName||("string"==typeof c.name&&c.name?c.name:void 0)});let l,u=d.connection.enabled?"saved":"disabled";const p=t.reverseTunnels();if(p)try{p.connectConfigured(),d.connection.enabled&&(u="connecting")}catch(e){u="failed",l=e instanceof Error?e.message:String(e)}return r.code(201).send({data:{pairing:n.listControlPlanePairings().find(e=>e.keyId===d.pairing.keyId),connection:d.connection,tunnel:{status:u,...l?{error:l}:{}}}})})})}(me,{identity:T,nodeId:b,nodeName:()=>R.node.name,fetchImpl:W,reverseTunnels:()=>me.nodeAgentReverseTunnels}),function(e,t){e.get("/api/node-agent/runtimes",async()=>({data:t.listRuntimes()})),e.post("/api/node-agent/runtimes",async(e,n)=>n.code(201).send({data:t.createRuntime(gA.parse(e.body))})),e.patch("/api/node-agent/runtimes/:id",async e=>({data:t.updateRuntime(e.params.id,fA.parse(e.body))})),e.delete("/api/node-agent/runtimes/:id",async e=>({data:{deleted:t.deleteRuntime(e.params.id)}})),e.post("/api/node-agent/runtimes/:id/check",async e=>({data:await t.checkRuntime(e.params.id)})),e.get("/api/node-agent/local-folders",async()=>({data:t.listLocalFolders()})),e.get("/api/node-agent/folders/places",async()=>({data:t.listFolderPlaces()})),e.get("/api/node-agent/folders/tree",async e=>({data:t.listFolderTree(pA.parse(e.query))})),e.post("/api/node-agent/local-folders",async(e,n)=>n.code(201).send({data:t.createLocalFolder(lA.parse(e.body))})),e.patch("/api/node-agent/local-folders/:id",async e=>({data:t.updateLocalFolder(e.params.id,uA.parse(e.body))})),e.delete("/api/node-agent/local-folders/:id",async e=>({data:{deleted:t.deleteLocalFolder(e.params.id)}}))}(me,{listRuntimes:()=>R.nodeRuntimes.list(),createRuntime:e=>R.createRuntime(e),updateRuntime:(e,t)=>R.updateRuntime(e,t),deleteRuntime:e=>R.deleteRuntime(e),checkRuntime:async e=>{if(await rt.checkRuntime(e))return R.requireRuntime(e);const t=R.requireRuntime(e);return R.checkRuntime(e,$.forRuntime(t))},listLocalFolders:()=>R.listLocalFolders(),listFolderPlaces:Nl,listFolderTree:Ol,createLocalFolder:e=>R.createLocalFolder(e),updateLocalFolder:(e,t)=>R.updateLocalFolder(e,t),deleteLocalFolder:e=>R.deleteLocalFolder(e)}),function(e,t,n,i){const s=async e=>{for(const i of t.referencingInstanceIds(e))await n(i)};e.get("/api/node-agent/models",async()=>({data:t.list()})),e.post("/api/node-agent/models",async(e,n)=>n.code(201).send({data:t.create(Jr.parse(e.body))})),e.post("/api/node-agent/models/discover",async e=>{const n=sf.parse(e.body);return{data:await Gg(i,{...n,key:t.resolveProbeKey(n.existingModelId,n.key)})}}),e.post("/api/node-agent/models/test",async e=>{const n=rf.parse(e.body);return{data:await Wg(i,{...n,key:t.resolveProbeKey(n.existingModelId,n.key)})}}),e.put("/api/node-agent/models/:id/deploy",async e=>{const n=e.params.id,i=Zr.parse(e.body);if(i.id!==n)throw Object.assign(new Error(`Model payload id ${i.id} does not match route id ${n}.`),{statusCode:400,code:"NODE_MODEL_ID_MISMATCH"});const r=t.deploy(i);return await s(r.id),{data:r}}),e.patch("/api/node-agent/models/:id",async e=>{const n=t.update(e.params.id,Qr.parse(e.body));return await s(n.id),{data:n}}),e.post("/api/node-agent/models/:id/merge",async e=>{const i=e.params.id,{targetModelId:s}=no.parse(e.body),r=t.merge(i,s);for(const e of r.reassignedInstances)await n(e);return{data:r}}),e.delete("/api/node-agent/models/:id",async e=>({data:{deleted:t.delete(e.params.id)}})),e.put("/api/node-agent/instances/:id/model-assignment",async e=>{const i=e.params.id,s=e.body&&"object"==typeof e.body&&!Array.isArray(e.body)&&Object.prototype.hasOwnProperty.call(e.body,"modelEntityIds"),r=t.assign(i,so.parse(e.body));if(await n(i),s)return{data:r};const{modelEntityIds:o,...a}=r.assignment;return{data:{...r,assignment:a}}}),e.post("/api/node-agent/instances/:id/sync-models",async e=>{const t=e.params.id;return{data:{synced:!0===await n(t)}}})}(me,R.modelRegistry,e=>xw(W,R,e,Ge.warn,V),W);const at=new Bf({resolver:new ig(R.modelRegistry),adapters:[{...vf({protocol:"openai-responses",responsePaths:[["model"],["response","model"]]}),planOperation:({method:e,operationPath:t,search:n,model:i})=>"GET"===e&&"/models"===t?Nf("models.list",wf(i)):"POST"===e&&"/responses"===t?Sf("responses.create","POST",Tf(i.endpoint,"/responses",n),"json"):bf("openai-responses")},{...vf({protocol:"openai-chat-completions",responsePaths:[["model"]]}),planOperation:({method:e,operationPath:t,search:n,model:i})=>"GET"===e&&"/models"===t?Nf("models.list",wf(i)):"POST"===e&&"/chat/completions"===t?Sf("chat.completions.create","POST",Tf(i.endpoint,"/chat/completions",n),"json"):bf("openai-chat-completions")},{...vf({protocol:"anthropic-messages",responsePaths:[["model"],["message","model"]]}),planOperation:({method:e,operationPath:t,search:n,model:i})=>{const s=function(e){return e.startsWith("/v1/")?e.slice(3):e}(t);return"GET"===e&&"/models"===s?Nf("models.list",function(e){const t=Af(e);return JSON.stringify({data:t.map(e=>({id:e,type:"model",display_name:e,created_at:"2026-01-01T00:00:00Z"})),has_more:!1,first_id:t[0]??null,last_id:t[t.length-1]??null})}(i)):"POST"===e&&"/messages"===s?Sf("messages.create","POST",Tf(i.endpoint,"/v1/messages",n),"json"):"POST"===e&&"/messages/count_tokens"===s?Sf("messages.count_tokens","POST",Tf(i.endpoint,"/v1/messages/count_tokens",n),"json"):"HEAD"===e&&"/api/hello"===s?{kind:"reject",name:"gateway.probe",status:404,code:cf,message:"The node model relay does not proxy gateway probes."}:bf("anthropic-messages")}}],log:me.log,fetchImpl:W});me.decorate("nodeAgentModelRelay",at),at.registerRoutes(me);const ct=new lg({settings:Dg(p,Cg("127.0.0.1",d)),registry:R.modelRegistry,relaySwitch:R.modelRelaySwitch});return ct.restore(),function(e,t){e.get("/api/node-agent/settings/model-relay",async()=>({data:t.effective()})),e.patch("/api/node-agent/settings/model-relay",async e=>{const n=t.enabled(),i=t.update(e.body);return n!==i.enabled&&await(async e=>{for(const e of R.modelRegistry.assignedInstanceIds())await xw(W,R,e,Ge.warn,V);e.enabled||await at.drainActive()})(i),{data:i}})}(me,ct),function(e,t){const n=new Xf(t.gitCredentials);e.addHook("onClose",async()=>n.close()),e.put("/api/node-agent/git-credentials/:credentialId",async e=>{const n=ey.parse(e.params),i=Ii.parse(e.body);if(i.credential.id!==n.credentialId)throw Object.assign(new Error("Credential payload identity mismatch."),{code:"GIT_CREDENTIAL_IDENTITY_MISMATCH",statusCode:409});return{data:t.gitCredentials.putPayload(i).credential}}),e.delete("/api/node-agent/git-credentials/:credentialId",async e=>({data:{deleted:t.gitCredentials.removePayload(ey.parse(e.params).credentialId)}})),e.get("/api/node-agent/instances/:id/git-credential-authorizations",async e=>{const{id:n}=ty.parse(e.params);return t.requireInstance(n),{data:t.gitCredentials.getAuthorizationSet(n)}}),e.put("/api/node-agent/instances/:id/git-credential-authorizations",async e=>{const{id:n}=ty.parse(e.params);t.requireInstance(n);const i=_i.parse(e.body);if(i.instanceId!==n)throw Object.assign(new Error("Git credential authorization identity mismatch."),{code:"GIT_CREDENTIAL_AUTHORIZATION_IDENTITY_MISMATCH",statusCode:409});return{data:t.gitCredentials.putAuthorizationSet(i)}}),e.post("/api/node-agent/instances/:id/git-credentials/https",async e=>{const{id:i}=ty.parse(e.params);t.authenticateInstance(i,iy(e.headers));const s=Ei.parse(e.body);return{data:Ai.parse(n.resolveHttps(i,s.remoteUrl))}}),e.post("/api/node-agent/instances/:id/git-credentials/ssh/prepare",async e=>{const{id:i}=ty.parse(e.params);t.authenticateInstance(i,iy(e.headers));const s=Ti.parse(e.body);return{data:bi.parse(await n.prepareSsh(i,s.remoteUrl))}}),e.post("/api/node-agent/instances/:id/git-credentials/ssh/agent",async e=>{const{id:i}=ty.parse(e.params);t.authenticateInstance(i,iy(e.headers));const s=wi.parse(e.body);return{data:Si.parse(await n.exchangeAgentFrame(i,s.invocationId,s.frame))}}),e.delete("/api/node-agent/instances/:id/git-credentials/ssh/:invocationId",async e=>{const{id:i,invocationId:s}=ny.parse(e.params);return t.authenticateInstance(i,iy(e.headers)),{data:{deleted:n.release(s,i)}}})}(me,R),function(e,t){e.get("/api/node-agent/agents",async()=>({data:tp.parse({agents:t.list()})})),e.post("/api/node-agent/agents",async(e,n)=>{const i=Zu.parse(e.body);return n.code(201).send({data:Ju.parse(t.create(i))})}),e.get("/api/node-agent/agents/:agentId",async e=>{const{agentId:n}=C_.parse(e.params);return{data:Ju.parse(t.get(n))}}),e.patch("/api/node-agent/agents/:agentId",async e=>{const{agentId:n}=C_.parse(e.params),i=ep.parse(e.body);return{data:Ju.parse(t.update(n,i))}}),e.delete("/api/node-agent/agents/:agentId",async e=>{const{agentId:n}=C_.parse(e.params),{referencingOrchestrations:i}=k_.parse(e.query??{}),s=t.delete(n,{referencingOrchestrations:i});return{data:np.parse({id:n,deleted:!0,...s})}})}(me,we),function(e,t){e.get("/api/node-agent/agent-orchestrations",async()=>({data:bp.parse({orchestrations:t.list()})})),e.post("/api/node-agent/agent-orchestrations",async(e,n)=>{const i=Ap.parse(e.body);return n.code(201).send({data:Ep.parse(t.create(i))})}),e.get("/api/node-agent/agent-orchestrations/:orchestrationId",async e=>{const{orchestrationId:n}=D_.parse(e.params);return{data:Ep.parse(t.get(n))}}),e.patch("/api/node-agent/agent-orchestrations/:orchestrationId",async e=>{const{orchestrationId:n}=D_.parse(e.params),i=Tp.parse(e.body);return{data:Ep.parse(t.update(n,i))}}),e.delete("/api/node-agent/agent-orchestrations/:orchestrationId",async e=>{const{orchestrationId:n}=D_.parse(e.params);return{data:wp.parse({id:n,deleted:t.delete(n)})}})}(me,be),function(e,t,n){e.get("/api/node-agent/agent-runs",async()=>({data:sm.parse({runs:t.list()})})),e.post("/api/node-agent/agent-runs",async(e,n)=>{const i=nm.parse(e.body);return n.code(201).send({data:tm.parse(t.create(i))})}),e.get("/api/node-agent/agent-runs/:runId",async e=>{const{runId:n}=L_.parse(e.params);return{data:tm.parse(t.get(n))}}),e.get("/api/node-agent/agent-runs/:runId/members/:memberId",async e=>{const{runId:n,memberId:i}=P_.parse(e.params);return{data:Zp.parse(t.getMember(n,i))}}),e.post("/api/node-agent/agent-runs/:runId/cancel",async e=>{const{runId:n}=L_.parse(e.params),i=im.parse(e.body??{});return{data:tm.parse(t.cancel(n,i))}}),e.post("/api/node-agent/agent-runs/:runId/members/:memberId/ai-sessions/:sessionId/agent-runs",async e=>{if(!n)throw Object.assign(new Error("Agent Run member invocation is unavailable."),{code:"AGENT_RUN_MEMBER_INVOCATION_UNAVAILABLE",statusCode:503});const{runId:i,memberId:s,sessionId:r}=M_.parse(e.params),o=t.getMember(i,s);if(!o.aiSessionId||o.aiSessionId!==r)throw Object.assign(new Error("The provider session does not own this Agent Run member."),{code:"AGENT_RUN_MEMBER_SESSION_MISMATCH",statusCode:403});const a=e.headers.authorization,c="string"==typeof a&&a.startsWith("Bearer ")?a.slice(7).trim():void 0;n.authenticateInstance(o.instanceId,c);const d=tI.parse(e.body),l=t.addMember({runId:i,parentMemberId:s,clientRequestId:d.clientRequestId,agentId:d.input.agentId,input:{prompt:d.input.prompt}});return{data:await t.waitForMemberToolResult(i,l.memberId,e.signal)}})}(me,ve,R),function(e,t){e.get("/api/node-agent/stories/:storyId/agent-entries",async e=>{const{storyId:n}=j_.parse(e.params);return{data:O_.parse(await t.get(n))}}),e.put("/api/node-agent/stories/:storyId/agent-entries",async e=>{const{storyId:n}=j_.parse(e.params),i=R_.parse(e.body);return{data:O_.parse(await t.update(n,i))}})}(me,Le),function(e,t,n,i={}){if(e.hasContentTypeParser("application/octet-stream")||e.addContentTypeParser("application/octet-stream",(e,t,n)=>n(null,t)),e.get("/api/node-agent/stories",async()=>({data:{stories:await n.list()}})),e.post("/api/node-agent/stories",async(e,t)=>{const s=My.parse(e.body),r=i.commands?await i.commands.create(s):await n.create(s);return i.onRetentionSettingsChanged?.(),t.code(201).send({data:r})}),e.get("/api/node-agent/stories/:storyId",async e=>{const{storyId:t}=u_.parse(e.params);return{data:await n.get(t)||(()=>{throw Object.assign(new Error("Story was not found."),{code:"STORY_NOT_FOUND",statusCode:404})})()}}),e.patch("/api/node-agent/stories/:storyId",async e=>{const{storyId:t}=u_.parse(e.params),s=jy.parse(e.body),r=i.commands?await i.commands.update(t,s):await n.update(t,s);return void 0!==s.maxIdleAiSessions&&i.onRetentionSettingsChanged?.(),{data:r}}),e.get("/api/node-agent/stories/:storyId/settings",async e=>{const{storyId:t}=u_.parse(e.params);return{data:await n.retentionSettings(t)}}),e.get("/api/node-agent/stories/:storyId/settings/agent-tools",async e=>{const{storyId:t}=u_.parse(e.params);if(!i.toolPolicy)throw Object.assign(new Error("Story Agent Tool policy is unavailable."),{code:"STORY_AGENT_TOOL_POLICY_UNAVAILABLE",statusCode:503});return{data:await i.toolPolicy.settings(t)}}),e.post("/api/node-agent/stories/:storyId/actions/:actionId/run",async e=>{const{storyId:t,actionId:n}=f_.parse(e.params);if(!i.actionExecution)throw Object.assign(new Error("Story Action execution is unavailable."),{code:"STORY_ACTION_EXECUTION_UNAVAILABLE",statusCode:503});const s=OI.omit({actionId:!0}).parse(e.body||{});return{data:py.parse(await i.actionExecution.run(t,n,s.clientRequestId))}}),e.put("/api/node-agent/stories/:storyId/settings/agent-tools",async e=>{const{storyId:t}=u_.parse(e.params);if(!i.toolPolicy)throw Object.assign(new Error("Story Agent Tool policy is unavailable."),{code:"STORY_AGENT_TOOL_POLICY_UNAVAILABLE",statusCode:503});const{policy:s}=gI.parse(e.body),r=await i.toolPolicy.update(t,s),o=await n.get(t);o&&n.notifyUpdated(o);const a=await i.toolPolicy.resolve(t);return await(i.onToolPolicyInvalidated?.({storyId:t,revision:a.revision})),{data:r}}),e.get("/api/node-agent/stories/:storyId/decisions",async e=>{const{storyId:t}=u_.parse(e.params);if(!i.decisions)throw Object.assign(new Error("Story decisions are unavailable."),{code:"STORY_DECISION_UNAVAILABLE",statusCode:503});return{data:Ly.parse(await i.decisions.list(t))}}),e.get("/api/node-agent/stories/:storyId/decisions/:decisionId",async e=>{const{storyId:t,decisionId:n}=y_.parse(e.params);if(!i.decisions)throw Object.assign(new Error("Story decisions are unavailable."),{code:"STORY_DECISION_UNAVAILABLE",statusCode:503});return{data:xy.parse(await i.decisions.get(t,n))}}),e.post("/api/node-agent/stories/:storyId/decisions/:decisionId/decide",async e=>{const{storyId:t,decisionId:n}=y_.parse(e.params);if(!i.decisions)throw Object.assign(new Error("Story decisions are unavailable."),{code:"STORY_DECISION_UNAVAILABLE",statusCode:503});const s=ky.parse(e.body||{});return{data:xy.parse(await i.decisions.decide(t,n,s))}}),e.post("/api/node-agent/stories/:storyId/decisions/:decisionId/cancel",async e=>{const{storyId:t,decisionId:n}=y_.parse(e.params);if(!i.decisions)throw Object.assign(new Error("Story decisions are unavailable."),{code:"STORY_DECISION_UNAVAILABLE",statusCode:503});const s=Dy.parse(e.body||{});return{data:xy.parse(await i.decisions.cancel(t,n,s))}}),e.post("/api/node-agent/stories/:storyId/archive",async e=>({data:i.commands?await i.commands.archive(u_.parse(e.params).storyId):await n.archive(u_.parse(e.params).storyId)})),e.post("/api/node-agent/stories/:storyId/restore",async e=>({data:i.commands?await i.commands.restore(u_.parse(e.params).storyId):await n.restore(u_.parse(e.params).storyId)})),e.delete("/api/node-agent/stories/:storyId",async e=>{const{storyId:t}=u_.parse(e.params);if(!i.commands)throw Object.assign(new Error("Story command service is unavailable."),{code:"STORY_COMMAND_UNAVAILABLE",statusCode:503});return{data:{deleted:await i.commands.delete(t)}}}),i.scheduler){const t=i.scheduler,s=async(e,n)=>{const i=await t.status(n);if(i.automation.storyId!==e)throw Object.assign(new Error("Story Automation belongs to another Story."),{code:"STORY_AUTOMATION_STORY_MISMATCH",statusCode:409});return i};e.get("/api/node-agent/stories/:storyId/automations",async e=>{const{storyId:i}=u_.parse(e.params);return await n.require(i),{data:wy.parse({automations:await t.list(i)})}}),e.post("/api/node-agent/stories/:storyId/automations",async(e,n)=>{const{storyId:i}=u_.parse(e.params),s=fy.parse(e.body);if(s.storyId!==i)throw Object.assign(new Error("Automation storyId does not match the route."),{code:"STORY_AUTOMATION_STORY_MISMATCH",statusCode:409});return n.code(201).send({data:by.parse(await t.create(s))})}),e.post("/api/node-agent/stories/:storyId/automations/with-action",async(e,t)=>{const{storyId:n}=u_.parse(e.params);if(!i.commands)throw Object.assign(new Error("Story command service is unavailable."),{code:"STORY_COMMAND_UNAVAILABLE",statusCode:503});const s=yy.parse(e.body);return t.code(201).send({data:by.parse(await i.commands.createAutomationWithAction(n,s))})}),e.get("/api/node-agent/stories/:storyId/automations/:automationId",async e=>{const{storyId:t,automationId:n}=m_.parse(e.params);return{data:by.parse(await s(t,n))}}),e.patch("/api/node-agent/stories/:storyId/automations/:automationId",async e=>{const{storyId:n,automationId:i}=m_.parse(e.params);return await s(n,i),{data:by.parse(await t.update(i,Iy.parse(e.body)))}}),e.delete("/api/node-agent/stories/:storyId/automations/:automationId",async e=>{const{storyId:n,automationId:i}=m_.parse(e.params);return await s(n,i),{data:{deleted:await t.delete(i)}}});for(const n of["enable","disable"])e.post(`/api/node-agent/stories/:storyId/automations/:automationId/${n}`,async e=>{const{storyId:i,automationId:r}=m_.parse(e.params);return await s(i,r),{data:by.parse(await t.setEnabled(r,"enable"===n))}});e.post("/api/node-agent/stories/:storyId/automations/:automationId/run",async e=>{const{storyId:n,automationId:i}=m_.parse(e.params);return await s(n,i),{data:await t.manualRun(i,Ny.parse(e.body))}}),e.get("/api/node-agent/stories/:storyId/automations/:automationId/runs",async e=>{const{storyId:n,automationId:i}=m_.parse(e.params);return await s(n,i),{data:Sy.parse({runs:await t.runs(i)})}})}e.get("/api/node-agent/stories/:storyId/content",async e=>{const{storyId:t}=u_.parse(e.params);return{data:$y.parse({documents:await n.listContent(t)})}}),e.get("/api/node-agent/stories/:storyId/content/file",async(e,t)=>{const{storyId:i}=u_.parse(e.params),{storyPath:s}=I_.parse(e.query),r=await n.readContent(i,s);return S_(t,r.stream,r.revision,r.size)}),e.put("/api/node-agent/stories/:storyId/content/file",{bodyLimit:33555456},async e=>{const{storyId:t}=u_.parse(e.params),i=__.parse(e.query),{storyPath:s,revision:r,size:o}=await n.writeContent(t,{...i,stream:e.body});return{data:{storyPath:s,revision:r,size:o}}}),e.patch("/api/node-agent/stories/:storyId/documents/:storyPath",async e=>{const t=p_.parse(e.params),i=ry.parse(decodeURIComponent(t.storyPath));return{data:await n.updateDocument(t.storyId,i,Uy.parse(e.body))}}),e.delete("/api/node-agent/stories/:storyId/documents/:storyPath",async e=>{const t=p_.parse(e.params);return{data:{deleted:await n.deleteDocument(t.storyId,ry.parse(decodeURIComponent(t.storyPath)))}}}),e.post("/api/node-agent/stories/:storyId/documents/order",async e=>{const{storyId:t}=u_.parse(e.params);return{data:await n.reorderDocuments(t,e.body)}}),e.get("/api/node-agent/instances/:id/ai-sessions/:sessionId/story-content",async e=>{const{id:s,sessionId:r}=h_.parse(e.params),o=await w_(t,n,s,r,A_(e.headers));await(i.toolPolicy?.assertEnabled(o.id,"story_list_content"));const{page:a,pageSize:c}=By.parse(e.query||{});return{data:Gy.parse(await n.pageContent(o.id,a,c))}}),e.get("/api/node-agent/instances/:id/story-agent-tools",async e=>{const{id:n}=c.z.object({id:c.z.string().trim().min(1).max(120)}).strict().parse(e.params),{storyId:s}=E_.parse(e.query);if(t.authenticateInstance(n,A_(e.headers)),!i.toolPolicy)throw Object.assign(new Error("Story Agent Tool policy is unavailable."),{code:"STORY_AGENT_TOOL_POLICY_UNAVAILABLE",statusCode:503});return{data:fI.parse(await i.toolPolicy.resolve(s))}}),e.get("/api/node-agent/instances/:id/ai-sessions/:sessionId/story-agent-tools",async e=>{const{id:s,sessionId:r}=h_.parse(e.params),o=await w_(t,n,s,r,A_(e.headers));if(!i.toolPolicy)throw Object.assign(new Error("Story Agent Tool policy is unavailable."),{code:"STORY_AGENT_TOOL_POLICY_UNAVAILABLE",statusCode:503});return{data:fI.parse(await i.toolPolicy.resolve(o.id))}}),e.post("/api/node-agent/instances/:id/ai-sessions/:sessionId/agent-runs",async e=>{const{id:s,sessionId:r}=h_.parse(e.params),o=await w_(t,n,s,r,A_(e.headers));if(!i.toolPolicy||!i.agentRuns)throw Object.assign(new Error("Story Agent invocation is unavailable."),{code:"STORY_AGENT_INVOCATION_UNAVAILABLE",statusCode:503});const a=tI.parse(e.body),c=await i.toolPolicy.assertAgentInvocation(o.id,a.input.agentId,a.input.orchestrationId),d=i.agentRuns.create({clientRequestId:a.clientRequestId,orchestrationId:c.orchestrationId,entryAgentId:c.agentId,input:{prompt:a.input.prompt},provenance:{initiatingInstanceId:s,initiatingAiSessionId:r,storyId:o.id},budget:a.input.budget});return{data:Xp.parse(await i.agentRuns.waitForToolResult(d.runId,e.signal))}}),e.post("/api/node-agent/instances/:id/ai-sessions/:sessionId/story-agent-tools/:tool",async e=>{const{id:s,sessionId:r,tool:o}=g_.parse(e.params),a=await w_(t,n,s,r,A_(e.headers));await(i.toolPolicy?.assertEnabled(a.id,o));const d=c.z.object({input:c.z.unknown()}).strict().parse(e.body||{}),l=l_[o].input.parse(d.input??{});if("story_list_actions"===o){const{page:e,pageSize:n}=NI.parse(l),i=(e-1)*n,s=new Set(t.listInstances().filter(e=>e.nodeId===t.node.id).map(e=>e.id)),r=a.actions.slice(i,i+n).map(e=>{const t=a.archivedAt?"STORY_ARCHIVED":e.targetInstanceId?s.has(e.targetInstanceId)?void 0:"STORY_ACTION_TARGET_UNAVAILABLE":"STORY_ACTION_TARGET_REQUIRED";return{id:e.id,title:e.title,promptPreview:e.promptTemplate.slice(0,500),promptTruncated:e.promptTemplate.length>500,executable:!t,unavailableReason:t}}),o=a.actions.length;return{data:vI.parse({actions:r,pagination:EI(o,e,n)})}}if("story_run_action"===o){if(!i.actionExecution)throw Object.assign(new Error("Story Action execution is unavailable."),{code:"STORY_ACTION_EXECUTION_UNAVAILABLE",statusCode:503});const e=OI.parse(l),t=await i.actionExecution.run(a.id,e.actionId,e.clientRequestId);return{data:RI.parse({session:{instanceId:t.targetInstanceId,sessionId:t.aiSessionId}})}}if("story_list_automations"===o){const{page:e,pageSize:t}=zI.parse(l);if(!i.scheduler)throw Object.assign(new Error("Story Automation scheduler is unavailable."),{code:"STORY_AUTOMATION_UNAVAILABLE",statusCode:503});const n=await i.scheduler.list(a.id),s=(e-1)*t;return{data:l_[o].output.parse({automations:n.slice(s,s+t).map(b_),pagination:EI(n.length,e,t)})}}if("story_create_automation"===o){if(!i.scheduler)throw Object.assign(new Error("Story Automation scheduler is unavailable."),{code:"STORY_AUTOMATION_UNAVAILABLE",statusCode:503});const e=xI.parse(l);return{data:l_[o].output.parse(b_(await i.scheduler.create({storyId:a.id,...e})))}}if("story_update_automation"===o){if(!i.scheduler)throw Object.assign(new Error("Story Automation scheduler is unavailable."),{code:"STORY_AUTOMATION_UNAVAILABLE",statusCode:503});const{automationId:e,expectedUpdatedAt:t,...n}=CI.parse(l);if((await i.scheduler.status(e)).automation.storyId!==a.id)throw N_();return{data:l_[o].output.parse(b_(await i.scheduler.update(e,n,t)))}}if("story_delete_automation"===o){if(!i.scheduler)throw Object.assign(new Error("Story Automation scheduler is unavailable."),{code:"STORY_AUTOMATION_UNAVAILABLE",statusCode:503});const{automationId:e,expectedUpdatedAt:t}=kI.parse(l);if((await i.scheduler.status(e)).automation.storyId!==a.id)throw N_();return{data:PI.parse({deleted:await i.scheduler.delete(e,t)})}}if("story_run_automation"===o){if(!i.scheduler)throw Object.assign(new Error("Story Automation scheduler is unavailable."),{code:"STORY_AUTOMATION_UNAVAILABLE",statusCode:503});const{automationId:e,clientRequestId:t}=DI.parse(l);if((await i.scheduler.status(e)).automation.storyId!==a.id)throw N_();return{data:l_[o].output.parse(T_(await i.scheduler.manualRun(e,{clientRequestId:t})))}}if("story_list_automation_runs"===o){if(!i.scheduler)throw Object.assign(new Error("Story Automation scheduler is unavailable."),{code:"STORY_AUTOMATION_UNAVAILABLE",statusCode:503});const{automationId:e,page:t,pageSize:n}=LI.parse(l);if((await i.scheduler.status(e)).automation.storyId!==a.id)throw N_();const s=await i.scheduler.runs(e),r=(t-1)*n;return{data:l_[o].output.parse({runs:s.slice(r,r+n).map(T_),pagination:EI(s.length,t,n)})}}const u={instanceId:s,sessionId:r,storyId:a.id};if("story_request_decision"===o){if(!i.decisions)throw Object.assign(new Error("Story decisions are unavailable."),{code:"STORY_DECISION_UNAVAILABLE",statusCode:503});const{session:c}=await async function(e,t,n,i,s){const r=e.authenticateInstance(n,s).aiSessions.sessions.find(e=>e.id===i);if(!r)throw Object.assign(new Error("AI Session was not found in the authoritative instance snapshot."),{code:"AI_SESSION_NOT_FOUND",statusCode:404});if(!r.storyId)throw Object.assign(new Error("AI Session is not assigned to a Story."),{code:"STORY_CONTEXT_REQUIRED",statusCode:409});const o=await t.get(r.storyId);if(!o)throw Object.assign(new Error("Story was not found."),{code:"STORY_NOT_FOUND",statusCode:404});return{session:r,story:o}}(t,n,s,r,A_(e.headers)),d=await i.decisions.register({storyId:a.id,sessionId:r,turnId:c.activeTurnId},l_[o].input.parse(l));return{data:d_.parse({decisionId:d.id,status:d.status})}}if("story_list_ai_sessions"===o){if(!i.aiSessionRead)throw Object.assign(new Error("Story AI Session read is unavailable."),{code:"STORY_AI_SESSION_READ_UNAVAILABLE",statusCode:503});const{page:e,pageSize:t}=HI.parse(l);return{data:qI.parse(i.aiSessionRead.list(u,e,t))}}if("story_get_ai_session"===o){if(!i.aiSessionRead)throw Object.assign(new Error("Story AI Session read is unavailable."),{code:"STORY_AI_SESSION_READ_UNAVAILABLE",statusCode:503});const e=VI.parse(l);return{data:XI.parse(await i.aiSessionRead.get(u,e.instanceId,e.sessionId,e.page,e.pageSize))}}if("story_get_ai_session_turn"===o){if(!i.aiSessionRead)throw Object.assign(new Error("Story AI Session read is unavailable."),{code:"STORY_AI_SESSION_READ_UNAVAILABLE",statusCode:503});const e=JI.parse(l);return{data:s_.parse(await i.aiSessionRead.turn(u,e.instanceId,e.sessionId,e.turnId,e.page,e.pageSize,e.maxTextChars))}}throw Object.assign(new Error("Story Agent Tool is not implemented."),{code:"STORY_AGENT_TOOL_NOT_IMPLEMENTED",statusCode:501})}),e.get("/api/node-agent/instances/:id/ai-sessions/:sessionId/story-content/file",async(e,s)=>{const{id:r,sessionId:o}=h_.parse(e.params),a=await w_(t,n,r,o,A_(e.headers));await(i.toolPolicy?.assertEnabled(a.id,"story_get_content"));const{storyPath:c}=I_.parse(e.query),d=await n.readContent(a.id,c);return S_(s,d.stream,d.revision,d.size)}),e.put("/api/node-agent/instances/:id/ai-sessions/:sessionId/story-content/file",{bodyLimit:33555456},async e=>{const{id:s,sessionId:r}=h_.parse(e.params),o=await w_(t,n,s,r,A_(e.headers));await(i.toolPolicy?.assertEnabled(o.id,"story_set_content"));const a=__.parse(e.query);return{data:await n.writeContent(o.id,{...a,stream:e.body})}}),e.put("/api/node-agent/instances/:id/ai-sessions/:sessionId/story",async e=>{const{id:s,sessionId:r}=h_.parse(e.params),o=t.requireInstance(s),a=c.z.object({storyId:ze.nullable()}).strict().parse(e.body||{});if(a.storyId){const e=await n.get(a.storyId);if(!e)throw Object.assign(new Error("Story belongs to another node or was not found."),{code:"STORY_NODE_MISMATCH",statusCode:409});if(e.archivedAt)throw Object.assign(new Error("Archived Story cannot receive new Session associations."),{code:"STORY_ARCHIVED",statusCode:409})}if(!i.fetchImpl||!i.resolveInstanceWeb||!o.registrationToken)throw Object.assign(new Error("Managed instance Session association is unavailable."),{code:"STORY_SESSION_ASSOCIATION_UNAVAILABLE",statusCode:503});const d=await i.resolveInstanceWeb(o),l=await i.fetchImpl(`${d}/api/ai-sessions/${encodeURIComponent(r)}/story`,{method:"PUT",headers:{"content-type":"application/json",authorization:`Bearer ${o.registrationToken}`},body:JSON.stringify(a)}),u=await l.json().catch(()=>({}));if(!l.ok)throw Object.assign(new Error(u.error?.message||"Controlled instance rejected Story association."),{code:u.error?.code||"STORY_SESSION_ASSOCIATION_FAILED",statusCode:l.status});return u})}(me,R,x,{fetchImpl:W,resolveInstanceWeb:V,onRetentionSettingsChanged:()=>K.reconcile(),commands:$e,scheduler:Fe,toolPolicy:C,actionExecution:Pe,aiSessionRead:Me,decisions:Ue,agentRuns:ve,onToolPolicyInvalidated:e=>X.notify(e)}),function(e,t){e.get("/api/node-agent/environment-templates",async()=>({data:t.list()})),e.get("/api/node-agent/environment-templates/:id",async e=>({data:Js.parse(t.require(e.params.id))})),e.post("/api/node-agent/instances/:id/environment-templates",async(e,n)=>{const i=await t.create(e.params.id,e.body);return n.code(201).send({data:i})}),e.delete("/api/node-agent/environment-templates/:id",async e=>({data:await t.delete(e.params.id)}))}(me,Ke),function(e,t){e.get("/api/node-agent/instances",async()=>({data:t.list()})),e.post("/api/node-agent/instances",async(e,n)=>{const i=await t.create(mA.parse(e.body));return t.afterCreate(i),n.code(201).send({data:i})}),e.post("/api/node-agent/instances/:id/image-provisioning/retry",async e=>{const n=t.retryImageProvisioning(e.params.id);return t.afterImageRetry(n),{data:n}}),e.post("/api/node-agent/instances/:id/git-provisioning/retry",async e=>{const n=t.retryGitProvisioning(e.params.id);return t.afterGitRetry(n),{data:n}}),e.patch("/api/node-agent/instances/:id",async e=>{const n=t.update(e.params.id,hA.parse(e.body));return await t.afterUpdate(n),{data:n}}),e.post("/api/node-agent/instances/:id/register",async(e,n)=>{const i=e.params.id,s=t.sanitizeReport(i,"register",e.body),r=t.register(i,Ra.parse(s),yA(e.headers));return t.afterReport(r,"register"),n.header("x-task-handoff-node-agent-protocol-version",Qi).code(201).send({data:r})}),e.post("/api/node-agent/instances/:id/heartbeat",async e=>{const n=e.params.id,i=t.sanitizeReport(n,"heartbeat",e.body),s=t.heartbeat(n,za.parse(i),yA(e.headers));return t.afterReport(s,"heartbeat"),{data:s}})}(me,{list:()=>R.listInstances(),create:e=>"template"===e.environmentSource?.type?Ke.runTemplateOperation(e.environmentSource.environmentTemplateId,()=>R.createInstance(e)):R.createInstance(e),retryImageProvisioning:e=>Qe.retry(e),retryGitProvisioning:e=>tt.retry(e),update:(e,t)=>{const n=R.requireInstance(e),i=t.config?.codexSettings?.multiAgent.defaultModel;if(i){const t=R.modelRegistry.privateCatalog(e).entities.find(e=>e.id===i.modelEntityId&&e.protocols.includes("openai-responses"));if(!t||!(Se(t.modelNames,i.modelUpstreamName??i.modelName)??Se(t.modelNames,i.modelName)))throw Object.assign(new Error("The Codex subagent model must be assigned to this instance."),{statusCode:400,code:"CODEX_SUBAGENT_MODEL_UNAVAILABLE"})}return R.controlledInstances.put(Ia.parse({...n,...t,...t.config?{config:{...n.config,...t.config}}:{},updatedAt:de()}))},register:(e,t,n)=>R.registerInstance(e,t,n),heartbeat:(e,t,n)=>R.heartbeatInstance(e,t,n),sanitizeReport:Ye,afterCreate:e=>{Ae.syncNow(),e.imageProvisioning&&Ze(e)},afterImageRetry:e=>{Ae.syncNow(),Ze(e)},afterGitRetry:e=>{Ae.syncNow(),nt(e)},afterUpdate:async e=>{Ae.syncNow(),await Promise.all([ee(e.id),te(e.id)])},afterReport:(e,t)=>{Ae.syncNow(),Fe.reconcileInstances("heartbeat"===t?e.id:void 0).catch(t=>me.log.warn({error:t,instanceId:e.id},"Story scheduler reconciliation failed")),Z(e),ee(e.id),te(e.id),ne.converge(e,t),K.reconcile(),Y.reconcile(),"register"===t?Ve({instanceId:e.id,action:t,protocolVersion:e.protocolVersion,build:e.build,targetStatus:e.targetStatus,targetStrategy:e.target.strategy},"node instance registered"):Ve({instanceId:e.id,action:t,status:e.status,health:e.health,protocolVersion:e.protocolVersion,build:e.build,targetStatus:e.targetStatus,apps:e.apps.runningCount},"node instance heartbeat accepted"),!ue(e)||e.ready&&"matched"===e.runtimeVersion?.phase||Te.schedule(e.id).catch(n=>me.log.error({instanceId:e.id,error:n},`runtime convergence after ${t} failed`))}}),me.get("/api/node-agent/events",{websocket:!0},(e,t)=>{const n=e;n.send(JSON.stringify({type:"node-agent.events.connected",nodeId:b,serverTime:(new Date).toISOString()}));const i=t.query,s=Ae.addOutput(n,{expectsTransientSubscription:"1"===i.aiSessionTransient});n.on("message",e=>{try{const t=JSON.parse(String(e));"subscribe"===t.type&&void 0!==t.aiSessionTransient&&Ae.setOutputSubscription(n,t.aiSessionTransient,t.eventEnvelopeVersion,t.aiSessionHierarchy)}catch{}}),n.on("close",s),n.on("error",s)}),me.get("/api/node-agent/docker/images",async()=>({data:await Bc(e.dockerCommandRunner)})),me.get("/api/node-agent/instances/:id/metrics",async e=>{const t=e.params.id,n=R.requireInstance(t);if("docker"!==R.requireRuntime(n.runtimeId).type){const e=new Error(`Runtime type ${R.requireRuntime(n.runtimeId).type} does not provide resource metrics.`);throw Object.assign(e,{statusCode:409,code:"INSTANCE_METRICS_UNSUPPORTED"}),e}return{data:await He.snapshot(t)}}),function(e,t,n,i,s,r=new IA){const o=e=>r.intent(e),a=e=>Promise.resolve(i.cancel(e)).then(()=>({ok:!0}),e=>({ok:!1,error:e})),c=(e,t)=>{if(!r.isIntentCurrent(e,t))throw Object.assign(new Error(`Instance operation for ${e} was superseded by stop or delete.`),{statusCode:409,code:"INSTANCE_OPERATION_SUPERSEDED"})},d=(e,t)=>{const n=r.signal;return"function"==typeof n?n.call(r,e,t):void 0},l=(e,n)=>{if(n){if(n.instanceId!==e)throw Object.assign(new Error(`Git provisioning belongs to ${n.instanceId}, not ${e}.`),{code:"GIT_WORKSPACE_PROVISIONING_INSTANCE_MISMATCH",statusCode:409});t.setGitWorkspaceProvisioning(n)}},u=(e,n)=>{if(!n)return e;const i=t.gitWorkspaceProvisioningStatus(e.id);return"consumed"===i?.status&&i.operationId===n.operationId?{instance:e,gitWorkspaceProvisioningOperationId:n.operationId}:e};e.post("/api/node-agent/instances/:id/start",async e=>{const t=_A.parse(e.body),n=e.params.id,i=o(n);return r.run(n,async()=>(c(n,i),l(n,t.gitWorkspaceProvisioning),s.allowRecovery(n),{data:u(await s.start(n,()=>r.isIntentCurrent(n,i),d(n,i)),t.gitWorkspaceProvisioning)}))}),e.post("/api/node-agent/instances/:id/runtime/reconcile",async e=>{const n=e.params.id;_A.parse(e.body);const a=o(n);return r.run(n,async()=>{c(n,a);const e=t.requireInstance(n);t.putInstance(Ia.parse({...e,ready:!1,runtimeVersion:wg(Wl(e)),updatedAt:de()})),c(n,a);const r=await i.schedule(n,{startRequested:!["created","stopped"].includes(e.status),resumeCancelled:!0});return c(n,a),s.sync(),{data:r}})}),e.post("/api/node-agent/instances/:id/stop",async e=>{const i=e.params.id;t.requireInstance(i),t.discardGitWorkspaceProvisioning(i),r.invalidate(i);const o=a(i);return r.run(i,async()=>{const e=t.requireInstance(i);t.applyLifecycle(i,{type:"stop-requested"});try{await s.suppressRecovery(i);const e=await o;if("error"in e)throw e.error;const r=t.requireInstance(i);s.diagnostic({instanceId:i,action:"stop",runtimeId:r.runtimeId,containerName:r.runtime.containerName},"node instance stop requested"),await n.forRuntime(t.requireRuntime(r.runtimeId)).stop(t.context(r))}catch(n){try{t.applyLifecycle(i,{type:"stop-failed",baseline:e}),s.sync()}finally{s.allowRecovery(i)}throw n}const r=t.applyLifecycle(i,{type:"stop-completed"});return s.completeSuppressedRecovery(i),s.sync(),s.diagnostic({instanceId:i,action:"stop",status:r.status,connectionStatus:r.connectionStatus,containerName:r.runtime.containerName},"node instance stop completed"),{data:r}})}),e.post("/api/node-agent/instances/:id/restart",async e=>{const a=e.params.id,d=_A.parse(e.body),p=o(a);return r.run(a,async()=>{c(a,p),l(a,d.gitWorkspaceProvisioning),s.allowRecovery(a);let e=t.requireInstance(a);if(s.isManaged(e)&&(!e.ready||"matched"!==e.runtimeVersion?.phase)){"failed"===e.runtimeVersion?.phase&&(e=t.putInstance(Ia.parse({...e,runtimeVersion:wg(Wl(e)),updatedAt:de()}))),c(a,p);const n=await i.schedule(a,{startRequested:!0});return c(a,p),s.sync(),{data:u(n,d.gitWorkspaceProvisioning)}}s.diagnostic({instanceId:a,action:"restart",runtimeId:e.runtimeId,imageId:e.imageSelection?.imageId,containerName:e.runtime.containerName},"node instance restart requested");const r=await n.forRuntime(t.requireRuntime(e.runtimeId)).restart(t.context(e));let o=t.applyLifecycle(a,{type:"runtime-lifecycle-completed",baseline:e,observation:{...r,target:r.target?{...e.target,...r.target}:void 0}});s.markRestarted(a),c(a,p);const m=Ia.parse({...o,updatedAt:de()}),h=await s.probe(m);return c(a,p),o=t.applyLifecycle(a,{type:"runtime-lifecycle-completed",baseline:o,observation:{target:{...o.target,status:h},targetStatus:h,uiAccessStatus:h}}),await s.autoImport(o),s.sync(),s.diagnostic({instanceId:a,action:"restart",status:o.status,connectionStatus:o.connectionStatus,targetStatus:o.targetStatus,targetWeb:o.target.web,containerName:o.runtime.containerName},"node instance restart completed"),{data:u(o,d.gitWorkspaceProvisioning)}})}),e.post("/api/node-agent/instances/:id/delete",async e=>{const i=e.params.id,o=Hs.parse(e.body);t.requireInstance(i),r.invalidate(i);const c=a(i);return r.run(i,async()=>{const e=t.requireInstance(i);"deleting"!==e.status&&t.applyLifecycle(i,{type:"stop-requested"});try{await s.suppressRecovery(i);const e=await c;if("error"in e)throw e.error;const a=t.requireInstance(i);t.putInstance(Ia.parse({...a,status:"deleting",ready:!1,updatedAt:de()})),s.diagnostic({instanceId:i,action:"delete",runtimeId:a.runtimeId,containerName:a.runtime.containerName},"node instance delete requested");const d=await n.forRuntime(t.requireRuntime(a.runtimeId)).delete(t.context(a,{}),o);if(!d.completed)return s.diagnostic({instanceId:i,action:"delete",volumeResults:d.volumeResults},"node instance delete requires retry"),s.sync(),{data:d};s.diagnostic({instanceId:i,action:"delete"},"node instance delete completed");const l=t.deleteInstance(i);return l&&(s.forgetRecovery(i),r.clearIntent(i)),s.deleteMetadata(i),l&&s.retireInstanceData(i),l&&a.environmentTemplateOrigin?.imageId&&s.releaseEnvironmentImage&&await s.releaseEnvironmentImage(a.environmentTemplateOrigin.imageId).catch(e=>{s.diagnostic({instanceId:i,action:"release-environment-image",error:e instanceof Error?e.message:String(e)},"environment image cleanup deferred after instance deletion")}),s.sync(),{data:d}}catch(n){try{t.putInstance(Ia.parse({...e,updatedAt:de()})),s.sync()}finally{s.allowRecovery(i)}throw n}})})}(me,{requireInstance:e=>R.requireInstance(e),requireRuntime:e=>R.requireRuntime(e),putInstance:e=>R.controlledInstances.put(e),deleteInstance:e=>R.controlledInstances.delete(e),applyLifecycle:(e,t)=>R.applyInstanceLifecycle(e,t),context:(e,t)=>R.context(e,t),setGitWorkspaceProvisioning:e=>R.setGitWorkspaceProvisioning(e),discardGitWorkspaceProvisioning:e=>R.discardGitWorkspaceProvisioning(e),gitWorkspaceProvisioningStatus:e=>R.gitWorkspaceProvisioningStatus(e)},$,Te,{start:(e,t,n)=>Je(e,"request",t,n),sync:()=>Ae.syncNow(),isManaged:ue,probe:e=>vw(W,e,V),autoImport:e=>zw(W,e,"restart",Ge,V),markRestarted:e=>U.markRestored(e),allowRecovery:e=>U.allowRecovery(e),suppressRecovery:e=>U.suppressRecovery(e),forgetRecovery:e=>U.forgetInstance(e),completeSuppressedRecovery:e=>U.completeSuppressedOperation(e),deleteMetadata:e=>{J.delete(e),R.modelRegistry.deleteInstanceMetadata(e),R.gitCredentials.removeInstance(e),R.gitCredentials.collectUnreferencedPayloads(),R.discardGitWorkspaceProvisioning(e),R.instancePrivateConfigs.delete(e)},retireInstanceData:e=>{he.retire(e)},releaseEnvironmentImage:e=>Ke.releaseUnusedImage(e),diagnostic:Ve},We),function(e,t){const{fetchImpl:n,metrics:i,diagnostic:s}=t;e.post("/api/node-agent/instances/:id/proxy",async(e,i)=>{const r=performance.now(),o=e.params.id,a=dA.parse(e.body),c=await t.instanceBase(o),d=CA(a.path);"POST"===a.method&&"/api/apps/sessions"===d&&await t.syncModelEnvironment(o),s({instanceId:o,action:"proxy",method:a.method,path:d,instanceBase:c},"node instance proxy requested");const l=await DA(n,`${c}${d}`,{method:a.method,headers:{...a.headers},body:RA(a)},{instanceId:o,method:a.method,path:d,diagnostic:s}),u=l.headers.get("content-type")||"application/octet-stream",p=await l.text(),m=performance.now()-r,h=l.headers.get(xA)||a.headers[xA],g=function(...e){return e.map(e=>String(e||"").trim()).filter(Boolean).join(", ")}(l.headers.get("server-timing"),function(e,t){return`node_proxy;dur=${(Number.isFinite(t)?Math.max(0,t):0).toFixed(1)}`}(0,m));i.header("server-timing",g),h&&i.header(xA,h),s({instanceId:o,action:"proxy",method:a.method,path:d,statusCode:l.status,contentType:u,durationMs:m,traceId:h},"node instance proxy completed"),i.code(l.status).type(u).send(p)}),e.post("/api/node-agent/instances/:id/proxy/stream",{bodyLimit:vA},async(e,r)=>{const o=Date.now();i.requests+=1,i.active+=1;const a=new AbortController;let c=0,d=!1,l=!1;const u=e=>{l||(l=!0,i.active-=1,i.totalDurationMs+=Date.now()-o,i.responseBytes+=c,i[e]+=1)},p=()=>{a.abort(),d&&u("aborted")};e.raw.once("aborted",p),r.raw.once("close",p);try{const o=e.params.id,l=dA.parse(e.body),p=await t.instanceBase(o),m=CA(l.path);s({instanceId:o,action:"proxy.stream",method:l.method,path:m,instanceBase:p},"node instance streaming proxy requested");const h=await DA(n,`${p}${m}`,{method:l.method,headers:{...l.headers},body:RA(l),signal:a.signal},{instanceId:o,method:l.method,path:m,diagnostic:s}),g=Number(h.headers.get("content-length"));if(Number.isFinite(g)&&g>i.maxResponseBytes)return i.limitRejected+=1,a.abort(),kA(r,i.maxResponseBytes);r.code(h.status);for(const[e,t]of Object.entries(OA(h.headers)))r.header(e,t);if(!h.body||"HEAD"===l.method)return u("completed"),r.send();const y=new f.Transform({transform(e,t,n){if(c+=e.length,c>i.maxResponseBytes)return i.limitRejected+=1,a.abort(),void n(Object.assign(new Error("Instance proxy response limit exceeded."),{code:"INSTANCE_PROXY_RESPONSE_TOO_LARGE"}));n(null,e)}});return d=!0,y.once("end",()=>u("completed")),y.once("error",()=>u("aborted")),r.send(f.Readable.fromWeb(h.body).pipe(y))}catch(e){throw u("aborted"),e}finally{e.raw.off("aborted",p),d||u("completed")}}),e.post("/api/node-agent/instances/:id/proxy/raw",{bodyLimit:vA},async(e,r)=>{const o=e.params.id,a=dA.parse(e.body),c=await t.instanceBase(o),d=CA(a.path);s({instanceId:o,action:"proxy.raw",method:a.method,path:d,instanceBase:c},"node instance raw proxy requested");const l=await DA(n,`${c}${d}`,{method:a.method,headers:{...a.headers},body:RA(a)},{instanceId:o,method:a.method,path:d,diagnostic:s}),u=Number(l.headers.get("content-length"));if(Number.isFinite(u)&&u>i.maxResponseBytes)return i.limitRejected+=1,await(l.body?.cancel("Instance proxy response limit exceeded.").catch(()=>{})),kA(r,i.maxResponseBytes);let p;try{p=await async function(e,t){if(!e.body)return Buffer.alloc(0);const n=[];let i=0;const s=e.body.getReader();for(;;){const{done:e,value:r}=await s.read();if(e)break;if(i+=r.byteLength,i>t)throw await s.cancel("Instance proxy response limit exceeded.").catch(()=>{}),Object.assign(new Error("Instance proxy response limit exceeded."),{code:"INSTANCE_PROXY_RESPONSE_TOO_LARGE"});n.push(Buffer.from(r))}return Buffer.concat(n,i)}(l,i.maxResponseBytes)}catch(e){if(!(e instanceof Error)||"INSTANCE_PROXY_RESPONSE_TOO_LARGE"!==e.code)throw e;return i.limitRejected+=1,kA(r,i.maxResponseBytes)}return s({instanceId:o,action:"proxy.raw",method:a.method,path:d,statusCode:l.status,byteLength:p.length},"node instance raw proxy completed"),{data:{status:l.status,headers:OA(l.headers),bodyBase64:p.toString("base64")}}}),e.get("/api/node-agent/instances/:id/proxy/ws/*",{websocket:!0},async(e,n)=>{const i=n.params.id,r=n.params["*"]||"",o=n.url.indexOf("?"),a=o>=0?n.url.slice(o):"";let c;try{const o=await t.instanceBase(i),d=new URL(`/${r}${a}`,`${o}/`);d.protocol="https:"===d.protocol?"wss:":"ws:";const l=function(e){const t=Object.entries(e).find(([e])=>"sec-websocket-protocol"===e.toLowerCase()),n=t?.[1],i=(Array.isArray(n)?n.join(","):"string"==typeof n?n:"").split(",").map(e=>e.trim()).filter(Boolean);return i.length?i:void 0}(n.headers);s({instanceId:i,action:"proxy.ws",path:`/${r}${a}`,upstreamUrl:d.toString(),protocols:l||[]},"node instance websocket proxy opening"),c=l?new h(d,l,{perMessageDeflate:!1}):new h(d,{perMessageDeflate:!1}),c.on("open",()=>{s({instanceId:i,action:"proxy.ws",path:`/${r}${a}`},"node instance websocket proxy opened")}),c.on("close",()=>{s({instanceId:i,action:"proxy.ws",path:`/${r}${a}`},"node instance websocket proxy closed")}),c.on("error",e=>{s({instanceId:i,action:"proxy.ws",path:`/${r}${a}`,error:e instanceof Error?e.message:String(e)},"node instance websocket proxy failed")}),F(e,c,{upstreamOpenTimeoutMs:1e4})}catch(t){s({instanceId:i,action:"proxy.ws",path:`/${r}${a}`,error:t instanceof Error?t.message:String(t)},"node instance websocket endpoint unavailable"),c?.close(),e.close(1011,"Instance websocket endpoint is not reachable.")}})}(me,{fetchImpl:W,metrics:Ee,instanceBase:e=>V(R.requireInstance(e)),syncModelEnvironment:e=>xw(W,R,e,Ge.warn,V),diagnostic:Ve}),me}catch(e){throw await g.close(),e}var I}async function Dw(e){const r=function(e=Date.now()){return(t,n={})=>{try{process.stdout.write(`${JSON.stringify({level:30,time:Date.now(),pid:process.pid,hostname:s.hostname(),...n,elapsedMs:Date.now()-e,msg:`node agent ${t}`})}\n`)}catch{}}}();r("starting",{dataDir:e.dataDir||process.env.TASK_HANDOFF_NODE_AGENT_DATA_DIR||"",version:process.env.TASK_HANDOFF_VERSION||""});const o=zl(e.dataDir);let a;try{a=function(e,i={}){return function(e,i={}){t.mkdirSync(n.dirname(e),{recursive:!0});const r=B.processStartIdentity(process.pid),o={pid:process.pid,hostname:s.hostname(),command:process.argv.join(" "),acquiredAt:(new Date).toISOString(),token:d.randomUUID(),...void 0!==i.component?{component:i.component}:{},...r?{startIdentity:r}:{},...void 0!==i.dataDir?{dataDir:i.dataDir}:{},...void 0!==i.host?{host:i.host}:{},...void 0!==i.port?{port:i.port}:{},...void 0!==i.instanceId?{instanceId:i.instanceId}:{}};for(let n=0;n<5;n+=1)try{return t.mkdirSync(e),t.writeFileSync(G(e),`${JSON.stringify({token:o.token,pid:o.pid,startIdentity:o.startIdentity,startedAt:(new Date).toISOString()})}\n`,{encoding:"utf8",mode:384,flag:"wx"}),Z(e,o),{lockPath:e,owner:o,updateDetails:t=>ee(e,o,t),release(){const n=X(e);n?.token===o.token&&t.rmSync(e,{recursive:!0,force:!0})}}}catch(s){if("EEXIST"!==s.code)throw s;const r=X(e);if(Q(r))throw new q(e,r,i.error);if(!r&&(ne(e)||re(e)<(i.incompleteLockStaleMs??2e3))){if(n+1<5){se();continue}throw new q(e,void 0,i.error)}const o=d.randomUUID();if(!oe(e,o)){if(n+1<5){se();continue}throw new q(e,X(e),i.error)}const a=X(e);if(Q(a))throw ie(W(e)),new q(e,a,i.error);if(r?.token&&a?.token!==r.token){ie(W(e));continue}if(!ce(e,o))continue;t.rmSync(e,{recursive:!0,force:!0})}const a=X(e);throw new q(e,a,i.error)}(e,{...i,component:"node-agent",error:{label:"Node agent",code:"NODE_AGENT_ALREADY_RUNNING"}})}(function(){const e=process.env.TASK_HANDOFF_NODE_AGENT_LOCK_PATH?.trim();return e?n.resolve(e):n.join(s.tmpdir(),`task-handoff-node-agent-${process.getuid?.()??"user"}.lock`)}(),{dataDir:o.dataDir})}catch(e){throw r("startup failed",{error:e instanceof Error?e.message:String(e)}),e}r("singleton lease acquired",{lockPath:a.lockPath});try{const s=Cg(e.host,e.port),d=t.existsSync(o.settingsPath),l=Dg(o,s);let u=l.get().externalListener;"allocate"===process.env.TASK_HANDOFF_NODE_AGENT_PORT_CONFLICT&&(u=await async function(e,t=20){for(let n=0;n<t&&e.port+n<=65535;n+=1){const t={...e,port:e.port+n};if(await MA(t))return t}throw Object.assign(new Error(`No available node-agent port found starting at ${e.port}.`),{statusCode:503,code:"NODE_AGENT_LISTENER_PORT_UNAVAILABLE"})}(u));const p=e=>{if(!a.updateDetails({dataDir:o.dataDir,host:e.host,port:e.port,instanceId:void 0}))throw new Error("Node agent singleton ownership changed while publishing listener state.")},m=e.ipcPath||process.env.TASK_HANDOFF_NODE_AGENT_IPC_PATH||Dl(o.dataDir),h="linux"===(e.platform||process.platform)?e.containerIpcPath||process.env.TASK_HANDOFF_NODE_AGENT_CONTAINER_IPC_PATH||(c=o.dataDir,n.join(n.resolve(c),"container-ipc","node-agent.sock")):void 0,g={...e,port:u.port,ipcPath:m,containerIpcPath:h},f=await kw(g);r("application initialized",{ipcPath:m});const y=f.nodeAgentState;if(!y)throw new Error("Node agent state was not initialized.");const I=f.nodeAgentIdentityService;if(!I)throw new Error("Node agent identity service was not initialized.");const _=f.nodeAgentResolveInstanceNodeAgentUrl;if(!_)throw new Error("Node agent runtime transport resolver was not initialized.");const E=I.resolveNodeId(e.nodeId||process.env.TASK_HANDOFF_NODE_ID),A=function(e,t,n,i,s){const r=t.token||process.env.TASK_HANDOFF_NODE_AGENT_TOKEN,o=s||new KA(n),a=new Map;let c=!1;const d=(t,n)=>{if(c||n.retry.pending||a.get(t)!==n)return;const s=n.retry.schedule(()=>{c||a.get(t)!==n||n.socket||l(t,n)});s&&(n.status="reconnecting",n.nextRetryAt=new Date(Date.now()+s.delay).toISOString(),e.log.info({nodeId:i,tunnelUrl:new URL(n.config.tunnelUrl).origin,attempt:s.attempt,delay:s.delay},"node agent reverse tunnel reconnect scheduled"))},l=(n,s)=>{let o;s.status=s.lastDisconnectedAt?"reconnecting":"connecting",s.error=void 0,s.failureReason=void 0,s.nextRetryAt=void 0;try{o=lT(e,{...s.config,nodeId:i,port:()=>e.nodeAgentState.currentListenerPort,token:r})}catch(e){return s.status="failed",s.lastDisconnectedAt=(new Date).toISOString(),s.error=e instanceof Error?e.message:String(e),void d(n,s)}s.socket=o;const l=new hT({connectTimeoutMs:t.connectTimeoutMs,handshakeTimeoutMs:t.handshakeTimeoutMs,heartbeatIntervalMs:t.heartbeatIntervalMs,heartbeatTimeoutMs:t.heartbeatTimeoutMs,heartbeatMissThreshold:t.heartbeatMissThreshold,stableThresholdMs:t.stableThresholdMs,ping:()=>o.ping(),onTimeout:e=>{a.get(n)===s&&s.socket===o&&(s.status="failed",s.failureReason=`Reverse tunnel ${e} timeout.`,s.error=s.failureReason,o.terminate())},onStable:()=>s.retry.reset()});return s.supervisor=l,l.start(),o.on("open",()=>{a.get(n)===s&&s.socket===o&&(s.status="connecting",l.opened())}),o.on("message",t=>{if(a.get(n)!==s||s.socket!==o)return;if(l.activity(),"connected"===s.status)return;let r;try{r=JSON.parse(String(t))}catch{return}const c=r&&"object"==typeof r?r.type:void 0;"control-plane.hello"!==c&&"control-plane.identified"!==c||(l.activity(),l.healthy(),s.status="connected",s.lastConnectedAt=(new Date).toISOString(),s.nextRetryAt=void 0,s.error=void 0,e.log.info({nodeId:i,tunnelUrl:new URL(s.config.tunnelUrl).origin},"node agent reverse tunnel connected"))}),o.on("pong",()=>l.pong()),o.on("close",(t,r)=>{if(a.get(n)!==s||s.socket!==o)return;l.close(),s.socket=void 0,s.lastDisconnectedAt=(new Date).toISOString();const u=`WebSocket closed${t?` (${t})`:""}${r?`: ${Buffer.isBuffer(r)?r.toString("utf8"):String(r)}`:""}`;s.error=s.failureReason||u,c||(e.log.warn({nodeId:i,tunnelUrl:new URL(s.config.tunnelUrl).origin,code:t,reason:Buffer.isBuffer(r)?r.toString("utf8"):String(r||""),error:s.error,closeOrigin:s.failureReason?"supervisor":"transport"},"node agent reverse tunnel disconnected"),d(n,s))}),o.on("error",e=>{a.get(n)===s&&s.socket===o&&(s.status="failed",s.failureReason=e instanceof Error?e.message:String(e),s.error=s.failureReason,o.terminate())}),o},u=(e,t)=>{const n=a.get(e);n?.retry.cancel(),n?.supervisor?.close();const i={config:t,retry:new el,status:"connecting"};return a.set(e,i),n?.socket?.close(1e3,"Reverse tunnel reconnecting."),l(e,i)},p=(e,t)=>e.tunnelUrl===t.tunnelUrl&&e.keyId===t.keyId&&e.secret===t.secret;return{connectConfigured:()=>{c=!1;const n=new Map,s=o.resolvedControlPlaneAccess(),r=new Set;for(const{connection:t,pairing:o}of s.connections){if(!t.enabled)continue;if(!o){e.log.warn({nodeId:i,connectionId:t.id,pairingKeyId:t.pairingKeyId},"node agent control-plane connection has no pairing");continue}const s=gT(t.url);n.set(t.id,{tunnelUrl:s,keyId:o.keyId,secret:o.secret}),r.add(s)}const d=function(e){const t=e.controlPlaneTunnelUrl||process.env.TASK_HANDOFF_CONTROL_PLANE_TUNNEL_URL;return t?new URL(t).toString():void 0}(t);if(d&&!r.has(d)){const e=o.reverseTunnelSecret(process.env.TASK_HANDOFF_CONTROL_PLANE_URL,t.remoteSecret||process.env.TASK_HANDOFF_NODE_AGENT_REMOTE_SECRET,t.remoteKeyId||process.env.TASK_HANDOFF_NODE_AGENT_REMOTE_KEY_ID);n.set(`explicit:${d}`,{tunnelUrl:d,keyId:e?.keyId,secret:e?.secret}),r.add(d)}const l=s.hasPersistedAccess?void 0:function(){const e=process.env.TASK_HANDOFF_CONTROL_PLANE_URL;if(!e)return;const t=new URL(FA,e);return t.protocol="https:"===t.protocol?"wss:":"ws:",t.toString()}();if(l&&!r.has(l)){const e=o.reverseTunnelSecret(process.env.TASK_HANDOFF_CONTROL_PLANE_URL,t.remoteSecret||process.env.TASK_HANDOFF_NODE_AGENT_REMOTE_SECRET,t.remoteKeyId||process.env.TASK_HANDOFF_NODE_AGENT_REMOTE_KEY_ID);n.set(`bootstrap:${l}`,{tunnelUrl:l,keyId:e?.keyId,secret:e?.secret})}(e=>{for(const[t,n]of a)e.has(t)||(n.retry.cancel(),n.supervisor?.close(),a.delete(t),n.socket?.close(1e3,"Reverse tunnel configuration removed."));for(const[t,n]of e){const e=a.get(t);e&&p(e.config,n)||u(t,n)}})(n)},state:e=>{const t=a.get(e);if(!t)return;const n=t.supervisor?.diagnostics();return{status:t.status,...void 0===n?.pingRttMs?{}:{pingRttMs:n.pingRttMs},...void 0===n?.pingRttP95Ms?{}:{pingRttP95Ms:n.pingRttP95Ms},consecutiveReconnects:t.retry.attempts,...t.lastConnectedAt?{lastConnectedAt:t.lastConnectedAt}:{},...t.lastDisconnectedAt?{lastDisconnectedAt:t.lastDisconnectedAt}:{},...t.nextRetryAt?{nextRetryAt:t.nextRetryAt}:{},...t.error?{error:t.error}:{}}},closeAll:()=>{c=!0;for(const e of a.values())e.retry.cancel(),e.supervisor?.close(),e.socket?.close(1001,"Node agent shutting down.");a.clear()}}}({log:f.log,inject:e=>f.inject(e),nodeAgentEventForwarder:f.nodeAgentEventForwarder,nodeAgentState:y},g,o,E,I);f.decorate("nodeAgentReverseTunnels",A);const T=new jA({app:f,state:y,settings:l,config:u,source:d?"persisted":"bootstrap",onActiveListener:p,validateUpdate:()=>{const e=y.listInstances().filter(e=>!["created","stopped","failed"].includes(e.status)).filter(e=>"reachable"!==e.targetStatus||!hs(e.capabilities).features.nodeAgentConnectionUpdate);if(e.length)throw Object.assign(new Error(`Cannot change the node agent port while ${e.length} controlled instance(s) cannot switch endpoints live.`),{statusCode:409,code:"NODE_AGENT_LISTENER_LIVE_UPDATE_UNSUPPORTED",details:{instanceIds:e.map(e=>e.id)}})},synchronizeUpdate:async()=>{const t=y.listInstances().filter(e=>!["created","stopped","failed"].includes(e.status));await Promise.all(t.map(async t=>{const n=await _(t);return Rw(e.fetchImpl||fetch,t,n).then(e=>{if("applied"!==e)throw new Error(`Controlled instance ${t.id} did not apply the node-agent endpoint update (${e}).`)})}))}});let b,w;f.decorate("nodeAgentListenerManager",T),function(e){let t=!1;const n=async n=>{if(!t){t=!0,A.closeAll(),b?.close(),w?.close();try{await e.close()}finally{process.exitCode=n?0:process.exitCode}}},i=()=>{n("SIGINT")},s=()=>{n("SIGTERM")};process.once("SIGINT",i),process.once("SIGTERM",s),e.addHook("onClose",async()=>{process.off("SIGINT",i),process.off("SIGTERM",s)})}(f),f.addHook("onClose",async()=>{b?.close(),w?.close(),a.release()});try{await f.ready(),b=await async function(e,t){Ll(t);const n=i.createServer((t,n)=>{e.server.emit("request",t,n)});return n.on("upgrade",(t,n,i)=>{e.server.emit("upgrade",t,n,i)}),await new Promise((e,i)=>{n.once("error",i),n.listen(t,()=>{n.off("error",i),e()})}),n}(f,m),r("ipc listener ready",{ipcPath:m}),h&&(w=await async function(e,t){Ll(t);const n=i.createServer((t,n)=>{Ew.add(t),e.server.emit("request",t,n)});return await new Promise((e,i)=>{n.once("error",i),n.listen(t,()=>{n.off("error",i),e()})}),n}(f,h)),await T.start(),A.connectConfigured(),f.nodeAgentStartRuntimeAvailabilityMonitor?.(),f.nodeAgentStartRecoverySupervisor?.(),f.nodeAgentStartWslSessionSupervisor?.(),f.nodeAgentPrefetchWslBaseTemplate?.().catch(e=>{r("wsl base template prefetch failed",{error:e instanceof Error?e.message:String(e)})})}catch(e){throw await f.close(),e}}catch(e){throw r("startup failed",{error:e instanceof Error?e.message:String(e)}),a.release(),e}var c}const Lw="task-handoff-node-agent.service",Pw=`/etc/systemd/system/${Lw}`,Mw="/etc/task-handoff/node-agent.env",jw=["@task-handoff/node-agent","@task-handoff/controlled-instance"];function Uw(e,t,n){const i=e.run(t,n);if(0!==i.status){const e=function(e){return[e.stdout,e.stderr].filter(Boolean).map(e=>String(e).trim()).filter(Boolean).join("\n")}(i);throw new Error(`${t} ${n.join(" ")} failed${e?`:\n${e}`:""}`)}}function Fw(e,t){for(const n of e.split(/\r?\n/)){const e=n.indexOf("=");if(!(e<0||n.slice(0,e).trim()!==t))return n.slice(e+1).trim()}}const $w={getuid:()=>process.getuid?.(),exists:t.existsSync,readText:e=>t.readFileSync(e,"utf8"),remove:(e,n)=>t.rmSync(e,n),run:(e,t)=>l.spawnSync(e,t,{encoding:"utf8"}),confirmDeleteData:async function(e){if(!R.stdin.isTTY||!R.stdout.isTTY)return!1;const t=O.createInterface({input:R.stdin,output:R.stdout});try{const n=await t.question(`Delete Node Agent data at ${e}? This removes identity, configuration, logs, and managed-instance metadata. Docker volumes are preserved. [y/N] `);return/^(?:y|yes)$/i.test(n.trim())}finally{t.close()}},log:e=>console.log(e)};function Hw(e){const t=Number(e);if(!Number.isInteger(t)||t<=0||t>65535)throw new Error("Port must be a valid TCP port.");return t}function Bw(e){if("local-ipc"!==e&&"local-loopback"!==e)throw new Error("Connection mode must be local-ipc or local-loopback.");return e}function qw(e){const t=Number(e);if(!Number.isInteger(t)||t<=0)throw new Error("Expiry must be a positive integer.");return t}(async function(){const t=new e.Command;t.name("task-handoff-node-agent").description("Run a TaskHandoff node agent.").version(k("@task-handoff/cli")).option("--host <host>","Node agent host",process.env.TASK_HANDOFF_NODE_AGENT_HOST||"127.0.0.1").option("-p, --port <port>","Node agent port",Hw,Number(process.env.TASK_HANDOFF_NODE_AGENT_PORT)||8091).option("--data-dir <path>","Node agent data directory").option("--token <token>","Bearer token required by the control plane").option("--connection-mode <mode>","Local control connection mode",Bw).option("--ipc-path <path>","Unix socket path used by local-ipc mode").option("--control-plane-tunnel-url <url>","Control plane reverse WebSocket tunnel URL").action(async e=>{await Dw({host:e.host,port:e.port,dataDir:e.dataDir,token:e.token,connectionMode:e.connectionMode,ipcPath:e.ipcPath,controlPlaneTunnelUrl:e.controlPlaneTunnelUrl})}),t.command("invite").description("Create a one-time token for pairing this node agent with a control plane.").option("--endpoint <url>","Use the node-agent HTTP endpoint instead of its local IPC socket").option("--ipc-path <path>","Local node-agent IPC socket path").option("--data-dir <path>","Node-agent data directory used to locate its IPC socket").option("--token <token>","Bearer token for local node-agent access",process.env.TASK_HANDOFF_NODE_AGENT_TOKEN).option("--expires-in-ms <ms>","Invite expiry in milliseconds",qw).option("--json","Print raw JSON output").action(async e=>{const n=t.opts(),i=e.ipcPath||n.ipcPath||process.env.TASK_HANDOFF_NODE_AGENT_IPC_PATH,s=e.dataDir||n.dataDir||process.env.TASK_HANDOFF_NODE_AGENT_DATA_DIR,r=e.endpoint?void 0:i||Dl(s||Rl()),o=await async function(e){const t={"content-type":"application/json",...e.token?{authorization:`Bearer ${e.token}`}:{}},n=JSON.stringify({...e.expiresInMs?{expiresInMs:e.expiresInMs}:{}}),i=e.endpoint?await fetch(`${e.endpoint.replace(/\/$/,"")}/api/node-agent/pairing/invites`,{method:"POST",headers:t,body:n}):await Pl(e.ipcPath,"/pairing/invites",{method:"POST",headers:t,body:n}),s=await i.json().catch(()=>({}));if(!i.ok)throw new Error(s.error?.message||`Node agent pairing invite failed with HTTP ${i.status}`);const r="string"==typeof s.data?.joinToken?s.data.joinToken:"";if(!r)throw new Error("Node agent pairing invite response did not include a join token.");return{nodeId:"string"==typeof s.data?.nodeId?s.data.nodeId:"",joinToken:r,expiresAt:"string"==typeof s.data?.expiresAt?s.data.expiresAt:""}}({endpoint:e.endpoint,ipcPath:r,token:e.token,expiresInMs:e.expiresInMs});e.json?console.log(JSON.stringify(o,null,2)):(o.nodeId&&console.log(`Node: ${o.nodeId}`),console.log(`Join token: ${o.joinToken}`),o.expiresAt&&console.log(`Expires: ${o.expiresAt}`))}),t.command("connect").description("Connect this Node Agent to a reachable Control Plane.").requiredOption("--control-plane <url>","Public Control Plane base URL").requiredOption("--join-token <token>","One-time join token issued by the Control Plane").option("--control-plane-name <name>","Control Plane display name").option("--endpoint <url>","Use the Node Agent HTTP endpoint instead of its local IPC socket").option("--ipc-path <path>","Local Node Agent IPC socket path").option("--data-dir <path>","Node Agent data directory used to locate its IPC socket").option("--token <token>","Bearer token for local Node Agent access",process.env.TASK_HANDOFF_NODE_AGENT_TOKEN).option("--json","Print raw JSON output").action(async e=>{const n=t.opts(),i=e.ipcPath||n.ipcPath||process.env.TASK_HANDOFF_NODE_AGENT_IPC_PATH,s=e.dataDir||n.dataDir||process.env.TASK_HANDOFF_NODE_AGENT_DATA_DIR,r=e.endpoint?void 0:i||Dl(s||Rl()),o=await async function(e){const t={"content-type":"application/json",...e.token?{authorization:`Bearer ${e.token}`}:{}},n=JSON.stringify({controlPlaneUrl:e.controlPlane,joinToken:e.joinToken,...e.controlPlaneName?{controlPlaneName:e.controlPlaneName}:{},activate:!0}),i=e.endpoint?await fetch(`${e.endpoint.replace(/\/$/,"")}/api/node-agent/control-plane-connections`,{method:"POST",headers:t,body:n}):await Pl(e.ipcPath,"/control-plane-connections",{method:"POST",headers:t,body:n}),s=await i.json().catch(()=>({}));if(!i.ok)throw new Error(s.error?.message||`Node Agent connection failed with HTTP ${i.status}`);return s.data}({controlPlane:e.controlPlane,joinToken:e.joinToken,controlPlaneName:e.controlPlaneName,endpoint:e.endpoint,ipcPath:r,token:e.token});e.json?console.log(JSON.stringify(o,null,2)):(console.log(`Control Plane: ${String(o?.connection?.url||e.controlPlane)}`),console.log(`Connection: ${String(o?.tunnel?.status||"saved")}`))}),t.command("uninstall").description("Uninstall the Node Agent service and packages; data is preserved by default.").option("--data-dir <path>","Override the installed Node Agent data directory").option("--delete-data","Delete Node Agent data without prompting").option("--keep-data","Preserve Node Agent data without prompting").action(async e=>{await async function(e,t=$w){if(e.deleteData&&e.keepData)throw new Error("--delete-data and --keep-data cannot be used together.");if(0!==t.getuid())throw new Error("Run this command as root so the Node Agent service and packages can be removed.");const i=t.exists(Mw)?t.readText(Mw):"",s=function(e,t){if(e.dataDir?.trim())return n.resolve(e.dataDir.trim());if(t.exists(Mw)){const e=Fw(t.readText(Mw),"TASK_HANDOFF_NODE_AGENT_DATA_DIR");if(e)return n.resolve(e)}return n.resolve(Rl())}(e,{exists:e=>e===Mw&&Boolean(i),readText:()=>i});if(s===n.parse(s).root)throw new Error(`Refusing to use a filesystem root as the Node Agent data directory: ${s}`);const r=Fw(i,"TASK_HANDOFF_NPM_COMMAND")||process.env.TASK_HANDOFF_NPM_COMMAND||"npm";if(t.exists(Pw)){const e=t.readText(Pw);if(!/^ExecStart=\S*task-handoff-node-agent(?:\s|$)/m.test(e))throw new Error(`Refusing to remove ${Lw} because it is not owned by a standalone Node Agent installation.`);Uw(t,"systemctl",["disable","--now",Lw]),t.remove(Pw,{force:!0}),Uw(t,"systemctl",["daemon-reload"])}Uw(t,r,["uninstall","--global",...jw]),t.remove(Mw,{force:!0}),t.log("TaskHandoff Node Agent service and packages were removed.");const o=!!e.deleteData||!e.keepData&&await t.confirmDeleteData(s);return o?(t.remove(s,{recursive:!0,force:!0}),t.log(`Node Agent data was deleted from ${s}.`)):t.log(`Node Agent data was preserved at ${s}.`),{dataDir:s,dataDeleted:o}}(e)}),await t.parseAsync(process.argv)})().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});