@task-handoff/controlled-instance 0.0.3-alpha.2 → 0.0.3-alpha.3
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.
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("commander"),t=require("node:fs"),s=require("node:path"),n=require("node:os"),r=require("write-file-atomic"),i=require("zod"),o=require("node:net"),a=require("node:stream"),d=require("node:stream/promises"),c=require("@fastify/static"),p=require("@fastify/websocket"),u=require("fastify"),l=require("httpxy"),m=require("node:child_process"),h=require("node:crypto"),g=require("node:events"),f=require("node-pty"),y=require("ws"),v=require("node:url");const S=process.env.TASK_HANDOFF_CONFIG||s.join(process.env.XDG_CONFIG_HOME||s.join(n.homedir(),".config"),"task-handoff","config.json"),I=i.z.record(i.z.string(),i.z.unknown());function A(){try{return I.parse(JSON.parse(t.readFileSync(S,"utf8")))}catch(e){return e&&"object"==typeof e&&"code"in e&&e.code,{}}}function b(e,t){const s={...e};for(const[e,n]of Object.entries(t))if(n&&"object"==typeof n&&!Array.isArray(n)){const t=s[e];s[e]=b(t&&"object"==typeof t&&!Array.isArray(t)?I.parse(t):{},n)}else void 0===n?delete s[e]:s[e]=n;return s}function _(e){const n=b(A(),e);return function(e){t.mkdirSync(s.dirname(S),{recursive:!0}),r.sync(S,`${JSON.stringify(I.parse(e),null,2)}\n`,{mode:384})}(n),n}const w=A(),T=Number(w.defaultConversationId)||1,N=process.env.TASK_HANDOFF_SOCKET||s.join(n.tmpdir(),`task-handoff-${process.getuid?process.getuid():"user"}.sock`),O=w.chatTools?.telegram?.default||{},E=O.defaultChatId,z=E?w.chatBindings?.telegram?.default?.[E]:void 0;function x(e){return Array.isArray(e)?e.map(e=>String(e).trim()).filter(Boolean):String(e||"").split(",").map(e=>e.trim()).filter(Boolean)}const D=E,k=O.token,C=x(O.allowedUserIds),P=Number(z?.conversationId)||T,F=w.wechat||{},R=F.baseUrl,M=F.chatId,j=F.contextToken,H=F.token,L=F.updatesBuf,$=Number(F.conversationId)||T,U=w.chatTools?.dingding?.default||{},q=U.defaultChatId,K=q?w.chatBindings?.dingding?.default?.[q]:void 0,B=U.clientId,V=U.clientSecret,G=U.corpId,W=U.robotCode,X=U.cardTemplateId||"13fc6717-12e4-43ed-8533-111a310d4995.schema",J=U.cardCallbackRouteKey||"bi_workflow_ticket",Y=Number(U.cardUserIdType)||1,Q=q,Z=x(U.allowedUserIds),ee=Number(K?.conversationId)||T,te=/(TOKEN|KEY|SECRET|AUTH|PASSWORD|COOKIE)/i,se=/^(TASK_HANDOFF|CODEX|CLAUDE|PWD$|OLDPWD$|SHELL$|TERM$)/;function ne(e,t){if(void 0!==t)return te.test(e)?"[redacted]":t}function re(e=process.env){return Object.fromEntries(Object.entries(e).filter(([e])=>se.test(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,ne(e,t)]))}function ie(e){if(e)try{return m.execFileSync("ps",["-p",String(e),"-o","pid=,ppid=,comm=,args="],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e3}).trim()||void 0}catch{return}}function oe(e,n){t.mkdirSync(s.dirname(e),{recursive:!0}),t.appendFileSync(e,`${JSON.stringify({time:(new Date).toISOString(),...n})}\n`,{mode:384})}function ae(e){const t=Number(String(e||"").trim());return Number.isInteger(t)&&t>0?t:void 0}function de(e){return"codex"===e||"claude"===e||"passive"===e?e:void 0}function ce(e){const t=Number(e);return Number.isFinite(t)&&t>0?t:void 0}function pe(e){return"codex"===e||"claude"===e?e:void 0}function ue(e,t="open"){return function(e,t="passive",s="open"){const n=(new Date).toISOString();return{id:e,mode:t,status:s,createdAt:n,updatedAt:n,agent:"codex"===t||"claude"===t?t:void 0}}(e,"passive",t)}const le=i.z.record(i.z.string(),i.z.unknown());class me{filePath;options;constructor(e,t){this.filePath=e,this.options=t}path(){return this.filePath}load(){try{const e=JSON.parse(t.readFileSync(this.filePath,"utf8"));return this.options.schema.parse(e)}catch(e){if(e&&"object"==typeof e&&"code"in e&&"ENOENT"===e.code)return this.options.defaultValue();throw e}}save(e){t.mkdirSync(s.dirname(this.filePath),{recursive:!0}),r.sync(this.filePath,`${JSON.stringify(this.options.schema.parse(e),null,2)}\n`,{mode:384})}patch(e){const t=this.load(),s=he(le.parse(t),e),n=this.options.schema.parse(s);return this.save(n),n}}function he(e,t){const s={...e};for(const[e,n]of Object.entries(t))if(n&&"object"==typeof n&&!Array.isArray(n)){const t=s[e];s[e]=he(t&&"object"==typeof t&&!Array.isArray(t)?le.parse(t):{},le.parse(n))}else void 0===n?delete s[e]:s[e]=n;return s}const ge=i.z.enum(["passive","codex","claude"]),fe=i.z.enum(["open","closed"]),ye=i.z.enum(["codex","claude"]),ve=i.z.object({schemaVersion:i.z.literal(1).default(1),id:i.z.number().int().positive(),mode:ge.default("passive"),status:fe.default("open"),title:i.z.string().optional(),cwd:i.z.string().optional(),timeoutMs:i.z.number().positive().optional(),agent:ye.optional(),agentSessionId:i.z.string().optional(),codexSessionId:i.z.string().optional(),createdAt:i.z.string(),updatedAt:i.z.string(),closedAt:i.z.string().optional()}),Se=i.z.object({id:i.z.number().int().positive(),status:fe.default("open"),mode:ge.default("passive"),title:i.z.string().optional(),updatedAt:i.z.string()}),Ie=i.z.object({schemaVersion:i.z.literal(1).default(1),defaultConversationId:i.z.number().int().positive().default(T),nextConversationId:i.z.number().int().positive().default(T+1),items:i.z.array(Se).default([])}),Ae=i.z.object({mode:ge.optional(),status:fe.optional(),title:i.z.string().trim().min(1).optional(),cwd:i.z.string().trim().min(1).optional(),timeoutMs:i.z.number().positive().optional(),agent:ye.optional(),agentSessionId:i.z.string().trim().min(1).optional(),codexSessionId:i.z.string().trim().min(1).optional()});function be(){return(new Date).toISOString()}function _e(e){const t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}function we(e){return Array.isArray(e)?e.map(we):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).filter(([,e])=>null!=e&&""!==e).map(([e,t])=>[e,we(t)])):e}function Te(e){return{id:e.id,status:e.status,mode:e.mode,title:e.title,updatedAt:e.updatedAt}}class Ne{paths;indexStore;constructor(e){this.paths=e,this.indexStore=new me(s.join(e.conversationsDir,"index.json"),{schema:Ie,defaultValue:()=>({schemaVersion:1,defaultConversationId:T,nextConversationId:T+1,items:[]})})}indexPath(){return this.indexStore.path()}list(){const e=this.ensureSeeded(),t=e.items.map(e=>this.loadRecord(e.id)).filter(e=>Boolean(e)).sort((e,t)=>e.id-t.id);return{schemaVersion:1,defaultConversationId:e.defaultConversationId,nextConversationId:e.nextConversationId,indexPath:this.indexStore.path(),items:t}}get(e){return this.ensureSeeded(),this.loadRecord(e)}create(e={}){const t=this.ensureSeeded(),s=be(),n=_e(e.id)||t.nextConversationId;if(this.loadRecord(n))throw Object.assign(new Error(`Conversation ${n} already exists.`),{code:"CONVERSATION_EXISTS"});const r=Ae.parse(we(e)),i=ve.parse({schemaVersion:1,id:n,mode:r.mode||"passive",status:r.status||"open",title:r.title,cwd:r.cwd,timeoutMs:r.timeoutMs,agent:r.agent||("codex"===r.mode||"claude"===r.mode?r.mode:void 0),agentSessionId:r.agentSessionId,codexSessionId:r.codexSessionId,createdAt:s,updatedAt:s});return this.saveRecord(i),this.saveIndex({...t,nextConversationId:Math.max(t.nextConversationId,n+1),items:[...t.items,Te(i)].sort((e,t)=>e.id-t.id)}),i}update(e,t){const s=this.getRequired(e),n=Ae.parse(we(t)),r=be(),i=ve.parse({...s,...n,agent:n.agent||("codex"===n.mode||"claude"===n.mode?n.mode:s.agent),updatedAt:r,closedAt:"closed"===n.status?s.closedAt||r:"open"===n.status?void 0:s.closedAt});return this.saveRecord(i),this.updateIndexItem(i),i}use(e){const t=this.getRequired(e),s=this.ensureSeeded();return this.saveIndex({...s,defaultConversationId:e}),_({defaultConversationId:e}),t}close(e){return this.update(e,{status:"closed"})}reopen(e){return this.update(e,{status:"open"})}delete(e){const s=this.ensureSeeded();if(e===s.defaultConversationId)throw Object.assign(new Error("Default conversation cannot be deleted."),{code:"CONVERSATION_DEFAULT"});const n=this.getRequired(e),r=this.recordPath(e);return t.existsSync(r)&&t.unlinkSync(r),this.saveIndex({...s,items:s.items.filter(t=>t.id!==e)}),n}ensureSeeded(){if(t.existsSync(this.indexStore.path()))return this.indexStore.load();const e=A(),s=function(e){const t=new Map;for(const s of Array.isArray(e.conversations)?e.conversations:[]){const e=ae(s?.id);if(!e)continue;const n=de(s.mode)||"passive",r=pe(s.agent)||("codex"===n||"claude"===n?n:void 0),i="string"==typeof s.agentSessionId&&s.agentSessionId.trim()?s.agentSessionId.trim():"codex"===r&&"string"==typeof s.codexSessionId&&s.codexSessionId.trim()?s.codexSessionId.trim():void 0;t.set(e,{id:e,mode:n,status:"closed"===s.status?"closed":"open",createdAt:s.createdAt||(new Date).toISOString(),updatedAt:s.updatedAt||(new Date).toISOString(),closedAt:s.closedAt,cwd:"string"==typeof s.cwd&&s.cwd.trim()?s.cwd.trim():void 0,timeoutMs:ce(s.timeoutMs),agent:r,aiSessionId:"string"==typeof s.aiSessionId&&s.aiSessionId.trim()?s.aiSessionId.trim():void 0,agentSessionId:i,codexSessionId:"string"==typeof s.codexSessionId&&s.codexSessionId.trim()?s.codexSessionId.trim():"codex"===r&&i?i:void 0})}const s=ae(e.defaultConversationId)||T;t.has(s)||t.set(s,ue(s)),t.has(T)||t.set(T,ue(T));const n=[...t.values()].sort((e,t)=>e.id-t.id),r=Math.max(Number(e.nextConversationId)||1,n.reduce((e,t)=>Math.max(e,t.id+1),1));return{conversations:n,defaultConversationId:s,nextConversationId:r}}(e),n=s.conversations.map(e=>ve.parse({schemaVersion:1,...e,agentSessionId:e.agentSessionId,codexSessionId:e.codexSessionId}));for(const e of n)this.saveRecord(e);const r=_e(e.defaultConversationId)||s.defaultConversationId||T,i=Ie.parse({schemaVersion:1,defaultConversationId:r,nextConversationId:s.nextConversationId,items:n.map(Te)});return this.saveIndex(i),_({defaultConversationId:r}),i}getRequired(e){const t=this.get(e);if(!t)throw Object.assign(new Error("Conversation not found."),{code:"CONVERSATION_NOT_FOUND"});return t}recordPath(e){return s.join(this.paths.conversationsDir,`conversation-${e}.json`)}loadRecord(e){const s=this.recordPath(e);try{return ve.parse(JSON.parse(t.readFileSync(s,"utf8")))}catch(e){if(e&&"object"==typeof e&&"code"in e&&"ENOENT"===e.code)return;throw e}}saveRecord(e){new me(this.recordPath(e.id),{schema:ve,defaultValue:()=>e}).save(e)}saveIndex(e){this.indexStore.save(Ie.parse(e))}updateIndexItem(e){const t=this.ensureSeeded();this.saveIndex({...t,items:t.items.map(t=>t.id===e.id?Te(e):t).sort((e,t)=>e.id-t.id)})}}function Oe(e){const t=_e(e);if(!t)throw Object.assign(new Error("Conversation id must be a positive integer."),{code:"CONVERSATION_ID_INVALID"});return t}class Ee{store;receiverControl;aiSessionController;constructor(e,t,s){this.store=e,this.receiverControl=t,this.aiSessionController=s}async execute(e){const t=this.store.startRun(e.config,e.deployment,e.eventType,e.eventSummary),s=e.promptOverride||(n=e.config.action.promptTemplate,r={trigger:e.config,event:{type:e.eventType,summary:e.eventSummary||""}},n.replaceAll("{{trigger.configHash}}",r.trigger.configHash).replaceAll("{{trigger.name}}",r.trigger.name).replaceAll("{{event.type}}",r.event.type).replaceAll("{{event.summary}}",r.event.summary));var n,r;try{if("ai-session"===e.deployment.target.type){if(!this.aiSessionController)throw Object.assign(new Error("AI session trigger targets are not available."),{code:"TRIGGER_AI_SESSION_TARGET_UNAVAILABLE",statusCode:400});let n;try{n=await this.aiSessionController.sendMessage(e.deployment.target.aiSessionId,{message:s})}catch(t){throw t&&"object"==typeof t&&"code"in t&&"AI_SESSION_NOT_FOUND"===String(t.code)&&this.store.deleteDeployment(e.deployment.configHash,e.deployment.deploymentId||e.deployment.configHash),t}return{run:this.store.completeRun(t),result:n}}const n=await this.receiverControl.message({channel:"web",chatSessionId:`trigger:${e.deployment.deploymentId||e.deployment.configHash}`,userId:"trigger",conversationId:e.deployment.target.conversationId,text:s,attachments:[]});return{run:this.store.completeRun(t),result:n}}catch(e){const s=this.store.completeRun(t,e);throw Object.assign(e instanceof Error?e:new Error(String(e)),{run:s})}}}class ze{store;executor;paths;publish;timers=new Map;watches=new Map;running=new Set;queued=new Map;lastRunAt=new Map;previousAiSessions=new Map;constructor(e,t,s,n){this.store=e,this.executor=t,this.paths=s,this.publish=n}start(){this.stop();const e=this.store.list();for(const t of e.deployments.filter(e=>e.enabled)){const s=e.configs.find(e=>e.configHash===t.configHash);s&&("schedule"===s.source.type&&this.startSchedule(s,t),"file-change"===s.source.type&&this.startFileWatch(s,t))}}restart(){this.start()}stop(){for(const e of this.timers.values())clearInterval(e);this.timers.clear();for(const e of this.watches.values()){for(const t of e.watchers)t.close();e.debounce&&clearTimeout(e.debounce)}this.watches.clear()}handleAiSessions(e){const t=new Map(e.sessions.map(e=>[e.id,e])),s=this.store.pruneMissingAiSessionDeployments(new Set(t.keys()));s.length&&(this.restart(),this.publish?.("trigger.deployment.pruned",{deployments:s}),this.publish?.("trigger.updated",this.store.list()));const n=this.store.list();for(const t of n.deployments.filter(e=>e.enabled)){const s=n.configs.find(e=>e.configHash===t.configHash);if(s&&"ai-session"===s.source.type)for(const n of e.sessions){const e=this.previousAiSessions.get(n.id);if(!e||!this.aiSessionMatches(s,n))continue;const r=e.status!==n.status,i=e.phase!==n.phase;if(!r&&!i)continue;const o=`AI session ${n.id}: ${e.status}/${e.phase} -> ${n.status}/${n.phase}`;this.execute(s,t,"ai-session",o)}}this.previousAiSessions=t}startSchedule(e,t){if("schedule"!==e.source.type)return;const s=e.source,n=xe(t);if("intervalMs"in s)return void this.timers.set(n,setInterval(()=>{this.execute(e,t,"schedule",`Interval ${s.intervalMs}ms`)},s.intervalMs));const r=()=>{const i=function(e){if("intervalMs"in e)return new Date(Date.now()+e.intervalMs);const[t,s]=e.timeOfDay.split(":").map(Number),n=new Date;for(let r=0;r<=14;r+=1){const i=new Date(n.getTime()+864e5*r);if("weekly"===e.scheduleKind&&!e.weekdays.includes(ke(i,e.timezone).weekday))continue;const o=De(i,e.timezone,t,s);if(o.getTime()>n.getTime()+500)return o}return new Date(Date.now()+864e5)}(s),o=Math.max(1e3,i.getTime()-Date.now()),a=setTimeout(()=>{this.execute(e,t,"schedule",function(e){return"intervalMs"in e?`Interval ${e.intervalMs}ms`:"daily"===e.scheduleKind?`Daily at ${e.timeOfDay} ${e.timezone}`:`Weekly on ${e.weekdays.join(",")} at ${e.timeOfDay} ${e.timezone}`}(s)),r()},o);this.timers.set(n,a)};r()}startFileWatch(e,n){if("file-change"!==e.source.type)return;const r=e.source,i=xe(n),o={watchers:[],changed:new Set};for(const i of e.source.roots){const a=s.resolve(i),d=Ce();if(a.startsWith(d)&&t.existsSync(a))for(const i of Re(a)){const a=t.watch(i,(t,a)=>{const c=a?s.join(i,String(a)):i;this.fileMatches(e,c)&&(o.changed.add(s.relative(d,c)),o.debounce&&clearTimeout(o.debounce),o.debounce=setTimeout(()=>{const t=[...o.changed].sort();o.changed.clear(),this.execute(e,n,"file-change",`Changed files:\n${t.join("\n")}`)},r.debounceMs))});o.watchers.push(a)}}o.watchers.length&&this.watches.set(i,o)}fileMatches(e,t){if("file-change"!==e.source.type)return!1;const n=s.relative(Ce(),t).replaceAll(s.sep,"/");return!Pe(n)&&!(e.source.ignore||[]).some(e=>Fe(e,n))&&e.source.globs.some(e=>Fe(e,n))}aiSessionMatches(e,t){return!("ai-session"!==e.source.type||e.source.conversationId&&t.conversationId!==e.source.conversationId||e.source.agent&&t.agent!==e.source.agent||e.source.statuses?.length&&!e.source.statuses.includes(t.status)||e.source.phases?.length&&!e.source.phases.includes(t.phase))}async execute(e,t,s,n){const r=xe(t),i=Date.now(),o=e.policy.cooldownMs||0,a=this.lastRunAt.get(r)||0;if(o&&i-a<o)return this.store.skipRun(e,t,s,"Skipped by cooldown policy."),void this.publish?.("trigger.run.skipped",{configHash:e.configHash,deploymentId:t.deploymentId,reason:"cooldown"});if(this.running.has(r))"queue"===e.policy.whenBusy?this.queued.set(r,{config:e,deployment:t,eventType:s,eventSummary:n}):(this.store.skipRun(e,t,s,"Skipped because trigger is already running."),this.publish?.("trigger.run.skipped",{configHash:e.configHash,deploymentId:t.deploymentId,reason:"busy"}));else{this.running.add(r),this.lastRunAt.set(r,i),this.publish?.("trigger.run.started",{configHash:e.configHash,deploymentId:t.deploymentId,eventType:s});try{const r=await this.executor.execute({config:e,deployment:t,eventType:s,eventSummary:n});this.publish?.("trigger.run.completed",r),this.publish?.("trigger.updated",this.store.list())}catch(t){this.publish?.("trigger.run.failed",{configHash:e.configHash,error:t instanceof Error?t.message:String(t)}),this.publish?.("trigger.updated",this.store.list())}finally{this.running.delete(r);const e=this.queued.get(r);e&&(this.queued.delete(r),setTimeout(()=>{this.execute(e.config,e.deployment,e.eventType,e.eventSummary)},0))}}}}function xe(e){return e.deploymentId||e.configHash}function De(e,t,s,n){const r=ke(e,t),i=Date.UTC(r.year,r.month-1,r.day,s,n,0,0),o=new Date(i),a=ke(o,t),d=(Date.UTC(a.year,a.month-1,a.day,a.hour,a.minute)-o.getTime())/6e4;return new Date(i-6e4*d)}function ke(e,t){const s=new Intl.DateTimeFormat("en-US",{timeZone:t,weekday:"short",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).formatToParts(e),n=e=>s.find(t=>t.type===e)?.value||"";return{year:Number(n("year")),month:Number(n("month")),day:Number(n("day")),hour:Number(n("hour")),minute:Number(n("minute")),weekday:{Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6}[n("weekday")]??0}}function Ce(){return s.resolve(process.env.TASK_HANDOFF_WORKSPACE||process.env.WORKSPACE||"/workspace")}function Pe(e){return/(^|\/)(\.git|node_modules|dist|build)\//.test(e)||/\.(log|tmp|swp)$/.test(e)}function Fe(e,t){if("**/*"===e||"**"===e)return!0;const s=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replaceAll("**",".*").replaceAll("*","[^/]*");return new RegExp(`^${s}$`).test(t)}function Re(e){if("darwin"===process.platform||"win32"===process.platform)return[e];const n=[e],r=[e];for(;r.length;){const e=r.pop();let i=[];try{i=t.readdirSync(e,{withFileTypes:!0})}catch{continue}for(const t of i){if(!t.isDirectory())continue;const i=s.join(e,t.name);Pe(`${s.relative(Ce(),i).replaceAll(s.sep,"/")}/`)||(n.push(i),r.push(i))}}return n}const Me=i.z.union([i.z.object({type:i.z.literal("schedule"),scheduleKind:i.z.literal("interval").default("interval"),intervalMs:i.z.number().int().min(1e3)}).strict(),i.z.object({type:i.z.literal("schedule"),scheduleKind:i.z.literal("daily"),timeOfDay:i.z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/),timezone:i.z.string().trim().min(1).max(120)}).strict(),i.z.object({type:i.z.literal("schedule"),scheduleKind:i.z.literal("weekly"),weekdays:i.z.array(i.z.number().int().min(0).max(6)).min(1).max(7),timeOfDay:i.z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/),timezone:i.z.string().trim().min(1).max(120)}).strict()]),je=i.z.union([Me,i.z.object({type:i.z.literal("file-change"),roots:i.z.array(i.z.string().trim().min(1).max(4096)).min(1).max(50),globs:i.z.array(i.z.string().trim().min(1).max(500)).min(1).max(100),ignore:i.z.array(i.z.string().trim().min(1).max(500)).max(100).optional(),debounceMs:i.z.number().int().min(100).max(6e4).default(1500)}).strict(),i.z.object({type:i.z.literal("ai-session"),conversationId:i.z.number().int().positive().optional(),agent:i.z.string().trim().min(1).max(80).optional(),statuses:i.z.array(i.z.enum(["running","waiting","idle","failed"])).max(20).optional(),phases:i.z.array(i.z.enum(["thinking","tool","editing","approval","responding","unknown"])).max(20).optional()}).strict()]),He=i.z.object({promptTemplate:i.z.string().trim().min(1).max(2e4)}).strict(),Le=i.z.object({cooldownMs:i.z.number().int().min(0).max(864e5).optional(),maxConcurrentRuns:i.z.number().int().min(1).max(20).default(1),whenBusy:i.z.enum(["skip","queue"]).default("skip")}).strict(),$e=i.z.object({configHash:i.z.string().trim().min(8).max(80),name:i.z.string().trim().min(1).max(160),description:i.z.string().trim().max(1e3).optional(),source:je,action:He,policy:Le.default({maxConcurrentRuns:1,whenBusy:"skip"}),createdAt:i.z.string().datetime(),updatedAt:i.z.string().datetime()}).strict(),Ue=i.z.discriminatedUnion("type",[i.z.object({type:i.z.literal("conversation"),conversationId:i.z.number().int().positive()}).strict(),i.z.object({type:i.z.literal("ai-session"),aiSessionId:i.z.string().trim().min(1).max(160)}).strict()]),qe=i.z.object({configHash:i.z.string().trim().min(8).max(80),deploymentId:i.z.string().trim().min(1).max(240).optional(),instanceId:i.z.string().trim().min(1).max(160),origin:i.z.enum(["control-plane","controlled-instance"]).default("controlled-instance"),enabled:i.z.boolean().default(!0),target:Ue,localName:i.z.string().trim().min(1).max(160).optional(),createdAt:i.z.string().datetime(),updatedAt:i.z.string().datetime()}).strict(),Ke=i.z.object({configHash:i.z.string().trim().min(8).max(80),deploymentId:i.z.string().trim().min(1).max(240).optional(),instanceId:i.z.string().trim().min(1).max(160),status:i.z.enum(["idle","running","disabled","error"]).default("idle"),lastTriggeredAt:i.z.string().datetime().optional(),lastCompletedAt:i.z.string().datetime().optional(),lastSkippedAt:i.z.string().datetime().optional(),lastError:i.z.string().trim().max(4e3).optional(),runCount:i.z.number().int().min(0).default(0),skippedCount:i.z.number().int().min(0).default(0)}).strict(),Be=i.z.object({id:i.z.string().trim().min(1).max(160),configHash:i.z.string().trim().min(8).max(80),deploymentId:i.z.string().trim().min(1).max(240).optional(),instanceId:i.z.string().trim().min(1).max(160),eventType:i.z.enum(["manual","schedule","file-change","ai-session"]),status:i.z.enum(["started","completed","failed","skipped"]),target:Ue,promptPreview:i.z.string().trim().max(500),eventSummary:i.z.string().trim().max(1e3).optional(),error:i.z.string().trim().max(4e3).optional(),startedAt:i.z.string().datetime(),completedAt:i.z.string().datetime().optional()}).strict(),Ve=i.z.object({schemaVersion:i.z.literal(1).default(1),configs:i.z.array($e).default([]),deployments:i.z.array(qe).default([]),runtime:i.z.array(Ke).default([]),recentRuns:i.z.array(Be).default([])}).strict();function Ge(e){return Array.isArray(e)?e.map(Ge):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Ge(t)])):e}function We(){return(new Date).toISOString()}function Xe(e){return e.deploymentId||e.configHash}function Je(e){return Ke.parse({configHash:e.configHash,deploymentId:e.deploymentId,instanceId:e.instanceId,status:e.enabled?"idle":"disabled",runCount:0,skippedCount:0})}function Ye(e){return e.trim().slice(0,500)}class Qe{indexStore;constructor(e){this.indexStore=new me(s.join(e.triggersDir,"index.json"),{schema:Ve,defaultValue:()=>({schemaVersion:1,configs:[],deployments:[],runtime:[],recentRuns:[]})})}indexPath(){return this.indexStore.path()}list(){return this.indexStore.load()}get(e){const t=this.list(),s=t.configs.find(t=>t.configHash===e),n=t.deployments.filter(t=>t.configHash===e);if(s)return{config:s,deployments:n,runtime:t.runtime.filter(t=>t.configHash===e),recentRuns:t.recentRuns.filter(t=>t.configHash===e)}}create(e){const t=We(),s={maxConcurrentRuns:e.policy?.maxConcurrentRuns??1,whenBusy:e.policy?.whenBusy??"skip",cooldownMs:e.policy?.cooldownMs},n=function(e){const t=Ge({source:e.source,action:e.action,policy:Le.parse(e.policy||{})});return`trg_${h.createHash("sha256").update(JSON.stringify(t)).digest("hex").slice(0,24)}`}({source:e.source,action:e.action,policy:s}),r=$e.parse({configHash:n,name:e.name,description:e.description,source:e.source,action:e.action,policy:s,createdAt:t,updatedAt:t}),i=function(e,t={}){const s=We();return qe.parse({configHash:e,deploymentId:t.deploymentId,instanceId:process.env.TASK_HANDOFF_INSTANCE_ID||"local",origin:t.origin||"controlled-instance",enabled:t.enabled??!0,target:t.target||{type:"conversation",conversationId:1},localName:t.localName,createdAt:s,updatedAt:s})}(n,e.deployment),o=this.list(),a=o.configs.some(e=>e.configHash===n)?o.configs:[...o.configs,r],d=Xe(i),c=[...o.deployments.filter(e=>Xe(e)!==d),i],p=[...o.runtime.filter(e=>Xe(e)!==d),Je(i)];return this.save({...o,configs:a,deployments:c,runtime:p}),{config:r,deployment:i,runtime:Je(i)}}patch(e,t){const s=this.list(),n=s.configs.find(t=>t.configHash===e);if(!n)return;const r=$e.parse({...n,name:t.name??n.name,description:null===t.description?void 0:t.description??n.description,updatedAt:We()});return this.save({...s,configs:s.configs.map(t=>t.configHash===e?r:t)}),r}setEnabled(e,t){const s=this.list(),n=We();let r=!1;const i=s.deployments.map(s=>s.configHash!==e?s:(r=!0,qe.parse({...s,enabled:t,updatedAt:n})));if(!r)return;const o=s.runtime.map(s=>s.configHash===e?Ke.parse({...s,status:t?"idle":"disabled"}):s);return this.save({...s,deployments:i,runtime:o}),this.get(e)}delete(e){const t=this.list();return!!t.configs.some(t=>t.configHash===e)&&(this.save({...t,configs:t.configs.filter(t=>t.configHash!==e),deployments:t.deployments.filter(t=>t.configHash!==e),runtime:t.runtime.filter(t=>t.configHash!==e),recentRuns:t.recentRuns.filter(t=>t.configHash!==e)}),!0)}deleteDeployment(e,t){const s=this.list();if(!s.deployments.some(s=>s.configHash===e&&Xe(s)===t))return!1;const n=s.deployments.filter(s=>!(s.configHash===e&&Xe(s)===t)),r=n.some(t=>t.configHash===e);return this.save({...s,configs:r?s.configs:s.configs.filter(t=>t.configHash!==e),deployments:n,runtime:s.runtime.filter(s=>!(s.configHash===e&&Xe(s)===t))}),!0}pruneMissingAiSessionDeployments(e){const t=this.list(),s=t.deployments.filter(t=>"ai-session"===t.target.type&&!e.has(t.target.aiSessionId));if(!s.length)return[];const n=new Set(s.map(e=>Xe(e))),r=t.deployments.filter(e=>!n.has(Xe(e))),i=new Set(r.map(e=>e.configHash));return this.save({...t,configs:t.configs.filter(e=>i.has(e.configHash)),deployments:r,runtime:t.runtime.filter(e=>!n.has(Xe(e)))}),s}startRun(e,t,s,n){const r=We(),i=Be.parse({id:`run_${Date.now().toString(36)}_${Math.random().toString(16).slice(2)}`,configHash:e.configHash,deploymentId:t.deploymentId,instanceId:t.instanceId,eventType:s,status:"started",target:t.target,promptPreview:Ye(e.action.promptTemplate),eventSummary:n,startedAt:r}),o=this.list(),a=this.upsertRuntime(o,t,{status:"running",lastTriggeredAt:r});return this.save({...o,runtime:a,recentRuns:[i,...o.recentRuns].slice(0,100)}),i}completeRun(e,t){const s=We(),n=Boolean(t),r=this.list(),i=r.recentRuns.map(r=>r.id===e.id?Be.parse({...r,status:n?"failed":"completed",error:t instanceof Error?t.message:t?String(t):void 0,completedAt:s}):r),o=r.deployments.find(t=>t.configHash===e.configHash&&Xe(t)===(e.deploymentId||e.configHash)),a=o?this.upsertRuntime(r,o,{status:n?"error":o.enabled?"idle":"disabled",lastCompletedAt:s,lastError:n?t instanceof Error?t.message:String(t):void 0,runCount:(r.runtime.find(t=>t.configHash===e.configHash&&Xe(t)===Xe(o))?.runCount||0)+1}):r.runtime;return this.save({...r,runtime:a,recentRuns:i}),i.find(t=>t.id===e.id)}skipRun(e,t,s,n){const r=We(),i=Be.parse({id:`run_${Date.now().toString(36)}_${Math.random().toString(16).slice(2)}`,configHash:e.configHash,deploymentId:t.deploymentId,instanceId:t.instanceId,eventType:s,status:"skipped",target:t.target,promptPreview:Ye(e.action.promptTemplate),eventSummary:n,startedAt:r,completedAt:r}),o=this.list(),a=this.upsertRuntime(o,t,{status:t.enabled?"idle":"disabled",lastSkippedAt:r,skippedCount:(o.runtime.find(e=>Xe(e)===Xe(t))?.skippedCount||0)+1});return this.save({...o,runtime:a,recentRuns:[i,...o.recentRuns].slice(0,100)}),i}primaryDeployment(e){return this.list().deployments.find(t=>t.configHash===e)}upsertRuntime(e,t,s){const n=Xe(t),r=e.runtime.find(e=>Xe(e)===n)||Je(t),i=Ke.parse({...r,...s});return[...e.runtime.filter(e=>Xe(e)!==n),i]}save(e){this.indexStore.save(Ve.parse(e))}}function Ze(e,t){const n=process.env[e];return n&&n.trim()?s.resolve(n.trim()):t}function et(){const e=s.join(process.env.XDG_DATA_HOME||s.join(n.homedir(),".local","share"),"task-handoff"),t=Ze("TASK_HANDOFF_CONFIG",S),r=Ze("TASK_HANDOFF_DATA_DIR",s.dirname(t)||e);return{configPath:t,dataDir:r,channelsDir:Ze("TASK_HANDOFF_CHANNELS_DIR",s.join(r,"channels")),conversationsDir:Ze("TASK_HANDOFF_CONVERSATIONS_DIR",s.join(r,"conversations")),appCatalogDir:Ze("TASK_HANDOFF_APP_CATALOG_DIR",s.join(r,"app-catalog")),appSessionsDir:Ze("TASK_HANDOFF_APP_SESSION_DIR",s.join(r,"app-sessions")),triggersDir:Ze("TASK_HANDOFF_TRIGGERS_DIR",s.join(r,"triggers")),runtimeDir:Ze("TASK_HANDOFF_RUNTIME_DIR",s.join(r,"runtime")),eventsDir:Ze("TASK_HANDOFF_EVENTS_DIR",s.join(r,"events")),artifactDir:Ze("TASK_HANDOFF_ARTIFACT_DIR",s.join(r,"artifacts")),logDir:Ze("TASK_HANDOFF_LOG_DIR",s.join(r,"logs")),webTokenPath:Ze("TASK_HANDOFF_WEB_TOKEN_FILE",s.join(r,"web-token"))}}const tt=i.z.object({schemaVersion:i.z.literal(1).default(1),channel:i.z.enum(["telegram","wechat","dingding"]),instanceId:i.z.string().default("default"),enabled:i.z.boolean().default(!1),defaultChatId:i.z.string().optional(),allowedUserIds:i.z.array(i.z.string()).optional(),bindings:i.z.record(i.z.string(),i.z.object({conversationId:i.z.number(),contextToken:i.z.string().optional()})).optional(),secrets:i.z.record(i.z.string(),i.z.unknown()).optional(),state:i.z.record(i.z.string(),i.z.unknown()).optional()}),st=i.z.object({schemaVersion:i.z.literal(1).default(1),defaultConversationId:i.z.number().default(1),nextConversationId:i.z.number().default(2),items:i.z.array(i.z.record(i.z.string(),i.z.unknown())).default([])}),nt=i.z.object({schemaVersion:i.z.literal(1).default(1),items:i.z.array(i.z.record(i.z.string(),i.z.unknown())).default([])}),rt=/^[a-f0-9]{8}$/;function it(e=process.env){return e.CLAUDE_CONTROL_SOCK||s.join(function(e=process.env){const t=process.getuid?.()??0,r=e.TERMUX_VERSION&&e.PREFIX?s.join(e.PREFIX,"tmp"):"/tmp",i=(e.CLAUDE_CONFIG_DIR??s.join(n.homedir(),".claude")).normalize("NFC"),o=h.createHash("sha256").update(s.resolve(i)).digest("hex").slice(0,8);return s.join(r,`cc-daemon-${t}`,o)}(e),"control.sock")}function ot(e,t={}){const s=t.sockPath||it(),n=t.timeoutMs??5e3;return new Promise(t=>{let r;try{r=o.connect(s)}catch(e){return void t({ok:!1,code:"ENOCONN",error:String(e)})}let i=!1,a="";const d=e=>{i||(i=!0,r.destroy(),t(e))};r.setTimeout(n,()=>d({ok:!1,code:"ETIMEOUT",error:"control socket timeout"})),r.on("error",e=>d({ok:!1,code:"ENOCONN",error:String(e)})),r.once("connect",()=>{r.write(`${JSON.stringify({proto:1,...e})}\n`)}),r.on("data",e=>{a+=e.toString("utf8");const t=a.indexOf("\n");if(t<0)return;const s=a.slice(0,t);try{d(JSON.parse(s))}catch(e){d({ok:!1,code:"EBADJSON",error:String(e),raw:s})}}),r.once("close",()=>{i||d({ok:!1,code:"ENOCONN",error:"connection dropped mid-request"})})})}function at(e,t,s){return pt(e),ot({op:"reply",short:e,text:t},s)}function dt(e,t="SIGTERM",s){return pt(e),ot({op:"kill",short:e,signal:t},s)}function ct(e,{tail:t,onMessage:s,options:n={}}={}){pt(e);const r=o.connect(n.sockPath||it());let i="";return r.on("connect",()=>{r.write(`${JSON.stringify({proto:1,op:"subscribe",short:e,tail:t})}\n`)}),r.on("data",e=>{i+=e.toString("utf8");let t=i.indexOf("\n");for(;t>=0;){const e=i.slice(0,t);if(i=i.slice(t+1),e.trim())try{s?.(JSON.parse(e))}catch{s?.({raw:e})}t=i.indexOf("\n")}}),r.on("error",()=>{}),()=>r.destroy()}function pt(e){if(!rt.test(e))throw new Error(`Claude worker short id must be 8 hex chars: ${e}`)}function ut(e,t=!1){const s=process.env[e];return void 0===s||""===s?t:["1","true","yes","on"].includes(s.toLowerCase())}function lt(...e){for(const t of e){const e=process.env[t]?.trim();if(e)return["--model",e]}return[]}const mt=i.z.string().trim().min(1).max(512).refine(e=>!/\s/.test(e)&&!/[;&|<>`$]/.test(e),"Command must be a single executable path or name."),ht=i.z.object({id:i.z.string().trim().min(1).max(80).regex(/^[a-z0-9][a-z0-9._-]*$/),name:i.z.string().trim().min(1).max(120),kind:i.z.enum(["tty","gui"]),description:i.z.string().max(500).optional(),command:mt,args:i.z.array(i.z.string().max(1024)).max(64).default([]).optional(),cwd:i.z.string().max(512).optional(),env:i.z.record(i.z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),i.z.string().max(4096)).optional(),display:i.z.object({width:i.z.number().int().min(320).max(7680).optional(),height:i.z.number().int().min(240).max(4320).optional(),depth:i.z.union([i.z.literal(16),i.z.literal(24),i.z.literal(32)]).optional()}).optional(),defaultDisplayTarget:i.z.object({mode:i.z.enum(["isolated","shared"]),id:i.z.string().trim().min(1).max(80).regex(/^[a-z0-9][a-z0-9._-]*$/).optional(),autoCreate:i.z.boolean().optional()}).optional(),automation:i.z.object({type:i.z.literal("cdp"),portArg:i.z.string().optional(),endpointPath:i.z.string().optional()}).optional()}),gt=i.z.object({schemaVersion:i.z.literal(1).default(1),items:i.z.array(ht).default([])}).superRefine((e,t)=>{const s=new Set(vt({includeOptional:!0}).map(e=>e.id)),n=new Set;for(const[r,o]of e.items.entries())s.has(o.id)&&t.addIssue({code:i.z.ZodIssueCode.custom,path:["items",r,"id"],message:"Custom apps cannot override built-in app ids."}),n.has(o.id)&&t.addIssue({code:i.z.ZodIssueCode.custom,path:["items",r,"id"],message:"Custom app ids must be unique."}),n.add(o.id)}),ft=[{id:"terminal-tty",name:"Terminal",kind:"tty",description:"Interactive shell in the task workspace.",command:process.env.SHELL||"/bin/bash"},{id:"codex",name:"Codex",kind:"tty",description:"OpenAI Codex CLI in the task workspace.",command:process.env.TASK_HANDOFF_CODEX_COMMAND||"codex"},{id:"claude",name:"Claude",kind:"tty",description:"Claude Code CLI in the task workspace.",command:process.env.TASK_HANDOFF_CLAUDE_COMMAND||"claude"},{id:"terminal-gui",name:"GUI Terminal",kind:"gui",description:"xterm terminal in an isolated virtual desktop with VNC access.",command:process.env.TASK_HANDOFF_XTERM_COMMAND||"xterm",args:["-geometry","120x32"],display:{width:1024,height:768,depth:24}},{id:"chromium",name:"Browser",kind:"gui",description:"Chromium browser with VNC and CDP endpoints.",command:process.env.TASK_HANDOFF_CHROMIUM_COMMAND||"chromium",args:["about:blank"],display:{width:1440,height:900,depth:24},automation:{type:"cdp",portArg:"--remote-debugging-port={port}"}},{id:"vscode-web",name:"VS Code",kind:"web",description:"VS Code Web in the task workspace.",command:process.env.TASK_HANDOFF_VSCODE_WEB_COMMAND||"code-server",args:["--auth","none","--bind-addr","127.0.0.1:{port}","--disable-telemetry","--user-data-dir","{sessionDir}/user-data","--extensions-dir","{sessionDir}/extensions","{cwd}"],web:{readyPath:"/"}}];function yt(e){return"codex"===e.id?{...e,command:process.env.TASK_HANDOFF_CODEX_COMMAND||e.command,args:lt("TASK_HANDOFF_CODEX_MODEL","CODEX_MODEL")}:"claude"===e.id?{...e,command:process.env.TASK_HANDOFF_CLAUDE_COMMAND||e.command,args:[...ut("TASK_HANDOFF_CLAUDE_DANGEROUSLY_SKIP_PERMISSIONS")||ut("TASK_HANDOFF_CLAUDE_SKIP_PERMISSIONS")?["--dangerously-skip-permissions"]:[],...lt("TASK_HANDOFF_CLAUDE_MODEL","CLAUDE_MODEL")]}:e}function vt(e={}){return[...ft.map(yt),...e.includeOptional||ut("TASK_HANDOFF_ENABLE_CC_SWITCH")?[{id:"cc-switch",name:"CC Switch",kind:"gui",description:"CC Switch desktop app in an isolated virtual desktop.",command:process.env.TASK_HANDOFF_CC_SWITCH_COMMAND||"cc-switch",display:{width:1440,height:900,depth:24}}].map(yt):[]]}vt({includeOptional:!0});class St{customStore;constructor(e){this.customStore=new me(s.join(e.appCatalogDir,"custom.json"),{schema:gt,defaultValue:()=>({schemaVersion:1,items:[]})})}list(){const e=new Map;for(const t of vt())e.set(t.id,t);const t=this.safeCustom();if(t.data)for(const s of t.data.items)e.set(s.id,s);return Array.from(e.values())}find(e){return this.list().find(t=>t.id===e)}custom(){return this.customStore.load()}safeCustom(){try{return{data:this.customStore.load(),error:void 0}}catch(e){return{data:void 0,error:{code:"APP_CATALOG_INVALID",message:e instanceof Error?e.message:String(e)}}}}saveCustom(e){return this.customStore.save(gt.parse(e)),this.customStore.load()}customPath(){return this.customStore.path()}}class It{socketPath;onThreadBound;server;port;stopped=!1;constructor(e,t){this.socketPath=e,this.onThreadBound=t}get endpoint(){return this.port?`ws://127.0.0.1:${this.port}`:void 0}start(e){if(this.server)return;this.port=e;const t=new y.WebSocketServer({host:"127.0.0.1",port:e});this.server=t,t.on("connection",e=>this.attach(e))}stop(){this.stopped=!0,this.server?.close();for(const e of this.server?.clients||[])e.close();this.server=void 0}attach(e){if(this.stopped)return void e.close();const t=new y("ws://localhost/rpc",{createConnection:()=>o.createConnection(this.socketPath),perMessageDeflate:!1}),s=new Map,n=[];e.on("message",(e,r)=>{r||this.observeClientMessage(e.toString(),s),t.readyState===y.OPEN?t.send(e,{binary:r}):t.readyState===y.CONNECTING&&n.push({data:e,isBinary:r})}),t.on("open",()=>{for(;t.readyState===y.OPEN&&n.length>0;){const e=n.shift();e&&t.send(e.data,{binary:e.isBinary})}}),t.on("message",(t,n)=>{n||this.observeServerMessage(t.toString(),s),e.readyState===y.OPEN&&e.send(t,{binary:n})});const r=()=>{e.readyState!==y.OPEN&&e.readyState!==y.CONNECTING||e.close(),t.readyState!==y.OPEN&&t.readyState!==y.CONNECTING||t.close()};e.on("close",r),e.on("error",r),t.on("close",r),t.on("error",r)}observeClientMessage(e,t){const s=At(e);if(!s)return;const n=bt(s.id),r="string"==typeof s.method?s.method:"",i=s.params&&"object"==typeof s.params?s.params:{};if(n&&("thread/start"===r||"thread/resume"===r||"thread/fork"===r))return t.set(n,{method:r,threadId:"string"==typeof i.threadId?i.threadId:void 0}),void("string"==typeof i.threadId&&this.onThreadBound(i.threadId));"string"!=typeof i.threadId||"turn/start"!==r&&"turn/steer"!==r&&"turn/interrupt"!==r&&"thread/unsubscribe"!==r||this.onThreadBound(i.threadId)}observeServerMessage(e,t){const s=At(e);if(!s)return;const n=bt(s.id);if(!n)return;const r=t.get(n);if(!r)return;if(t.delete(n),s.error)return;const i=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return;const t=e,s=t.thread&&"object"==typeof t.thread&&!Array.isArray(t.thread)?t.thread:void 0;return"string"==typeof s?.id?s.id:"string"==typeof t.threadId?t.threadId:void 0}(s.result)||r.threadId;i&&this.onThreadBound(i)}}function At(e){try{const t=JSON.parse(e);return t&&"object"==typeof t&&!Array.isArray(t)?t:void 0}catch{return}}function bt(e){return"string"==typeof e&&e?e:"number"==typeof e&&Number.isFinite(e)?String(e):void 0}function _t(e){const t=Number(e.TASK_HANDOFF_GUI_SCALE||process.env.TASK_HANDOFF_GUI_SCALE||"1");return Number.isFinite(t)?Math.min(3,Math.max(1,t)):1}function wt(e){return e.toFixed(2).replace(/\.?0+$/,"")}function Tt(){return process.env.TASK_HANDOFF_GUI_APP_HOME||process.env.HOME||n.homedir()}function Nt(){return`app_${Date.now().toString(36)}_${Math.random().toString(16).slice(2)}`}function Ot(){return(new Date).toISOString()}function Et(e,t=!1){const s=process.env[e];return void 0===s||""===s?t:["1","true","yes","on"].includes(s.toLowerCase())}const zt=new Set(["stopped","exited","failed"]),xt={"workbench.colorTheme":"Default Dark Modern","workbench.preferredDarkColorTheme":"Default Dark Modern"};class Dt extends g.EventEmitter{paths;sessions=new Map;persistedSessions=new Map;nextDisplay=101;nextVncPort=6101;nextWebsockifyPort=7101;nextWebPort=8101;nextCdpPort=9201;sharedDisplays=new Map;sharedCodexAppServer;catalogRepository;persistSessionMetadata;constructor(e){super(),this.paths=e,this.catalogRepository=new St(e),this.persistSessionMetadata=Et("TASK_HANDOFF_APP_SESSION_PERSIST"),this.persistSessionMetadata&&(this.loadPersistedSessions(),this.cleanupExpiredSessions())}catalog(){return this.catalogRepository.list()}customCatalog(){const e=this.catalogRepository.safeCustom();return e.data?{data:{path:this.catalogRepository.customPath(),...e.data},error:void 0}:{data:void 0,error:e.error}}saveCustomCatalog(e){return{path:this.catalogRepository.customPath(),...this.catalogRepository.saveCustom({schemaVersion:1,items:e})}}listSessions(){return Array.from(this.persistedSessions.values()).sort((e,t)=>t.createdAt.localeCompare(e.createdAt))}sharedCodexAppServerInfo(){const e=this.sharedCodexAppServer;if(e&&!e.child.killed&&null===e.child.exitCode&&t.existsSync(e.socketPath))return{transport:"unix",endpoint:e.endpoint,socketPath:e.socketPath,pid:e.child.pid,command:e.command,args:e.args,logPath:e.logPath,status:"running"}}ensureSharedCodexAppServer(){const e=this.catalogRepository.find("codex"),t=e?.command||process.env.TASK_HANDOFF_CODEX_COMMAND||"codex";if(!this.hasCommand(t))throw Object.assign(new Error(`Missing required command: ${t}`),{code:"APP_DEPENDENCY_MISSING"});const s=e?.cwd||process.env.TASK_HANDOFF_WORKSPACE||process.cwd(),n={...process.env,...e?.env,TERM:"xterm-256color"};return this.acquireSharedCodexAppServer(t,s,n,"__shared_codex_app_server__")}_createCodexAppServerConnectionProxyForTest(e,t){return new It(e,t)}getSession(e){return this.sessions.get(e)?.metadata||this.persistedSessions.get(e)}runningSessionCount(){return Array.from(this.sessions.values()).filter(e=>"running"===e.metadata.status).length}problemSessionCount(){return Array.from(this.sessions.values()).filter(e=>"failed"===e.metadata.status).length}readLogs(e,n=65536){const r=this.getSession(e);if(!r)throw Object.assign(new Error("App session not found."),{code:"APP_SESSION_NOT_FOUND"});const i=s.resolve(r.paths.logDir),o=(t.existsSync(i)?t.readdirSync(i,{withFileTypes:!0}):[]).filter(e=>e.isFile()&&e.name.endsWith(".log")).sort((e,t)=>e.name.localeCompare(t.name)).map(e=>{const r=s.resolve(i,e.name);if(!r.startsWith(`${i}${s.sep}`))throw Object.assign(new Error("Invalid log path."),{code:"APP_LOG_PATH_INVALID"});const o=t.statSync(r),a=Math.max(0,o.size-n),d=t.openSync(r,"r");try{const s=Buffer.alloc(o.size-a);return t.readSync(d,s,0,s.length,a),{name:e.name,size:o.size,updatedAt:o.mtime.toISOString(),truncated:a>0,content:s.toString("utf8")}}finally{t.closeSync(d)}});return{sessionId:e,logDir:i,maxBytes:n,files:o}}start(e="terminal-tty",n={}){const r=this.catalogRepository.find(e);if(!r)throw Object.assign(new Error("App not found."),{code:"APP_NOT_FOUND"});if("gui"===r.kind)return this.startGuiApp(r,n);if("web"===r.kind)return this.startWebApp(r,n);if("tty"!==r.kind)throw Object.assign(new Error("App kind is not implemented yet."),{code:"APP_NOT_IMPLEMENTED"});const i=Nt(),o=r.command||process.env.SHELL||"/bin/bash",a=n.cwd||r.cwd||process.env.TASK_HANDOFF_WORKSPACE||process.cwd(),d=this.normalizeLaunchOptions(n);let c=[...r.args||[],...d.args||[]],p={...process.env,...r.env,...d.env,TERM:"xterm-256color"};const u=s.join(this.paths.appSessionsDir,i),l=s.join(this.paths.logDir,"app-sessions",i);t.mkdirSync(u,{recursive:!0}),t.mkdirSync(l,{recursive:!0});const m="codex"!==r.id||Et("TASK_HANDOFF_CODEX_APP_SERVER_DISABLED")?void 0:this.acquireSharedCodexAppServer(o,a,p,i);let h,g,f,y=m?.endpoint;if(m){const e=this.allocatePort("web");h=new It(m.socketPath,e=>this.bindCodexThreadToAppSession(i,e)),h.start(e),g=e,y=h.endpoint||m.endpoint,c=[...r.args||[],"--remote",y,"--cd",a,...d.args||[]],p={...p,TASK_HANDOFF_APP_SESSION_ID:i,TASK_HANDOFF_CODEX_APP_SERVER_SOCKET:m.socketPath,TASK_HANDOFF_CODEX_APP_SERVER_URL:m.endpoint,TASK_HANDOFF_CODEX_APP_SERVER_PROXY_URL:y}}"claude"!==r.id||Et("TASK_HANDOFF_CLAUDE_BG_DISABLED")||(f=this.launchClaudeBackground(o,c,a,p),c=["attach",f.short],p={...p,TASK_HANDOFF_APP_SESSION_ID:i,TASK_HANDOFF_CLAUDE_SHORT:f.short,TASK_HANDOFF_CLAUDE_CONTROL_SOCK:f.controlSock});const v={id:i,appId:e,title:d.title||r.name,kind:"tty",status:"running",createdAt:Ot(),updatedAt:Ot(),launch:d,tty:{webPath:`/api/apps/sessions/${i}/tty`,shell:o,cwd:a,mode:f?"claude-attach":"pty"},process:{command:o},ai:f?{agent:"claude",claude:{short:f.short,controlSock:f.controlSock,cwd:a}}:m?{agent:"codex",appServer:{transport:"unix",endpoint:m.endpoint,socketPath:m.socketPath,proxyEndpoint:y,proxyPort:g,pid:m.child.pid,command:m.command,args:m.args,logPath:m.logPath,status:"running"}}:void 0,paths:{sessionDir:u,logDir:l}},S=t.createWriteStream(s.join(l,"tty.log"),{flags:"a"}),I={metadata:v,processes:[],codexAppServerProxy:h,ttyDimensions:{cols:120,rows:32},ttyLogStream:S,outputBacklog:"",clients:new Set};S.on("error",()=>{I.ttyLogClosed=!0}),S.on("close",()=>{I.ttyLogClosed=!0});const A=(e,t)=>{I.stopping||(v.status="exited",v.updatedAt=Ot(),v.process={...v.process,exitCode:e,signal:void 0===t?void 0:String(t)},this.persist(v),this.emit("updated",v)),"codex"===r.id&&(I.codexAppServerProxy?.stop(),this.releaseSharedCodexAppServer(i)),this.broadcast(I,{type:"exit",code:e,signal:t}),this.closeTtyLog(I)};let b;try{b=this.spawnTerminalPty(o,c,a,p)}catch(e){throw"codex"===r.id&&(h?.stop(),this.releaseSharedCodexAppServer(i)),f&&this.stopClaudeBackgroundLaunch(f.command,f.short,a,p),e}return v.process={...v.process,pid:b.pid},I.pty=b,b.onData(e=>{this.writeTtyLog(I,e),I.outputBacklog=`${I.outputBacklog}${e}`.slice(-65536),this.broadcast(I,{type:"output",data:e})}),b.onExit(({exitCode:e,signal:t})=>A(e,t)),this.sessions.set(i,I),this.persist(v),this.emit("created",v),v}launchClaudeBackground(e,t,s,n){const r=["--bg",...t],i=m.spawnSync(e,r,{cwd:s,env:n,encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:Number(process.env.TASK_HANDOFF_CLAUDE_BG_TIMEOUT_MS)||15e3}),o=`${i.stdout||""}\n${i.stderr||""}`;if(i.error)throw Object.assign(new Error(`Claude background launch failed: ${i.error.message}`),{code:"APP_LAUNCH_FAILED"});if(0!==i.status)throw Object.assign(new Error(`Claude background launch exited with code ${i.status}: ${o.trim()}`),{code:"APP_LAUNCH_FAILED"});const a=function(e){const t=e.match(/\b(?:short|id|worker|session)\D+([a-f0-9]{8})\b/i)?.[1];return t||e.match(/\b([a-f0-9]{8})\b/i)?.[1]}(o);if(!a)throw Object.assign(new Error("Claude background launch did not report a worker id."),{code:"APP_LAUNCH_FAILED"});return{short:a,controlSock:it(n),command:e,bgArgs:r}}stopClaudeBackgroundLaunch(e,t,s,n){try{m.spawnSync(e,["stop",t],{cwd:s,env:n,encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:Number(process.env.TASK_HANDOFF_CLAUDE_BG_TIMEOUT_MS)||15e3})}catch{}}startWebApp(e,n){const r=e.command||e.id;if(!this.hasCommand(r))throw Object.assign(new Error(`Missing required command: ${r}`),{code:"APP_DEPENDENCY_MISSING"});const i=Nt(),o=s.join(this.paths.appSessionsDir,i),a=s.join(this.paths.logDir,"app-sessions",i);t.mkdirSync(o,{recursive:!0}),t.mkdirSync(a,{recursive:!0});const d=this.normalizeLaunchOptions(n),c=d.cwd||e.cwd||process.env.TASK_HANDOFF_WORKSPACE||process.cwd(),p=this.allocatePort("web"),u={...process.env,...e.env,...d.env},l=this.webArgs(e,o,c,p,d.args||[]);this.prepareWebAppSession(e,o);const m=this.spawnLogged(r,l,u,a,`${e.id}.log`,c),h={id:i,appId:e.id,title:d.title||e.name,kind:"web",status:"running",createdAt:Ot(),updatedAt:Ot(),launch:d,web:{host:"127.0.0.1",port:p,webPath:`/api/apps/sessions/${i}/web/`,readyPath:e.web?.readyPath},process:{pid:m.pid,command:r},paths:{sessionDir:o,logDir:a}},g={metadata:h,processes:[m],outputBacklog:"",clients:new Set};return this.sessions.set(i,g),this.persist(h),this.watchLoggedProcess(g,m,e.id,!1),this.emit("created",h),h}startGuiApp(e,n){const r=e.command||e.id,i="kasmvnc"===process.env.TASK_HANDOFF_VNC_BACKEND?"kasmvnc":"novnc",o="kasmvnc"===i?["vncserver","vncpasswd","openssl","xrdb","xrandr","openbox",r]:["Xvfb","openbox","x11vnc","websockify",r];for(const e of o)if(!this.hasCommand(e))throw Object.assign(new Error(`Missing required command: ${e}`),{code:"APP_DEPENDENCY_MISSING"});const a=Nt(),d=s.join(this.paths.appSessionsDir,a),c=s.join(this.paths.logDir,"app-sessions",a);t.mkdirSync(d,{recursive:!0}),t.mkdirSync(c,{recursive:!0});const p=this.normalizeLaunchOptions(n),u=p.displayTarget||this.normalizeDisplayTarget(e.defaultDisplayTarget)||{mode:"isolated"};p.displayTarget=u;const l=p.cwd||e.cwd||process.env.TASK_HANDOFF_WORKSPACE||process.cwd(),m=this.allocatePort("cdp"),h=this.guiArgs(e,d,m,p.args||[]);if("shared"===u.mode){const t=this.ensureSharedDisplay(e,p,i,l),s=this.appEnvForDisplay(e,p,t),n=this.spawnLogged(r,h,s,c,`${e.id}.log`,l),o=e.automation?{type:e.automation.type,port:m,endpoint:`http://127.0.0.1:${m}${e.automation.endpointPath||""}`}:void 0,u={id:a,appId:e.id,title:p.title||e.name,kind:"gui",status:"running",createdAt:Ot(),updatedAt:Ot(),launch:p,display:{display:t.display,mode:"shared",displaySessionId:t.id,width:t.width,height:t.height,depth:t.depth,xPid:t.xPid,wmPid:t.wmPid,compositorPid:t.compositorPid,xauthority:t.xauthority},vnc:{backend:t.backend,host:"127.0.0.1",port:t.vncPort,websockifyPort:t.websockifyPort,webPath:"kasmvnc"===t.backend?`/api/apps/sessions/${a}/web/`:`/api/apps/sessions/${a}/vnc`,noVncPath:"kasmvnc"===t.backend?`/api/apps/sessions/${a}/web/`:`/api/apps/sessions/${a}/novnc/vnc.html`},web:"kasmvnc"===t.backend?{host:"127.0.0.1",port:t.vncPort,webPath:`/api/apps/sessions/${a}/web/`}:void 0,automation:o,process:{pid:n.pid,command:r},paths:{sessionDir:d,logDir:c}},g={metadata:u,processes:[n],outputBacklog:"",clients:new Set};return t.appSessionIds.add(a),this.sessions.set(a,g),this.persist(u),this.watchLoggedProcess(g,n,e.id,!1,()=>this.releaseSharedDisplaySession(t.id,a)),this.emit("created",u),u}const g=`:${this.allocateDisplay()}`,f="kasmvnc"===i?this.allocatePort("web"):this.allocatePort("vnc"),y="novnc"===i?this.allocatePort("websockify"):void 0,v=p.display?.width||e.display?.width||1440,S=p.display?.height||e.display?.height||900,I=p.display?.depth||e.display?.depth||24,A={...process.env,...e.env,...p.env,DISPLAY:g},b=_t(A),_=s.join(d,"home"),w="kasmvnc"===i?s.join(_,".Xauthority"):void 0,T="kasmvnc"===i?this.startKasmVncDisplay(g,v,S,I,f,A,d,c,b):this.startNoVncDisplay(g,v,S,I,f,y,A,c,l),N="kasmvnc"===i?this.guiScaleEnv({...A,HOME:Tt(),XAUTHORITY:w},b):A;try{this.waitForXDisplay(g)}catch(e){for(const e of T)e.killed||e.kill("SIGTERM");throw Object.assign(e instanceof Error?e:new Error(String(e)),{code:"APP_DISPLAY_START_FAILED"})}"kasmvnc"===i&&this.applyGuiScale(N,d,b);const O=this.spawnLogged("openbox",[],N,c,"openbox.log"),E=this.startCompositor(N,c,l),z=this.spawnLogged(r,h,N,c,`${e.id}.log`,l),x=e.automation?{type:e.automation.type,port:m,endpoint:`http://127.0.0.1:${m}${e.automation.endpointPath||""}`}:void 0,D={id:a,appId:e.id,title:p.title||e.name,kind:"gui",status:"running",createdAt:Ot(),updatedAt:Ot(),launch:p,display:{display:g,mode:"isolated",width:v,height:S,depth:I,xPid:T[0]?.pid,wmPid:O.pid,compositorPid:E?.pid,xauthority:w},vnc:{backend:i,host:"127.0.0.1",port:f,websockifyPort:y,webPath:"kasmvnc"===i?`/api/apps/sessions/${a}/web/`:`/api/apps/sessions/${a}/vnc`,noVncPath:"kasmvnc"===i?`/api/apps/sessions/${a}/web/`:`/api/apps/sessions/${a}/novnc/vnc.html`},web:"kasmvnc"===i?{host:"127.0.0.1",port:f,webPath:`/api/apps/sessions/${a}/web/`}:void 0,automation:x,process:{pid:z.pid,command:r},paths:{sessionDir:d,logDir:c}},k={metadata:D,processes:[z,...T,O,...E?[E]:[]],outputBacklog:"",clients:new Set};this.sessions.set(a,k),this.persist(D);for(const e of T)this.watchLoggedProcess(k,e,"kasmvnc"===i?"kasmvnc":"display",!0);return this.watchLoggedProcess(k,O,"openbox",!0),this.watchLoggedProcess(k,z,e.id,!1),this.emit("created",D),D}ensureSharedDisplay(e,n,r,i){const o="shared"===n.displayTarget?.mode?n.displayTarget:void 0,a=o?.id||"main",d=this.sharedDisplays.get(a);if(d)return d;if(!1===o?.autoCreate)throw Object.assign(new Error(`Shared display session not found: ${a}`),{code:"APP_DISPLAY_SESSION_NOT_FOUND"});const c=a.replace(/[^a-z0-9._-]/gi,"_"),p=s.join(this.paths.appSessionsDir,`display_${c}`),u=s.join(this.paths.logDir,"app-sessions",`display_${c}`);t.mkdirSync(p,{recursive:!0}),t.mkdirSync(u,{recursive:!0});const l=`:${this.allocateDisplay()}`,m="kasmvnc"===r?this.allocatePort("web"):this.allocatePort("vnc"),h="novnc"===r?this.allocatePort("websockify"):void 0,g=n.display?.width||e.display?.width||1440,f=n.display?.height||e.display?.height||900,y=n.display?.depth||e.display?.depth||24,v={...process.env,...e.env,...n.env,DISPLAY:l},S=_t(v),I=s.join(p,"home"),A="kasmvnc"===r?s.join(I,".Xauthority"):void 0,b="kasmvnc"===r?this.startKasmVncDisplay(l,g,f,y,m,v,p,u,S):this.startNoVncDisplay(l,g,f,y,m,h,v,u,i),_="kasmvnc"===r?this.guiScaleEnv({...v,HOME:Tt(),XAUTHORITY:A},S):v;try{this.waitForXDisplay(l)}catch(e){for(const e of b)e.killed||e.kill("SIGTERM");throw Object.assign(e instanceof Error?e:new Error(String(e)),{code:"APP_DISPLAY_START_FAILED"})}"kasmvnc"===r&&this.applyGuiScale(_,p,S);const w=this.spawnLogged("openbox",[],_,u,"openbox.log"),T=this.startCompositor(_,u,i),N={id:a,display:l,width:g,height:f,depth:y,backend:r,vncPort:m,websockifyPort:h,xPid:b[0]?.pid,wmPid:w.pid,compositorPid:T?.pid,xauthority:A,sessionDir:p,logDir:u,processes:[...b,w,...T?[T]:[]],appSessionIds:new Set};this.sharedDisplays.set(a,N);for(const e of[...b,w])this.watchSharedDisplayProcess(N,e);return N}appEnvForDisplay(e,t,s){const n={...process.env,...e.env,...t.env,DISPLAY:s.display},r=_t(n);return"kasmvnc"===s.backend?this.guiScaleEnv({...n,HOME:Tt(),XAUTHORITY:s.xauthority},r):n}releaseSharedDisplaySession(e,t){const s=this.sharedDisplays.get(e);s&&(s.appSessionIds.delete(t),s.appSessionIds.size>0||this.stopSharedDisplay(e))}stopSharedDisplay(e){const t=this.sharedDisplays.get(e);if(t){this.sharedDisplays.delete(e);for(const e of t.processes)e.killed||e.kill("SIGTERM")}}acquireSharedCodexAppServer(e,r,i,o){const a=this.sharedCodexAppServer;if(a&&null===a.child.exitCode&&!a.child.killed&&t.existsSync(a.socketPath))return a.appSessionIds.add(o),a;if(a&&!a.child.killed&&a.child.kill("SIGTERM"),"win32"===process.platform)throw Object.assign(new Error("Codex shared app-server uses unix sockets, which are unavailable on Windows."),{code:"CODEX_APP_SERVER_UNSUPPORTED"});const d=s.join(this.paths.runtimeDir,"codex-app-server"),c=s.join(this.paths.logDir,"app-sessions","codex-app-server"),p=function(e){const r=process.env.TASK_HANDOFF_CODEX_APP_SERVER_SOCKET_DIR?.trim(),i=r?t.realpathSync(r):"darwin"===process.platform?"/private/tmp":t.realpathSync(n.tmpdir()),o=h.createHash("sha256").update(e).digest("hex").slice(0,16);return s.join(i,`task-handoff-codex-${o}`,"app-server.sock")}(d),u=`unix://${p}`,l=process.env.TASK_HANDOFF_CODEX_APP_SERVER_COMMAND||e,m=["app-server","--listen",u];t.mkdirSync(d,{recursive:!0}),t.mkdirSync(c,{recursive:!0}),t.mkdirSync(s.dirname(p),{recursive:!0,mode:448}),t.rmSync(p,{force:!0});const g=this.spawnLogged(l,m,i,c,"codex-app-server.log",r),f={command:l,args:m,socketPath:p,endpoint:u,logPath:s.join(c,"codex-app-server.log"),child:g,appSessionIds:new Set([o])};let y;this.sharedCodexAppServer=f,g.once("error",e=>{y=e}),g.on("exit",(e,t)=>{if(this.sharedCodexAppServer?.child!==g)return;const s=0===e?"exited":"failed";for(const n of f.appSessionIds)this.updateCodexAppServerMetadata(n,s,e,t);this.sharedCodexAppServer=void 0});try{this.waitForUnixSocket(p,5e3,()=>y)}catch(e){throw g.killed||g.kill("SIGTERM"),this.sharedCodexAppServer=void 0,Object.assign(e instanceof Error?e:new Error(String(e)),{code:"CODEX_APP_SERVER_START_FAILED"})}return f}releaseSharedCodexAppServer(e){const s=this.sharedCodexAppServer;s&&(s.appSessionIds.delete(e),s.appSessionIds.size>0||(this.sharedCodexAppServer=void 0,s.child.killed||null!==s.child.exitCode||s.child.kill("SIGTERM"),t.rmSync(s.socketPath,{force:!0})))}stopSharedCodexAppServer(){const e=this.sharedCodexAppServer;e&&(this.sharedCodexAppServer=void 0,e.child.killed||null!==e.child.exitCode||e.child.kill("SIGTERM"),t.rmSync(e.socketPath,{force:!0}))}updateCodexAppServerMetadata(e,t,s,n){const r=this.sessions.get(e);r?.metadata.ai?.appServer&&(r.metadata.ai.appServer={...r.metadata.ai.appServer,status:t,exitCode:s,signal:n},r.metadata.updatedAt=Ot(),this.persist(r.metadata),this.emit("updated",r.metadata))}bindCodexThreadToAppSession(e,t){const s=this.sessions.get(e);if(!s?.metadata.ai||"codex"!==s.metadata.appId)return;const n=Array.isArray(s.metadata.ai.threadIds)?s.metadata.ai.threadIds:[];s.metadata.ai={...s.metadata.ai,activeThreadId:t,threadIds:n.includes(t)?n:[...n,t]},s.metadata.updatedAt=Ot(),this.persist(s.metadata),this.emit("updated",s.metadata)}watchSharedDisplayProcess(e,t){t.on("exit",(t,s)=>{if(this.sharedDisplays.has(e.id)&&0!==t&&0!==e.appSessionIds.size){this.sharedDisplays.delete(e.id);for(const n of e.appSessionIds){const r=this.sessions.get(n);r&&this.markFailed(r,"APP_DISPLAY_PROCESS_EXITED",`Shared display ${e.id} exited unexpectedly with code ${t??"null"} signal ${s??"null"}.`)}}})}startCompositor(e,t,s){if(this.hasCommand("picom"))return this.spawnLogged("picom",["--config","/dev/null","--backend","xrender"],e,t,"picom.log",s)}startNoVncDisplay(e,t,s,n,r,i,o,a,d){return[this.spawnLogged("Xvfb",[e,"-screen","0",`${t}x${s}x${n}`,"-nolisten","tcp"],o,a,"xvfb.log"),this.spawnLogged("x11vnc",["-display",e,"-localhost","-forever","-shared","-nopw","-xrandr","resize","-rfbport",String(r)],o,a,"x11vnc.log"),this.spawnLogged("websockify",[String(i),`127.0.0.1:${r}`],o,a,"websockify.log",d)]}waitForXDisplay(e,n=5e3){const r=e.replace(/^:/,"").split(".")[0],i=s.join("/tmp/.X11-unix",`X${r}`),o=Date.now();for(;Date.now()-o<n;){if(t.existsSync(i))return;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,50)}throw new Error(`Display ${e} did not become ready within ${n}ms.`)}startKasmVncDisplay(e,t,n,r,i,o,a,d,c){this.prepareKasmVncHome(a,t,n,r,i,c);const p={...o,HOME:s.join(a,"home")},u=this.writeKasmVncLauncher(a,e,t,n,r);return[this.spawnLogged("bash",[u],p,d,"kasmvnc.log")]}guiScaleEnv(e,t){return{...e,TASK_HANDOFF_GUI_SCALE:wt(t),XCURSOR_SIZE:"24"}}applyGuiScale(e,n,r){if(r<=1)return;const i=s.join(n,"home",".Xresources");if(t.existsSync(i))try{m.execFileSync("xrdb",["-merge",i],{env:e,stdio:"ignore"})}catch{}}writeKasmVncLauncher(e,n,r,i,o){const a=s.join(e,"kasmvnc-launcher.sh");return t.writeFileSync(a,["#!/usr/bin/env bash","set -euo pipefail",`display=${JSON.stringify(n)}`,`geometry=${JSON.stringify(`${r}x${i}`)}`,`depth=${JSON.stringify(String(o))}`,'tail_pid=""',"cleanup() {",' if [ -n "${tail_pid:-}" ]; then',' kill "$tail_pid" >/dev/null 2>&1 || true',' wait "$tail_pid" >/dev/null 2>&1 || true'," fi",' HOME="$HOME" vncserver -kill "$display" >/dev/null 2>&1 || true',"}","trap cleanup EXIT","trap 'cleanup; exit 0' TERM INT",'HOME="$HOME" vncserver "$display" -noxstartup -geometry "$geometry" -depth "$depth" -publicIP 127.0.0.1','log_file=$(ls -t "$HOME/.vnc"/*.log 2>/dev/null | head -n 1 || true)','if [ -z "$log_file" ]; then'," while true; do sleep 3600; done","fi",'tail -F "$log_file" &',"tail_pid=$!",'wait "$tail_pid"',""].join("\n"),{mode:493}),a}prepareKasmVncHome(e,n,r,i,o,a){const d=s.join(e,"home"),c=s.join(d,".vnc"),p=s.join(d,".config","gtk-3.0"),u=s.join(d,".config","fontconfig"),l=Math.round(96*a),h=1024*l,g=process.env.TASK_HANDOFF_KASMVNC_USERNAME||"agent",f=process.env.TASK_HANDOFF_KASMVNC_PASSWORD||"taskhandoff",y=s.join(c,"self.pem");t.mkdirSync(c,{recursive:!0}),t.mkdirSync(p,{recursive:!0}),t.mkdirSync(u,{recursive:!0}),m.execFileSync("openssl",["req","-x509","-nodes","-newkey","rsa:2048","-keyout",y,"-out",y,"-days","3650","-subj","/CN=localhost"],{stdio:"ignore"}),t.writeFileSync(s.join(d,".Xresources"),[`Xft.dpi: ${l}`,"Xft.antialias: 1","Xft.hinting: 1","Xft.hintstyle: hintslight","Xft.rgba: rgb","Xft.lcdfilter: lcddefault","Xcursor.size: 24","XTerm*faceName: Monospace","XTerm*faceSize: 11","XTerm*renderFont: true",""].join("\n")),t.writeFileSync(s.join(p,"settings.ini"),["[Settings]",`gtk-xft-dpi=${h}`,"gtk-xft-antialias=1","gtk-xft-hinting=1","gtk-xft-hintstyle=hintslight","gtk-xft-rgba=rgb","gtk-cursor-theme-size=24",""].join("\n")),t.writeFileSync(s.join(d,".gtkrc-2.0"),[`gtk-xft-dpi = ${h}`,"gtk-xft-antialias = 1","gtk-xft-hinting = 1",'gtk-xft-hintstyle = "hintslight"','gtk-xft-rgba = "rgb"',"gtk-cursor-theme-size = 24",""].join("\n")),t.writeFileSync(s.join(u,"fonts.conf"),['<?xml version="1.0"?>','<!DOCTYPE fontconfig SYSTEM "urn:fontconfig:fonts.dtd">',"<fontconfig>",' <match target="font">',' <edit name="antialias" mode="assign"><bool>true</bool></edit>',' <edit name="hinting" mode="assign"><bool>true</bool></edit>',' <edit name="hintstyle" mode="assign"><const>hintslight</const></edit>',' <edit name="rgba" mode="assign"><const>rgb</const></edit>',' <edit name="lcdfilter" mode="assign"><const>lcddefault</const></edit>'," </match>","</fontconfig>",""].join("\n")),t.writeFileSync(s.join(c,"kasmvnc.yaml"),["desktop:"," resolution:",` width: ${n}`,` height: ${r}`," allow_resize: true",` pixel_depth: ${i}`,"network:"," protocol: http"," interface: 127.0.0.1",` websocket_port: ${o}`," use_ipv4: true"," use_ipv6: false"," ssl:",` pem_certificate: ${y}`,` pem_key: ${y}`," require_ssl: false","user_session:"," session_type: shared"," concurrent_connections_prompt: false"," idle_timeout: never","command_line:"," prompt: false",""].join("\n")),m.execFileSync("vncpasswd",["-u",g,"-w","-r"],{env:{...process.env,HOME:d},input:`${f}\n${f}\n`,stdio:["pipe","ignore","pipe"]})}stop(e){const t=this.sessions.get(e);if(!t){const t=this.persistedSessions.get(e);if(t)return t;throw Object.assign(new Error("App session not found."),{code:"APP_SESSION_NOT_FOUND"})}t.metadata.status="stopping",t.metadata.updatedAt=Ot(),t.stopping=!0,this.persist(t.metadata),this.stopClaudeDaemonForSession(t.metadata),t.pty?.kill("SIGTERM"),this.closeTtyLog(t);for(const e of t.clients)e.send(JSON.stringify({type:"exit",code:null,signal:"SIGTERM"})),e.close?.();t.clients.clear();for(const e of t.processes)e.killed||e.kill("SIGTERM");return t.codexAppServerProxy?.stop(),"codex"===t.metadata.appId&&this.releaseSharedCodexAppServer(e),"shared"===t.metadata.display?.mode&&t.metadata.display.displaySessionId&&this.releaseSharedDisplaySession(t.metadata.display.displaySessionId,e),t.metadata.status="stopped",t.metadata.updatedAt=Ot(),this.persist(t.metadata),this.sessions.delete(e),this.emit("updated",t.metadata),t.metadata}stopClaudeDaemonForSession(e){const t=e.ai?.claude?.short;t&&dt(t,"SIGTERM",{sockPath:e.ai?.claude?.controlSock,timeoutMs:Number(process.env.TASK_HANDOFF_CLAUDE_CONTROL_TIMEOUT_MS)||5e3})}restart(e){const t=this.getSession(e);if(!t)throw Object.assign(new Error("App session not found."),{code:"APP_SESSION_NOT_FOUND"});const{appId:s,title:n}=t,r={...t.launch,title:n};return this.sessions.has(e)&&this.stop(e),this.start(s,r)}rename(e,t){const s=this.getSession(e);if(!s)throw Object.assign(new Error("App session not found."),{code:"APP_SESSION_NOT_FOUND"});const n="string"==typeof t?t.trim():"";if(!n||n.length>120)throw Object.assign(new Error("App session title must contain between 1 and 120 characters."),{code:"APP_SESSION_TITLE_INVALID"});return s.title=n,s.launch={...s.launch,title:n},s.updatedAt=Ot(),this.persist(s),this.emit("updated",s),s}async delete(e){const t=this.getSession(e);if(!t)throw Object.assign(new Error("App session not found."),{code:"APP_SESSION_NOT_FOUND"});const s=this.sessions.get(e);if(s){const t=[...s.processes],n=t.map(e=>this.waitForProcessClose(e,5e3));this.stop(e);const r=await Promise.all(n);let i=t.filter((e,t)=>!r[t]);if(i.length>0){const e=i.map(e=>this.waitForProcessClose(e,1e3));for(const e of i)null===e.exitCode&&null===e.signalCode&&e.kill("SIGKILL");const t=await Promise.all(e);i=i.filter((e,s)=>!t[s])}if(i.length>0)throw Object.assign(new Error(`App session processes did not exit: ${i.map(e=>e.pid??"unknown").join(", ")}.`),{code:"APP_PROCESS_STOP_TIMEOUT"})}return this.sessions.delete(e),this.persistedSessions.delete(e),this.removeSessionFiles(t),this.emit("deleted",t),t}cleanupExpiredSessions(e=new Date){const t=this.sessionRetentionMs();if(!t)return[];const s=e.getTime()-t,n=[];for(const e of this.persistedSessions.values()){if(this.sessions.has(e.id)||!zt.has(e.status))continue;const t=Date.parse(e.updatedAt||e.createdAt);!Number.isFinite(t)||t>s||(this.persistedSessions.delete(e.id),this.removeSessionFiles(e),n.push(e))}return n}screenshot(e){const t=this.sessions.get(e);if(!t)throw Object.assign(new Error("App session not found."),{code:"APP_SESSION_NOT_FOUND"});if(!t.metadata.display)throw Object.assign(new Error("Screenshots are only available for GUI sessions."),{code:"APP_SCREENSHOT_UNAVAILABLE"});if(!this.hasCommand("import"))throw Object.assign(new Error("Missing required command: import. Install ImageMagick in the runtime image."),{code:"APP_DEPENDENCY_MISSING"});try{const e=t.metadata.display.xauthority;return m.execFileSync("import",["-window","root","png:-"],{env:{...process.env,DISPLAY:t.metadata.display.display,...e?{XAUTHORITY:e,HOME:s.dirname(e)}:{}},maxBuffer:20971520})}catch(e){throw Object.assign(new Error(`Screenshot failed: ${e instanceof Error?e.message:String(e)}`),{code:"APP_SCREENSHOT_FAILED"})}}resizeDisplay(e,t){const s=this.sessions.get(e),n=s?.metadata;if(!s||!n?.display)throw Object.assign(new Error("Display session not found."),{code:"APP_DISPLAY_NOT_FOUND"});const r=this.normalizeDisplayOptions(t),i=r.width||n.display.width,o=r.height||n.display.height,a=r.depth||n.display.depth,d=this.displayCommandEnv(n);try{this.resizeDisplayWithXrandr(d,i,o)}catch(e){throw Object.assign(new Error(`Display resize failed: ${e instanceof Error?e.message:String(e)}`),{code:"APP_DISPLAY_RESIZE_FAILED"})}return n.display={...n.display,width:i,height:o,depth:a},this.persist(n),this.emit("updated",n),n}async automationStatus(e){const t=this.sessions.get(e),s=t?.metadata||this.persistedSessions.get(e);if(!s)throw Object.assign(new Error("App session not found."),{code:"APP_SESSION_NOT_FOUND"});if(!s.automation)throw Object.assign(new Error("Automation is not configured for this app session."),{code:"APP_AUTOMATION_UNAVAILABLE"});const n={sessionId:e,type:s.automation.type,endpoint:s.automation.endpoint,port:s.automation.port,ready:!1};if(!t||"running"!==s.status)return{...n,error:{code:"APP_AUTOMATION_NOT_RUNNING",message:"Automation endpoint is only available while the app session is running."}};try{const e=await this.fetchCdpVersion(s.automation.endpoint);return{...n,ready:!0,browser:"string"==typeof e.Browser?e.Browser:void 0,protocolVersion:"string"==typeof e["Protocol-Version"]?e["Protocol-Version"]:void 0,webSocketDebuggerUrl:"string"==typeof e.webSocketDebuggerUrl?e.webSocketDebuggerUrl:void 0}}catch(e){return{...n,error:{code:"APP_AUTOMATION_NOT_READY",message:e instanceof Error?e.message:String(e)}}}}stopAll(){for(const e of this.sessions.values()){e.stopping=!0,e.metadata.status="stopped",e.metadata.updatedAt=Ot(),this.persist(e.metadata),this.stopClaudeDaemonForSession(e.metadata),e.pty?.kill("SIGTERM"),this.closeTtyLog(e);for(const t of e.processes)t.kill("SIGTERM")}for(const e of Array.from(this.sharedDisplays.keys()))this.stopSharedDisplay(e);this.stopSharedCodexAppServer(),this.sessions.clear()}vncTarget(e){const t=this.sessions.get(e);if(t?.metadata.vnc)return{host:t.metadata.vnc.host,port:t.metadata.vnc.port}}webTarget(e){const t=this.sessions.get(e);if(t?.metadata.web&&"running"===t.metadata.status)return{host:t.metadata.web.host,port:t.metadata.web.port}}attachTty(e,t){const s=this.sessions.get(e);if(!s||"running"!==s.metadata.status)return t.send(JSON.stringify({type:"error",message:"TTY session not found."})),void t.close?.();s.clients.add(t),t.send(JSON.stringify({type:"connected",session:s.metadata,dimensions:s.ttyDimensions})),s.outputBacklog&&t.send(JSON.stringify({type:"output",data:s.outputBacklog})),t.on("message",e=>{const n=Buffer.isBuffer(e)?e.toString("utf8"):String(e||"");try{const e=JSON.parse(n);if("input"===e.type&&"string"==typeof e.data)s.pty?.write(e.data);else if("resize"===e.type&&Number.isInteger(e.cols)&&Number.isInteger(e.rows)){const n=e.cols,r=e.rows;s.ttyDimensions={cols:n,rows:r},s.pty?.resize(n,r);for(const e of s.clients)e!==t&&e.send(JSON.stringify({type:"resize",cols:n,rows:r}))}}catch{s.pty?.write(n)}}),t.on("close",()=>{s.clients.delete(t)})}broadcast(e,t){const s=JSON.stringify(t);for(const t of e.clients)t.send(s)}writeTtyLog(e,t){const s=e.ttyLogStream;!s||e.ttyLogClosed||s.destroyed||s.closed||s.writableEnded||s.write(t,t=>{t&&(e.ttyLogClosed=!0)})}closeTtyLog(e){const t=e.ttyLogStream;!t||e.ttyLogClosed||t.destroyed||t.closed||t.writableEnded?e.ttyLogClosed=!0:(e.ttyLogClosed=!0,t.end())}persist(e){this.persistedSessions.set(e.id,e),this.persistSessionMetadata&&(t.mkdirSync(e.paths.sessionDir,{recursive:!0}),r.sync(s.join(e.paths.sessionDir,"metadata.json"),`${JSON.stringify(e,null,2)}\n`,{mode:384}))}removeSessionFiles(e){t.rmSync(e.paths.sessionDir,{recursive:!0,force:!0}),t.rmSync(e.paths.logDir,{recursive:!0,force:!0})}sessionRetentionMs(){const e=process.env.TASK_HANDOFF_APP_SESSION_RETENTION_DAYS;if(!e)return;const t=Number(e);return!Number.isFinite(t)||t<=0?void 0:24*t*60*60*1e3}loadPersistedSessions(){if(t.existsSync(this.paths.appSessionsDir))for(const e of t.readdirSync(this.paths.appSessionsDir,{withFileTypes:!0})){if(!e.isDirectory())continue;const n=s.join(this.paths.appSessionsDir,e.name,"metadata.json");if(t.existsSync(n))try{const s=JSON.parse(t.readFileSync(n,"utf8"));if(!s.id||!s.paths?.sessionDir||s.id!==e.name)continue;const r=this.recoverPersistedSession(s);this.persistedSessions.set(r.id,r),r!==s&&this.persist(r)}catch{continue}}}recoverPersistedSession(e){return"running"!==e.status&&"stopping"!==e.status?e:{...e,status:"exited",updatedAt:Ot(),error:e.error||{code:"APP_SESSION_RESTORED_WITHOUT_PROCESS",message:"Runtime restarted; previous app processes are not attached. Use restart to launch a new session."},process:{...e.process,exitCode:e.process?.exitCode??null,signal:e.process?.signal??null}}}allocateDisplay(){const e=new Set([...Array.from(this.sessions.values()).map(e=>e.metadata.display?.display),...Array.from(this.sharedDisplays.values()).map(e=>e.display)].filter(e=>Boolean(e)).map(e=>Number(e.replace(/^:/,""))).filter(e=>Number.isInteger(e))),s=this.findAvailableNumber(this.nextDisplay,101,199,s=>!e.has(s)&&!t.existsSync(`/tmp/.X${s}-lock`)&&!t.existsSync(`/tmp/.X11-unix/X${s}`));return this.nextDisplay=this.nextNumber(s,101,199),s}allocatePort(e){const t="vnc"===e?{start:6101,end:6199,next:this.nextVncPort}:"websockify"===e?{start:7101,end:7199,next:this.nextWebsockifyPort}:"web"===e?{start:8101,end:8199,next:this.nextWebPort}:{start:9201,end:9299,next:this.nextCdpPort},s=new Set([...Array.from(this.sessions.values()).flatMap(e=>[e.metadata.vnc?.port,e.metadata.vnc?.websockifyPort,e.metadata.web?.port,e.metadata.automation?.port,e.metadata.ai?.appServer?.proxyPort]),...Array.from(this.sharedDisplays.values()).flatMap(e=>[e.vncPort,e.websockifyPort,"kasmvnc"===e.backend?e.vncPort:void 0])].filter(e=>Number.isInteger(e))),n=this.findAvailableNumber(t.next,t.start,t.end,e=>!s.has(e)&&this.isPortAvailable(e)),r=this.nextNumber(n,t.start,t.end);return"vnc"===e?this.nextVncPort=r:"websockify"===e?this.nextWebsockifyPort=r:"web"===e?this.nextWebPort=r:this.nextCdpPort=r,n}findAvailableNumber(e,t,s,n){const r=s-t+1;for(let s=0;s<r;s+=1){const i=t+(Math.max(e,t)-t+s)%r;if(n(i))return i}throw Object.assign(new Error(`No available allocation in range ${t}-${s}.`),{code:"APP_RESOURCE_EXHAUSTED"})}nextNumber(e,t,s){return e>=s?t:e+1}isPortAvailable(e){const t=["const net=require('node:net');","const server=net.createServer();","server.once('error',()=>process.exit(1));","server.listen(Number(process.argv[1]),'127.0.0.1',()=>server.close(()=>process.exit(0)));"].join("");return 0===m.spawnSync(process.execPath,["-e",t,String(e)],{stdio:"ignore"}).status}waitForUnixSocket(e,s,n){const r=Date.now();for(;Date.now()-r<s;){const s=n?.();if(s)throw s;if(t.existsSync(e)&&this.canConnectUnixSocket(e))return;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,50)}throw new Error(`${e} did not become ready within ${s}ms.`)}canConnectUnixSocket(e){const t=["const net=require('node:net');","const socket=net.createConnection(process.argv[1]);","const done=(code)=>{socket.destroy();process.exit(code);};","socket.once('connect',()=>done(0));","socket.once('error',()=>done(1));","setTimeout(()=>done(1),250);"].join("");return 0===m.spawnSync(process.execPath,["-e",t,e],{stdio:"ignore"}).status}markFailed(e,t,s){e.stopping||"stopped"===e.metadata.status||"failed"===e.metadata.status||(e.metadata.status="failed",e.metadata.updatedAt=Ot(),e.metadata.error={code:t,message:s},this.persist(e.metadata),this.emit("updated",e.metadata))}waitForProcessClose(e,t){return null!==e.exitCode||null!==e.signalCode?Promise.resolve(!0):new Promise(s=>{let n=!1;const r=t=>{n||(n=!0,clearTimeout(a),e.off("close",i),e.off("error",o),s(t))},i=()=>r(!0),o=()=>r(!0),a=setTimeout(()=>r(!1),t);e.once("close",i),e.once("error",o)})}watchLoggedProcess(e,t,s,n,r){t.on("error",t=>{this.markFailed(e,"APP_PROCESS_ERROR",`${s} failed: ${t.message}`)}),t.on("exit",(t,i)=>{if(e.stopping)r?.();else{if(n&&0!==t)return this.markFailed(e,"APP_PROCESS_EXITED",`${s} exited unexpectedly with code ${t??"null"} signal ${i??"null"}.`),void r?.();n||(e.metadata.status=0===t?"exited":"failed",e.metadata.updatedAt=Ot(),e.metadata.process={...e.metadata.process,exitCode:t,signal:i},0!==t&&(e.metadata.error={code:"APP_PROCESS_EXITED",message:`${s} exited with code ${t??"null"} signal ${i??"null"}.`}),this.persist(e.metadata),this.emit("updated",e.metadata)),r?.()}})}guiArgs(e,t,n,r){const i=[...e.args||[],...r].map(e=>e.replaceAll("{sessionDir}",t).replaceAll("{cdpPort}",String(n)));if("chromium"===e.id){const r=Et("TASK_HANDOFF_CHROMIUM_NO_SANDBOX")?["--no-sandbox"]:[],o=function(e){const t=process.env.TASK_HANDOFF_CHROMIUM_USER_DATA_DIR?.trim();return t||s.join(e,"profile")}(t);return[...r,"--disable-dev-shm-usage","--no-first-run",...this.chromiumExtensionArgs(),"--remote-debugging-address=127.0.0.1",...o?[`--user-data-dir=${o}`]:[],...e.automation?.portArg?[e.automation.portArg.replaceAll("{port}",String(n))]:[`--remote-debugging-port=${n}`],...i]}return e.automation?.portArg&&i.unshift(e.automation.portArg.replaceAll("{port}",String(n))),this.isXtermApp(e)?["-fa",process.env.TASK_HANDOFF_XTERM_FONT_FAMILY||"Monospace","-fs",process.env.TASK_HANDOFF_XTERM_FONT_SIZE||"11",...i]:i}chromiumExtensionArgs(){const e=this.chromiumExtensionDirs();return e.length>0?[`--load-extension=${e.join(",")}`]:[]}chromiumExtensionDirs(){const e=process.env.TASK_HANDOFF_CHROMIUM_EXTENSION_DIRS;if(e)return e.split(/[,;]/).map(e=>e.trim()).filter(e=>this.isChromiumExtensionDir(e));const n=process.env.TASK_HANDOFF_CHROMIUM_EXTENSION_DIR||"/opt/task-handoff/chromium-extensions";return t.existsSync(n)?t.readdirSync(n,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>s.join(n,e.name)).filter(e=>this.isChromiumExtensionDir(e)).sort():[]}isChromiumExtensionDir(e){return t.existsSync(s.join(e,"manifest.json"))}isXtermApp(e){const t=s.basename(e.command||e.id);return"terminal-gui"===e.id||"xterm"===t}webArgs(e,t,s,n,r){const i=e=>e.replaceAll("{sessionDir}",t).replaceAll("{cwd}",s).replaceAll("{port}",String(n)),o=[...e.args||[],...r].map(i);return e.web?.portArg&&o.unshift(i(e.web.portArg)),o}prepareWebAppSession(e,n){if("vscode-web"!==e.id)return;const i=s.join(n,"user-data","User"),o=s.join(i,"settings.json");let a={};if(t.mkdirSync(i,{recursive:!0}),t.existsSync(o))try{const e=JSON.parse(t.readFileSync(o,"utf8"));e&&"object"==typeof e&&!Array.isArray(e)&&(a=e)}catch{a={}}r.sync(o,`${JSON.stringify({...xt,...a},null,2)}\n`,{mode:384})}async fetchCdpVersion(e){const t=new URL(e);t.pathname=s.posix.join(t.pathname,"json","version");const n=new AbortController,r=setTimeout(()=>n.abort(),1e3);try{const e=await fetch(t,{signal:n.signal});if(!e.ok)throw new Error(`CDP version endpoint returned HTTP ${e.status}.`);return await e.json()}finally{clearTimeout(r)}}normalizeLaunchOptions(e={}){const t={};"string"==typeof e.title&&e.title.trim()&&(t.title=e.title.trim()),Array.isArray(e.args)&&(t.args=e.args.filter(e=>"string"==typeof e)),"string"==typeof e.cwd&&e.cwd.trim()&&(t.cwd=e.cwd.trim()),e.env&&"object"==typeof e.env&&!Array.isArray(e.env)&&(t.env=Object.fromEntries(Object.entries(e.env).filter(e=>"string"==typeof e[0]&&"string"==typeof e[1]&&e[0].trim().length>0).map(([e,t])=>[e.trim(),t])));const s=this.normalizeDisplayOptions(e.display||{});Object.keys(s).length>0&&(t.display=s);const n=this.normalizeDisplayTarget(e.displayTarget);return n&&(t.displayTarget=n),t}normalizeDisplayTarget(e){if(e&&"object"==typeof e){if("isolated"===e.mode)return{mode:"isolated"};if("shared"===e.mode)return{mode:"shared",id:"string"==typeof e.id&&e.id.trim()?e.id.trim():"main",autoCreate:!1!==e.autoCreate}}}normalizeDisplayOptions(e){const t=Number(e.width),s=Number(e.height),n=Number(e.depth),r={};return Number.isInteger(t)&&t>=320&&t<=7680&&(r.width=t),Number.isInteger(s)&&s>=240&&s<=4320&&(r.height=s),Number.isInteger(n)&&n>=8&&n<=32&&(r.depth=n),r}displayCommandEnv(e){const t=e.paths?.sessionDir,n=e.display?.xauthority?s.dirname(e.display.xauthority):t?s.join(t,"home"):void 0;return{...process.env,DISPLAY:e.display?.display,...n?{HOME:n,XAUTHORITY:e.display?.xauthority||s.join(n,".Xauthority")}:{}}}resizeDisplayWithXrandr(e,t,s){const n=`${t}x${s}`,r=this.connectedDisplayOutput(e),i=r?[["--output",r,"--mode",n],["--fb",n]]:[["--fb",n]];let o;for(const t of i)try{return void m.execFileSync("xrandr",t,{env:e,stdio:"ignore"})}catch(e){o=e}throw o instanceof Error?o:new Error(String(o))}connectedDisplayOutput(e){try{const t=m.execFileSync("xrandr",["--query"],{env:e,encoding:"utf8"});return t.match(/^(\S+)\s+connected\b/m)?.[1]}catch{return}}hasCommand(e){return 0===m.spawnSync("sh",["-lc",`command -v ${JSON.stringify(e)}`],{stdio:"ignore"}).status}spawnTerminalPty(e,n,r,i){try{return function(){if("darwin"===process.platform||"linux"===process.platform)try{const e=s.resolve(s.dirname(require.resolve("node-pty")),".."),n=s.join(e,"prebuilds",`${process.platform}-${process.arch}`,"spawn-helper"),r=t.statSync(n);73&r.mode||t.chmodSync(n,493|r.mode)}catch{}}(),f.spawn(e,n,{name:"xterm-256color",cols:120,rows:32,cwd:r,env:i})}catch(e){throw Object.assign(new Error(`PTY unavailable: ${e instanceof Error?e.message:String(e)}`),{code:"PTY_UNAVAILABLE"})}}spawnLogged(e,n,r,i,o,a){const d=t.createWriteStream(s.join(i,o),{flags:"a"}),c=m.spawn(e,n,{cwd:a,env:r,stdio:["ignore","pipe","pipe"]});return c.stdout.pipe(d),c.stderr.pipe(d),c}}const kt={"image/bmp":".bmp","image/gif":".gif","image/jpeg":".jpg","image/png":".png","image/webp":".webp"};function Ct(e=[]){if(!e.length)return[];const r=function(){const e=process.env.TASK_HANDOFF_AI_SESSION_ATTACHMENT_DIR?.trim();return e?s.resolve(e):s.join(n.tmpdir(),"task-handoff-ai-session-attachments")}();return t.mkdirSync(r,{recursive:!0}),function(e){const n=Date.now()-function(){const e=Number(process.env.TASK_HANDOFF_AI_SESSION_ATTACHMENT_RETENTION_MS);return Number.isFinite(e)&&e>0?e:864e5}();try{for(const r of t.readdirSync(e,{withFileTypes:!0})){if(!r.isFile())continue;const i=s.join(e,r.name);try{t.statSync(i).mtimeMs<n&&t.unlinkSync(i)}catch{}}}catch{}}(r),e.map(e=>{const n=kt[e.mime.toLowerCase()]||s.extname(e.name)||".img",i=`${e.id}-${(o=e.name,s.basename(o).replace(/[^\w.\- ()\u4e00-\u9fff]/g,"_").slice(0,160)||"image").replace(/\.[^.]+$/,"")}${n}`;var o;const a=s.join(r,i);return t.writeFileSync(a,Buffer.from(e.data,"base64")),{...e,path:a}})}async function Pt(e,t=[],s){const n=Ct(t);if(!n.length)return s(e);const r=n.map((e,t)=>`图片${n.length>1?t+1:""}路径:${e.path}`);return s([e.trim(),r.join("\n")].filter(Boolean).join("\n\n"))}class Ft{approvals=new Map;register(e){return this.approvals.set(e.id,e),e}latestForSession(e){return[...this.approvals.values()].filter(t=>t.sessionId===e).at(-1)}async resolveForSession(e,t){const s=this.latestForSession(e);if(s)return await s.resolve(t),this.approvals.delete(s.id),s}remove(e){return this.approvals.delete(e)}clearSession(e){for(const t of this.approvals.values())t.sessionId===e&&this.approvals.delete(t.id)}}class Rt{registry;providers=new Map;constructor(e){this.registry=e}register(e){this.providers.set(e.agent,e)}async sendMessage(e,t){const s=this.requireSession(e),n=t.message.trim();if(!n)throw jt("AI_SESSION_MESSAGE_EMPTY","Message is required.");const r=t.mode||"auto";if("queue"===r||"auto"===r&&Mt(s)){const e=this.registry.enqueueMessage(s.id,n,t.attachments||[]);if(!e)throw jt("AI_SESSION_NOT_FOUND","AI session not found.",404);return{session:e.session,provider:s.agent,action:"queue",queueId:e.item.id}}if("steer"===r)return this.steerMessage(s.id,{message:n,attachments:t.attachments||[]});if(Mt(s))throw jt("AI_SESSION_BUSY","AI session is busy. Queue the message or steer it into the running turn.",409);return this.startMessage(s.id,{message:n,attachments:t.attachments||[]})}async startMessage(e,t){const s=this.requireSession(e);if(Mt(s))throw jt("AI_SESSION_BUSY","AI session is busy. Queue the message or steer it into the running turn.",409);const n=this.requireProvider(s),r=n.startMessage||n.sendMessage;if(!r)throw jt("AI_SESSION_SEND_UNSUPPORTED",`${s.agent} sessions do not support starting turns.`,400);return r.call(n,s,t)}async steerMessage(e,t){const s=this.requireSession(e);if(!Mt(s))throw jt("AI_SESSION_NOT_ACTIVE","AI session is not active.",409);const n=this.requireProvider(s),r=n.steerMessage||n.sendMessage;if(!r)throw jt("AI_SESSION_STEER_UNSUPPORTED",`${s.agent} sessions do not support turn steering.`,400);const i="string"==typeof t?{message:t}:t;return r.call(n,s,i)}async sendNextQueuedMessage(e){const t=this.requireSession(e);if(Mt(t))return;const s=this.registry.nextQueuedMessage(t.id);if(s){this.registry.markQueuedMessageSending(t.id,s.id);try{const e=await this.startMessage(t.id,{message:s.message,attachments:this.registry.queuedMessageAttachments(s.id)}),n=this.registry.removeQueuedMessage(t.id,s.id);return{...e,session:n||e.session,queueId:s.id}}catch(e){throw this.registry.markQueuedMessageFailed(t.id,s.id,e),e}}}async steerQueuedMessage(e,t){const s=this.requireSession(e),n=s.queue.items.find(e=>e.id===t);if(!n)throw jt("AI_SESSION_QUEUE_ITEM_NOT_FOUND","Queued message not found.",404);const r=await this.steerMessage(s.id,{message:n.message,attachments:this.registry.queuedMessageAttachments(n.id)}),i=this.registry.removeQueuedMessage(s.id,n.id);return{...r,session:i||r.session,action:"steer",queueId:n.id}}retryQueuedMessage(e,t){const s=this.registry.retryQueuedMessage(e,t);if(!s)throw jt("AI_SESSION_QUEUE_ITEM_NOT_FOUND","Queued message not found.",404);return s}removeQueuedMessage(e,t){const s=this.registry.removeQueuedMessage(e,t);if(!s)throw jt("AI_SESSION_NOT_FOUND","AI session not found.",404);return s}reorderQueuedMessages(e,t){const s=this.registry.reorderQueuedMessages(e,t);if(!s)throw jt("AI_SESSION_NOT_FOUND","AI session not found.",404);return s}async interrupt(e){const t=this.requireSession(e);if("running"!==t.status&&"waiting"!==t.status)throw jt("AI_SESSION_NOT_ACTIVE","AI session is not active.",400);return this.requireProvider(t).interrupt(t)}async resolveApproval(e,t){const s=this.requireSession(e),n=this.requireProvider(s);if(n.resolveApproval)return n.resolveApproval(s,t);throw jt("AI_SESSION_APPROVAL_UNSUPPORTED",`${s.agent} sessions do not expose structured approval control.`,400)}requireSession(e){const t=this.registry.get(e);if(!t)throw jt("AI_SESSION_NOT_FOUND","AI session not found.",404);return t}requireProvider(e){const t=this.providers.get(e.agent);if(!t)throw jt("AI_SESSION_CONTROL_UNSUPPORTED",`${e.agent} sessions do not support direct control yet.`,400);return t}}function Mt(e){return"running"===e.status||"waiting"===e.status}function jt(e,t,s=400){const n=new Error(t);return n.code=e,n.statusCode=s,n}function Ht(e){const t=Xt(e);return/^\[(?:request interrupted by user|user interrupted request)\]$/i.test(t)}function Lt(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}function $t(e){if(e.timestamp)return e;const{timestamp:t,...s}=e;return s}function Ut(e){return Array.isArray(e)?e:[]}function qt(e){return"tool_use"===e.type}function Kt(e){return"tool_result"===e.type}function Bt(e){return"text"===e.type}function Vt(e){return"text"!==e.type&&"output_text"!==e.type&&"input_text"!==e.type||"string"!=typeof e.text?"":e.text}function Gt(e){if("string"==typeof e)return Xt(e);const t=Ut(e).map(Vt).filter(Boolean).join("\n");return t?Xt(t):""}function Wt(e,t=180){const s=String(e??"").replace(/\s+/g," ").trim();return s.length>t?`${s.slice(0,t-3)}...`:s}function Xt(e){return String(e??"").trim()}function Jt(e){try{const t=Lt(JSON.parse(String(e||"{}")));return Wt(t.cmd||t.command||t.path||t.ref_id||t.pattern||"")}catch{return""}}function Yt(e){if(e&&"object"==typeof e&&!Array.isArray(e)){const t=e;return Wt(t.command||t.cmd||t.file_path||t.filePath||t.path||t.ref_id||t.pattern||t.description||"")}return Jt(e)}function Qt(e){return/\b(task-handoff|result-ipc)(\.js)?\b/.test(e)}function Zt(e){return["edit","multiedit","write","notebookedit"].includes(e.toLowerCase())}function es(e,r,i=s.join(n.homedir(),".claude")){const o=Wt(e,200);if(!o)return;const a=s.join(i,"projects"),d=Wt(r);if(d){const e=s.join(a,function(e){return s.resolve(e).split(s.sep).join("-")}(d),`${o}.jsonl`);if(t.existsSync(e))return e}const c=[a];for(;c.length>0;){const e=c.pop();if(!e)continue;let n;try{n=t.readdirSync(e,{withFileTypes:!0})}catch{continue}for(const t of n){const n=s.join(e,t.name);if(t.isDirectory())c.push(n);else if(t.isFile()&&t.name.endsWith(".jsonl")&&t.name.includes(o))return n}}}function ts(e,t){let n;try{n=JSON.parse(e)}catch{return}const r=Lt(n),i=Lt(r.payload),o="string"==typeof Lt(n).timestamp?Lt(n).timestamp:void 0;if("turn_context"===r.type)return;if("event_msg"===r.type)return"agent_message"===i.type?$t({text:Xt(i.message),kind:"assistant",timestamp:o}):void 0;if("assistant"===r.type){const e=Ut(r.message?.content);let s,n;for(const r of e){if(qt(r)){const e=Wt(r.name||"tool",80),n=Yt(r.input),i=Qt(n),a=Zt(e)?"edit":void 0;if(r.id&&t.calls.set(r.id,{tool:e,command:n,ignored:i,action:a}),i)continue;s??=$t({key:r.id,text:"edit"===a?`Editing ${n||"files"}`:n?`Running ${e}: ${n}`:`Running ${e}`,kind:"tool",timestamp:o});continue}Bt(r)&&r.text&&(n??=Xt(r.text))}return s||(n?$t({text:n,kind:"assistant",timestamp:o}):void 0)}if("user"===r.type){const e=Gt(r.message?.content);if(e&&!Ht(e))return $t({text:e,kind:"user",timestamp:o});const s=Ut(r.message?.content);for(const e of s){if(!Kt(e))continue;const s=e.tool_use_id?t.calls.get(e.tool_use_id):void 0;if(!s||s.ignored)continue;const n=Boolean(e.is_error);return $t({key:e.tool_use_id,text:"edit"===s.action?n?`Edit failed: ${s.command||"files"}`:`Finished editing ${s.command||"files"}`:n?`Failed ${s.tool}${s.command?`: ${s.command}`:""}`:s.command?`Finished ${s.tool}: ${s.command}`:`Finished ${s.tool}`,kind:"tool",timestamp:o})}return}if("response_item"!==r.type)return;const a=r.payload;if(a){if("custom_tool_call"===a.type){const e=Wt(a.name||"custom_tool",80);if("apply_patch"!==e)return;const n=function(e){const t=[...String(e||"").matchAll(/^\*\*\* (?:Add|Delete|Update) File: (.+)$/gm)].map(e=>function(e){if(!s.isAbsolute(e))return e;const t=s.relative(process.cwd(),e);return!t||t.startsWith("..")||s.isAbsolute(t)?e:t}(e[1].trim()));if(0===t.length)return"files";const n=t.slice(0,2).join(", ");return t.length>2?`${n} +${t.length-2} more`:n}(a.input);return a.call_id&&t.calls.set(a.call_id,{tool:e,command:n,ignored:!1,action:"edit"}),$t({key:a.call_id,text:`Editing ${n}`,kind:"tool",timestamp:o})}if("custom_tool_call_output"===a.type){const e=a.call_id?t.calls.get(a.call_id):void 0;if(!e||e.ignored||"edit"!==e.action)return;const s=Wt(a.output,120),n=/failed|error/i.test(s);return $t({key:a.call_id,text:n?`Edit failed: ${e.command}`:`Finished editing ${e.command}`,kind:"tool",timestamp:o})}if("function_call"===a.type){const e=Wt(a.name||"tool",80),s=Jt(a.arguments),n="write_stdin"===e||Qt(s);if(a.call_id&&t.calls.set(a.call_id,{tool:e,command:s,ignored:n}),n)return;return $t({key:a.call_id,text:s?`Running ${e}: ${s}`:`Running ${e}`,kind:"tool",timestamp:o})}if("function_call_output"===a.type){const e=a.call_id?t.calls.get(a.call_id):void 0;if(!e||e.ignored)return;return $t({key:a.call_id,text:e.command?`Finished ${e.tool}: ${e.command}`:`Finished ${e.tool}`,kind:"tool",timestamp:o})}if("message"===a.type){const e=Gt(a.content);if(!e)return;return $t({text:Xt(e),kind:"user"===a.role?"user":"assistant",timestamp:o})}}}const ss=41943040,ns="ai-session.snapshot",rs=i.z.string().trim().min(1).max(80),is=i.z.enum(["running","waiting","idle","failed"]),os=i.z.enum(["thinking","tool","editing","approval","responding","unknown"]),as=i.z.object({name:i.z.string().trim().min(1).max(120),inputPreview:i.z.string().trim().max(500).optional(),startedAt:i.z.string().datetime().optional()}).strict(),ds=i.z.object({toolCalls:i.z.number().int().min(0).default(0),edits:i.z.number().int().min(0).default(0),approvals:i.z.number().int().min(0).default(0)}).strict().default({toolCalls:0,edits:0,approvals:0}),cs=i.z.object({send:i.z.boolean().optional(),interrupt:i.z.boolean().optional(),approval:i.z.boolean().optional()}).strict(),ps=i.z.object({id:i.z.string().trim().min(1).max(120),kind:i.z.enum(["image"]),name:i.z.string().trim().min(1).max(240),mime:i.z.string().trim().min(1).max(120),size:i.z.number().int().min(0).max(20971520),data:i.z.string().min(1).max(31457280)}).strict(),us=ps.omit({data:!0}),ls=i.z.object({id:i.z.string().trim().min(1).max(120),kind:i.z.enum(["image"]).optional()}).strict(),ms=i.z.enum(["auto","queue","steer","immediate"]),hs=i.z.object({message:i.z.string().trim().min(1).max(2e4),mode:ms.optional()}),gs=hs.extend({attachments:i.z.array(ps).max(6).default([])}).strict().superRefine((e,t)=>{e.attachments.reduce((e,t)=>e+t.size,0)>ss&&t.addIssue({code:i.z.ZodIssueCode.custom,path:["attachments"],message:"Images must be 41943040 bytes or less in total."})});hs.extend({attachments:i.z.array(ls).max(6).default([])}).strict();const fs=i.z.object({decision:i.z.enum(["allow","deny","skip"])}).strict(),ys=i.z.object({queueIds:i.z.array(i.z.string().trim().min(1).max(120)).max(100)}).strict(),vs=i.z.object({code:i.z.string().trim().min(1).max(160),message:i.z.string(),instanceId:i.z.string().trim().min(1).max(160).optional(),nodeId:i.z.string().trim().min(1).max(160).optional(),route:i.z.string().trim().min(1).max(4096).optional()}).strict(),Ss=i.z.object({id:i.z.string().trim().min(1).max(120),message:i.z.string().trim().min(1).max(2e4),attachments:i.z.array(us).max(6).default([]),status:i.z.enum(["queued","sending","failed"]).default("queued"),createdAt:i.z.string().datetime(),updatedAt:i.z.string().datetime(),error:i.z.string().trim().max(4e3).optional()}).strict(),Is=i.z.object({pendingCount:i.z.number().int().min(0).default(0),items:i.z.array(Ss).max(100).default([])}).strict().default({pendingCount:0,items:[]}),As=i.z.enum(["control","realtime","adapter-snapshot","transcript-tail","transcript-scan","process-scan","app-session"]),bs=i.z.object({id:i.z.string().trim().min(1).max(240),providerTurnId:i.z.string().trim().max(240).optional(),source:As.optional(),userPrompt:i.z.string().trim().optional(),status:i.z.enum(["queued","running","waiting","completed","failed"]).default("running"),phase:os.optional(),summary:i.z.string().trim().max(1e3).optional(),lastMessage:i.z.string().trim().optional(),revision:i.z.number().int().min(0).default(0),sourcePriority:i.z.number().int().min(0).max(100).optional(),snapshotVersion:i.z.number().int().min(0).optional(),observedAt:i.z.string().datetime().optional(),startedAt:i.z.string().datetime().optional(),updatedAt:i.z.string().datetime().optional(),completedAt:i.z.string().datetime().optional()}).strict(),_s=i.z.object({id:i.z.string().trim().min(1).max(120),agent:rs,appSessionId:i.z.string().trim().max(120).optional(),appId:i.z.string().trim().max(120).optional(),providerSessionId:i.z.string().trim().max(240).optional(),providerMeta:i.z.record(i.z.string(),i.z.unknown()).optional(),appBindingKeys:i.z.array(i.z.string().trim().min(1).max(240)).max(20).optional(),actions:cs.optional(),activeTurnId:i.z.string().trim().max(240).optional(),conversationId:i.z.number().int().positive().optional(),title:i.z.string().trim().max(240).optional(),cwd:i.z.string().trim().max(4096).optional(),userPrompt:i.z.string().trim().optional(),turns:i.z.array(bs).max(50).optional(),status:is.default("running"),phase:os.default("unknown"),summary:i.z.string().trim().max(1e3).optional(),lastMessage:i.z.string().trim().optional(),currentTool:as.optional(),transcriptPath:i.z.string().trim().max(4096).optional(),transcriptSize:i.z.number().int().min(0).optional(),startedAt:i.z.string().datetime(),updatedAt:i.z.string().datetime(),completedAt:i.z.string().datetime().optional(),error:i.z.string().trim().max(4e3).optional(),counters:ds,queue:Is}).strict(),ws=i.z.object({session:_s,provider:i.z.string().trim().min(1).max(80),action:i.z.enum(["send","queue","steer","interrupt","approval"]),decision:i.z.enum(["allow","deny","skip"]).optional(),turnId:i.z.string().trim().min(1).max(240).optional(),providerTurnId:i.z.string().trim().min(1).max(240).optional(),queueId:i.z.string().trim().min(1).max(120).optional()}).strict(),Ts=_s.pick({id:!0,agent:!0,appSessionId:!0,appId:!0,providerSessionId:!0,providerMeta:!0,appBindingKeys:!0,actions:!0,activeTurnId:!0,conversationId:!0,title:!0,cwd:!0,userPrompt:!0,turns:!0,status:!0,phase:!0,summary:!0,lastMessage:!0,currentTool:!0,queue:!0,startedAt:!0,updatedAt:!0,error:!0}),Ns=i.z.object({runningCount:i.z.number().int().min(0).default(0),waitingCount:i.z.number().int().min(0).default(0),staleCount:i.z.number().int().min(0).default(0),sessions:i.z.array(Ts).default([]),updatedAt:i.z.string().datetime()}).strict();i.z.object({revision:i.z.number().int().min(0),lastEventAt:i.z.string().datetime(),snapshot:Ns}).strict(),Ns.pick({runningCount:!0,waitingCount:!0,staleCount:!0,updatedAt:!0}).extend({idleCount:i.z.number().int().min(0).default(0),problemCount:i.z.number().int().min(0).default(0),revision:i.z.number().int().min(0).optional()});const Os=i.z.enum(["provider-event","app-session-created","app-session-updated","app-session-deleted","discovery-scan","control-action","heartbeat-sync","startup"]),Es=i.z.object({instanceId:i.z.string().trim().min(1).max(160),nodeId:i.z.string().trim().min(1).max(160).optional(),snapshotRevision:i.z.number().int().min(0),previousRevision:i.z.number().int().min(0).optional(),eventSeq:i.z.number().int().min(1),traceId:i.z.string().trim().min(1).max(160),generatedAt:i.z.string().datetime(),reason:Os}).strict(),zs=i.z.object({meta:Es,snapshot:Ns}).strict(),xs=i.z.object({meta:Es,upserted:i.z.array(Ts).default([]),removed:i.z.array(i.z.string().trim().min(1).max(120)).default([])}).strict(),Ds=i.z.object({meta:Es,sessionIds:i.z.array(i.z.string().trim().min(1).max(120)).default([]),expiresAt:i.z.string().datetime()}).strict(),ks=i.z.object({instanceId:i.z.string().trim().min(1).max(160),sinceRevision:i.z.number().int().min(0),latestRevision:i.z.number().int().min(0),syncRequired:i.z.boolean().default(!1),events:i.z.array(i.z.discriminatedUnion("type",[i.z.object({type:i.z.literal(ns),payload:zs}).strict(),i.z.object({type:i.z.literal("ai-session.patch"),payload:xs}).strict(),i.z.object({type:i.z.literal("ai-session.removed"),payload:Ds}).strict()])).default([])}).strict(),Cs=i.z.object({source:As,sourcePriority:i.z.number().int().min(0).max(100).optional(),observedAt:i.z.string().datetime().optional(),snapshotVersion:i.z.number().int().min(0).optional()}).strict(),Ps=Cs.extend({type:i.z.literal("snapshot"),agent:i.z.string().trim().min(1).max(80),appSessionId:i.z.string().trim().max(120).optional(),appId:i.z.string().trim().max(120).optional(),providerSessionId:i.z.string().trim().max(240).optional(),providerMeta:i.z.record(i.z.string(),i.z.unknown()).optional(),appBindingKeys:i.z.array(i.z.string().trim().min(1).max(240)).max(20).optional(),actions:cs.optional(),conversationId:i.z.number().int().positive().optional(),title:i.z.string().trim().max(240).optional(),cwd:i.z.string().trim().max(4096).optional(),activeTurnId:i.z.string().trim().max(240).optional(),userPrompt:i.z.string().trim().optional(),turns:i.z.array(bs).max(50).optional(),status:is.optional(),phase:os.optional(),summary:i.z.string().trim().max(1e3).optional(),lastMessage:i.z.string().trim().optional(),transcriptPath:i.z.string().trim().max(4096).optional(),transcriptSize:i.z.number().int().min(0).optional(),replaceActivity:i.z.boolean().optional()}).strict(),Fs=Cs.extend({type:i.z.literal("event"),sessionId:i.z.string().trim().min(1).max(120),kind:i.z.enum(["lifecycle","send-ack","turn-started","user-message","assistant-message","approval-requested","turn-completed"]),activeTurnId:i.z.string().trim().max(240).optional(),providerTurnId:i.z.string().trim().max(240).optional(),userPrompt:i.z.string().trim().optional(),text:i.z.string().optional(),status:is.optional(),phase:os.optional(),summary:i.z.string().trim().max(1e3).optional(),error:i.z.string().trim().max(4e3).optional(),counters:i.z.object({toolCalls:i.z.number().int().min(0).optional(),edits:i.z.number().int().min(0).optional(),approvals:i.z.number().int().min(0).optional()}).strict().optional()}).strict();function Rs(e,t=500){const s=String(e??"").replace(/\s+/g," ").trim();return s.length>t?`${s.slice(0,t-3)}...`:s}function Ms(e){return String(e??"").trim()}i.z.discriminatedUnion("type",[Ps,Fs]);const js={control:90,realtime:80,"adapter-snapshot":60,"transcript-tail":50,"app-session":40,"process-scan":30,"transcript-scan":20};function Hs(e,t){return Math.max(0,Math.min(100,Number.isInteger(t)?Number(t):e?js[e]:0))}function Ls(e){const t={};return e.source&&(t.source=e.source,t.sourcePriority=Hs(e.source,e.sourcePriority)),e.providerTurnId&&(t.providerTurnId=Rs(e.providerTurnId,240)),Number.isInteger(e.snapshotVersion)&&(t.snapshotVersion=Number(e.snapshotVersion)),e.observedAt&&(t.observedAt=e.observedAt),t}function $s(e){const t=Rs(e,120),s=t.replace(/[^a-zA-Z0-9_.:-]+/g,"_").replace(/^_+|_+$/g,""),n=h.createHash("sha1").update(t).digest("hex").slice(0,10);return s?`${s}_${n}`:n}function Us(e,t){return`turn_${$s(e)}_${$s(t)}`}function qs(e,t,s=1){return Us(e,t||`${e}:${s}`)}function Ks(e,t){return`turn_legacy_${t}_${$s(e.userPrompt||e.updatedAt||e.lastMessage||e.summary)}`}function Bs(e,t={}){const s=[];for(const[n,r]of(e||[]).entries()){const e=r&&"object"==typeof r?r:void 0;if(!e)continue;const i={id:e.id?Rs(e.id,240):Ks(e,n),providerTurnId:e.providerTurnId?Rs(e.providerTurnId,240):t.providerTurnId,source:e.source||t.source,userPrompt:e.userPrompt?Ms(e.userPrompt):void 0,status:e.status||"completed",phase:e.phase,summary:e.summary?Rs(e.summary,1e3):void 0,lastMessage:e.lastMessage?Ms(e.lastMessage):void 0,revision:Math.max(0,Number(e.revision)||0),sourcePriority:Number.isInteger(e.sourcePriority)?Number(e.sourcePriority):t.sourcePriority,snapshotVersion:Number.isInteger(e.snapshotVersion)?Number(e.snapshotVersion):t.snapshotVersion,observedAt:e.observedAt||t.observedAt,startedAt:e.startedAt,updatedAt:e.updatedAt,completedAt:e.completedAt};(i.userPrompt||i.summary||i.lastMessage)&&s.push(i)}return s.slice(-50)}function Vs(e,t){if(!e)return!0;const s=Hs(e.source,e.sourcePriority),n=Hs(t.source,t.sourcePriority);if(n!==s)return n>s||Boolean(t.lastMessage||t.summary)&&!e.lastMessage&&!e.summary;const r=Number(e.snapshotVersion)||0,i=Number(t.snapshotVersion)||0;return i!==r?i>r:(t.revision||0)>=(e.revision||0)||Date.parse(t.observedAt||t.updatedAt||"")>=Date.parse(e.observedAt||e.updatedAt||"")}function Gs(e,t){const s=function(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e))}(t);if(!e)return s;const n=e.userPrompt===(t.userPrompt??e.userPrompt)&&e.summary===(t.summary??e.summary)&&e.lastMessage===(t.lastMessage??e.lastMessage),r=e.status===(t.status??e.status)&&e.phase===(t.phase??e.phase);return n&&r&&(delete s.observedAt,delete s.updatedAt,delete s.completedAt),s}function Ws(e){return Boolean(e?.lastMessage||e?.summary)}function Xs(e){if(!e.activeTurnId||"running"!==e.status)return!1;const t=Bs(e.turns).find(t=>t.id===e.activeTurnId);return Boolean(!t||!Ws(t))}function Js(e,t,s){return s?e.activeTurnId:"idle"!==t.status&&"failed"!==t.status?t.activeTurnId?Rs(t.activeTurnId,240):e.activeTurnId:void 0}function Ys(e,t,s,n={}){const r=function(e,t,s={}){const n=Bs(e),r=Bs(t,s);function i(e,t){const s=r.slice(0,t).reverse().find(e=>n.some(t=>t.id===e.id));if(s){const t=n.findIndex(e=>e.id===s.id);return void n.splice(t+1,0,e)}const i=r.slice(t+1).find(e=>n.some(t=>t.id===e.id));if(i){const t=n.findIndex(e=>e.id===i.id);return void n.splice(t,0,e)}n.push(e)}for(const[e,t]of r.entries()){let s=!1;for(const[e,r]of n.entries())if(r.id!==t.id&&r.userPrompt&&r.userPrompt===t.userPrompt&&!r.lastMessage&&!r.summary&&(t.lastMessage||t.summary)){const i={...r,...Gs(r,t),id:r.id,providerTurnId:t.providerTurnId||t.id,revision:Math.max(r.revision||0,t.revision||0)};Vs(r,i)&&(n[e]=i),s=!0;break}if(s)continue;const r=n.findIndex(e=>e.id===t.id),o=r>=0?n[r]:void 0;if(Vs(o,t)){const s={...o,...Gs(o,t),revision:Math.max(o?.revision||0,t.revision||0)};r>=0?n[r]=s:i(s,e)}}return n.slice(-50)}(e,t.turns,n),i=t.userPrompt?Ms(t.userPrompt):"",o=t.activeTurnId?Rs(t.activeTurnId,240):"";if(i){const e=r.at(-1),a=(o?r.find(e=>e.id===o):void 0)||[...r].reverse().find(e=>e.userPrompt===i&&!e.lastMessage&&!e.summary),d=Boolean(t.turns?.some(e=>e.userPrompt&&Ms(e.userPrompt)===i));a?(o&&a.id!==o&&(a.id=o),a.userPrompt=i,a.updatedAt=s,a.status="waiting"===t.status?"waiting":"running",a.phase=t.phase||a.phase||"thinking",Object.assign(a,n),a.revision+=1):!e||e.lastMessage||e.summary||e.userPrompt!==i?d||r.push({id:o||Us(i,s),...n,userPrompt:i,status:"waiting"===t.status?"waiting":"running",phase:t.phase||"thinking",revision:0,startedAt:s,updatedAt:s}):(e.updatedAt=s,e.status="waiting"===t.status?"waiting":"running",e.phase=t.phase||e.phase||"thinking",Object.assign(e,n),e.revision+=1)}if(t.lastMessage||t.summary){let e=o?r.find(e=>e.id===o):r.at(-1);if(!e&&o){const t=[...r].reverse().find(e=>e.userPrompt&&!e.lastMessage&&!e.summary);t&&(t.id=o,e=t)}!e&&o&&(e={id:o,...n,status:"waiting"===t.status?"waiting":"failed"===t.status?"failed":"running",phase:t.phase||"unknown",revision:0,startedAt:s,updatedAt:s},r.push(e));const i={summary:t.summary?Rs(t.summary,1e3):e?.summary,lastMessage:t.lastMessage?Ms(t.lastMessage):e?.lastMessage,status:"idle"===t.status?"completed":"waiting"===t.status?"waiting":"failed"===t.status?"failed":e?.status||"running",phase:t.phase||e?.phase,updatedAt:s,completedAt:"idle"===t.status||"failed"===t.status?s:e?.completedAt,...n};if(e){const t=e.summary===i.summary&&e.lastMessage===i.lastMessage,s=e.status===i.status&&e.phase===i.phase,n=t&&s;Object.assign(e,{...i,observedAt:n?e.observedAt:i.observedAt,updatedAt:n||t?e.updatedAt:i.updatedAt,completedAt:n?e.completedAt:i.completedAt}),t&&s||(e.revision+=1)}else r.push({id:`turn_${h.randomUUID().replace(/-/g,"").slice(0,20)}`,...i,status:i.status||"running",revision:0,startedAt:s})}else if((t.status||t.phase)&&o){const e=r.find(e=>e.id===o);if(e){const r="idle"===t.status?"completed":"waiting"===t.status?"waiting":"failed"===t.status?"failed":e.status,i=t.phase||e.phase,o="idle"===t.status||"failed"===t.status?s:e.completedAt,a=e.status!==r||e.phase!==i||e.completedAt!==o;Object.assign(e,{status:r,phase:i,completedAt:o,updatedAt:a?s:e.updatedAt,...n}),a&&(e.revision+=1)}}if(("running"===t.status||"waiting"===t.status)&&o){const e=r.findIndex(e=>e.id===o);if(e>=0&&e!==r.length-1){const[t]=r.splice(e,1);r.push(t)}}return Bs(r)}function Qs(){return(new Date).toISOString()}function Zs(e){t.mkdirSync(e,{recursive:!0})}function en(e){try{return JSON.parse(t.readFileSync(e,"utf8"))}catch{return}}function tn(e,t,s){if(!Array.isArray(e))return;const n=[...new Set(e.map(e=>Rs(e,s)).filter(Boolean))].slice(0,t);return n.length?n:void 0}function sn(e){const t=e&&"object"==typeof e&&!Array.isArray(e)?e:{},s={send:"boolean"==typeof t.send?t.send:void 0,interrupt:"boolean"==typeof t.interrupt?t.interrupt:void 0,approval:"boolean"==typeof t.approval?t.approval:void 0};return void 0===s.send&&void 0===s.interrupt&&void 0===s.approval?void 0:s}function nn(e){const t=e.map(on).filter(e=>Boolean(e)).slice(0,100);return{pendingCount:t.filter(e=>"queued"===e.status||"sending"===e.status).length,items:t}}function rn(e){const t=e&&"object"==typeof e&&!Array.isArray(e)?e:{};return nn(Array.isArray(t.items)?t.items:[])}function on(e){const t=e&&"object"==typeof e&&!Array.isArray(e)?e:void 0;if(!(t?.id&&t.message&&t.createdAt&&t.updatedAt))return;const s="sending"===t.status||"failed"===t.status?t.status:"queued";return{id:Rs(t.id,120),message:Ms(t.message),attachments:an(t.attachments),status:s,createdAt:t.createdAt,updatedAt:t.updatedAt,error:t.error?Rs(t.error,4e3):void 0}}function an(e){return Array.isArray(e)?e.map(e=>{const t=us.safeParse(e);return t.success?t.data:void 0}).filter(e=>Boolean(e)).slice(0,6):[]}function dn(e=[]){return e.slice(0,6).map(e=>us.parse({id:e.id,kind:e.kind,name:e.name,mime:e.mime,size:e.size}))}function cn(e){const t=e&&"object"==typeof e?e:void 0;var s;if(t?.id&&t.agent&&t.startedAt&&t.updatedAt)return{id:Rs(t.id,120),agent:Rs(t.agent,80),appSessionId:t.appSessionId?Rs(t.appSessionId,120):void 0,appId:t.appId?Rs(t.appId,120):void 0,providerSessionId:t.providerSessionId?Rs(t.providerSessionId,240):void 0,providerMeta:t.providerMeta&&"object"==typeof t.providerMeta&&!Array.isArray(t.providerMeta)?t.providerMeta:void 0,appBindingKeys:tn(t.appBindingKeys,20,240),actions:sn(t.actions),activeTurnId:t.activeTurnId?Rs(t.activeTurnId,240):void 0,conversationId:Number.isInteger(t.conversationId)&&Number(t.conversationId)>0?Number(t.conversationId):void 0,title:t.title?Rs(t.title,240):void 0,cwd:t.cwd?Rs(t.cwd,4096):void 0,userPrompt:t.userPrompt?Ms(t.userPrompt):void 0,turns:Bs(t.turns),status:pn(t.status),phase:un(t.phase),summary:t.summary?Rs(t.summary,1e3):void 0,lastMessage:t.lastMessage?Ms(t.lastMessage):void 0,currentTool:t.currentTool?.name?{name:Rs(t.currentTool.name,120),inputPreview:t.currentTool.inputPreview?Rs(t.currentTool.inputPreview,500):void 0,startedAt:t.currentTool.startedAt}:void 0,transcriptPath:t.transcriptPath?Rs(t.transcriptPath,4096):void 0,transcriptSize:Number.isInteger(t.transcriptSize)&&Number(t.transcriptSize)>=0?Number(t.transcriptSize):void 0,startedAt:t.startedAt,updatedAt:t.updatedAt,completedAt:t.completedAt,error:t.error?Rs(t.error,4e3):void 0,counters:(s=t.counters,{toolCalls:Math.max(0,Number(s?.toolCalls)||0),edits:Math.max(0,Number(s?.edits)||0),approvals:Math.max(0,Number(s?.approvals)||0)}),queue:rn(t.queue)}}function pn(e){const t=String(e||"").trim().toLowerCase();return"waiting"===t?"waiting":"failed"===t?"failed":"idle"===t||"completed"===t||"stale"===t||"stopped"===t||"exited"===t?"idle":"running"}function un(e){return["thinking","tool","editing","approval","responding","unknown"].includes(String(e))?e:"unknown"}function ln(e){return e.appSessionId?`${e.agent}:app:${e.appSessionId}`:e.providerSessionId?`${e.agent}:provider:${e.providerSessionId}`:e.transcriptPath?`${e.agent}:transcript:${e.transcriptPath}`:`${e.agent}:id:${e.id}`}function mn(e,t){const s=Number(Boolean(e.userPrompt))+Number(Boolean(e.summary))+Number(Boolean(e.lastMessage))+(e.turns?.length||0),n=Number(Boolean(t.userPrompt))+Number(Boolean(t.summary))+Number(Boolean(t.lastMessage))+(t.turns?.length||0);return s!==n?s>n?e:t:Date.parse(e.updatedAt)>=Date.parse(t.updatedAt)?e:t}function hn(e){return{id:e.id,agent:e.agent,appSessionId:e.appSessionId,appId:e.appId,providerSessionId:e.providerSessionId,providerMeta:e.providerMeta,appBindingKeys:e.appBindingKeys,actions:gn(e),activeTurnId:e.activeTurnId,conversationId:e.conversationId,title:e.title,cwd:e.cwd,userPrompt:e.userPrompt,turns:e.turns,status:e.status,phase:e.phase,summary:e.summary,lastMessage:e.lastMessage,currentTool:e.currentTool,queue:e.queue,startedAt:e.startedAt,updatedAt:e.updatedAt,error:e.error}}function gn(e){const t="running"===e.status||"waiting"===e.status,s=e.actions||{};return{send:s.send??!0,interrupt:Boolean(t&&!1!==s.interrupt),approval:Boolean("waiting"===e.status&&"approval"===e.phase&&!1!==s.approval)}}function fn(e,t){const s=Rs(e,1e3);return"user"===t?{userPrompt:Ms(e)}:"assistant"===t?{status:"running",phase:"responding",summary:s,lastMessage:Ms(e)}:/approval|permission|approve|deny/i.test(s)?{status:"waiting",phase:"approval",summary:s,counters:{approvals:1}}:/^Editing\b|Finished editing\b|Edit failed/i.test(s)?{status:"running",phase:"editing",summary:s,counters:{edits:1}}:/^Tool\b|^Running\b|^Finished\b|^Failed\b/i.test(s)?{status:"running",phase:"tool",summary:s,counters:{toolCalls:1}}:s?{status:"running",phase:"responding",summary:s,lastMessage:Ms(e)}:{}}function yn(e,t,s){const n=t.activeTurnId?Rs(t.activeTurnId,240):void 0;if("transcript-tail"!==t.source||!n||!e.activeTurnId||n===e.activeTurnId)return n||e.activeTurnId;const r=Bs(e.turns).find(t=>t.id===e.activeTurnId);if(!r||Ws(r))return n;const i=s?Ms(s):"";return i&&r.userPrompt&&r.userPrompt!==i?n:e.activeTurnId}function vn(e,r,i){if(r)return"claude"===e?es(r,i):function(e,r=s.join(n.homedir(),".codex")){const i=Wt(e,200);if(!i)return;const o=[s.join(r,"sessions")];for(;o.length>0;){const e=o.pop();if(!e)continue;let n;try{n=t.readdirSync(e,{withFileTypes:!0})}catch{continue}for(const t of n){const n=s.join(e,t.name);if(t.isDirectory())o.push(n);else if(t.isFile()&&t.name.endsWith(".jsonl")&&t.name.includes(i))return n}}}(r)}class Sn{dir;retentionMs;idleAfterMs;staleAfterMs;orphanedAppSessionRetentionMs;orphanedAppSessionAt=new Map;queuedAttachmentPayloads=new Map;changes=new g.EventEmitter;constructor(e={}){this.dir=e.dir||function(){const e=process.env.TASK_HANDOFF_AI_SESSION_DIR;return e?.trim()?s.resolve(e.trim()):s.join(et().dataDir,"ai-sessions")}(),this.retentionMs=e.retentionMs??(Number(process.env.TASK_HANDOFF_AI_SESSION_RETENTION_MS)||864e5),this.idleAfterMs=e.idleAfterMs??(Number(process.env.TASK_HANDOFF_AI_SESSION_IDLE_AFTER_MS)||3e4),this.staleAfterMs=e.staleAfterMs??(Number(process.env.TASK_HANDOFF_AI_SESSION_STALE_AFTER_MS)||3e5),this.orphanedAppSessionRetentionMs=e.orphanedAppSessionRetentionMs??(Number(process.env.TASK_HANDOFF_AI_SESSION_ORPHAN_RETENTION_MS)||3e5)}sessionPath(e){return s.join(this.dir,`${e}.json`)}onChange(e){return this.changes.on("change",e),()=>{this.changes.off("change",e)}}start(e,t={}){const s=t.timestamp||Qs(),n=t.meta||Ls({source:"control",observedAt:s}),r={id:`ais_${h.randomUUID().replace(/-/g,"").slice(0,20)}`,agent:Rs(e.agent||"unknown",80),appSessionId:e.appSessionId?Rs(e.appSessionId,120):void 0,appId:e.appId?Rs(e.appId,120):void 0,providerSessionId:e.providerSessionId?Rs(e.providerSessionId,240):void 0,providerMeta:void 0,activeTurnId:void 0,conversationId:e.conversationId,title:e.title?Rs(e.title,240):void 0,cwd:e.cwd?Rs(e.cwd,4096):void 0,userPrompt:e.userPrompt?Ms(e.userPrompt):void 0,turns:Ys(void 0,{userPrompt:t.suppressPromptTurn?void 0:e.userPrompt,turns:e.turns},s,n),status:pn(e.status||"idle"),phase:un(e.phase||"unknown"),summary:e.summary?Rs(e.summary,1e3):void 0,startedAt:s,updatedAt:s,counters:{toolCalls:0,edits:0,approvals:0},queue:{pendingCount:0,items:[]}};return this.put(r),r}get(e){return cn(en(this.sessionPath(e)))}put(e){return Zs(this.dir),function(e,n){Zs(s.dirname(e));const r=`${e}.${process.pid}.${Date.now()}.tmp`;t.writeFileSync(r,`${JSON.stringify(n,null,2)}\n`,"utf8"),t.renameSync(r,e)}(this.sessionPath(e.id),e),this.emitChange("write"),e}update(e,t,s={}){const n=this.get(e);if(!n)return;const r={toolCalls:n.counters.toolCalls+Math.max(0,Number(t.counters?.toolCalls)||0),edits:n.counters.edits+Math.max(0,Number(t.counters?.edits)||0),approvals:n.counters.approvals+Math.max(0,Number(t.counters?.approvals)||0)},i=s.preserveUpdatedAt?n.updatedAt:s.updatedAt||Qs(),o=s.suppressPromptTurn?{...t,userPrompt:void 0}:t,a=s.suppressTurnUpdate?Bs(s.replaceTurns?void 0:n.turns):Ys(s.replaceTurns?void 0:n.turns,o,i,s.meta),d=t.userPrompt?Ms(t.userPrompt):"",c=a.at(-1),p=Boolean(d&&!t.lastMessage&&c?.userPrompt===d&&!c.summary&&!c.lastMessage),u={...n,...t,id:n.id,agent:n.agent,startedAt:n.startedAt,updatedAt:i,status:t.status?pn(t.status):n.status,phase:t.phase?un(t.phase):n.phase,summary:s.replaceActivity?t.summary?Rs(t.summary,1e3):void 0:s.clearResponse?void 0:t.summary?Rs(t.summary,1e3):p?void 0:n.summary,lastMessage:s.replaceActivity?t.lastMessage?Ms(t.lastMessage):void 0:s.clearResponse?void 0:t.lastMessage?Ms(t.lastMessage):p?void 0:n.lastMessage,userPrompt:s.replaceActivity?t.userPrompt?Ms(t.userPrompt):void 0:t.userPrompt?Ms(t.userPrompt):n.userPrompt,turns:a,error:t.error?Rs(t.error,4e3):n.error,counters:r,queue:t.queue?rn(t.queue):n.queue};return this.put(u)}enqueueMessage(e,t,s=[]){const n=this.get(e);if(!n)return;const r=Qs(),i={id:`aiq_${h.randomUUID().replace(/-/g,"").slice(0,20)}`,message:Ms(t),attachments:dn(s),status:"queued",createdAt:r,updatedAt:r},o=[...n.queue?.items||[],i],a=this.update(e,{queue:nn(o)},{updatedAt:r,suppressTurnUpdate:!0});return a&&s.length&&this.queuedAttachmentPayloads.set(i.id,s.slice(0,6)),a?{session:a,item:i}:void 0}queuedMessages(e){return this.get(e)?.queue||{pendingCount:0,items:[]}}nextQueuedMessage(e){return this.queuedMessages(e).items.find(e=>"queued"===e.status)}queuedMessageAttachments(e){return this.queuedAttachmentPayloads.get(e)||[]}markQueuedMessageSending(e,t){return this.patchQueuedMessage(e,t,{status:"sending",error:void 0})}markQueuedMessageFailed(e,t,s){const n=s instanceof Error?s.message:String(s);return this.patchQueuedMessage(e,t,{status:"failed",error:Rs(n,4e3)})}retryQueuedMessage(e,t){return this.patchQueuedMessage(e,t,{status:"queued",error:void 0})}removeQueuedMessage(e,t){const s=this.get(e);if(!s)return;const n=(s.queue?.items||[]).filter(e=>e.id!==t);return this.queuedAttachmentPayloads.delete(t),this.update(e,{queue:nn(n)},{suppressTurnUpdate:!0})}reorderQueuedMessages(e,t){const s=this.get(e);if(!s)return;const n=s.queue?.items||[],r=new Map(n.map(e=>[e.id,e])),i=t.map(e=>r.get(e)).filter(e=>Boolean(e)),o=n.filter(e=>!t.includes(e.id));return this.update(e,{queue:nn([...i,...o])},{suppressTurnUpdate:!0})}patchQueuedMessage(e,t,s){const n=this.get(e);if(!n)return;const r=Qs();let i=!1;const o=(n.queue?.items||[]).map(e=>e.id!==t?e:(i=!0,{...e,...s,updatedAt:r}));return i?this.update(e,{queue:nn(o)},{updatedAt:r,suppressTurnUpdate:!0}):void 0}bindProviderSession(e,t){const s=this.get(e),n=s?vn(s.agent,t,s.cwd):void 0;return this.update(e,{providerSessionId:t,transcriptPath:n,status:"running",phase:"thinking",summary:`${s?.agent||"AI"} session ${t} started`})}apply(e){const t=e.observedAt||Qs(),s={...e,observedAt:t,sourcePriority:Hs(e.source,e.sourcePriority)};return"snapshot"===e.type?this.reduceSnapshotInput(s):this.reduceRealtimeInput(s)}applyRealtimeEvent(e,t){return this.apply({type:"event",sessionId:e,source:t.source||"realtime",...t})}reduceRealtimeInput(e){const t=e.sessionId,s=this.get(t);if(!s)return;const n=Ls(e);if("send-ack"===e.kind){const s=e.observedAt||Qs(),r=Ms(e.userPrompt);return this.update(t,{activeTurnId:e.activeTurnId||Us(r,s),status:e.status||"running",phase:e.phase||"thinking",userPrompt:r},{updatedAt:s,meta:n})}if("lifecycle"===e.kind){const r=e.status||s.status;return"idle"!==r&&"failed"!==r||!Xs(s)?this.update(t,{activeTurnId:("running"===r||"waiting"===r)&&e.activeTurnId||s.activeTurnId,status:r,phase:e.phase||s.phase},{updatedAt:e.observedAt,meta:n}):s}if("turn-started"===e.kind)return this.update(t,{activeTurnId:e.activeTurnId||s.activeTurnId,status:e.status||"running",phase:e.phase||"thinking"},{updatedAt:e.observedAt,meta:n});if("user-message"===e.kind){const r=yn(s,e,e.userPrompt);return this.update(t,{activeTurnId:r,status:e.status||"running",phase:e.phase||"thinking",userPrompt:e.userPrompt},{updatedAt:e.observedAt,meta:n})}if("assistant-message"===e.kind){const r=yn(s,e),i="transcript-tail"===e.source;return this.update(t,{activeTurnId:r,status:e.status||(i?"idle":"running"),phase:e.phase||(i?"unknown":"responding"),summary:e.text,lastMessage:e.text},{updatedAt:e.observedAt,meta:n})}if("approval-requested"===e.kind)return this.update(t,{activeTurnId:e.activeTurnId||s.activeTurnId,status:e.status||"waiting",phase:e.phase||"approval",summary:e.summary||e.text,counters:e.counters||{approvals:1}},{updatedAt:e.observedAt,meta:n});if("turn-completed"===e.kind){const r=e.error?Rs(e.error,4e3):void 0,i=e.text||e.summary||("failed"===e.status?r:void 0),o=Boolean(i);return this.update(t,{activeTurnId:e.activeTurnId&&e.activeTurnId!==s.activeTurnId?s.activeTurnId:void 0,status:e.status||"idle",phase:e.phase||"unknown",summary:i,lastMessage:i,error:r},{updatedAt:e.observedAt,meta:n,clearResponse:!o})}}applyAdapterSnapshot(e){return this.apply({type:"snapshot",source:e.source||"control",...e})}reduceSnapshotInput(e){const t=Ls(e),s=this.readSessions().find(t=>e.appSessionId&&t.appSessionId===e.appSessionId||e.providerSessionId&&t.providerSessionId===e.providerSessionId||e.transcriptPath&&t.transcriptPath===e.transcriptPath);if(!s){const s=this.start({agent:e.agent,appSessionId:e.appSessionId,appId:e.appId,providerSessionId:e.providerSessionId,conversationId:e.conversationId,title:e.title,cwd:e.cwd,userPrompt:e.userPrompt,turns:e.turns,status:e.status||"idle",phase:e.phase||"unknown",summary:e.summary},{meta:t,timestamp:e.observedAt,suppressPromptTurn:!e.turns?.length});return this.update(s.id,{providerMeta:e.providerMeta,appBindingKeys:e.appBindingKeys,actions:e.actions,lastMessage:e.lastMessage,transcriptPath:e.transcriptPath,transcriptSize:e.transcriptSize,status:e.status||s.status,phase:e.phase||"unknown"},{updatedAt:e.observedAt,meta:t,suppressTurnUpdate:!e.turns?.length})}return this.orphanedAppSessionAt.delete(s.id),this.reduceSnapshot(s.id,e)}reduceSnapshot(e,t){const s=this.get(e);if(!s)return;const n=Ls(t),r=Bs(t.turns,n),i=function(e,t){if(!Xs(e))return!1;const s=Bs(e.turns).find(t=>t.id===e.activeTurnId);return!Bs(t).some(t=>t.id===e.activeTurnId||Boolean(s?.userPrompt&&t.userPrompt===s.userPrompt&&Ws(t)&&!Ws(s)))}(s,r),o=Boolean(s.activeTurnId&&r.some(e=>e.id===s.activeTurnId)),a=s.activeTurnId?r.find(e=>e.id===s.activeTurnId):void 0,d=Boolean(t.replaceActivity&&s.activeTurnId&&o&&!Ws(a)),c=function(e){return"app-session"===e.source||"adapter-snapshot"===e.source&&"codex"===e.agent&&"codex-app-server"===e.appId}(t);return this.update(e,{appSessionId:c?t.appSessionId:t.appSessionId||s.appSessionId,appId:t.appId||s.appId,providerSessionId:t.providerSessionId||s.providerSessionId,providerMeta:t.providerMeta||s.providerMeta,appBindingKeys:c?t.appBindingKeys:t.appBindingKeys||s.appBindingKeys,actions:t.actions||s.actions,activeTurnId:Js(s,t,i),conversationId:t.conversationId||s.conversationId,title:t.title||s.title,cwd:t.cwd||s.cwd,userPrompt:i?s.userPrompt:t.userPrompt||s.userPrompt,turns:i?s.turns:t.turns,lastMessage:i?s.lastMessage:d?void 0:t.lastMessage||s.lastMessage,transcriptPath:t.transcriptPath||s.transcriptPath,transcriptSize:t.transcriptSize??s.transcriptSize,status:i?s.status:t.status||s.status,phase:i?s.phase:t.phase||s.phase,summary:i?s.summary:d?void 0:t.replaceActivity?t.summary:t.summary||s.summary},{updatedAt:t.observedAt,meta:n,replaceActivity:Boolean(t.replaceActivity),suppressPromptTurn:!r.length,suppressTurnUpdate:!r.length,replaceTurns:Boolean(t.replaceActivity&&!i&&0===r.length&&!t.userPrompt&&!t.summary&&!t.lastMessage)})}attachTranscript(e,t){if(!t){const s=this.get(e);t=s?vn(s.agent,s.providerSessionId,s.cwd):void 0}const s=this.get(e);return t&&s?this.applyAdapterSnapshot({source:"transcript-scan",agent:s.agent,appId:s.appId,appSessionId:s.appSessionId,providerSessionId:s.providerSessionId,cwd:s.cwd,transcriptPath:t,status:s.status,phase:s.phase}):s}progress(e,t,s){if("user"===s)return this.applyRealtimeEvent(e,{kind:"user-message",userPrompt:t});if("assistant"===s)return this.applyRealtimeEvent(e,{kind:"assistant-message",text:t});const n=fn(t,s);return this.applyRealtimeEvent(e,{kind:"waiting"===n.status?"approval-requested":"assistant-message",text:n.summary||t,status:n.status,phase:n.phase,counters:n.counters,source:"realtime"})}complete(e,t){return this.applyRealtimeEvent(e,{kind:"turn-completed",status:"idle",phase:"responding",text:t?Ms(t):"Completed",source:"control"})}fail(e,t){const s=t instanceof Error?t.message:String(t);return this.applyRealtimeEvent(e,{kind:"turn-completed",status:"failed",phase:"unknown",text:`Failed: ${s}`,source:"control"})}markWaitingByConversation(e,t){const s=this.list().filter(t=>t.conversationId===e&&!["idle","failed"].includes(t.status)).sort((e,t)=>Date.parse(t.updatedAt)-Date.parse(e.updatedAt))[0];return s?this.applyRealtimeEvent(s.id,{kind:"approval-requested",status:"waiting",phase:"approval",summary:t,counters:{approvals:1},source:"realtime"}):void 0}list(){return this.canonicalSessions(this.readSessions().filter(e=>!this.orphanedAppSessionAt.has(e.id)))}readSessions(){Zs(this.dir);let e=[];try{e=t.readdirSync(this.dir).filter(e=>e.endsWith(".json"))}catch{return[]}const n=Date.now();return e.map(e=>cn(en(s.join(this.dir,e)))).filter(e=>Boolean(e)).map(e=>this.withDerivedLifecycle(e,n)).sort((e,t)=>Date.parse(t.updatedAt)-Date.parse(e.updatedAt))}canonicalSessions(e){const t=new Map;for(const s of e){const e=ln(s),n=t.get(e);t.set(e,n?mn(n,s):s)}return[...t.values()].sort((e,t)=>Date.parse(t.updatedAt)-Date.parse(e.updatedAt))}reconcileAppSessionBindings(e=[],s=Date.now()){const n=new Set(e.filter(e=>"string"!=typeof e.status||"running"===e.status).map(e=>"string"==typeof e.id?e.id.trim():"").filter(Boolean));let r=0,i=0;for(const e of this.readSessions()){if(!e.appSessionId){this.orphanedAppSessionAt.delete(e.id);continue}if(n.has(e.appSessionId)){this.orphanedAppSessionAt.delete(e.id);continue}const o=this.orphanedAppSessionAt.get(e.id)??s;this.orphanedAppSessionAt.set(e.id,o),r+=1,s-o>=this.orphanedAppSessionRetentionMs&&(t.rmSync(this.sessionPath(e.id),{force:!0}),this.orphanedAppSessionAt.delete(e.id),i+=1,this.emitChange("delete"))}return{hidden:r,deleted:i}}reconcileAdapterSessions(e){const s=e.appSessionIds||new Set,n=e.providerSessionIds||new Set,r=e.providerShorts||new Set;let i=0;for(const o of this.readSessions()){if(o.agent!==e.agent)continue;if(!o.appSessionId&&!o.providerSessionId&&!o.providerMeta?.short)continue;if(o.appSessionId&&s.has(o.appSessionId)){this.orphanedAppSessionAt.delete(o.id);continue}if(o.providerSessionId&&n.has(o.providerSessionId)){this.orphanedAppSessionAt.delete(o.id);continue}const a="string"==typeof o.providerMeta?.short?o.providerMeta.short:"";a&&r.has(a)?this.orphanedAppSessionAt.delete(o.id):(t.rmSync(this.sessionPath(o.id),{force:!0}),this.orphanedAppSessionAt.delete(o.id),i+=1,this.emitChange("delete"))}return{deleted:i}}snapshot(e=20){const t=this.list().slice(0,e);return this.snapshotFromSessions(t)}boundSnapshot(e=[],t=20){const s=new Set(e.filter(e=>"string"!=typeof e.status||"running"===e.status).map(e=>"string"==typeof e.id?e.id.trim():"").filter(Boolean)),n=this.list().filter(e=>Boolean(e.appSessionId&&s.has(e.appSessionId))).slice(0,t);return this.snapshotFromSessions(n)}snapshotFromSessions(e){return{runningCount:e.filter(e=>"running"===e.status).length,waitingCount:e.filter(e=>"waiting"===e.status).length,staleCount:0,sessions:e.map(hn),updatedAt:Qs()}}prune(){const e=new Set(this.canonicalSessions(this.readSessions()).map(e=>e.id));for(const s of this.readSessions())e.has(s.id)||(t.rmSync(this.sessionPath(s.id),{force:!0}),this.emitChange("delete"));const s=Date.now()-this.retentionMs;for(const e of this.readSessions())["idle","failed"].includes(e.status)&&Date.parse(e.updatedAt)<s&&t.rm(this.sessionPath(e.id),{force:!0},()=>this.emitChange("delete"))}ingestTranscriptLine(e,t,s){const n=ts(t,s);if(!n?.text)return this.get(e);const r=n.timestamp||Qs();if("user"===n.kind){const t=Ms(n.text),i=n.key||n.timestamp;if(i)s.activeTurnId=qs(t,i);else{s.promptCounts||=new Map;const e=(s.promptCounts.get(t)||0)+1;s.promptCounts.set(t,e),s.activeTurnId=qs(t,void 0,e)}return this.applyRealtimeEvent(e,{kind:"user-message",activeTurnId:s.activeTurnId,providerTurnId:s.activeTurnId,userPrompt:t,observedAt:r,source:"transcript-tail"})}if("assistant"===n.kind)return this.applyRealtimeEvent(e,{kind:"assistant-message",activeTurnId:s.activeTurnId,providerTurnId:s.activeTurnId,text:n.text,observedAt:r,source:"transcript-tail"});const i=fn(n.text,n.kind);return this.applyRealtimeEvent(e,{kind:"waiting"===i.status?"approval-requested":"assistant-message",activeTurnId:s.activeTurnId,providerTurnId:s.activeTurnId,text:i.summary||n.text,status:i.status,phase:i.phase,counters:i.counters,observedAt:r,source:"transcript-tail"})}createFromTranscript(e,s,n={}){const r=t.statSync(s),i=r.mtime.toISOString(),o=function(e,s=t.statSync(e)){const n={calls:new Map},r={};let i;const o=new Map;for(const a of function(e,s=t.statSync(e)){const n=Math.max(0,s.size-524288),r=t.openSync(e,"r");try{const e=Buffer.alloc(s.size-n);return t.readSync(r,e,0,e.length,n),e.toString("utf8")}finally{t.closeSync(r)}}(e,s).split(/\r?\n/)){const e=ts(a,n);if(!e?.text)continue;const t=e.timestamp||s.mtime.toISOString();if("user"===e.kind){const s=Ms(e.text);r.userPrompt=s;const n=e.key||e.timestamp;if(n)i=qs(s,n);else{const e=(o.get(s)||0)+1;o.set(s,e),i=qs(s,void 0,e)}r.turns=Ys(r.turns,{activeTurnId:i,userPrompt:s},t);continue}r.summary=Rs(e.text,1e3),r.lastMessage=Ms(e.text),r.turns=Ys(r.turns,{activeTurnId:i,summary:r.summary,lastMessage:r.lastMessage},t)}return r}(s,r),a=this.readSessions().find(e=>e.transcriptPath===s||n.providerSessionId&&e.providerSessionId===n.providerSessionId);if(a){const t=!a.appSessionId&&!a.conversationId,p=Number.isInteger(a.transcriptSize)&&r.size>Number(a.transcriptSize),u=t&&p?Qs():t&&!p?a.updatedAt:(d=a.updatedAt,c=i,Date.parse(d)>=Date.parse(c)?d:c);return this.applyAdapterSnapshot({source:"transcript-scan",agent:e,transcriptPath:s,transcriptSize:r.size,providerSessionId:n.providerSessionId||a.providerSessionId,cwd:n.cwd||a.cwd,userPrompt:a.userPrompt||o.userPrompt,turns:o.turns?.length?o.turns:a.turns,summary:o.summary||a.summary,lastMessage:o.lastMessage||a.lastMessage,status:t&&p?"running":a.status,phase:t&&p&&"unknown"===a.phase?"responding":a.phase,observedAt:u,replaceActivity:Boolean(o.turns?.length)})||a}var d,c;const p=this.start({agent:e,providerSessionId:n.providerSessionId,cwd:n.cwd,userPrompt:o.userPrompt,turns:o.turns,status:this.lifecycleForTranscriptMtime(r.mtimeMs),phase:"unknown",summary:o.summary||`${e} transcript detected`},{meta:Ls({source:"transcript-scan",observedAt:i}),timestamp:i,suppressPromptTurn:!o.turns?.length});return this.applyAdapterSnapshot({source:"transcript-scan",agent:p.agent,providerSessionId:p.providerSessionId,cwd:p.cwd,userPrompt:p.userPrompt,turns:p.turns,summary:p.summary,lastMessage:o.lastMessage,transcriptPath:s,transcriptSize:r.size,status:p.status,phase:p.phase,observedAt:i})||p}emitChange(e){this.changes.emit("change",e)}reconcileActiveProcesses(e){const t=new Set;for(const s of e){const e=this.list().find(e=>e.agent===s.agent&&(s.providerSessionId&&e.providerSessionId===s.providerSessionId||s.transcriptPath&&e.transcriptPath===s.transcriptPath));e&&(t.add(e.id),this.applyAdapterSnapshot({source:"process-scan",agent:e.agent,appId:e.appId,appSessionId:e.appSessionId,providerSessionId:s.providerSessionId||e.providerSessionId,cwd:s.cwd||e.cwd,title:e.title,userPrompt:e.userPrompt,turns:e.turns,summary:e.summary,lastMessage:e.lastMessage,status:"running",phase:"unknown"===e.phase?"thinking":e.phase,transcriptPath:s.transcriptPath||e.transcriptPath}))}return t}withDerivedLifecycle(e,t=Date.now()){if(["idle","failed","waiting"].includes(e.status))return e;const s=t-Date.parse(e.updatedAt);return s>this.staleAfterMs&&e.transcriptPath&&!e.conversationId||s>this.idleAfterMs&&"running"===e.status?{...e,status:"idle"}:e}lifecycleForTranscriptMtime(e){const t=Date.now()-e;return t>this.staleAfterMs||t>this.idleAfterMs?"idle":"running"}}function In(e={}){return new Sn(e)}function An(e){const t=String(e||"").trim().toLowerCase();return t&&"idle"!==t?"stopped"===t||"exited"===t||"failed"===t?"failed"===t?"failed":"idle":["active","busy","running","thinking","working"].includes(t)?"running":"idle":"idle"}class bn{providers=new Map;register(e){this.providers.set(e.id,e)}async refresh(e){for(const t of this.providers.values())await t.refresh(e)}}class _n{id="claude-app-session-binding";refresh(e){!function(e=In(),r=[],i=process.env.CLAUDE_HOME||s.join(n.homedir(),".claude")){const o=function(e){const r=function(e=process.env.CLAUDE_HOME||s.join(n.homedir(),".claude")){return s.join(e,"sessions")}(e);let i=[];try{i=t.readdirSync(r,{withFileTypes:!0})}catch{return new Map}const o=new Map;for(const e of i){if(!e.isFile()||!e.name.endsWith(".json"))continue;const t=en(s.join(r,e.name)),n=Number(t?.pid||s.basename(e.name,".json"));t?.sessionId&&Number.isInteger(n)&&n>0&&o.set(n,t)}return o}(i);for(const t of r){const s=Rs(t.appId,120),n=Rs(t.id,120),r=Rs(t.status,80).toLowerCase(),a=Number(t.process?.pid);if("claude"!==s||!n||r&&"running"!==r||!Number.isInteger(a)||a<=0)continue;const d=o.get(a),c=Rs(d?.sessionId,240);if(!c)continue;const p=Rs(d?.cwd||t.tty?.cwd||t.launch?.cwd,4096);e.applyAdapterSnapshot({agent:"claude",appId:s,appSessionId:n,providerSessionId:c,title:Rs(t.title,240)||"Claude",cwd:p,transcriptPath:es(c,p,i),status:An(d?.status)})}e.snapshot()}(e.registry,e.appSessions)}}class wn{id="transcript-tail-discovery";tailState=new Map;refresh(e){!function(e,s){for(const n of e.list()){if(!n.transcriptPath||"failed"===n.status)continue;let r;try{r=t.statSync(n.transcriptPath)}catch{continue}const i=s.get(n.id)||{offset:Math.max(0,r.size-65536),partial:"",calls:new Map,promptCounts:new Map};if(r.size<i.offset&&(i.offset=0,i.partial="",i.calls.clear(),i.promptCounts?.clear(),i.activeTurnId=void 0),r.size===i.offset){s.set(n.id,i);continue}const o=t.readFileSync(n.transcriptPath).subarray(i.offset).toString("utf8");i.offset=r.size,i.partial+=o;const a=i.partial.split(/\r?\n/);i.partial=a.pop()||"";for(const t of a)e.ingestTranscriptLine(n.id,t,i);s.set(n.id,i)}}(e.registry,this.tailState)}}const Tn=process.env.TASK_HANDOFF_RECEIVER_LOG||(process.env.TASK_HANDOFF_LOG_DIR?`${process.env.TASK_HANDOFF_LOG_DIR}/receiver.log`:void 0)||(Nn=S,On="receiver.log",process.env.CODEX_SANDBOX?s.join(process.cwd(),".task-handoff",On):s.join(s.dirname(Nn),On));var Nn,On;class En{registry;client;id="claude-control-sock";agent="claude";subscriptions=new Map;textByShort=new Map;constructor(e,t={list:()=>ot({op:"list"},{timeoutMs:Number(process.env.TASK_HANDOFF_CLAUDE_CONTROL_TIMEOUT_MS)||5e3}),reply:at,kill:dt,subscribe:ct}){this.registry=e,this.client=t}async refresh(e){if(!Rn("TASK_HANDOFF_AI_SESSION_SCAN",!0)||!Rn("TASK_HANDOFF_CLAUDE_CONTROL_SCAN",!0))return;const t=await this.client.list(),s=t.ok&&Array.isArray(t.jobs)?t.jobs:[],n=e.appSessions.filter(Hn),r=new Map;for(const e of n){const t=kn(e.ai?.claude?.short,80);t&&r.set(t,e)}for(const e of n){const t=kn(e.ai?.claude?.short,80);if(!t)continue;const n=s.find(e=>e.short===t);this.upsertJob(n||Mn(e)||{short:t},e)}for(const e of s)e.short&&!r.has(e.short)&&this.upsertJob(e);this.reconcileSubscriptions(new Set([...s.map(e=>kn(e.short,80)).filter(Boolean),...Array.from(r.keys())])),e.registry.reconcileAdapterSessions({agent:this.agent,appSessionIds:new Set(n.map(e=>kn(e.id,120)).filter(Boolean)),providerSessionIds:new Set(s.map(e=>kn(e.sessionId,240)).filter(Boolean)),providerShorts:new Set([...s.map(e=>kn(e.short,80)).filter(Boolean),...Array.from(r.keys())])})}async sendMessage(e,t){return this.startMessage(e,t)}async startMessage(e,t){const s=this.requireShort(e),n=await Pt(t.message,t.attachments,t=>this.client.reply(s,t.endsWith("\n")?t:`${t}\n`,{sockPath:this.controlSockForSession(e),timeoutMs:Number(process.env.TASK_HANDOFF_CLAUDE_CONTROL_TIMEOUT_MS)||5e3}));if(!n.ok)throw jt("AI_SESSION_SEND_FAILED",n.error||`Claude reply failed: ${n.code||"unknown"}`);const r=this.registry.applyRealtimeEvent(e.id,{kind:"send-ack",userPrompt:t.message,source:"control"})||e;return{session:r,provider:this.agent,action:"send",turnId:r.activeTurnId}}async steerMessage(e,t){return{...await this.startMessage(e,t),action:"steer"}}async interrupt(e){const t=this.requireShort(e),s=await this.client.kill(t,"SIGTERM",{sockPath:this.controlSockForSession(e),timeoutMs:Number(process.env.TASK_HANDOFF_CLAUDE_CONTROL_TIMEOUT_MS)||5e3});if(!s.ok)throw jt("AI_SESSION_INTERRUPT_FAILED",s.error||`Claude interrupt failed: ${s.code||"unknown"}`);return{session:this.registry.applyRealtimeEvent(e.id,{kind:"lifecycle",status:"running",phase:"unknown",source:"control"})||e,provider:this.agent,action:"interrupt"}}async resolveApproval(e,t){throw jt("AI_SESSION_APPROVAL_UNSUPPORTED","Claude daemon sessions do not expose structured approval control.",400)}stop(){for(const e of this.subscriptions.values())e();this.subscriptions.clear(),this.textByShort.clear()}upsertJob(e,t){const s=kn(e.short,80);if(!s)return;const n=kn(e.sessionId||t?.ai?.claude?.providerSessionId,240),r=kn(e.cwd||t?.ai?.claude?.cwd||t?.tty?.cwd||t?.launch?.cwd,4096),i=this.sessionForShort(s),o=zn(e.state||t?.ai?.claude?.state,{hasWorkSignal:Dn(e),isAppSession:Boolean(t||i?.appSessionId)}),a=kn(t?.ai?.claude?.controlSock,4096)||it();this.registry.applyAdapterSnapshot({source:"adapter-snapshot",agent:"claude",appId:kn(t?.appId,120)||(t?"claude":"claude-daemon"),appSessionId:kn(t?.id,120),providerSessionId:n,appBindingKeys:jn(t,s),actions:xn(o),providerMeta:{short:s,controlSock:a,pid:Number(e.pid||t?.ai?.claude?.pid)||void 0,state:kn(e.state||t?.ai?.claude?.state,80),tempo:kn(e.tempo||t?.ai?.claude?.tempo,80),cliVersion:kn(e.cliVersion||t?.ai?.claude?.cliVersion,80),source:kn(e.source||t?.ai?.claude?.source,80)},title:kn(t?.title,240)||"Claude",cwd:r,transcriptPath:es(n,r),status:o.status,phase:o.phase})&&this.ensureSubscription(s,a)}reconcileSubscriptions(e){for(const[t,s]of this.subscriptions)e.has(t)||(s(),this.subscriptions.delete(t),this.textByShort.delete(t))}ensureSubscription(e,t){if(this.subscriptions.has(e))return;this.subscriptions.set(e,()=>{});const s=this.client.subscribe(e,{tail:Number(process.env.TASK_HANDOFF_CLAUDE_SUBSCRIBE_TAIL_BYTES)||4096,options:{sockPath:t},onMessage:s=>this.applySubscribeMessage(e,t,s)});this.subscriptions.set(e,s)}applySubscribeMessage(e,t,s){const n=Cn(s.record);n&&this.upsertJob(n);const r=this.textFromSubscribeMessage(e,s);if(r){const t=this.sessionForShort(e);t&&this.registry.applyRealtimeEvent(t.id,{kind:"assistant-message",text:r,source:"realtime"})}const i=this.stateFromSubscribeMessage(s,n);if(i.observedState){const r=this.sessionForShort(e),o=i.lifecycleState?zn(i.lifecycleState,{hasWorkSignal:!1,isAppSession:Boolean(r?.appSessionId)}):void 0;this.logSubscribeMessage(e,t,s,n,i,r,o),r&&this.registry.applyAdapterSnapshot({source:"adapter-snapshot",agent:r.agent,appId:r.appId,appSessionId:r.appSessionId,providerSessionId:r.providerSessionId,appBindingKeys:r.appBindingKeys,actions:xn(o),providerMeta:{...r.providerMeta||{},short:e,controlSock:t,state:i.observedState,stateSource:i.source},status:o?.status,phase:o?.phase,cwd:r.cwd,title:r.title})}else this.logSubscribeMessage(e,t,s,n,i,this.sessionForShort(e))}sessionForShort(e){return this.registry.list().find(t=>"claude"===t.agent&&t.providerMeta?.short===e)}stateFromSubscribeMessage(e,t){const s=Cn(e.patch),n="settled"===kn(e.type,80)?e.outcome:void 0,r=[{source:"message.state",value:e.state},{source:"patch.state",value:s?.state},{source:"record.state",value:t?.state},{source:"settled.outcome",value:n}].find(e=>kn(e.value,80));return{observedState:kn(r?.value,80),lifecycleState:kn(n,80),source:r?.source,patch:s}}logSubscribeMessage(e,t,s,n,r,i,o){if(Rn("TASK_HANDOFF_DIAGNOSTIC_LOGS"))try{oe(Tn,{event:"claude_control_subscribe",short:e,controlSock:t,messageType:kn(s.type,80)||void 0,state:r.observedState||void 0,lifecycleState:r.lifecycleState||void 0,stateSource:r.source,recordState:kn(n?.state,80)||void 0,patchKeys:r.patch?Object.keys(r.patch).sort():void 0,outcome:kn(s.outcome,80)||void 0,streamLineBytes:"string"==typeof s.line?Buffer.byteLength(s.line):void 0,streamTailCount:Pn(s.streamTail).length||void 0,aiSessionId:i?.id,appSessionId:i?.appSessionId,providerSessionId:i?.providerSessionId,mappedStatus:o?.status,mappedPhase:o?.phase})}catch{}}textFromSubscribeMessage(e,t){const s=[...Pn(t.streamTail).map(e=>String(e||"")),...Pn(t.output).map(e=>String(e||"")),Fn(t.data),Fn(t.text),Fn(t.delta),Fn(t.raw)].filter(Boolean);if(0===s.length)return"";const n=(r=s.join("\n"),String(r).replace(/\x1B\][^\x07]*(?:\x07|\x1B\\)?/g,"").replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,"").replace(/\x1B[\x30-\x7E]/g,"").replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g,"")).replace(/\u0007/g,"").split(/\r?\n/).map(e=>e.trim()).filter(Boolean).filter(e=>!function(e){const t=e.replace(/[─━═_\-]{3,}/g,"").replace(/[⏺●•·]/g,"").replace(/\s+/g," ").trim();return!t||[/^claude code\b/i,/\bapi usage billing\b/i,/\/effort\b/i,/\bauto mode on\b/i,/\bshift\+tab to cycle\b/i,/\bfor agents\b/i,/^log an error\??"?$/i,/^~\/\S+/,/^\S+\s+·\s+\S+.*\b\/project\/work\b/i,/^\S+\s+·\s+\/?(?:workspace|project|Users|home)\b/i,/^(?:high|medium|low)\s*·\s*\/?effort\b/i,/^[›>]\s*try\s+["'`]/i,/^try\s+["'`]/i].some(e=>e.test(t))}(e)).slice(-8).join("\n").trim();var r;return n&&this.textByShort.get(e)!==n?(this.textByShort.set(e,n),n):""}requireShort(e){const t="string"==typeof e.providerMeta?.short?e.providerMeta.short:void 0;if(!t)throw jt("AI_SESSION_CLAUDE_SHORT_NOT_FOUND","Claude session is not bound to a daemon worker.");return t}controlSockForSession(e){return"string"==typeof e.providerMeta?.controlSock?e.providerMeta.controlSock:void 0}}function zn(e,t={}){const s=String(e||"").trim().toLowerCase();return s&&"idle"!==s?"blocked"===s?{status:"idle",phase:"unknown"}:"waiting"===s?{status:"waiting",phase:"unknown"}:"failed"===s?{status:"failed",phase:"unknown"}:["stopped","exited","completed","done"].includes(s)?{status:"idle",phase:"unknown"}:["active","busy","running","thinking","working"].includes(s)?t.isAppSession&&!t.hasWorkSignal?{status:"idle",phase:"unknown"}:{status:"running",phase:"thinking"}:{status:"idle",phase:"unknown"}:{status:"idle",phase:"unknown"}}function xn(e){return{send:!0,interrupt:"running"===e?.status||"waiting"===e?.status,approval:!1}}function Dn(e){return Boolean(kn(e.detail,500)||kn(e.intent,500)||kn(e.needs,500))}function kn(e,t=500){const s=String(e??"").replace(/\s+/g," ").trim();return s.length>t?`${s.slice(0,t-3)}...`:s}function Cn(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:void 0}function Pn(e){return Array.isArray(e)?e:[]}function Fn(e){return"string"==typeof e?e:""}function Rn(e,t=!1){const s=process.env[e];return void 0===s||""===s?t:!["0","false","no","off"].includes(String(s).toLowerCase())}function Mn(e){const t=e.ai?.claude,s=kn(t?.short,80);if(s)return{short:s,sessionId:kn(t?.providerSessionId,240)||void 0,pid:Number(t?.pid)||void 0,cwd:kn(t?.cwd||e.tty?.cwd||e.launch?.cwd,4096)||void 0,state:kn(t?.state,80)||void 0,tempo:kn(t?.tempo,80)||void 0,cliVersion:kn(t?.cliVersion,80)||void 0,source:kn(t?.source,80)||void 0}}function jn(e,t){const s=[e?.id?`app:${kn(e.id,120)}`:"",t?`claude-short:${t}`:""].filter(Boolean);return s.length?s:void 0}function Hn(e){const t=kn(e.status,80).toLowerCase();return!t||"running"===t}function Ln(e){return"allow"===e?"allowed":"deny"===e?"denied":"skipped"}function $n(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}function Un(e){const t=e.turn&&"object"==typeof e.turn?e.turn:void 0;return"string"==typeof t?.id?t.id:void 0}function qn(e){return e instanceof Error&&/no active turn/i.test(e.message)}function Kn(e){if(e instanceof Error)return e.message.match(/expected active turn id `[^`]+` but found `([^`]+)`/i)?.[1]}function Bn(e){const t=String(e.type||""),s=Array.isArray(e.activeFlags)?e.activeFlags.map(String):[];return"active"===t&&s.includes("waitingOnApproval")?{status:"waiting",phase:"approval"}:"active"===t&&s.includes("waitingOnUserInput")?{status:"waiting",phase:"thinking"}:"active"===t?{status:"running",phase:"thinking"}:"systemError"===t?{status:"failed",phase:"unknown"}:{status:"idle",phase:"unknown"}}function Vn(e,t){const s=e[t];return"string"==typeof s&&s.trim()?s:void 0}function Gn(e){const t=$n(e);return"text"===t.type&&"string"==typeof t.text?t.text.trim():""}function Wn(e){return(Array.isArray(e.content)?e.content:[]).map(Gn).filter(Boolean).join("\n").trim()}class Xn extends g.EventEmitter{child;proxyChild;socket;buffer="";nextId=1;pending=new Map;mode;requestTimeoutMs;constructor(e={}){super(),this.mode=e.socketPath?{type:"unix",command:e.command||process.env.TASK_HANDOFF_CODEX_APP_SERVER_COMMAND||process.env.TASK_HANDOFF_CODEX_COMMAND||"codex",socketPath:e.socketPath}:{type:"stdio",command:e.command||process.env.TASK_HANDOFF_CODEX_APP_SERVER_COMMAND||process.env.TASK_HANDOFF_CODEX_COMMAND||"codex"},this.requestTimeoutMs=e.requestTimeoutMs||Number(process.env.TASK_HANDOFF_CODEX_APP_SERVER_TIMEOUT_MS)||5e3}get connected(){return Boolean(this.child&&!this.child.killed||this.proxyChild&&!this.proxyChild.killed||this.socket?.readyState===y.OPEN)}async start(){if(this.connected)return;if("unix"===this.mode.type)return void await this.startUnixSocket(this.mode.command,this.mode.socketPath);const e=m.spawn(this.mode.command,["app-server","--listen","stdio://"],{stdio:["pipe","pipe","ignore"],env:process.env});this.child=e,e.stdout.on("data",e=>this.onData(e)),e.once("exit",()=>{this.child=void 0;for(const[e,t]of this.pending)clearTimeout(t.timer),t.reject(new Error("Codex app-server exited.")),this.pending.delete(e);this.emit("disconnect")}),await this.initialize()}stop(){this.child&&!this.child.killed&&(this.child.removeAllListeners(),this.child.kill("SIGTERM")),this.socket&&this.socket.readyState===y.OPEN&&(this.socket.removeAllListeners(),this.socket.close()),this.proxyChild&&!this.proxyChild.killed&&(this.proxyChild.removeAllListeners(),this.proxyChild.kill("SIGTERM"));for(const[e,t]of this.pending)clearTimeout(t.timer),t.reject(new Error("Codex app-server stopped.")),this.pending.delete(e);this.child=void 0,this.proxyChild=void 0,this.socket=void 0}async listLoadedThreadIds(){const e=[];let t;for(let s=0;s<20;s+=1){const s=await this.request("thread/loaded/list",{cursor:t,limit:100});if(Array.isArray(s.data)&&e.push(...s.data.filter(e=>"string"==typeof e)),t="string"==typeof s.nextCursor&&s.nextCursor?s.nextCursor:null,!t)break}return e}async readThread(e,t={}){const s=await this.request("thread/read",{threadId:e,includeTurns:Boolean(t.includeTurns)});return s.thread&&"object"==typeof s.thread?s.thread:void 0}async listThreads(){const e=[];let t;for(let s=0;s<10;s+=1){const s=await this.request("thread/list",{cursor:t,limit:100,sortKey:null,sortDirection:null,modelProviders:null,sourceKinds:[],archived:!1,cwd:null,useStateDbOnly:!1,searchTerm:null});if(Array.isArray(s.data)?e.push(...s.data.filter(e=>Boolean(e&&"object"==typeof e&&!Array.isArray(e)))):Array.isArray(s.threads)&&e.push(...s.threads.filter(e=>Boolean(e&&"object"==typeof e&&!Array.isArray(e)))),t="string"==typeof s.nextCursor?s.nextCursor:null,!t)break}return e}async startTurn(e,t){return{turnId:Un(await this.request("turn/start",{threadId:e,input:[{type:"text",text:t,text_elements:[]}]}))}}async steerTurn(e,t,s){const n=await this.request("turn/steer",{threadId:e,expectedTurnId:t,input:[{type:"text",text:s,text_elements:[]}]});return{turnId:"string"==typeof n.turnId?n.turnId:t}}async interruptTurn(e,t){await this.request("turn/interrupt",{threadId:e,turnId:t})}async resumeThread(e){const t=await this.request("thread/resume",{threadId:e});return t.thread&&"object"==typeof t.thread?t.thread:void 0}async respondToApproval(e,t){this.sendResponse(e.id,function(e,t){if("command"===e.kind)return{decision:"allow"===t?"accept":"skip"===t?"cancel":"decline"};if("file-change"===e.kind)return{decision:"allow"===t?"accept":"skip"===t?"cancel":"decline"};if("allow"!==t)return{permissions:{},scope:"turn"};const s=$n(e.params.permissions),n=$n(s.fileSystem);return{permissions:{...s.network?{network:s.network}:{},...Object.keys(n).length?{fileSystem:{...Array.isArray(n.read)?{read:n.read}:{},...Array.isArray(n.write)?{write:n.write}:{},...Array.isArray(n.entries)?{entries:n.entries}:{},...n.globScanMaxDepth?{globScanMaxDepth:n.globScanMaxDepth}:{}}}:{}},scope:"turn"}}(e,t))}request(e,t){const s=this.child?.stdin.writable,n=this.socket?.readyState===y.OPEN;if(!s&&!n)return Promise.reject(new Error("Codex app-server is not connected."));const r=this.nextId++,i=JSON.stringify({id:r,method:e,params:t});return new Promise((t,s)=>{const o=setTimeout(()=>{this.pending.delete(r),s(new Error(`Codex app-server request timed out: ${e}`))},this.requestTimeoutMs);this.pending.set(r,{resolve:t,reject:s,timer:o}),n?this.socket?.send(i):this.child?.stdin.write(`${i}\n`)})}async initialize(){await this.request("initialize",{clientInfo:{name:"task-handoff",version:"1.0.0"},capabilities:{experimentalApi:!0}}),this.notify("initialized",{})}notify(e,t){const s=JSON.stringify({method:e,params:t});this.socket?.readyState!==y.OPEN?this.child?.stdin.writable&&this.child.stdin.write(`${s}\n`):this.socket.send(s)}sendResponse(e,t){const s=JSON.stringify({id:e,result:t});this.socket?.readyState!==y.OPEN?this.child?.stdin.writable&&this.child.stdin.write(`${s}\n`):this.socket.send(s)}startUnixSocket(e,t){return new Promise((s,n)=>{const r=m.spawn(e,["app-server","proxy","--sock",t],{stdio:["pipe","pipe","ignore"],env:process.env});this.proxyChild=r;const i=new y("ws://localhost/rpc",{createConnection:()=>function(e){const t=new a.Duplex({read(){e.stdout.resume()},write(t,s,n){e.stdin.write(t,n)},final(t){e.stdin.end(t)},destroy(t,s){e.killed||e.kill("SIGTERM"),s(t)}});e.stdout.on("data",s=>{t.push(s)||e.stdout.pause()}),e.stdout.on("end",()=>t.push(null)),e.stdout.on("error",e=>t.destroy(e)),e.stdin.on("error",e=>t.destroy(e));const s=t;return s.setTimeout=()=>t,s.setNoDelay=()=>t,s.setKeepAlive=()=>t,s}(r),perMessageDeflate:!1});this.socket=i;let o=!1;const d=e=>{o||(o=!0,this.socket=void 0,this.proxyChild=void 0,r.killed||r.kill("SIGTERM"),n(e))};r.once("error",d),r.once("exit",(e,t)=>{o?this.proxyChild===r&&(this.proxyChild=void 0,this.emit("disconnect")):d(new Error(`Codex app-server proxy exited before connect: code=${e??"null"} signal=${t??"null"}.`))}),i.once("error",d),i.once("open",()=>{o=!0,r.off("error",d),i.off("error",d),i.on("message",e=>this.handleLine(e.toString())),i.once("close",()=>{this.socket=void 0,this.proxyChild===r&&(this.proxyChild=void 0),r.killed||r.kill("SIGTERM");for(const[e,t]of this.pending)clearTimeout(t.timer),t.reject(new Error("Codex app-server disconnected.")),this.pending.delete(e);this.emit("disconnect")}),this.initialize().then(()=>s()).catch(e=>{i.close(),n(e)})})})}onData(e){this.buffer+=e.toString("utf8");let t=this.buffer.indexOf("\n");for(;t>=0;){const e=this.buffer.slice(0,t).trim();this.buffer=this.buffer.slice(t+1),e&&this.handleLine(e),t=this.buffer.indexOf("\n")}this.buffer.length>8388608&&(this.buffer="")}handleLine(e){let t;try{t=JSON.parse(e)}catch{return}const s=Number(t.id);if(Number.isInteger(s)){const e=this.pending.get(s);if(e){clearTimeout(e.timer),this.pending.delete(s);const n=t.error&&"object"==typeof t.error?t.error:void 0;return void(n?e.reject(new Error(String(n.message||"Codex app-server error."))):e.resolve(t.result&&"object"==typeof t.result?t.result:{}))}}const n=String(t.method||""),r=t.params&&"object"==typeof t.params?t.params:{};if(Number.isInteger(s)){const e=function(e,t,s){if("item/commandExecution/requestApproval"===t){const n=Vn(s,"threadId");if(!n)return;const r=Vn(s,"command"),i=Vn(s,"reason");return{id:e,method:t,kind:"command",threadId:n,turnId:Vn(s,"turnId"),itemId:Vn(s,"itemId"),summary:i||(r?`Approve command: ${r}`:"Codex is requesting command approval."),params:s}}if("item/fileChange/requestApproval"===t){const n=Vn(s,"threadId");if(!n)return;const r=Vn(s,"grantRoot");return{id:e,method:t,kind:"file-change",threadId:n,turnId:Vn(s,"turnId"),itemId:Vn(s,"itemId"),summary:Vn(s,"reason")||(r?`Approve file changes under ${r}`:"Codex is requesting file change approval."),params:s}}if("item/permissions/requestApproval"===t){const n=Vn(s,"threadId");if(!n)return;return{id:e,method:t,kind:"permissions",threadId:n,turnId:Vn(s,"turnId"),itemId:Vn(s,"itemId"),summary:Vn(s,"reason")||"Codex is requesting additional permissions.",params:s}}}(s,n,r);return void(e&&this.emit("event",{type:"approval-request",request:e}))}const i=function(e,t){if("thread/started"===e){const e=t.thread&&"object"==typeof t.thread?t.thread:void 0;return e?{type:"thread",thread:e}:void 0}if("thread/status/changed"===e&&"string"==typeof t.threadId)return{type:"thread-status",threadId:t.threadId,status:t.status||{}};if("thread/closed"===e&&"string"==typeof t.threadId)return{type:"thread-closed",threadId:t.threadId};if("turn/started"===e&&"string"==typeof t.threadId){const e=t.turn&&"object"==typeof t.turn?t.turn:{};return{type:"turn-started",threadId:t.threadId,turnId:"string"==typeof e.id?e.id:void 0}}if("turn/completed"===e&&"string"==typeof t.threadId){const e=t.turn&&"object"==typeof t.turn?t.turn:{},s=function(e){const t=$n(e),s="string"==typeof t.message?t.message.trim():"",n="string"==typeof t.additionalDetails?t.additionalDetails.trim():"";return s&&n?`${s}\n\n${n}`:s||n||void 0}(e.error);return{type:"turn-completed",threadId:t.threadId,turnId:"string"==typeof e.id?e.id:void 0,status:"string"==typeof e.status?e.status:void 0,error:s}}if(("item/started"===e||"item/completed"===e)&&"string"==typeof t.threadId){const e=t.item&&"object"==typeof t.item?t.item:{};if("userMessage"===e.type){const s=Wn(e);return s?{type:"user-message",threadId:t.threadId,turnId:"string"==typeof t.turnId?t.turnId:void 0,text:s}:void 0}}if("item/agentMessage/delta"===e&&"string"==typeof t.threadId&&"string"==typeof t.delta)return{type:"agent-message-delta",threadId:t.threadId,turnId:"string"==typeof t.turnId?t.turnId:void 0,itemId:"string"==typeof t.itemId?t.itemId:void 0,delta:t.delta};if("item/completed"===e&&"string"==typeof t.threadId){const e=t.item&&"object"==typeof t.item?t.item:{};if("agentMessage"===e.type&&"string"==typeof e.text)return{type:"agent-message-completed",threadId:t.threadId,turnId:"string"==typeof t.turnId?t.turnId:void 0,text:e.text}}}(n,r);i&&this.emit("event",i)}}class Jn{registry;id="codex-app-server";agent="codex";client;started=!1;retryAfter=0;activeSocketPath;appSessions=[];agentMessageBuffers=new Map;approvals=new Ft;injectedClient;options;constructor(e,t={}){this.registry=e,"start"in t&&"listLoadedThreadIds"in t?(this.injectedClient=t,this.options={allowSpawn:!0},this.attachClient(this.injectedClient)):this.options=t}async sync(e=[]){const t=this.setAppSessions(e),s=this.activeSocketPath;if(!this.injectedClient&&!t&&!this.options.allowSpawn)return void this.stop();this.injectedClient||this.client&&s===t||(this.stop(),this.client=this.createClient(t?{socketPath:t}:{}),this.attachClient(this.client)),this.activeSocketPath=t;const n=this.client;if(n){if(!this.started){if(Date.now()<this.retryAfter)return;try{await n.start(),this.started=!0}catch{return void(this.retryAfter=Date.now()+3e4)}}try{const e=await n.listLoadedThreadIds(),t=new Map;if(n.listThreads)for(const e of await n.listThreads()){const s="string"==typeof e.id?e.id:void 0;s&&t.set(s,e)}for(const s of e){let e=t.get(s);if(n.readThread)try{e={...e||{},...await n.readThread(s,{includeTurns:!0})}}catch{e||={id:s}}this.upsertThread(e||{id:s},{bindAppSession:!0})}}catch{this.started=!1,n.stop()}}}async refresh(e){await this.sync(e.appSessions)}stop(){this.client?.stop(),this.injectedClient||(this.client=void 0),this.started=!1,this.activeSocketPath=void 0,this.agentMessageBuffers.clear(),this.retryAfter=0}async sendMessage(e,t){const s=await this.requireReadyClient(),n=this.requireThreadId(e),r=await Pt(t.message,t.attachments,t=>this.steerOrStartTurnForCompatibility(s,n,e,t)),i=this.registry.applyRealtimeEvent(e.id,{kind:r.started?"send-ack":"user-message",activeTurnId:r.turnId,providerTurnId:r.turnId,userPrompt:t.message,source:"control"})||e;return{session:i,provider:this.agent,action:r.started?"send":"steer",turnId:i.activeTurnId,providerTurnId:r.turnId}}async startMessage(e,t){const s=await this.requireReadyClient(),n=this.requireThreadId(e),r=await Pt(t.message,t.attachments,e=>this.startTurn(s,n,e)),i=this.registry.applyRealtimeEvent(e.id,{kind:"send-ack",activeTurnId:r.turnId,providerTurnId:r.turnId,userPrompt:t.message,source:"control"})||e;return{session:i,provider:this.agent,action:"send",turnId:i.activeTurnId,providerTurnId:r.turnId}}async steerMessage(e,t){const s=await this.requireReadyClient(),n=this.requireThreadId(e),r=await Pt(t.message,t.attachments,t=>this.steerTurn(s,n,e,t)),i=this.registry.applyRealtimeEvent(e.id,{kind:"user-message",activeTurnId:r.turnId,providerTurnId:r.turnId,userPrompt:t.message,source:"control"})||e;return{session:i,provider:this.agent,action:"steer",turnId:i.activeTurnId,providerTurnId:r.turnId}}async steerTurn(e,t,s,n){if(!s.activeTurnId)throw jt("AI_SESSION_NO_ACTIVE_TURN","AI session has no active turn to steer.",409);if(!e.steerTurn)throw jt("AI_SESSION_STEER_UNSUPPORTED","Codex app-server client does not support turn steering.");try{return{turnId:(await e.steerTurn(t,s.activeTurnId,n)).turnId||s.activeTurnId}}catch(s){const r=Kn(s);if(r)return{turnId:(await e.steerTurn(t,r,n)).turnId||r};throw s}}async steerOrStartTurnForCompatibility(e,t,s,n){if(!Boolean(s.activeTurnId&&("running"===s.status||"waiting"===s.status)))return this.startTurn(e,t,n);try{return{...await this.steerTurn(e,t,s,n),started:!1}}catch(s){if(!qn(s))throw s;return this.startTurn(e,t,n)}}async startTurn(e,t,s){if(!e.startTurn)throw jt("AI_SESSION_SEND_UNSUPPORTED","Codex app-server client does not support starting turns.");return{turnId:(await e.startTurn(t,s)).turnId,started:!0}}async interrupt(e){const t=await this.requireReadyClient(),s=this.requireThreadId(e),n=e.activeTurnId;if(!n)throw jt("AI_SESSION_NO_ACTIVE_TURN","AI session has no active turn to interrupt.");if(!t.interruptTurn)throw jt("AI_SESSION_INTERRUPT_UNSUPPORTED","Codex app-server client does not support turn interruption.");try{await t.interruptTurn(s,n)}catch(r){const i=Kn(r);if(i)return await t.interruptTurn(s,i),{session:this.registry.applyRealtimeEvent(e.id,{kind:"lifecycle",activeTurnId:i,status:"running",phase:"unknown",source:"control"})||e,provider:this.agent,action:"interrupt",providerTurnId:i};if(!qn(r))throw r;return{session:this.registry.applyRealtimeEvent(e.id,{kind:"turn-completed",activeTurnId:void 0,status:"idle",phase:"unknown",text:"Codex turn is no longer active.",source:"control"})||e,provider:this.agent,action:"interrupt",providerTurnId:n}}return{session:this.registry.applyRealtimeEvent(e.id,{kind:"lifecycle",status:"running",phase:"unknown",source:"control"})||e,provider:this.agent,action:"interrupt",providerTurnId:n}}async resolveApproval(e,t){if(await this.resolveAttachedApproval(e,t))return{session:this.registry.applyRealtimeEvent(e.id,{kind:"assistant-message",status:"skip"===t?"idle":"running",phase:"skip"===t?"unknown":"thinking",text:`Codex approval ${Ln(t)}.`,source:"control"})||e,provider:this.agent,action:"approval",decision:t};throw jt("AI_SESSION_APPROVAL_NOT_ATTACHED","Codex approval request is not attached to this control connection. The app-server did not replay a pending approval request for this session.",409)}async resolveAttachedApproval(e,t){return await this.approvals.resolveForSession(e.id,t)||(await this.attachPendingApprovalRequest(e),this.approvals.resolveForSession(e.id,t))}async attachPendingApprovalRequest(e){const t=await this.requireReadyClient();if(!t.resumeThread||this.approvals.latestForSession(e.id))return;const s=this.requireThreadId(e),n=await t.resumeThread(s);n&&this.upsertThread(n,{bindAppSession:!0}),await async function(e){const t=Date.now()+1e3;for(;Date.now()<t;){if(e())return!0;await new Promise(e=>setTimeout(e,25))}return e()}(()=>Boolean(this.approvals.latestForSession(e.id)))}attachClient(e){e.on("event",e=>this.applyProviderEvent(e)),e.on("disconnect",()=>{this.started=!1,this.retryAfter=Date.now()+3e4}),this.client=e}createClient(e){return this.options.createClient?this.options.createClient(e):new Xn(e)}codexAppServerSocketPath(e){return e.map(e=>e.ai?.appServer?.socketPath).find(e=>"string"==typeof e&&e.trim().length>0)}setAppSessions(e){return this.appSessions=e,this.codexAppServerSocketPath(e)}appSessionIdForThread(e){if(this.activeSocketPath)for(const t of this.appSessions)if("string"==typeof t.id&&"codex"===t.appId&&t.ai?.appServer?.socketPath===this.activeSocketPath&&"running"===t.status){if(t.ai?.activeThreadId===e)return t.id;if(Array.isArray(t.ai?.threadIds)&&t.ai.threadIds.includes(e))return t.id}}applyProviderEvent(e){if("thread"===e.type)return void this.upsertThread(e.thread,{bindAppSession:!0});if("approval-request"===e.type)return void this.applyApprovalRequest(e.request);const t=this.registry.list().find(t=>"codex"===t.agent&&t.providerSessionId===e.threadId);if(t)if("thread-closed"!==e.type){if("thread-status"===e.type){const s=Bn(e.status);return void this.registry.applyRealtimeEvent(t.id,{kind:"lifecycle",activeTurnId:t.activeTurnId,status:s.status,phase:s.phase,source:"realtime"})}if("turn-started"!==e.type)if("user-message"!==e.type)if("turn-completed"!==e.type){if("agent-message-delta"===e.type){const s=`${e.threadId}:${e.turnId||""}:${e.itemId||""}`,n=`${this.agentMessageBuffers.get(s)||""}${e.delta}`;return this.agentMessageBuffers.set(s,n),void this.registry.applyRealtimeEvent(t.id,{kind:"assistant-message",activeTurnId:e.turnId||t.activeTurnId,providerTurnId:e.turnId||t.activeTurnId,text:n,source:"realtime"})}"agent-message-completed"===e.type&&this.registry.applyRealtimeEvent(t.id,{kind:"assistant-message",activeTurnId:e.turnId||t.activeTurnId,providerTurnId:e.turnId||t.activeTurnId,text:e.text,status:t.status,source:"realtime"})}else this.registry.applyRealtimeEvent(t.id,{kind:"turn-completed",activeTurnId:e.turnId,providerTurnId:e.turnId,status:"failed"===e.status?"failed":"idle",error:"failed"===e.status?e.error:void 0,source:"realtime"});else this.registry.applyRealtimeEvent(t.id,{kind:"user-message",activeTurnId:e.turnId||t.activeTurnId,providerTurnId:e.turnId||t.activeTurnId,userPrompt:e.text,source:"realtime"});else this.registry.applyRealtimeEvent(t.id,{kind:"turn-started",activeTurnId:e.turnId,providerTurnId:e.turnId,source:"realtime"})}else this.registry.applyRealtimeEvent(t.id,{kind:"turn-completed",activeTurnId:t.activeTurnId,status:"idle",phase:"unknown",text:"Codex thread closed.",source:"realtime"})}upsertThread(e,t){const s="string"==typeof e.id?e.id:void 0;if(!s||!0===e.ephemeral)return;const n=Bn(e.status||{}),r=t.bindAppSession?this.appSessionIdForThread(s):void 0,i=function(e){let t,s;const n=[],r=Array.isArray(e.turns)?e.turns:[];for(const[e,i]of r.entries()){const r=$n(i),o={id:"string"==typeof r.id&&r.id.trim()?r.id.trim():`turn_${e}`,status:"completed",revision:0},a=Array.isArray(r.items)?r.items:[];for(const e of a){const n=$n(e);if("userMessage"===n.type){const e=Wn(n);e&&!Ht(e)&&(t=e,o.userPrompt=e)}else"agentMessage"===n.type&&"string"==typeof n.text&&n.text.trim()&&(s=n.text.trim(),o.lastMessage=s,o.summary=s.length>1e3?`${s.slice(0,997)}...`:s)}(o.userPrompt||o.lastMessage||o.summary)&&n.push(o)}return{userPrompt:t,turns:n,summary:s,lastMessage:s}}(e);this.registry.applyAdapterSnapshot({source:"adapter-snapshot",agent:"codex",appId:r?"codex":"codex-app-server",appSessionId:r,providerSessionId:s,appBindingKeys:r?[`app:${r}`]:void 0,actions:{send:!0,interrupt:"running"===n.status||"waiting"===n.status,approval:"waiting"===n.status&&"approval"===n.phase},title:"string"==typeof e.name?e.name:void 0,cwd:"string"==typeof e.cwd?e.cwd:void 0,userPrompt:i.userPrompt,turns:i.turns,summary:i.summary,lastMessage:i.lastMessage,status:n.status,phase:n.phase,replaceActivity:!0})}applyApprovalRequest(e){const t=this.registry.list().find(t=>"codex"===t.agent&&t.providerSessionId===e.threadId);if(!t)return;const s=this.client;s?.respondToApproval&&(this.approvals.register({id:`${e.threadId}:${e.id}`,sessionId:t.id,provider:this.agent,summary:e.summary,metadata:{kind:e.kind,requestId:e.id,itemId:e.itemId},resolve:t=>s.respondToApproval?.(e,t)}),this.registry.applyRealtimeEvent(t.id,{kind:"approval-requested",activeTurnId:e.turnId||t.activeTurnId,providerTurnId:e.turnId||t.activeTurnId,status:"waiting",phase:"approval",summary:e.summary,counters:{approvals:1},source:"realtime"}))}async requireReadyClient(){const e=this.client;if(!e)throw jt("AI_SESSION_CONTROL_NOT_CONNECTED","Codex app-server is not connected.",503);return this.started||(await e.start(),this.started=!0),e}requireThreadId(e){if(!e.providerSessionId)throw jt("AI_SESSION_THREAD_NOT_FOUND","AI session is not bound to a Codex thread.");return e.providerSessionId}}class Yn{registeredInstanceId="";timer;config;snapshotProvider;fetchImpl;constructor(e,t,s=fetch){this.config=e,this.snapshotProvider=t,this.fetchImpl=s}enabled(){return Boolean("controlled"===this.config.controlMode&&this.config.nodeAgentUrl&&this.config.registrationToken&&this.config.instanceId)}async start(){this.enabled()&&(await this.register(),this.timer=setInterval(()=>{this.heartbeat().catch(e=>{console.warn(`node agent heartbeat failed: ${e instanceof Error?e.message:String(e)}`)})},this.config.heartbeatIntervalMs))}stop(){this.timer&&(clearInterval(this.timer),this.timer=void 0)}async register(){const e=await this.snapshotProvider(),t=this.requiredInstanceId(),s=await this.request(`node-agent/instances/${encodeURIComponent(t)}/register`,{instanceId:this.config.instanceId,name:this.config.instanceName,projectId:this.config.projectId,nodeId:this.config.nodeId,runtimeId:this.config.runtimeId,imageId:this.config.imageId,instanceVersion:e.instanceVersion,protocolVersion:e.protocolVersion,build:e.build,controlMode:"controlled",capabilities:e.capabilities,target:e.target,workspace:e.workspace});this.registeredInstanceId=String(s.id||t),await this.heartbeat()}async heartbeat(){const e=this.registeredInstanceId||this.config.instanceId;if(!e)return;const t=await this.snapshotProvider();await this.request(`node-agent/instances/${encodeURIComponent(e)}/heartbeat`,{status:t.status,health:t.health,protocolVersion:t.protocolVersion,build:t.build,capabilities:t.capabilities,receiver:t.receiver,apps:t.apps,aiSessions:t.aiSessions,workspace:t.workspace,target:t.target})}async request(e,t){const s=this.config.nodeAgentUrl?.replace(/\/$/,"");if(!s)throw new Error("Node agent URL is required.");const n=await this.fetchImpl(`${s}/api/${e}`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${this.config.registrationToken}`},body:JSON.stringify((r=t,Object.fromEntries(Object.entries(r).filter(([,e])=>void 0!==e))))});var r;const i=await n.json().catch(()=>({}));if(!n.ok)throw new Error(i.error?.message||`Node agent request failed with HTTP ${n.status}`);return i.data||{}}requiredInstanceId(){if(!this.config.instanceId)throw new Error("Instance id is required for controlled mode registration.");return this.config.instanceId}}function Qn(e,t){return e&&"object"==typeof e&&"code"in e?String(e.code):t}function Zn(e){return e instanceof Error?e.message:String(e)}const er=/^(telegram|wechat|dingding)\.([^.]+)\.json$/;function tr(e){return("string"==typeof e?e.trim():"")||void 0}function sr(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e))}function nr(e){const t=e.secrets||{};return"telegram"===e.channel?sr({enabled:e.enabled,token:tr(t.botToken),allowedUserIds:e.allowedUserIds,defaultChatId:tr(e.defaultChatId)}):"wechat"===e.channel?sr({enabled:e.enabled,token:tr(t.token)||tr(t.webhookUrl),baseUrl:tr(t.baseUrl),contextToken:tr(t.contextToken),updatesBuf:tr(e.state?.updatesBuf),defaultChatId:tr(e.defaultChatId)}):sr({enabled:e.enabled,clientId:tr(t.clientId),clientSecret:tr(t.clientSecret),corpId:tr(t.corpId),robotCode:tr(t.robotCode),cardTemplateId:tr(t.cardTemplateId),cardCallbackRouteKey:tr(t.cardCallbackRouteKey),cardUserIdType:t.cardUserIdType,allowedUserIds:e.allowedUserIds,defaultChatId:tr(e.defaultChatId)})}function rr(e){try{const s=JSON.parse(t.readFileSync(e,"utf8"));return s&&"object"==typeof s&&!Array.isArray(s)?s:{}}catch{return{}}}function ir(e,n){const i=rr(n),o=i.chatTools&&"object"==typeof i.chatTools&&!Array.isArray(i.chatTools)?i.chatTools:{},a=i.chatBindings&&"object"==typeof i.chatBindings&&!Array.isArray(i.chatBindings)?i.chatBindings:{},d={...o,[e.channel]:{...o[e.channel]||{},[e.instanceId]:nr(e)}},c=function(e){const t=tr(e.defaultChatId),s=e.bindings||{},n={};for(const[e,t]of Object.entries(s))n[e]=sr({conversationId:t.conversationId,contextToken:tr(t.contextToken)});return t&&!n[t]&&(n[t]={conversationId:1}),Object.keys(n).length>0?n:void 0}(e),p={...a,[e.channel]:{...a[e.channel]||{},...c?{[e.instanceId]:c}:{}}},u={...i,chatTools:d,chatBindings:p};return function(e,n){t.mkdirSync(s.dirname(e),{recursive:!0}),r.sync(e,`${JSON.stringify(n,null,2)}\n`,{mode:384})}(n,u),u}function or(e,n){if(!t.existsSync(e))return rr(n);let r=rr(n);for(const i of t.readdirSync(e,{withFileTypes:!0})){if(!i.isFile())continue;const o=i.name.match(er);if(o)try{const a=JSON.parse(t.readFileSync(s.join(e,i.name),"utf8"));if(a.channel!==o[1]||a.instanceId!==o[2])continue;r=ir(a,n)}catch{continue}}return r}function ar(e){return e.startsWith("ai-session.")||e.startsWith("ai.session.")?"ai.sessions":e.startsWith("app-session.")?"app.sessions":e.startsWith("receiver.")?"receiver":e.startsWith("conversation.")?"conversations":e.startsWith("trigger.")?"triggers":e.startsWith("channel.")?"channels":e.startsWith("instance.")?"instances":e.startsWith("node.")?"nodes":e.startsWith("project.")?"projects":e.startsWith("model.")?"models":e.startsWith("image.")?"images":"system"}class dr{clients=new Set;seq=0;connect(e){const t=e;t.topics=new Set(["*"]),this.clients.add(e),e.on("close",()=>{this.clients.delete(e)}),e.on("message",e=>{const s=function(e){try{const t=JSON.parse(String(e||"{}"));return t&&"object"==typeof t?t:void 0}catch{return}}(e);"subscribe"===s?.type&&(t.topics=new Set(s.topics?.length?s.topics:["*"]))})}publish(e,t){const s=this.createEvent(e,t),n=s.topic,r=JSON.stringify(s);for(const t of this.clients)t.readyState===t.OPEN&&cr(t.topics,n,e)&&t.send(r);return s}send(e,t,s){const n=this.createEvent(t,s);return e.send(JSON.stringify(n)),n}createEvent(e,t){return{v:1,id:`evt_${Date.now().toString(36)}_${Math.random().toString(16).slice(2)}`,seq:++this.seq,type:e,topic:ar(e),createdAt:(new Date).toISOString(),payload:t}}}function cr(e,t,s){return!e||e.has("*")||e.has(t)||e.has(s)}const pr=i.z.object({type:i.z.literal("result"),result:i.z.unknown(),attachments:i.z.array(i.z.object({id:i.z.string(),kind:i.z.enum(["image","file"]),path:i.z.string(),name:i.z.string(),mime:i.z.string().optional(),size:i.z.number().nonnegative().optional()})).optional(),conversationId:i.z.number().int().positive().optional(),timeoutMs:i.z.number().positive().optional(),source:i.z.enum(["cli","mcp"]).optional(),kind:i.z.enum(["task","approval"]).optional(),cwd:i.z.string().optional(),sessionIds:i.z.record(i.z.string(),i.z.string()).optional()}),ur=i.z.discriminatedUnion("action",[i.z.object({type:i.z.literal("control"),action:i.z.literal("pending.list"),requestId:i.z.string().optional()}),i.z.object({type:i.z.literal("control"),action:i.z.literal("pending.reply"),requestId:i.z.string().optional(),id:i.z.number().int().positive(),markdown:i.z.string()}),i.z.object({type:i.z.literal("control"),action:i.z.literal("pending.drop"),requestId:i.z.string().optional(),id:i.z.number().int().positive()}),i.z.object({type:i.z.literal("control"),action:i.z.literal("pending.approval"),requestId:i.z.string().optional(),id:i.z.number().int().positive(),decision:i.z.enum(["allow","deny","skip"])}),i.z.object({type:i.z.literal("control"),action:i.z.literal("receiver.message"),requestId:i.z.string().optional(),channel:i.z.string().trim().min(1).max(80),chatSessionId:i.z.string().trim().min(1).max(240),userId:i.z.string().trim().max(240).optional(),text:i.z.string().trim().min(1).max(2e4),attachments:i.z.array(i.z.record(i.z.string(),i.z.unknown())).default([]),conversationId:i.z.number().int().positive().optional()})]);i.z.union([pr,ur]);const lr=i.z.object({type:i.z.literal("reply"),value:i.z.string()}),mr=i.z.object({type:i.z.literal("error"),message:i.z.string()}),hr=i.z.object({type:i.z.literal("control.response"),requestId:i.z.string().optional(),ok:i.z.boolean(),data:i.z.unknown().optional(),error:i.z.object({code:i.z.string(),message:i.z.string()}).optional()});function gr(e){return`${JSON.stringify(e)}\n`}i.z.union([lr,mr,hr]);class fr{socketPath;constructor(e){this.socketPath=e}pendingList(){return this.request({type:"control",action:"pending.list"})}reply(e,t){return this.request({type:"control",action:"pending.reply",id:e,markdown:t})}drop(e){return this.request({type:"control",action:"pending.drop",id:e})}approval(e,t){return this.request({type:"control",action:"pending.approval",id:e,decision:t})}message(e){return this.request({type:"control",action:"receiver.message",channel:e.channel,chatSessionId:e.chatSessionId,userId:e.userId,text:e.text,attachments:e.attachments||[],conversationId:e.conversationId})}request(e){const t=h.randomUUID();return new Promise((s,n)=>{const r=o.createConnection(this.socketPath),i=setTimeout(()=>{r.destroy(),n(Object.assign(new Error("Receiver control request timed out."),{code:"RECEIVER_CONTROL_TIMEOUT"}))},5e3),a=e=>{clearTimeout(i),r.end(),e()};r.once("connect",()=>{r.write(gr({...e,requestId:t}))}),function(e,t,s){let n="";e.on("data",r=>{n+=r.toString("utf8");let i=n.indexOf("\n");for(;-1!==i;){const r=n.slice(0,i);if(n=n.slice(i+1),i=n.indexOf("\n"),r.trim())try{const n=t.safeParse(JSON.parse(r));if(!n.success){e.write(gr({type:"error",message:"Invalid message shape."}));continue}s(n.data)}catch(t){e.write(gr({type:"error",message:"Invalid JSON message."}))}}})}(r,hr,e=>{e.requestId===t&&a(()=>{if(e.ok)s(e.data);else{const t=Object.assign(new Error(e.error?.message||"Receiver control request failed."),{code:e.error?.code||"RECEIVER_CONTROL_FAILED"});n(t)}})}),r.once("error",e=>{a(()=>{n(Object.assign(new Error(`Receiver is not available at ${this.socketPath}: ${e.message}`),{code:"RECEIVER_UNAVAILABLE"}))})}),r.once("close",()=>{clearTimeout(i)})})}}class yr extends g.EventEmitter{socketPath;child;statusValue={running:!1};logPath;exitPromise;constructor(e,t){super(),this.socketPath=e,this.logPath=t?s.join(t,"receiver.log"):void 0}status(){return{...this.statusValue}}start(){if(this.child&&!this.child.killed&&this.statusValue.running)return this.status();const e=process.env.TASK_HANDOFF_CLI_PATH||s.resolve(__dirname,"cli.js");let t;return this.child=m.spawn(process.execPath,[e,"receiver","--headless","--socket",this.socketPath],{env:{...process.env,TASK_HANDOFF_RECEIVER_HEADLESS:"1"},stdio:["ignore","pipe","pipe"]}),this.statusValue={running:!0,pid:this.child.pid,startedAt:(new Date).toISOString(),exitedAt:void 0,exitCode:void 0,signal:void 0},this.appendLog(`\n[${this.statusValue.startedAt}] receiver started pid=${this.child.pid}\n`),this.child.stdout?.on("data",e=>this.handleLog(e)),this.child.stderr?.on("data",e=>this.handleLog(e)),this.exitPromise=new Promise(e=>{t=e}),this.child.on("exit",(e,s)=>{const n=(new Date).toISOString();this.statusValue={...this.statusValue,running:!1,exitedAt:n,exitCode:e,signal:s},this.appendLog(`[${n}] receiver exited code=${e??"null"} signal=${s??"null"}\n`),this.emit("exit",this.status()),this.child=void 0,t?.(this.status())}),this.emit("start",this.status()),this.status()}stop(){return this.child&&this.statusValue.running?(this.child.kill("SIGTERM"),this.status()):this.status()}async stopAndWait(e=2e3){if(!this.child||!this.statusValue.running)return this.status();const t=this.exitPromise;return this.stop(),t?await Promise.race([t,new Promise(t=>{setTimeout(()=>t(this.status()),e)})]):this.status()}readLogs(e=65536){const s=this.logPath;if(!s||!t.existsSync(s))return{logPath:s,maxBytes:e,size:0,truncated:!1,content:""};const n=t.statSync(s),r=Math.max(0,n.size-e),i=t.openSync(s,"r");try{const o=Buffer.alloc(n.size-r);return t.readSync(i,o,0,o.length,r),{logPath:s,maxBytes:e,size:n.size,updatedAt:n.mtime.toISOString(),truncated:r>0,content:o.toString("utf8")}}finally{t.closeSync(i)}}handleLog(e){const t=String(e);this.appendLog(t),this.emit("log",t)}appendLog(e){this.logPath&&(t.mkdirSync(s.dirname(this.logPath),{recursive:!0}),t.appendFileSync(this.logPath,e))}}function vr(){return process.env.HOME||n.homedir()||"/home/agent"}function Sr(){return process.env.TASK_HANDOFF_WORKSPACE||process.env.WORKSPACE||"/workspace"}function Ir(){const e=vr(),t=function(){const e=[s.join(vr(),".config","chromium")],t=process.env.TASK_HANDOFF_CHROMIUM_USER_DATA_DIR?.trim();return t&&!e.includes(t)&&e.push(t),e}().map((e,t)=>({id:0===t?"chromium-profile":`chromium-profile-${t+1}`,type:"dir",projectPath:0===t?"chromium":`chromium-${t+1}`,containerPath:e}));return[{id:"codex",label:"Codex",projectRoot:".task-handoff/configs/codex",items:[{id:"config",type:"file",projectPath:"config.toml",containerPath:s.join(e,".codex","config.toml")},{id:"auth",type:"file",projectPath:"auth.json",containerPath:s.join(e,".codex","auth.json")},{id:"agents",type:"file",projectPath:"AGENTS.md",containerPath:s.join(e,".codex","AGENTS.md")},{id:"skills",type:"dir",projectPath:"skills",containerPath:s.join(e,".codex","skills")}]},{id:"claude",label:"Claude",projectRoot:".task-handoff/configs/claude",items:[{id:"claude-json",type:"file",projectPath:".claude.json",containerPath:s.join(e,".claude.json")},{id:"settings",type:"file",projectPath:"settings.json",containerPath:s.join(e,".claude","settings.json")},{id:"claude-md",type:"file",projectPath:"CLAUDE.md",containerPath:s.join(e,".claude","CLAUDE.md")},{id:"commands",type:"dir",projectPath:"commands",containerPath:s.join(e,".claude","commands")},{id:"agents",type:"dir",projectPath:"agents",containerPath:s.join(e,".claude","agents")},{id:"skills",type:"dir",projectPath:"skills",containerPath:s.join(e,".claude","skills")}]},{id:"browser",label:"Browser",projectRoot:".task-handoff/configs/browser",items:t}]}function Ar(e,n,r){return t.existsSync(n)?(t.mkdirSync(s.dirname(r),{recursive:!0}),"dir"===e?t.cpSync(n,r,{recursive:!0,force:!0}):t.copyFileSync(n,r),"copied"):"skipped_missing_source"}function br(e,t,n){const r=n||Ir().find(e=>e.id===t);if(!r){const e=new Error(`Config sync preset ${t} was not found.`);throw Object.assign(e,{statusCode:404,code:"CONFIG_SYNC_PRESET_NOT_FOUND"}),e}const i=r.items.map(t=>{const n=function(e,t){const n=s.resolve(Sr(),e),r=s.resolve(n,t);if(r!==n&&!r.startsWith(`${n}${s.sep}`)){const e=new Error(`Config sync path escapes project root: ${t}`);throw Object.assign(e,{statusCode:400,code:"CONFIG_SYNC_PATH_INVALID"}),e}return r}(r.projectRoot,t.projectPath),i=function(e){const t=s.resolve(function(e){const t={HOME:vr(),WORKSPACE:Sr(),CODEX_HOME:process.env.CODEX_HOME||s.join(vr(),".codex"),CLAUDE_HOME:process.env.CLAUDE_HOME||s.join(vr(),".claude")};return e.replace(/\$\{([A-Z_]+)\}/g,(e,s)=>t[s]||e)}(e));if(![s.resolve(vr()),s.resolve(Sr()),s.resolve(process.env.TASK_HANDOFF_DATA_DIR||"/data/task-handoff"),s.resolve(process.env.TASK_HANDOFF_LOG_DIR||"/data/logs"),s.resolve(process.env.TASK_HANDOFF_ARTIFACT_DIR||"/data/artifacts")].some(e=>t===e||t.startsWith(`${e}${s.sep}`))){const t=new Error(`Config sync target path is not allowed: ${e}`);throw Object.assign(t,{statusCode:400,code:"CONFIG_SYNC_CONTAINER_PATH_INVALID"}),t}return t}(t.containerPath),o="import"===e?n:i,a="import"===e?i:n;try{return{...t,source:o,target:a,status:Ar(t.type,o,a)}}catch(e){return{...t,source:o,target:a,status:"failed",error:e instanceof Error?e.message:String(e)}}});return{preset:{id:r.id,label:r.label,projectRoot:r.projectRoot},direction:e,items:i}}const _r="2026-06-23",wr=i.z.string().trim().min(1).max(120).regex(/^[a-zA-Z0-9][a-zA-Z0-9_.:-]*$/),Tr=i.z.string().datetime(),Nr=i.z.record(i.z.string(),i.z.string()).default({}),Or=i.z.record(i.z.string(),i.z.string()).default({}),Er=i.z.object({codexModelId:wr.optional(),claudeModelId:wr.optional()}).strict().default({}),zr=i.z.object({component:i.z.enum(["control-plane","node-agent","controlled-instance"]),packageName:i.z.string().trim().max(160).optional(),packageVersion:i.z.string().trim().max(80).optional(),protocolVersion:i.z.string().trim().max(80).optional(),buildId:i.z.string().trim().max(160).optional(),builtAt:i.z.string().trim().max(120).optional(),gitCommit:i.z.string().trim().max(120).optional(),imageRef:i.z.string().trim().max(512).optional(),imageDigest:i.z.string().trim().max(240).optional()}).strict(),xr=i.z.object({type:i.z.enum(["branch","tag","commit"]),name:i.z.string().trim().min(1).max(240).optional(),commit:i.z.string().trim().max(80).optional()}).strict(),Dr=i.z.object({type:i.z.enum(["none","ssh-key","https-token"]).default("none"),secretId:i.z.string().trim().min(1).max(120).optional()}).strict(),kr=i.z.object({depth:i.z.number().int().positive().max(1e5).optional(),submodules:i.z.boolean().default(!1),lfs:i.z.boolean().default(!1),subdirectory:i.z.string().trim().max(240).default("")}).strict();i.z.object({id:wr,name:i.z.string().trim().min(1).max(160),url:i.z.string().trim().min(1).max(2048),provider:i.z.string().trim().max(80).optional(),ref:xr.default({type:"branch",name:"main"}),auth:Dr.default({type:"none"}),clone:kr.default({submodules:!1,lfs:!1,subdirectory:""}),defaultImageId:wr.optional(),modelSelection:Er,labels:Nr,createdAt:Tr,updatedAt:Tr}).strict(),i.z.object({id:wr,nodeId:wr,name:i.z.string().trim().min(1).max(160),path:i.z.string().trim().min(1).max(4096),defaultImageId:wr.optional(),modelSelection:Er,labels:Nr,createdAt:Tr,updatedAt:Tr}).strict();const Cr=i.z.discriminatedUnion("type",[i.z.object({type:i.z.literal("git-repository"),repositoryId:wr.optional(),url:i.z.string().trim().min(1).max(2048),provider:i.z.string().trim().max(80).optional(),ref:xr.default({type:"branch",name:"main"}),auth:Dr.default({type:"none"}),clone:kr.default({submodules:!1,lfs:!1,subdirectory:""})}).strict(),i.z.object({type:i.z.literal("git-template"),url:i.z.string().trim().min(1).max(2048),templateId:i.z.string().trim().min(1).max(120).optional(),ref:xr.default({type:"branch",name:"main"}),auth:Dr.default({type:"none"}),clone:kr.default({submodules:!1,lfs:!1,subdirectory:""})}).strict(),i.z.object({type:i.z.literal("local-folder"),localFolderId:wr.optional(),path:i.z.string().trim().min(1).max(4096),ownerNodeId:wr.optional()}).strict()]),Pr=i.z.object({mode:i.z.enum(["local-bind","git-clone","empty-volume","persistent-volume"]),path:i.z.string().trim().min(1).max(4096).default("/workspace"),volumeName:i.z.string().trim().max(240).optional(),readOnly:i.z.boolean().default(!1)}).strict(),Fr=i.z.enum(["codex","claude"]);i.z.object({id:wr,name:i.z.string().trim().min(1).max(160),source:Cr,defaultImageId:wr.optional(),defaultNodeId:wr.optional(),defaultRuntimeId:wr.optional(),modelSelection:Er,workspacePolicy:Pr,labels:Nr,createdAt:Tr,updatedAt:Tr}).strict(),i.z.object({id:wr,name:i.z.string().trim().min(1).max(160),endpoint:i.z.string().trim().min(1).max(2048),key:i.z.string().trim().min(1).max(4096),model:i.z.string().trim().min(1).max(240),app:Fr,enabled:i.z.boolean().default(!0),order:i.z.number().int().min(0).max(1e6).default(0),labels:Nr,createdAt:Tr,updatedAt:Tr}).strict();const Rr=i.z.object({id:wr,name:i.z.string().trim().min(1).max(160),image:i.z.string().trim().min(1).max(512),registry:i.z.string().trim().min(1).max(160).default("local"),capabilities:i.z.array(i.z.string().trim().min(1).max(80)).default([]),optionalApps:i.z.array(i.z.string().trim().min(1).max(120)).default([]),defaultEnv:Or,labels:Nr,createdAt:Tr,updatedAt:Tr}).strict();i.z.object({id:wr,name:i.z.string().trim().min(1).max(160),connectionMode:i.z.enum(["local-ipc","local-loopback","direct-http","reverse-wss"]).default("direct-http"),auth:i.z.object({mode:i.z.enum(["local-static-key","paired-hmac"]).default("local-static-key"),keyId:wr.optional(),secret:i.z.string().trim().max(4096).optional(),pairedAt:Tr.optional(),pairing:i.z.object({status:i.z.enum(["pending","paired","expired"]).default("pending"),joinToken:i.z.string().trim().max(4096).optional(),expiresAt:Tr.optional()}).strict().optional()}).strict().default({mode:"local-static-key"}),endpoint:i.z.string().trim().max(2048).optional(),controlEndpoint:i.z.string().trim().max(2048).optional(),containerEndpoint:i.z.string().trim().max(2048).optional(),publicWebBase:i.z.string().trim().max(2048).optional(),status:i.z.enum(["unknown","online","offline","degraded"]).default("unknown"),health:i.z.enum(["unknown","ok","degraded","failed"]).default("unknown"),capabilities:i.z.record(i.z.string(),i.z.unknown()).default({}),labels:Nr,lastSeenAt:Tr.optional(),createdAt:Tr,updatedAt:Tr}).strict(),i.z.object({id:wr,nodeId:wr,name:i.z.string().trim().min(1).max(160),type:i.z.enum(["docker","kubernetes","local"]),status:i.z.enum(["unknown","online","offline","degraded"]).default("unknown"),accessStrategy:i.z.enum(["node-proxy","direct-port","kubernetes-ingress","kubernetes-port-forward"]).default("node-proxy"),capabilities:i.z.record(i.z.string(),i.z.unknown()).default({}),labels:Nr,createdAt:Tr,updatedAt:Tr}).strict(),i.z.object({ok:i.z.boolean().optional(),role:i.z.string().optional(),nodeId:wr.optional()}).passthrough(),i.z.object({nodeId:wr,joinToken:i.z.string().trim().min(1),expiresAt:Tr}).passthrough(),i.z.object({id:wr,keyId:wr,url:i.z.string().trim().min(1).max(2048).optional(),name:i.z.string().trim().min(1).max(160).optional(),pairedAt:Tr,updatedAt:Tr.optional(),active:i.z.boolean().optional(),current:i.z.boolean().optional()}).passthrough(),i.z.object({remote:i.z.object({id:wr,url:i.z.string().trim().min(1).max(2048).optional(),keyId:wr,pairedAt:Tr,active:i.z.boolean()}).passthrough(),tunnel:i.z.object({status:i.z.enum(["disabled","saved","connecting","connected","failed"]),error:i.z.string().trim().max(2048).optional()}).passthrough()}).passthrough(),i.z.object({deleted:i.z.boolean().optional()}).passthrough(),i.z.object({repository:i.z.string().trim().optional(),tag:i.z.string().trim().optional(),id:i.z.string().trim(),createdSince:i.z.string().trim().optional(),size:i.z.string().trim().optional(),reference:i.z.string().trim().min(1)}).passthrough();const Mr=i.z.lazy(()=>i.z.object({name:i.z.string().trim().min(1),path:i.z.string().trim().min(1).max(4096),children:i.z.array(Mr)}).passthrough());i.z.object({status:i.z.number().int().min(100).max(599).optional(),headers:i.z.record(i.z.string(),i.z.string()).optional(),bodyBase64:i.z.string().optional()}).passthrough();const jr=i.z.object({strategy:i.z.enum(["node-proxy","direct-port","kubernetes-ingress","kubernetes-port-forward"]).default("node-proxy"),web:i.z.string().trim().max(2048).optional(),api:i.z.string().trim().max(2048).optional(),vnc:i.z.string().trim().max(2048).optional(),tty:i.z.string().trim().max(2048).optional(),logs:i.z.string().trim().max(2048).optional(),status:i.z.enum(["unknown","reachable","endpoint-unreachable"]).default("unknown")}).strict(),Hr=i.z.object({strategy:i.z.enum(["control-plane-proxy","direct-port","node-proxy","kubernetes-ingress","kubernetes-port-forward"]).default("control-plane-proxy"),web:i.z.string().trim().max(2048).optional(),api:i.z.string().trim().max(2048).optional(),ws:i.z.string().trim().max(2048).optional(),status:i.z.enum(["unknown","reachable","endpoint-unreachable"]).default("unknown")}).strict().default({strategy:"control-plane-proxy",status:"unknown"}),Lr=i.z.object({mode:i.z.enum(["local-bind","git-clone","empty-volume","persistent-volume"]).optional(),status:i.z.enum(["unknown","pending","ready","failed"]).default("unknown"),path:i.z.string().trim().max(4096).optional(),resolvedCommit:i.z.string().trim().max(120).optional(),error:i.z.string().trim().max(2048).optional()}).passthrough(),$r=i.z.object({id:wr,name:i.z.string().trim().min(1).max(160),projectId:wr.optional(),source:Cr,sourceSnapshot:i.z.record(i.z.string(),i.z.unknown()).default({}),nodeId:wr,runtimeId:wr,imageId:wr.optional(),imageSnapshot:Rr.optional(),status:i.z.enum(["created","provisioning","starting","registering","registered","running","stopping","stopped","failed","unhealthy"]).default("created"),health:i.z.enum(["unknown","ok","degraded","failed"]).default("unknown"),connectionStatus:i.z.enum(["unknown","online","offline","endpoint-unreachable"]).default("unknown"),agentStatus:i.z.enum(["unknown","online","offline"]).default("unknown"),targetStatus:i.z.enum(["unknown","reachable","endpoint-unreachable"]).default("unknown"),uiAccessStatus:i.z.enum(["unknown","reachable","endpoint-unreachable"]).default("unknown"),controlMode:i.z.enum(["standalone","controlled"]).default("controlled"),protocolVersion:i.z.string().trim().max(80).optional(),instanceVersion:i.z.string().trim().max(80).optional(),build:zr.optional(),capabilities:i.z.record(i.z.string(),i.z.unknown()).default({}),config:i.z.object({autoImportAgentConfigs:i.z.boolean().default(!0)}).strict().default({autoImportAgentConfigs:!0}),workspace:Lr.default({status:"unknown"}),target:jr.default({strategy:"direct-port",status:"unknown"}),access:Hr,receiver:i.z.object({status:i.z.string().trim().max(80).default("unknown"),pendingCount:i.z.number().int().min(0).default(0)}).strict().default({status:"unknown",pendingCount:0}),apps:i.z.object({runningCount:i.z.number().int().min(0).default(0),problemCount:i.z.number().int().min(0).default(0),updatedAt:Tr.optional(),revision:i.z.number().int().min(0).optional()}).strict().default({runningCount:0,problemCount:0}),aiSessions:Ns.default(()=>({runningCount:0,waitingCount:0,staleCount:0,sessions:[],updatedAt:(new Date).toISOString()})),triggers:i.z.object({enabledCount:i.z.number().int().min(0).default(0),runningCount:i.z.number().int().min(0).default(0),errorCount:i.z.number().int().min(0).default(0),configs:i.z.array(i.z.object({configHash:i.z.string().trim().min(1),config:$e,deployments:i.z.array(qe).default([]),runtime:i.z.array(Ke).default([])}).strict()).default([]),recentRuns:i.z.array(Be).default([])}).strict().optional(),runtime:i.z.object({kind:i.z.string().trim().max(80).optional(),containerName:i.z.string().trim().max(240).optional(),containerId:i.z.string().trim().max(240).optional(),workspacePath:i.z.string().trim().max(4096).optional(),pid:i.z.number().int().positive().optional(),port:i.z.number().int().positive().max(65535).optional(),labels:i.z.record(i.z.string(),i.z.string()).default({})}).strict().default({labels:{}}),registrationToken:i.z.string().trim().min(1).max(240).optional(),lastHeartbeatAt:Tr.optional(),createdAt:Tr,updatedAt:Tr}).strict();i.z.object({instanceId:wr.optional(),name:i.z.string().trim().min(1).max(160),projectId:wr.optional(),source:Cr.optional(),nodeId:wr.optional(),runtimeId:wr.optional(),imageId:wr.optional(),instanceVersion:i.z.string().trim().max(80).optional(),protocolVersion:i.z.string().trim().max(80),build:zr.optional(),controlMode:i.z.enum(["standalone","controlled"]).default("controlled"),capabilities:i.z.record(i.z.string(),i.z.unknown()).default({}),target:jr.default({strategy:"direct-port",status:"unknown"}),workspace:Lr.default({status:"unknown"}),registrationToken:i.z.string().trim().max(240).optional()}).strict(),i.z.object({status:$r.shape.status.optional(),health:$r.shape.health.optional(),protocolVersion:i.z.string().trim().max(80),build:zr.optional(),capabilities:$r.shape.capabilities.optional(),receiver:$r.shape.receiver.optional(),apps:$r.shape.apps.optional(),aiSessions:$r.shape.aiSessions.optional(),triggers:$r.shape.triggers.optional(),workspace:Lr.optional(),target:jr.partial().optional()}).strict();const Ur=i.z.enum(["web","telegram","wechat","dingding"]);function qr(){try{const e=s.resolve(__dirname,"..","package.json");return JSON.parse(t.readFileSync(e,"utf8")).version||"unknown"}catch{return"unknown"}}function Kr(e){const t=process.env[e]?.trim();return t||void 0}function Br(){return"controlled"===process.env.TASK_HANDOFF_CONTROL_MODE}function Vr(e,r){const i=[{name:"Xvfb",requiredFor:["gui-display"]},{name:"openbox",requiredFor:["gui-window-manager"]},{name:"picom",requiredFor:["gui-compositor"]},{name:"x11vnc",requiredFor:["vnc"]},{name:"websockify",requiredFor:["novnc-proxy"]},{name:"vncserver",requiredFor:["kasmvnc"]},{name:"vncpasswd",requiredFor:["kasmvnc-auth"]},{name:"openssl",requiredFor:["kasmvnc-cert"]},{name:"xrdb",requiredFor:["kasmvnc-hidpi"]},{name:"xrandr",requiredFor:["kasmvnc-resize"]},{name:process.env.TASK_HANDOFF_CHROMIUM_COMMAND||"chromium",label:"chromium",requiredFor:["browser"]},{name:process.env.TASK_HANDOFF_VSCODE_WEB_COMMAND||"code-server",label:"code-server",requiredFor:["vscode-web"]},{name:process.env.TASK_HANDOFF_XTERM_COMMAND||"xterm",label:"xterm",requiredFor:["gui-terminal"]},{name:"import",requiredFor:["screenshot"]},{name:process.env.TASK_HANDOFF_CODEX_COMMAND||"codex",label:"codex",requiredFor:["active-codex-agent"]},{name:process.env.TASK_HANDOFF_CLAUDE_COMMAND||process.env.CLAUDE_CLI_PATH||"claude",label:"claude",requiredFor:["active-claude-agent"]}].map(e=>{const n=function(e){if(s.isAbsolute(e))try{return t.accessSync(e,t.constants.X_OK),e}catch{return}for(const n of(process.env.PATH||"").split(s.delimiter).filter(Boolean)){const r=s.join(n,e);try{return t.accessSync(r,t.constants.X_OK),r}catch{}}}(e.name);return{name:e.label||e.name,command:e.name,available:Boolean(n),path:n,requiredFor:e.requiredFor}}),o=function(e){return Object.entries(e).map(([e,n])=>{const r=s.resolve(n),i=e.endsWith("Path"),o=i?s.dirname(r):r;let a=!1,d=!1,c="missing";try{const e=t.existsSync(r)?t.statSync(r):void 0;a=Boolean(e),c=e?.isFile()?"file":e?.isDirectory()?"directory":"missing";const n=a?i?r:o:(e=>{let n=e;for(;!t.existsSync(n);){const e=s.dirname(n);if(e===n)return n;n=e}return t.statSync(n).isDirectory()?n:s.dirname(n)})(o);t.accessSync(n,t.constants.W_OK),d=!0}catch{d=!1}return{key:e,path:r,exists:a,type:c,writable:d}})}(e),a="linux"===process.platform;return{ok:a&&i.every(e=>e.available)&&Boolean(r)&&o.every(e=>e.writable),runtime:{platform:process.platform,arch:process.arch,linuxRuntime:a,node:process.version,pid:process.pid,hostname:n.hostname(),uptimeSeconds:Math.round(process.uptime())},noVnc:{available:Boolean(r),root:r},commands:i,storage:o}}async function Gr(e){try{const t=await e.pendingList();if(t&&"object"==typeof t&&"pending"in t&&Array.isArray(t.pending))return t.pending.length}catch{return 0}return 0}function Wr(){const e=process.env.TASK_HANDOFF_INSTANCE_WEB_URL||process.env.TASK_HANDOFF_PUBLIC_WEB_URL,t=process.env.TASK_HANDOFF_INSTANCE_API_URL||(e?`${e.replace(/\/$/,"")}/api`:void 0);return{strategy:process.env.TASK_HANDOFF_INSTANCE_ENDPOINT_STRATEGY||"direct-port",web:e,api:t,status:e||t?"reachable":"unknown"}}function Xr(e){const s=process.env.TASK_HANDOFF_WORKSPACE||process.env.WORKSPACE||"/workspace",n=t.existsSync(s);return{mode:process.env.TASK_HANDOFF_WORKSPACE_MODE||(process.env.TASK_HANDOFF_GIT_URL?"git-clone":"local-bind"),status:n?"ready":"unknown",path:s,exists:n,git:{url:process.env.TASK_HANDOFF_GIT_URL,ref:process.env.TASK_HANDOFF_GIT_REF,resolvedCommit:process.env.TASK_HANDOFF_GIT_COMMIT},storage:{dataDir:e.dataDir,logDir:e.logDir}}}function Jr(e){const t=e.catalog();return{protocolVersion:_r,apps:t.map(e=>({id:e.id,name:e.name,kind:e.kind,automation:e.automation})),features:{receiver:!0,appRuntime:!0,tty:t.some(e=>"tty"===e.kind),gui:t.some(e=>"gui"===e.kind),browser:t.some(e=>"browser"===e.id||"chromium"===e.id),screenshots:!0,logs:!0}}}function Yr(e){const t=e.list();return{enabledCount:t.deployments.filter(e=>e.enabled).length,runningCount:t.runtime.filter(e=>"running"===e.status).length,errorCount:t.runtime.filter(e=>"error"===e.status).length,configs:t.configs.map(e=>({configHash:e.configHash,config:e,deployments:t.deployments.filter(t=>t.configHash===e.configHash),runtime:t.runtime.filter(t=>t.configHash===e.configHash)})),recentRuns:t.recentRuns.slice(0,20)}}async function Qr(e,t,s,n,r=In(),i){const o=t.status(),a=e.listSessions();return{status:"running",health:"ok",instanceVersion:qr(),protocolVersion:_r,build:{component:"controlled-instance",packageName:"@task-handoff/controlled-instance",packageVersion:qr(),protocolVersion:_r,buildId:Kr("TASK_HANDOFF_BUILD_ID"),builtAt:Kr("TASK_HANDOFF_BUILT_AT"),gitCommit:Kr("TASK_HANDOFF_GIT_COMMIT"),imageRef:Kr("TASK_HANDOFF_IMAGE_REF"),imageDigest:Kr("TASK_HANDOFF_IMAGE_DIGEST")},controlMode:Br()?"controlled":"standalone",capabilities:Jr(e),receiver:{status:o.running?"running":"stopped",pendingCount:await Gr(s)},apps:{runningCount:e.runningSessionCount(),problemCount:e.problemSessionCount()},aiSessions:r.boundSnapshot(a),triggers:i?Yr(i):void 0,workspace:Xr(n),target:Wr()}}i.z.object({id:wr,channel:Ur,name:i.z.string().trim().min(1).max(160),enabled:i.z.boolean().default(!1),token:i.z.string().trim().max(4096).optional(),defaultChatId:i.z.string().trim().max(240).optional(),allowedUserIds:i.z.array(i.z.string().trim().min(1).max(240)).default([]),pollIntervalMs:i.z.number().int().positive().max(6e4).default(3e3),settings:i.z.record(i.z.string(),i.z.unknown()).default({}),createdAt:Tr,updatedAt:Tr}).strict(),i.z.object({id:wr,channel:Ur,bridgeId:wr.optional(),chatSessionId:i.z.string().trim().min(1).max(240),userId:i.z.string().trim().max(240).optional(),activeProjectId:wr.optional(),activeInstanceId:wr.optional(),activeAiSessionId:i.z.string().trim().min(1).max(120).optional(),lastUsedAt:Tr,createdAt:Tr,updatedAt:Tr}).strict(),i.z.object({source:i.z.object({type:i.z.literal("chat-gateway").default("chat-gateway"),channel:Ur,bridgeId:wr.optional(),chatSessionId:i.z.string().trim().min(1).max(240),userId:i.z.string().trim().max(240).optional()}).strict(),message:i.z.object({text:i.z.string().trim().max(2e4).default(""),attachments:i.z.array(ps).max(6).default([])}).strict().superRefine((e,t)=>{e.attachments.reduce((e,t)=>e+t.size,0)>ss&&t.addIssue({code:i.z.ZodIssueCode.custom,path:["attachments"],message:"Images must be 41943040 bytes or less in total."})}),target:i.z.object({instanceId:wr,aiSessionId:i.z.string().trim().min(1).max(120)}).strict().optional()}).strict(),i.z.object({id:wr,instanceId:wr,projectId:wr.optional(),aiSessionId:i.z.string().trim().min(1).max(120),providerSessionId:i.z.string().trim().max(240).optional(),result:i.z.string().default(""),timeoutMs:i.z.number().positive().optional(),source:i.z.string().trim().max(120).optional(),kind:i.z.enum(["task","approval"]).default("task"),status:i.z.enum(["pending","unreachable"]).default("pending"),error:i.z.string().trim().max(2048).optional(),lastSeenAt:Tr}).strict();const Zr=new Set(["ECONNREFUSED","ECONNRESET","EHOSTUNREACH"]);function ei(e){return new Promise(t=>setTimeout(t,e))}function ti(e){const t=e?.code;return Boolean(t&&Zr.has(t))}function si(e,t="/"){const s=new URL(t,"http://task-handoff.local"),n=`/api/apps/sessions/${e}/web`,r=s.pathname.startsWith(n)?s.pathname.slice(n.length):"/";return`${r.startsWith("/")?r:`/${r}`}${s.search}`}function ni(){const e=process.env.TASK_HANDOFF_KASMVNC_USERNAME||"agent",t=process.env.TASK_HANDOFF_KASMVNC_PASSWORD||"taskhandoff";return`Basic ${Buffer.from(`${e}:${t}`).toString("base64")}`}function ri(e,t,s,n={}){const r=new Set(["connection","content-length","host","keep-alive","proxy-authenticate","proxy-authorization","referer","referrer","te","trailer","transfer-encoding","upgrade"]);return{...Object.fromEntries(Object.entries(e).filter(([e,t])=>!(e=>{const t=e.toLowerCase();return r.has(t)||t.startsWith("sec-ch-")||t.startsWith("sec-fetch-")})(e)&&void 0!==t).map(([e,t])=>[e,Array.isArray(t)?t.join(", "):String(t)])),...Object.fromEntries(Object.entries(n).filter(([,e])=>void 0!==e).map(([e,t])=>[e,Array.isArray(t)?t.join(", "):String(t)])),host:`${t}:${s}`}}function ii(e,t,s,n={}){return Object.fromEntries(Object.entries(ri(e,t,s,n)).filter(([e])=>{const t=e.toLowerCase();return!t.startsWith("sec-websocket-")||"sec-websocket-origin"===t}))}function oi(e,t){const s=e[t];return Array.isArray(s)?s.join(","):s||""}function ai(e){if(oi(e,"content-encoding"))return!1;const t=oi(e,"content-type").toLowerCase();return t.includes("text/css")||t.includes("text/html")}function di(e,t){const s=oi(t,"content-type").toLowerCase(),n=e.toString("utf8");if(s.includes("text/css"))return n.replace(/(#noVNC_transition\s*\{[\s\S]*?background\s*:\s*)#fff(\s+url\()/g,"$1#05090b$2").replace(/(#noVNC_transition\s*\{[\s\S]*?background-color\s*:\s*)#fff\b/g,"$1#05090b");if(s.includes("text/html")){const e=['<style id="task-handoff-kasm-loading-theme">',"html,body{background:#05090b!important;}","#noVNC_transition{background-color:#05090b!important;color:#31c6b6!important;}","#noVNC_transition::after{color:#9fb4bc!important;}","html.task-handoff-kasm-quiet-start #noVNC_control_bar{transition:none!important;}","html.task-handoff-kasm-quiet-start #noVNC_control_bar.noVNC_open{left:-100%!important;}","html.task-handoff-kasm-quiet-start.noVNC_right #noVNC_control_bar.noVNC_open{left:100%!important;}","html.task-handoff-kasm-quiet-start #noVNC_control_bar_handle::after,html.task-handoff-kasm-quiet-start .noVNC_panel{transition:none!important;}","</style>",'<script id="task-handoff-kasm-quiet-start">',"(function(){","var root=document.documentElement;","root.classList.add('task-handoff-kasm-quiet-start');","var attempts=0;","var timer=window.setInterval(function(){","var bar=document.getElementById('noVNC_control_bar');","if(bar){bar.classList.remove('noVNC_open');}","attempts+=1;","if(attempts>=20){window.clearInterval(timer);root.classList.remove('task-handoff-kasm-quiet-start');}","},100);","})();","<\/script>"].join("");return n.includes("</head>")?n.replace("</head>",`${e}</head>`):`${e}${n}`}return n}function ci(e){const t={};e.forEach((e,s)=>{t[s]=e});const s=e.getSetCookie?.();return s?.length&&(t["set-cookie"]=s),t}function pi(e){const t={};e.forEach((e,s)=>{t[s]=e});const s=e.getSetCookie?.();return s?.length&&(t["set-cookie"]=s),t}const ui="app-session.snapshot",li="app-session.patch",mi="app-session.removed",hi=36e5,gi=i.z.enum(["created","starting","running","stopping","stopped","exited","failed","closed","terminated","unknown"]),fi=i.z.object({type:i.z.enum(["app-session","provider-session","adapter-key"]),id:i.z.string().trim().min(1).max(240),agent:i.z.string().trim().min(1).max(80).optional(),adapter:i.z.string().trim().min(1).max(80).optional(),key:i.z.string().trim().min(1).max(240).optional()}).strict(),yi=i.z.record(i.z.string(),i.z.unknown()).and(i.z.object({id:i.z.string().trim().min(1).max(160),appId:i.z.string().trim().min(1).max(160).optional(),title:i.z.string().trim().max(240).optional(),kind:i.z.string().trim().max(80).optional(),status:gi.default("unknown"),bindings:i.z.array(fi).max(40).default([]),workspace:i.z.object({cwd:i.z.string().trim().max(4096).optional()}).strict().optional(),createdAt:i.z.string().datetime().optional(),updatedAt:i.z.string().datetime().optional()})),vi=i.z.object({runningCount:i.z.number().int().min(0).default(0),problemCount:i.z.number().int().min(0).default(0),sessions:i.z.array(yi).default([]),updatedAt:i.z.string().datetime()}).strict();i.z.object({revision:i.z.number().int().min(0),lastEventAt:i.z.string().datetime(),snapshot:vi}).strict(),vi.pick({runningCount:!0,problemCount:!0,updatedAt:!0}).extend({revision:i.z.number().int().min(0).optional()});const Si=i.z.enum(["app-session-created","app-session-updated","app-session-deleted","app-session-recovered","control-action","heartbeat-sync","startup"]),Ii=i.z.object({instanceId:i.z.string().trim().min(1).max(160),nodeId:i.z.string().trim().min(1).max(160).optional(),snapshotRevision:i.z.number().int().min(0),previousRevision:i.z.number().int().min(0).optional(),eventSeq:i.z.number().int().min(1),traceId:i.z.string().trim().min(1).max(160),generatedAt:i.z.string().datetime(),reason:Si}).strict(),Ai=i.z.object({meta:Ii,snapshot:vi}).strict(),bi=i.z.object({meta:Ii,session:yi}).strict(),_i=i.z.object({meta:Ii,sessionId:i.z.string().trim().min(1).max(160),tombstone:yi.optional(),expiresAt:i.z.string().datetime().optional()}).strict(),wi=i.z.object({instanceId:i.z.string().trim().min(1).max(160),sinceRevision:i.z.number().int().min(0),latestRevision:i.z.number().int().min(0),syncRequired:i.z.boolean().default(!1),events:i.z.array(i.z.discriminatedUnion("type",[i.z.object({type:i.z.literal(ui),payload:Ai}).strict(),i.z.object({type:i.z.literal(li),payload:bi}).strict(),i.z.object({type:i.z.literal(mi),payload:_i}).strict()])).default([])}).strict();function Ti(e,t=(new Date).toISOString()){const s=e.map(e=>function(e){const t=function(e){const t=(e||"unknown").trim().toLowerCase();return"ended"===t?"closed":"terminating"===t?"stopping":gi.options.includes(t)?t:"unknown"}("string"==typeof e.status?e.status:void 0),s="string"==typeof e.id?e.id:"",n=function(e){const t=zi(e.workspace),s=zi(e.tty),n=zi(e.launch),r=zi(e.ai),i=zi(r.claude),o=xi(t.cwd)||xi(s.cwd)||xi(i.cwd)||xi(n.cwd);return o?{cwd:o}:void 0}(e),{workspace:r,...i}=e;return yi.parse({...i,status:t,bindings:Ei([...(o=e.bindings,Array.isArray(o)?o.flatMap(e=>{const t=fi.safeParse(e);return t.success?[t.data]:[]}):[]),...s?[{type:"app-session",id:s}]:[],...Oi(e)]),...n?{workspace:n}:{}});var o}(e));return vi.parse({runningCount:s.filter(e=>"running"===e.status).length,problemCount:s.filter(e=>"failed"===e.status).length,sessions:s,updatedAt:t})}function Ni(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 Oi(e){const t=zi(e.ai),s=zi(t.claude),n=zi(t.appServer),r=[],i=xi(s.short);i&&r.push({type:"adapter-key",adapter:"claude",agent:"claude",id:`short:${i}`,key:`short:${i}`});const o=xi(s.providerSessionId);o&&r.push({type:"provider-session",agent:"claude",id:o});const a=Array.isArray(t.threadIds)?t.threadIds.filter(e=>"string"==typeof e&&Boolean(e.trim())):[],d=xi(t.activeThreadId);for(const e of[...new Set([d,...a].filter(Boolean))])r.push({type:"provider-session",agent:"codex",id:e});const c=xi(n.socketPath);return c&&r.push({type:"adapter-key",adapter:"codex-app-server",agent:"codex",id:`socket:${c}`,key:`socket:${c}`}),r}function Ei(e){const t=new Map;for(const s of e)t.set(Ni(s),s);return[...t.values()]}function zi(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}function xi(e){return"string"==typeof e&&e.trim()?e.trim():""}function Di(e){return e.readyState===(e.OPEN??1)}function ki(e,t,s){e.close(function(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}(t),function(e){const t=Buffer.isBuffer(e)?e.toString("utf8"):"string"==typeof e?e:"";if(Buffer.byteLength(t,"utf8")<=123)return t;let s="";for(const e of t){const t=`${s}${e}`;if(Buffer.byteLength(t,"utf8")>123)break;s=t}return s}(s)||void 0)}function Ci(e,t){e.send(t.data,{binary:t.isBinary})}function Pi(e,t){if(Di(e))for(const s of t.splice(0))Ci(e,s)}const Fi=require("ws");function Ri(e){return{method:e.method,headers:e.headers,body:e.streamRawRequest?e.rawRequest:e.requestBody,...e.streamRawRequest?{duplex:"half"}:{}}}function Mi(e){return a.Readable.fromWeb(e)}function ji(e){const t=e();return{...t,secrets:t.secrets?Object.fromEntries(Object.entries(t.secrets).map(([e,t])=>[e,{configured:void 0!==t&&""!==t,preview:"string"==typeof t?`${t.slice(0,6)}***`:void 0}])):void 0}}const Hi=i.z.object({id:i.z.string().trim().min(1).max(120),label:i.z.string().trim().min(1).max(120),projectRoot:i.z.string().trim().min(1).max(500),items:i.z.array(i.z.object({id:i.z.string().trim().min(1).max(120),type:i.z.enum(["file","dir"]),projectPath:i.z.string().trim().min(1).max(500),containerPath:i.z.string().trim().min(1).max(500)}).strip()).min(1).max(50)}).strip(),Li=i.z.object({preset:Hi.optional()}).strip().default({}),$i=i.z.object({appId:i.z.string().min(1).max(80).regex(/^[a-z0-9][a-z0-9_.-]*$/).optional(),title:i.z.string().trim().min(1).max(120).optional(),args:i.z.array(i.z.string().max(4096)).max(64).optional(),cwd:i.z.string().trim().min(1).max(512).optional(),env:i.z.record(i.z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),i.z.string().max(4096)).optional(),display:i.z.object({width:i.z.number().int().min(320).max(7680).optional(),height:i.z.number().int().min(240).max(4320).optional(),depth:i.z.union([i.z.literal(16),i.z.literal(24),i.z.literal(32)]).optional()}).optional(),displayTarget:i.z.object({mode:i.z.enum(["isolated","shared"]),id:i.z.string().trim().min(1).max(80).regex(/^[a-z0-9][a-z0-9._-]*$/).optional(),autoCreate:i.z.boolean().optional()}).optional()}).strict(),Ui=i.z.object({width:i.z.number().int().min(320).max(7680).optional(),height:i.z.number().int().min(240).max(4320).optional(),depth:i.z.number().int().min(8).max(32).optional()}).strip(),qi=i.z.object({title:i.z.string().trim().min(1).max(120)}).strict(),Ki=i.z.object({source:i.z.object({type:i.z.literal("chat-gateway").default("chat-gateway"),channel:i.z.enum(["web","telegram","wechat","dingding"]),chatSessionId:i.z.string().trim().min(1).max(240),userId:i.z.string().trim().max(240).optional()}).strict(),message:i.z.object({text:i.z.string().trim().max(2e4).default(""),attachments:i.z.array(i.z.record(i.z.string(),i.z.unknown())).default([])}).strict(),routing:i.z.object({projectId:i.z.string().trim().min(1).max(120),instanceId:i.z.string().trim().min(1).max(120),conversationId:i.z.number().int().positive().optional()}).strict()}).strict(),Bi=i.z.object({name:i.z.string().trim().min(1).max(160),description:i.z.string().trim().max(1e3).optional(),source:je,action:He,policy:Le.partial().optional(),deployment:i.z.object({deploymentId:i.z.string().trim().min(1).max(240).optional(),origin:i.z.enum(["control-plane","controlled-instance"]).optional(),enabled:i.z.boolean().optional(),target:Ue.optional(),localName:i.z.string().trim().min(1).max(160).optional()}).strict().optional()}).strict(),Vi=i.z.object({name:i.z.string().trim().min(1).max(160).optional(),description:i.z.string().trim().max(1e3).nullable().optional()}).strict(),Gi=i.z.object({promptOverride:i.z.string().trim().min(1).max(2e4).optional(),eventSummary:i.z.string().trim().max(1e3).optional(),deploymentId:i.z.string().trim().min(1).max(240).optional()}).strict().default({});function Wi(e){return e instanceof i.z.ZodError?e.issues.map(e=>`${e.path.join(".")||"body"}: ${e.message}`).join("; "):e instanceof Error?e.message:String(e)}function Xi(e,t){if(t instanceof i.z.ZodError)return e.code(400).send({error:vs.parse({code:"AI_SESSION_CONTROL_INVALID",message:t.issues.map(e=>`${e.path.join(".")||"body"}: ${e.message}`).join("; ")})});const s=t&&"object"==typeof t?t:{},n="string"==typeof s.code?s.code:"AI_SESSION_CONTROL_FAILED",r="number"==typeof s.statusCode?s.statusCode:"AI_SESSION_NOT_FOUND"===n?404:400;return e.code(r).send({error:vs.parse({code:n,message:t instanceof Error?t.message:String(t)})})}function Ji(e,t=!1){const s=process.env[e];return void 0===s||""===s?t:["1","true","yes","on"].includes(s.toLowerCase())}function Yi(e){return process.env.TASK_HANDOFF_RECEIVER_LOG||s.join(e,"receiver.log")}function Qi(e){return Array.isArray(e)?e.map(Qi):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,null===t?void 0:Qi(t)])):e}function Zi(e,s=200){const n=Math.min(Math.max(1,Number(s)||200),1e3),r=t.readFileSync(e,"utf8").split(/\r?\n/);return{path:e,lineCount:r.length,tail:r.slice(-n).join("\n")}}async function eo(e={}){const r=e.socketPath||N,a=(new Date).toISOString(),m=function(){const e=et();return{paths:e,channel:(t,n="default")=>new me(s.join(e.channelsDir,`${t}.${n}.json`),{schema:tt,defaultValue:()=>({schemaVersion:1,channel:t,instanceId:n,enabled:!1})}),conversationIndex:()=>new me(s.join(e.conversationsDir,"index.json"),{schema:st,defaultValue:()=>({schemaVersion:1,defaultConversationId:1,nextConversationId:2,items:[]})}),appSessionIndex:()=>new me(s.join(e.appSessionsDir,"index.json"),{schema:nt,defaultValue:()=>({schemaVersion:1,items:[]})})}}();!function(e,t){if(Ji("TASK_HANDOFF_DIAGNOSTIC_LOGS"))try{oe(Yi(e),{event:"controlled_instance_start",component:"controlled-instance",controlMode:process.env.TASK_HANDOFF_CONTROL_MODE,diagnosticLogs:process.env.TASK_HANDOFF_DIAGNOSTIC_LOGS,dataDir:t,logDir:e,receiverLog:Yi(e),process:{pid:process.pid,ppid:process.ppid,cwd:process.cwd(),argv:process.argv,parent:ie(process.ppid),env:re()}})}catch{}}(m.paths.logDir,m.paths.dataDir);const g=function(e){if("off"===process.env.TASK_HANDOFF_WEB_AUTH)return{enabled:!1};const n=process.env.TASK_HANDOFF_WEB_TOKEN?.trim();if(n)return{enabled:!0,source:"env",token:n};const r=function(e){try{return t.readFileSync(e,"utf8").trim()||void 0}catch(e){if(e&&"object"==typeof e&&"code"in e&&"ENOENT"===e.code)return;throw e}}(e.webTokenPath);if(r)return{enabled:!0,source:"file",token:r,tokenFile:e.webTokenPath};if("required"===process.env.TASK_HANDOFF_WEB_AUTH){const n=h.randomBytes(24).toString("base64url");return function(e,n){t.mkdirSync(s.dirname(e),{recursive:!0}),t.writeFileSync(e,`${n}\n`,{mode:384})}(e.webTokenPath,n),{enabled:!0,source:"generated",token:n,tokenFile:e.webTokenPath}}return{enabled:!1,tokenFile:e.webTokenPath}}(m.paths),f=new dr,y=e.receiverProcess||new yr(r,m.paths.logDir),v=new fr(r),S=e.appRuntime||new Dt(m.paths),I=In(),b=new Rt(I),w=new Ne(m.paths),O=new Qe(m.paths),E=new Ee(O,v,b),z=new ze(O,E,m.paths,(e,t)=>f.publish(e,t)),x=new Yn(function(e=process.env){return{controlMode:"controlled"===e.TASK_HANDOFF_CONTROL_MODE?"controlled":"standalone",nodeAgentUrl:e.TASK_HANDOFF_NODE_AGENT_URL,registrationToken:e.TASK_HANDOFF_REGISTRATION_TOKEN,instanceId:e.TASK_HANDOFF_INSTANCE_ID,instanceName:e.TASK_HANDOFF_INSTANCE_NAME||e.HOSTNAME||"controlled-instance",projectId:e.TASK_HANDOFF_PROJECT_ID,nodeId:e.TASK_HANDOFF_NODE_ID,runtimeId:e.TASK_HANDOFF_RUNTIME_ID,imageId:e.TASK_HANDOFF_IMAGE_ID,heartbeatIntervalMs:Number(e.TASK_HANDOFF_HEARTBEAT_INTERVAL_MS)||1e4}}(),()=>Qr(S,y,v,m.paths,I,O)),D=u({logger:e.logger??!0,bodyLimit:67108864});await D.register(p),function(e,t){e.addHook("preHandler",async(e,s)=>{if(t.enabled&&"/api/health"!==e.url&&"/api/auth/status"!==e.url&&e.url.startsWith("/api/")&&function(e){const t=(e.headers.authorization||"").match(/^Bearer\s+(.+)$/i);if(t?.[1])return t[1];try{return new URL(e.url,"http://localhost").searchParams.get("token")||void 0}catch{return}}(e)!==t.token)return s.code(401).send({error:{code:"UNAUTHORIZED",message:"Missing or invalid web token."}})})}(D,g),y.on("start",e=>f.publish("receiver.started",e)),y.on("exit",e=>f.publish("receiver.exited",e)),D.addHook("onReady",async()=>{x.enabled()&&await x.start()}),D.addHook("onClose",async()=>{x.stop(),z.stop()});let k="",C=0,P=0;const F=[],R=new Set,M=new Map;let j,H="",L=0,$=0;const U=[];let q=Ti([]);const K=new bn,B=new Jn(I),V=new En(I);b.register(B),b.register(V),K.register(new _n),K.register(V),K.register(new wn),K.register(B);const G=()=>{const e=S.sharedCodexAppServerInfo();return e?[...S.listSessions(),{id:"__shared_codex_app_server__",appId:"codex",title:"Codex app-server",status:"running",createdAt:a,ai:{appServer:e}}]:S.listSessions()};let W;const X=async(e="discovery-scan")=>{W||(W=(async()=>{const e=G();I.reconcileAppSessionBindings(e),await K.refresh({registry:I,appSessions:e})})().finally(()=>{W=void 0})),await W,Y(e)},J=()=>{const e=Date.now()-36e5;for(;F.length&&F[0].createdAtMs<e;)F.shift()},Y=(e="provider-event")=>{const t=I.boundSnapshot(G()),s=JSON.stringify(t.sessions);if(s!==k){k=s,C+=1;const n=((e,t)=>({meta:{instanceId:process.env.TASK_HANDOFF_INSTANCE_ID||"standalone",nodeId:process.env.TASK_HANDOFF_NODE_ID,snapshotRevision:C,previousRevision:C>0?C-1:void 0,eventSeq:++P,traceId:`ais_evt_${Date.now().toString(36)}_${Math.random().toString(16).slice(2,10)}`,generatedAt:(new Date).toISOString(),reason:t},snapshot:e}))(t,e);(e=>{F.push({type:ns,payload:e,createdAtMs:Date.now()}),J()})(n),f.publish(ns,n),D.log.info({traceId:n.meta.traceId,instanceId:n.meta.instanceId,snapshotRevision:n.meta.snapshotRevision,eventSeq:n.meta.eventSeq,reason:e,sessionCount:t.sessions.length,runningCount:t.runningCount,waitingCount:t.waitingCount},"ai-session.snapshot.published"),z.handleAiSessions(t)}},Q=()=>{const e=Date.now()-hi;for(;U.length&&U[0].createdAtMs<e;)U.shift()},Z=e=>({instanceId:process.env.TASK_HANDOFF_INSTANCE_ID||"standalone",nodeId:process.env.TASK_HANDOFF_NODE_ID,snapshotRevision:L,previousRevision:L>0?L-1:void 0,eventSeq:++$,traceId:`aps_evt_${Date.now().toString(36)}_${Math.random().toString(16).slice(2,10)}`,generatedAt:(new Date).toISOString(),reason:e}),ee=(e,t)=>({meta:Z(t),session:e}),te=(e,t,s)=>({meta:Z(s),sessionId:e,tombstone:t,expiresAt:new Date(Date.now()+hi).toISOString()}),se=(e,t,s)=>{(e=>{U.push({...e,createdAtMs:Date.now()}),Q()})(e),f.publish(e.type,e.payload),D.log.info({traceId:e.payload.meta.traceId,instanceId:e.payload.meta.instanceId,snapshotRevision:e.payload.meta.snapshotRevision,eventSeq:e.payload.meta.eventSeq,reason:s,eventType:e.type,sessionCount:t.sessions.length,runningCount:t.runningCount,problemCount:t.problemCount},"app-session.event.published")},ne=e=>{Q();const t=L,s=process.env.TASK_HANDOFF_INSTANCE_ID||"standalone";if(e>t)return wi.parse({instanceId:s,sinceRevision:e,latestRevision:t,syncRequired:!0,events:[]});if(e===t)return wi.parse({instanceId:s,sinceRevision:e,latestRevision:t,syncRequired:!1,events:[]});const n=U.filter(t=>t.payload.meta.snapshotRevision>e),r=n[0]?.payload.meta.snapshotRevision,i=!n.length||r!==e+1;return wi.parse({instanceId:s,sinceRevision:e,latestRevision:t,syncRequired:i,events:i?[]:n.map(e=>({type:e.type,payload:e.payload}))})},ae=e=>{J();const t=C;if(e>t)return ks.parse({instanceId:process.env.TASK_HANDOFF_INSTANCE_ID||"standalone",sinceRevision:e,latestRevision:t,syncRequired:!0,events:[]});if(e===t)return ks.parse({instanceId:process.env.TASK_HANDOFF_INSTANCE_ID||"standalone",sinceRevision:e,latestRevision:t,syncRequired:!1,events:[]});const s=F.filter(t=>t.payload.meta.snapshotRevision>e),n=s[0]?.payload.meta.snapshotRevision,r=!s.length||n!==e+1;return ks.parse({instanceId:process.env.TASK_HANDOFF_INSTANCE_ID||"standalone",sinceRevision:e,latestRevision:t,syncRequired:r,events:r?[]:s.map(e=>({type:e.type,payload:e.payload}))})},de=async e=>{if(R.has(e))return;const t=I.get(e);if(t&&"idle"===t.status&&I.nextQueuedMessage(e)){R.add(e);try{await b.sendNextQueuedMessage(e)}catch(t){D.log.warn({err:t,sessionId:e},"failed to drain AI session message queue")}finally{R.delete(e),Y("control-action")}}};let ce;const pe=I.onChange(()=>{ce||(ce=setTimeout(()=>{ce=void 0,Y()},Number(process.env.TASK_HANDOFF_AI_SESSION_PUBLISH_DEBOUNCE_MS)||50));for(const e of I.list()){const t=M.get(e.id);M.set(e.id,e.status),t&&"idle"!==t&&"idle"===e.status&&e.queue.pendingCount>0&&de(e.id)}});D.addHook("onReady",async()=>{if(z.start(),Ji("TASK_HANDOFF_CODEX_APP_SERVER",!1))try{S.ensureSharedCodexAppServer()}catch(e){D.log.warn({err:e},"failed to start shared Codex app-server")}}),D.addHook("onReady",async()=>{await X("startup"),j=setInterval(()=>{X()},Number(process.env.TASK_HANDOFF_AI_SESSION_SCAN_INTERVAL_MS)||5e3)}),D.addHook("onClose",async()=>{pe(),ce&&(clearTimeout(ce),ce=void 0),j&&(clearInterval(j),j=void 0),B.stop(),V.stop()});const ue=(e,t)=>{(e=>{const t=Ti(S.listSessions()),s=JSON.stringify(t.sessions);if(s===H)return void D.log.info({instanceId:process.env.TASK_HANDOFF_INSTANCE_ID||"standalone",snapshotRevision:L,reason:e,sessionCount:t.sessions.length},"app-session.snapshot.skipped-unchanged");H=s;const n=function(e,t){const s=new Map(e.sessions.map(e=>[e.id,e])),n=new Map(t.sessions.map(e=>[e.id,e])),r=[];for(const e of t.sessions){const t=s.get(e.id);t&&JSON.stringify(t)===JSON.stringify(e)||r.push({type:"upsert",session:e})}for(const t of e.sessions)n.has(t.id)||r.push({type:"removed",sessionId:t.id,tombstone:t});return r}(q,t);if(0===L||1!==n.length){L+=1;const s=((e,t)=>({meta:{instanceId:process.env.TASK_HANDOFF_INSTANCE_ID||"standalone",nodeId:process.env.TASK_HANDOFF_NODE_ID,snapshotRevision:L,previousRevision:L>0?L-1:void 0,eventSeq:++$,traceId:`aps_evt_${Date.now().toString(36)}_${Math.random().toString(16).slice(2,10)}`,generatedAt:(new Date).toISOString(),reason:t},snapshot:e}))(t,e);se({type:ui,payload:s},t,e)}else{L+=1;const s=n[0],r="removed"===s.type?{type:mi,payload:te(s.sessionId,s.tombstone,e)}:{type:li,payload:ee(s.session,e)};se(r,t,e)}q=t})(e),X("app-session-recovered"===e?"discovery-scan":e).catch(s=>{D.log.warn({err:s,reason:e,sessionId:t.id},"failed to refresh AI sessions after app session event")})};y.on("log",e=>f.publish("receiver.log",{message:e})),S.on("created",e=>ue("app-session-created",e)),S.on("updated",e=>ue("app-session-updated",e)),S.on("deleted",e=>ue("app-session-deleted",e)),D.addHook("onClose",async()=>{await y.stopAndWait(),S.stopAll()}),!Br()&&(e.receiverAutoStart??Ji("TASK_HANDOFF_RECEIVER_AUTO_START"))&&D.addHook("onReady",async()=>{or(m.paths.channelsDir,m.paths.configPath),y.start()});const le=function(){const e=process.env.TASK_HANDOFF_NOVNC_ROOT?.trim();if(e){const n=s.resolve(e);return t.existsSync(s.join(n,"vnc.html"))?n:void 0}const n=["/usr/share/novnc","/usr/share/noVNC","/usr/local/share/novnc","/usr/local/share/noVNC"].filter(e=>Boolean(e));for(const e of n){const n=s.resolve(e);if(t.existsSync(s.join(n,"vnc.html")))return n}}();le?await D.register(c,{root:le,prefix:"/api/novnc/",decorateReply:!1}):D.get("/api/novnc/*",async(e,t)=>t.code(404).send({error:{code:"NOVNC_NOT_FOUND",message:"noVNC static files were not found. Install noVNC or set TASK_HANDOFF_NOVNC_ROOT to a directory containing vnc.html."}}));const he=s.resolve(e.staticDir||process.env.TASK_HANDOFF_WEB_STATIC_DIR||function(){const e=[s.resolve(process.cwd(),"packages","controlled-instance-ui","dist"),s.resolve(__dirname,"..","packages","controlled-instance-ui","dist"),s.resolve(__dirname,"..","..","..","controlled-instance-ui","dist"),s.resolve(__dirname,"..","..","..","..","packages","controlled-instance-ui","dist")];return e.find(e=>t.existsSync(e))||e[0]}());t.existsSync(he)&&await D.register(c,{root:he,prefix:"/"}),D.get("/api/health",async()=>({data:{ok:!0,version:qr(),startedAt:a}})),D.get("/api/auth/status",async()=>({data:{enabled:g.enabled,source:g.source,tokenFile:g.tokenFile}})),D.get("/api/events",{websocket:!0},e=>{f.connect(e),f.send(e,"events.connected",{});const t=I.boundSnapshot(G()),s={meta:{instanceId:process.env.TASK_HANDOFF_INSTANCE_ID||"standalone",nodeId:process.env.TASK_HANDOFF_NODE_ID,snapshotRevision:C,eventSeq:P,traceId:`ais_evt_${Date.now().toString(36)}_${Math.random().toString(16).slice(2,10)}`,generatedAt:(new Date).toISOString(),reason:"startup"},snapshot:t};f.send(e,ns,s)}),D.get("/api/status",async()=>{const e=A();return{data:{receiverReady:y.status().running,receiver:y.status(),socketPath:r,defaultConversationId:Number(e.defaultConversationId)||T,pendingTaskCount:await Gr(v),runningAppCount:S.runningSessionCount(),storage:m.paths}}}),D.get("/api/instance/status",async()=>{const e=A(),t=await Qr(S,y,v,m.paths,I,O);return{data:{id:process.env.TASK_HANDOFF_INSTANCE_ID,name:process.env.TASK_HANDOFF_INSTANCE_NAME||n.hostname(),...t,defaultConversationId:Number(e.defaultConversationId)||T,startedAt:a}}}),D.get("/api/instance/capabilities",async()=>({data:Jr(S)})),D.get("/api/workspace/status",async()=>({data:Xr(m.paths)})),D.get("/api/ai-sessions",async e=>{const t=void 0===e.query.sinceRevision?void 0:Number(e.query.sinceRevision);return Number.isInteger(t)&&t>=0?{data:ae(t)}:{data:I.boundSnapshot(G(),100)}}),D.get("/api/ai-sessions/state",async()=>({data:{revision:C,lastEventAt:F.at(-1)?.payload.meta.generatedAt||a,snapshot:I.boundSnapshot(G(),100)}})),D.get("/api/triggers",async()=>({data:O.list()})),D.get("/api/triggers/:configHash",async(e,t)=>{const s=O.get(e.params.configHash);return s?{data:s}:t.code(404).send({error:{code:"TRIGGER_NOT_FOUND",message:"Trigger not found."}})}),D.post("/api/triggers",async(e,t)=>{try{const t=Bi.parse(e.body||{}),s=O.create(t);return z.restart(),f.publish("trigger.created",s),f.publish("trigger.updated",Yr(O)),{data:s}}catch(e){return t.code(400).send({error:{code:"TRIGGER_INVALID",message:Wi(e)}})}}),D.patch("/api/triggers/:configHash",async(e,t)=>{try{const s=Vi.parse(e.body||{}),n=O.patch(e.params.configHash,s);return n?(z.restart(),f.publish("trigger.updated",O.get(e.params.configHash)),{data:n}):t.code(404).send({error:{code:"TRIGGER_NOT_FOUND",message:"Trigger not found."}})}catch(e){return t.code(400).send({error:{code:"TRIGGER_INVALID",message:Wi(e)}})}}),D.delete("/api/triggers/:configHash",async(e,t)=>{const s=O.delete(e.params.configHash);return s?(z.restart(),f.publish("trigger.deleted",{configHash:e.params.configHash}),f.publish("trigger.updated",Yr(O)),{data:{deleted:s}}):t.code(404).send({error:{code:"TRIGGER_NOT_FOUND",message:"Trigger not found."}})}),D.delete("/api/triggers/:configHash/deployments/:deploymentId",async(e,t)=>{const s=O.deleteDeployment(e.params.configHash,e.params.deploymentId);return s?(z.restart(),f.publish("trigger.deployment.deleted",{configHash:e.params.configHash,deploymentId:e.params.deploymentId}),f.publish("trigger.updated",Yr(O)),{data:{deleted:s}}):t.code(404).send({error:{code:"TRIGGER_DEPLOYMENT_NOT_FOUND",message:"Trigger deployment not found."}})}),D.post("/api/triggers/:configHash/enable",async(e,t)=>{const s=O.setEnabled(e.params.configHash,!0);return s?(z.restart(),f.publish("trigger.enabled",s),f.publish("trigger.updated",Yr(O)),{data:s}):t.code(404).send({error:{code:"TRIGGER_NOT_FOUND",message:"Trigger not found."}})}),D.post("/api/triggers/:configHash/disable",async(e,t)=>{const s=O.setEnabled(e.params.configHash,!1);return s?(z.restart(),f.publish("trigger.disabled",s),f.publish("trigger.updated",Yr(O)),{data:s}):t.code(404).send({error:{code:"TRIGGER_NOT_FOUND",message:"Trigger not found."}})}),D.post("/api/triggers/:configHash/run",async(e,t)=>{try{f.publish("trigger.run.started",{configHash:e.params.configHash});const t=await async function(e,t,s,n={}){const r=Gi.parse(n||{}),i=e.get(s);if(!i)throw Object.assign(new Error("Trigger not found."),{code:"TRIGGER_NOT_FOUND",statusCode:404});const o=r.deploymentId?i.deployments.find(e=>(e.deploymentId||e.configHash)===r.deploymentId):i.deployments[0];if(!o)throw Object.assign(new Error("Trigger has no deployment."),{code:"TRIGGER_DEPLOYMENT_NOT_FOUND",statusCode:404});return t.execute({config:i.config,deployment:o,eventType:"manual",eventSummary:r.eventSummary,promptOverride:r.promptOverride})}(O,E,e.params.configHash,e.body||{});return f.publish("trigger.run.completed",t),f.publish("trigger.updated",Yr(O)),{data:t}}catch(s){const n=s&&"object"==typeof s&&"code"in s?String(s.code):"TRIGGER_RUN_FAILED";return f.publish("trigger.run.failed",{configHash:e.params.configHash,error:Wi(s)}),t.code("TRIGGER_NOT_FOUND"===n?404:"RECEIVER_UNAVAILABLE"===n?503:400).send({error:{code:n,message:Wi(s)}})}}),D.get("/api/triggers/runs",async()=>({data:O.list().recentRuns})),D.get("/api/ai-sessions/:id",async(e,t)=>{const s=I.get(e.params.id);return s?{data:s}:t.code(404).send({error:{code:"AI_SESSION_NOT_FOUND",message:"AI session not found."}})}),D.get("/api/ai-sessions/:id/turns",async(e,t)=>{const s=I.get(e.params.id);if(!s)return t.code(404).send({error:{code:"AI_SESSION_NOT_FOUND",message:"AI session not found."}});const n=String(e.query.afterTurnId||"").trim(),r=Number(e.query.afterRevision),i=s.turns||[],o=n?i.findIndex(e=>e.id===n):-1,a=i.filter(e=>!n||o<0||(e.id!==n?i.findIndex(t=>t.id===e.id)>o:!!Number.isFinite(r)&&e.revision>r)),d=a.at(-1);return{data:{sessionId:s.id,turns:a,nextCursor:d?{turnId:d.id,revision:d.revision}:n?{turnId:n,revision:Number.isFinite(r)?r:0}:void 0}}}),D.get("/api/ai-sessions/:id/transcript",async(e,t)=>{const s=I.get(e.params.id);if(!s?.transcriptPath)return t.code(404).send({error:{code:"AI_SESSION_TRANSCRIPT_NOT_FOUND",message:"AI session transcript not found."}});try{return{data:Zi(s.transcriptPath,Number(e.query.tail)||200)}}catch(e){return t.code(404).send({error:{code:"AI_SESSION_TRANSCRIPT_NOT_READABLE",message:e instanceof Error?e.message:String(e)}})}}),D.post("/api/ai-sessions/:id/messages",async(e,t)=>{try{const t=gs.parse(e.body||{}),s=ws.parse(await b.sendMessage(e.params.id,t));return Y("control-action"),{data:s}}catch(e){return Xi(t,e)}}),D.get("/api/ai-sessions/:id/queue",async(e,t)=>{const s=I.get(e.params.id);return s?{data:s.queue}:t.code(404).send({error:{code:"AI_SESSION_NOT_FOUND",message:"AI session not found."}})}),D.post("/api/ai-sessions/:id/queue/:queueId/steer",async(e,t)=>{try{const t=ws.parse(await b.steerQueuedMessage(e.params.id,e.params.queueId));return Y("control-action"),{data:t}}catch(e){return Xi(t,e)}}),D.post("/api/ai-sessions/:id/queue/:queueId/retry",async(e,t)=>{try{const t=b.retryQueuedMessage(e.params.id,e.params.queueId);return Y("control-action"),{data:t}}catch(e){return Xi(t,e)}}),D.delete("/api/ai-sessions/:id/queue/:queueId",async(e,t)=>{try{const t=b.removeQueuedMessage(e.params.id,e.params.queueId);return Y("control-action"),{data:t}}catch(e){return Xi(t,e)}}),D.patch("/api/ai-sessions/:id/queue/reorder",async(e,t)=>{try{const t=ys.parse(e.body||{}),s=b.reorderQueuedMessages(e.params.id,t.queueIds);return Y("control-action"),{data:s}}catch(e){return Xi(t,e)}}),D.post("/api/ai-sessions/:id/interrupt",async(e,t)=>{try{const t=ws.parse(await b.interrupt(e.params.id));return Y("control-action"),{data:t}}catch(e){return Xi(t,e)}}),D.post("/api/ai-sessions/:id/approval",async(e,t)=>{try{const t=fs.parse(e.body||{}),s=ws.parse(await b.resolveApproval(e.params.id,t.decision));return Y("control-action"),{data:s}}catch(e){return Xi(t,e)}}),D.get("/api/diagnostics",async()=>({data:Vr(m.paths,le)})),D.get("/api/settings",async()=>({data:A()})),function(e,{conversations:t,events:s}){e.get("/api/conversations",async()=>({data:t.list()})),e.post("/api/conversations",async(e,n)=>{try{const n=t.create(e.body||{});return s.publish("conversation.created",n),{data:n}}catch(e){const t=Qn(e,"CONVERSATION_CREATE_FAILED");return n.code("CONVERSATION_EXISTS"===t?409:400).send({error:{code:t,message:Zn(e)}})}}),e.get("/api/conversations/:id",async(e,s)=>{try{const n=t.get(Oe(e.params.id));return n?{data:n}:s.code(404).send({error:{code:"CONVERSATION_NOT_FOUND",message:"Conversation not found."}})}catch(e){const t=Qn(e,"CONVERSATION_GET_FAILED");return s.code("CONVERSATION_ID_INVALID"===t?400:404).send({error:{code:t,message:Zn(e)}})}}),e.patch("/api/conversations/:id",async(e,n)=>{try{const n=t.update(Oe(e.params.id),e.body||{});return s.publish("conversation.updated",n),{data:n}}catch(e){const t=Qn(e,"CONVERSATION_UPDATE_FAILED");return n.code("CONVERSATION_NOT_FOUND"===t?404:400).send({error:{code:t,message:Zn(e)}})}}),e.post("/api/conversations/:id/use",async(e,n)=>{try{const n=t.use(Oe(e.params.id));return s.publish("conversation.default.updated",n),{data:n}}catch(e){const t=Qn(e,"CONVERSATION_USE_FAILED");return n.code("CONVERSATION_NOT_FOUND"===t?404:400).send({error:{code:t,message:Zn(e)}})}}),e.post("/api/conversations/:id/close",async(e,n)=>{try{const n=t.close(Oe(e.params.id));return s.publish("conversation.closed",n),{data:n}}catch(e){const t=Qn(e,"CONVERSATION_CLOSE_FAILED");return n.code("CONVERSATION_NOT_FOUND"===t?404:400).send({error:{code:t,message:Zn(e)}})}}),e.post("/api/conversations/:id/reopen",async(e,n)=>{try{const n=t.reopen(Oe(e.params.id));return s.publish("conversation.reopened",n),{data:n}}catch(e){const t=Qn(e,"CONVERSATION_REOPEN_FAILED");return n.code("CONVERSATION_NOT_FOUND"===t?404:400).send({error:{code:t,message:Zn(e)}})}}),e.delete("/api/conversations/:id",async(e,n)=>{try{const n=t.delete(Oe(e.params.id));return s.publish("conversation.deleted",n),{data:n}}catch(e){const t=Qn(e,"CONVERSATION_DELETE_FAILED"),s="CONVERSATION_NOT_FOUND"===t?404:"CONVERSATION_DEFAULT"===t?409:400;return n.code(s).send({error:{code:t,message:Zn(e)}})}})}(D,{conversations:w,events:f}),D.post("/api/receiver/start",async(e,t)=>Br()?t.code(409).send({error:{code:"RECEIVER_MANAGED_BY_CONTROL_PLANE",message:"Receiver chat bindings are managed by the control plane while this instance is node-agent controlled."}}):(or(m.paths.channelsDir,m.paths.configPath),{data:y.start()})),D.post("/api/receiver/stop",async()=>({data:y.stop()})),D.get("/api/receiver/logs",async e=>{const t=Number(e.query.maxBytes||65536),s=Number.isFinite(t)?Math.min(Math.max(1024,t),524288):65536;return{data:y.readLogs(s)}}),D.get("/api/receiver/status",async()=>({data:{...y.status(),pendingCount:await Gr(v)}})),D.post("/api/receiver/messages",async(e,t)=>{try{const s=Ki.parse(e.body);return s.message.text.trim()?{data:await v.message({channel:s.source.channel,chatSessionId:s.source.chatSessionId,userId:s.source.userId,text:s.message.text,attachments:s.message.attachments,conversationId:s.routing.conversationId})}:t.code(400).send({error:{code:"RECEIVER_MESSAGE_INVALID",message:"Message text is required."}})}catch(e){const s=e&&"object"==typeof e&&"code"in e?String(e.code):"RECEIVER_MESSAGE_INVALID";return t.code("RECEIVER_UNAVAILABLE"===s?503:400).send({error:{code:s,message:Wi(e)}})}});const ge=async(e,t)=>{try{return{data:await v.pendingList()}}catch(e){const s=e&&"object"==typeof e&&"code"in e?String(e.code):"RECEIVER_CONTROL_FAILED";return t.code("RECEIVER_UNAVAILABLE"===s?503:400).send({error:{code:s,message:e instanceof Error?e.message:String(e)}})}};D.get("/api/tasks/pending",ge),D.get("/api/receiver/pending",ge),D.post("/api/tasks/:id/reply",async(e,t)=>{const s=Number(e.params.id),n=e.body?.markdown;if(!Number.isInteger(s)||s<=0||!n?.trim())return t.code(400).send({error:{code:"TASK_REPLY_INVALID",message:"Task id and markdown are required."}});try{return{data:await v.reply(s,n)}}catch(e){const s=e&&"object"==typeof e&&"code"in e?String(e.code):"RECEIVER_CONTROL_FAILED";return t.code("PENDING_TASK_NOT_FOUND"===s?404:"RECEIVER_UNAVAILABLE"===s?503:400).send({error:{code:s,message:e instanceof Error?e.message:String(e)}})}}),D.post("/api/receiver/pending/:id/reply",async(e,t)=>{const s=Number(e.params.id),n=e.body?.markdown;if(!Number.isInteger(s)||s<=0||!n?.trim())return t.code(400).send({error:{code:"TASK_REPLY_INVALID",message:"Task id and markdown are required."}});try{return{data:await v.reply(s,n)}}catch(e){const s=e&&"object"==typeof e&&"code"in e?String(e.code):"RECEIVER_CONTROL_FAILED";return t.code("PENDING_TASK_NOT_FOUND"===s?404:"RECEIVER_UNAVAILABLE"===s?503:400).send({error:{code:s,message:e instanceof Error?e.message:String(e)}})}}),D.post("/api/tasks/:id/drop",async(e,t)=>{const s=Number(e.params.id);if(!Number.isInteger(s)||s<=0)return t.code(400).send({error:{code:"TASK_ID_INVALID",message:"Task id must be a positive integer."}});try{return{data:await v.drop(s)}}catch(e){const s=e&&"object"==typeof e&&"code"in e?String(e.code):"RECEIVER_CONTROL_FAILED";return t.code("PENDING_TASK_NOT_FOUND"===s?404:"RECEIVER_UNAVAILABLE"===s?503:400).send({error:{code:s,message:e instanceof Error?e.message:String(e)}})}});for(const[e,t]of[["approve","allow"],["deny","deny"],["skip","skip"]])D.post(`/api/tasks/:id/${e}`,async(e,s)=>{const n=Number(e.params.id);if(!Number.isInteger(n)||n<=0)return s.code(400).send({error:{code:"TASK_ID_INVALID",message:"Task id must be a positive integer."}});try{return{data:await v.approval(n,t)}}catch(e){const t=e&&"object"==typeof e&&"code"in e?String(e.code):"RECEIVER_CONTROL_FAILED";return s.code("PENDING_TASK_NOT_FOUND"===t?404:"RECEIVER_UNAVAILABLE"===t?503:400).send({error:{code:t,message:e instanceof Error?e.message:String(e)}})}}),D.post(`/api/receiver/pending/:id/${e}`,async(e,s)=>{const n=Number(e.params.id);if(!Number.isInteger(n)||n<=0)return s.code(400).send({error:{code:"TASK_ID_INVALID",message:"Task id must be a positive integer."}});try{return{data:await v.approval(n,t)}}catch(e){const t=e&&"object"==typeof e&&"code"in e?String(e.code):"RECEIVER_CONTROL_FAILED";return s.code("PENDING_TASK_NOT_FOUND"===t?404:"RECEIVER_UNAVAILABLE"===t?503:400).send({error:{code:t,message:e instanceof Error?e.message:String(e)}})}});D.post("/api/receiver/pending/:id/approval",async(e,t)=>{const s=Number(e.params.id),n=e.body?.decision;if(!Number.isInteger(s)||s<=0||!n)return t.code(400).send({error:{code:"TASK_APPROVAL_INVALID",message:"Task id and approval decision are required."}});try{return{data:await v.approval(s,n)}}catch(e){const s=e&&"object"==typeof e&&"code"in e?String(e.code):"RECEIVER_CONTROL_FAILED";return t.code("PENDING_TASK_NOT_FOUND"===s?404:"RECEIVER_UNAVAILABLE"===s?503:400).send({error:{code:s,message:e instanceof Error?e.message:String(e)}})}}),D.get("/api/apps/catalog",async()=>({data:S.catalog()})),D.get("/api/config-sync/presets",async()=>({data:Ir()})),D.post("/api/config-sync/:direction/:preset",async(e,t)=>{const s=e.params.direction;if("import"!==s&&"export"!==s)return t.code(400).send({error:{code:"CONFIG_SYNC_DIRECTION_INVALID",message:"Config sync direction must be import or export."}});try{const t=Li.parse(e.body||{});return{data:br(s,e.params.preset,t.preset)}}catch(e){const s=e&&"object"==typeof e?e:{};return t.code("number"==typeof s.statusCode?s.statusCode:500).send({error:{code:"string"==typeof s.code?s.code:"CONFIG_SYNC_FAILED",message:e instanceof Error?e.message:String(e)}})}}),D.get("/api/apps/catalog/custom",async(e,t)=>{const s=S.customCatalog();return s.error||!s.data?t.code(400).send({error:s.error||{code:"APP_CATALOG_INVALID",message:"Custom app catalog is invalid."}}):{data:s.data}}),D.patch("/api/apps/catalog/custom",async(e,t)=>{try{return{data:S.saveCustomCatalog(e.body?.items||[])}}catch(e){return t.code(400).send({error:{code:"APP_CATALOG_INVALID",message:e instanceof Error?e.message:String(e)}})}}),D.get("/api/apps/sessions",async(e,t)=>{if(void 0!==e.query.sinceRevision){const s=Number(e.query.sinceRevision);return!Number.isInteger(s)||s<0?t.code(400).send({error:{code:"APP_SESSION_DELTA_INVALID",message:"sinceRevision must be a non-negative integer."}}):{data:ne(s)}}return{data:S.listSessions()}}),D.get("/api/apps/sessions/state",async()=>({data:{revision:L,lastEventAt:U.at(-1)?.payload.meta.generatedAt||a,snapshot:Ti(S.listSessions())}})),D.post("/api/apps/sessions",async(e,t)=>{try{const t=function(e={}){const t=$i.parse(e||{}),s={};return t.title&&(s.title=t.title),t.args&&(s.args=t.args),t.cwd&&(s.cwd=t.cwd),t.env&&(s.env=t.env),t.display&&(s.display=t.display),t.displayTarget&&(s.displayTarget=t.displayTarget),{appId:t.appId||"terminal-tty",options:s}}(e.body);return{data:S.start(t.appId,t.options)}}catch(e){if(e instanceof i.z.ZodError)return t.code(400).send({error:{code:"APP_LAUNCH_INVALID",message:Wi(e)}});const s=e&&"object"==typeof e&&"code"in e?String(e.code):"APP_LAUNCH_FAILED";return t.code("APP_NOT_FOUND"===s?404:400).send({error:{code:s,message:e instanceof Error?e.message:String(e)}})}}),D.get("/api/apps/sessions/:id",async(e,t)=>{const s=S.getSession(e.params.id);return s?{data:s}:t.code(404).send({error:{code:"APP_SESSION_NOT_FOUND",message:"App session not found."}})}),D.patch("/api/apps/sessions/:id",async(e,t)=>{try{const{title:t}=qi.parse(e.body||{});return{data:S.rename(e.params.id,t)}}catch(e){if(e instanceof i.z.ZodError)return t.code(400).send({error:{code:"APP_SESSION_UPDATE_INVALID",message:Wi(e)}});const s=e&&"object"==typeof e&&"code"in e?String(e.code):"APP_SESSION_UPDATE_FAILED";return t.code("APP_SESSION_NOT_FOUND"===s?404:400).send({error:{code:s,message:e instanceof Error?e.message:String(e)}})}}),D.post("/api/apps/sessions/:id/stop",async(e,t)=>{try{return{data:S.stop(e.params.id)}}catch(e){return t.code(404).send({error:{code:"APP_SESSION_NOT_FOUND",message:e instanceof Error?e.message:String(e)}})}}),D.post("/api/apps/sessions/:id/restart",async(e,t)=>{try{return{data:S.restart(e.params.id)}}catch(e){const s=e&&"object"==typeof e&&"code"in e?String(e.code):"APP_RESTART_FAILED";return t.code("APP_SESSION_NOT_FOUND"===s?404:400).send({error:{code:s,message:e instanceof Error?e.message:String(e)}})}}),D.post("/api/apps/sessions/:id/display",async(e,t)=>{try{return{data:S.resizeDisplay(e.params.id,Ui.parse(e.body||{}))}}catch(e){const s=e&&"object"==typeof e&&"code"in e?String(e.code):"APP_DISPLAY_RESIZE_FAILED";return e instanceof i.z.ZodError?t.code(400).send({error:{code:"APP_DISPLAY_INVALID",message:Wi(e)}}):t.code("APP_DISPLAY_NOT_FOUND"===s?404:400).send({error:{code:s,message:e instanceof Error?e.message:String(e)}})}}),D.delete("/api/apps/sessions/:id",async(e,t)=>{try{return{data:await S.delete(e.params.id)}}catch(e){const s=e&&"object"==typeof e&&"code"in e?String(e.code):"APP_DELETE_FAILED";return t.code("APP_SESSION_NOT_FOUND"===s?404:400).send({error:{code:s,message:e instanceof Error?e.message:String(e)}})}}),D.get("/api/apps/sessions/:id/logs",async(e,t)=>{try{const t=Number(e.query.maxBytes||65536),s=Number.isFinite(t)?Math.min(Math.max(1024,t),524288):65536;return{data:S.readLogs(e.params.id,s)}}catch(e){const s=e&&"object"==typeof e&&"code"in e?String(e.code):"APP_LOGS_FAILED";return t.code("APP_SESSION_NOT_FOUND"===s?404:400).send({error:{code:s,message:e instanceof Error?e.message:String(e)}})}}),D.get("/api/apps/sessions/:id/screenshot",async(e,t)=>{try{const s=S.screenshot(e.params.id);return t.header("Cache-Control","no-store").type("image/png").send(s)}catch(e){const s=e&&"object"==typeof e&&"code"in e?String(e.code):"APP_SCREENSHOT_FAILED",n="APP_SESSION_NOT_FOUND"===s?404:"APP_SCREENSHOT_UNAVAILABLE"===s?409:400;return t.code(n).send({error:{code:s,message:e instanceof Error?e.message:String(e)}})}}),D.get("/api/apps/sessions/:id/snapshot",async(e,t)=>{try{const s=S.screenshot(e.params.id);return t.header("Cache-Control","no-store").type("image/png").send(s)}catch(e){const s=e&&"object"==typeof e&&"code"in e?String(e.code):"APP_SNAPSHOT_FAILED",n="APP_SESSION_NOT_FOUND"===s?404:"APP_SCREENSHOT_UNAVAILABLE"===s?409:400;return t.code(n).send({error:{code:s,message:e instanceof Error?e.message:String(e)}})}}),D.get("/api/apps/sessions/:id/automation",async(e,t)=>{try{return{data:await S.automationStatus(e.params.id)}}catch(e){const s=e&&"object"==typeof e&&"code"in e?String(e.code):"APP_AUTOMATION_FAILED",n="APP_SESSION_NOT_FOUND"===s?404:"APP_AUTOMATION_UNAVAILABLE"===s?409:400;return t.code(n).send({error:{code:s,message:e instanceof Error?e.message:String(e)}})}}),D.get("/api/apps/sessions/:id/tty",{websocket:!0},(e,t)=>{S.attachTty(t.params.id,e)}),D.get("/api/apps/sessions/:id/vnc",{websocket:!0},(e,t)=>{const s=S.vncTarget(t.params.id);if(!s)return e.send(JSON.stringify({error:{code:"VNC_SESSION_NOT_FOUND",message:"VNC session not found."}})),void e.close();const n=o.connect(s.port,s.host);n.on("data",t=>{e.readyState===e.OPEN&&e.send(t)}),n.on("close",()=>e.close()),n.on("error",()=>e.close()),e.on("message",e=>{n.write(function(e){return Buffer.isBuffer(e)?e:Array.isArray(e)?Buffer.concat(e):Buffer.from(e)}(e))}),e.on("close",()=>n.destroy())});const fe=async(e,t)=>{const s=S.webTarget(e.params.id);if(!s)return function(e,t,s,n=502){return e.code(n).send({error:{code:t,message:s}})}(t,"WEB_SESSION_NOT_FOUND","Web session not found.",404);const n="kasmvnc"===S.getSession(e.params.id)?.vnc?.backend,r=n?{authorization:ni()}:{};t.hijack();const i=function(e){if(void 0!==e)return Buffer.isBuffer(e)||"string"==typeof e?e:JSON.stringify(e)}(e.body),o=void 0!==i||"GET"===e.method||"HEAD"===e.method||"OPTIONS"===e.method,a=Date.now(),c=`http://${s.host}:${s.port}`,p=new URL(si(e.params.id,e.raw.url),`${c}/`).toString();for(;;)try{const a=await l.proxyFetch(c,p,Ri({method:e.method,headers:ri(e.headers,s.host,s.port,r),requestBody:i,rawRequest:e.raw,streamRawRequest:void 0===i&&!o})),u=ci(a.headers);if("HEAD"!==e.method&&n&&ai(u)){const e=Buffer.from(di(Buffer.from(await a.arrayBuffer()),u),"utf8"),s={...u,"content-length":String(e.byteLength)};delete s.etag,t.raw.writeHead(a.status||502,a.statusText,s),t.raw.end(e);break}if(t.raw.writeHead(a.status||502,a.statusText,pi(a.headers)),!a.body||"HEAD"===e.method){t.raw.end();break}await d.pipeline(Mi(a.body),t.raw);break}catch(e){if(o&&ti(e)&&Date.now()-a<8e3){await ei(200);continue}if(t.raw.headersSent||t.raw.destroyed){t.raw.destroyed||t.raw.destroy(e instanceof Error?e:void 0);break}t.raw.headersSent||t.raw.writeHead(502,{"content-type":"application/json"}),t.raw.end(JSON.stringify({error:{code:"WEB_PROXY_FAILED",message:e instanceof Error?e.message:String(e)}}));break}return t};D.route({method:"GET",url:"/api/apps/sessions/:id/web/*",wsHandler:(e,t)=>{const s=S.webTarget(t.params.id);if(!s)return e.send(JSON.stringify({error:{code:"WEB_SESSION_NOT_FOUND",message:"Web session not found."}})),void e.close();const n=`http://${s.host}:${s.port}`,r="kasmvnc"===S.getSession(t.params.id)?.vnc?.backend?{authorization:ni(),origin:n,"sec-websocket-origin":t.headers.origin||n}:{origin:n},i=Date.now(),o=`ws://${s.host}:${s.port}${si(t.params.id,t.raw.url)}`,a=function(e){const t=e["sec-websocket-protocol"],s=(Array.isArray(t)?t:t?[t]:[]).flatMap(e=>e.split(",").map(e=>e.trim()).filter(Boolean));return s.length?s:void 0}(t.headers)||("kasmvnc"===S.getSession(t.params.id)?.vnc?.backend?["binary"]:void 0),d=()=>{if(e.readyState!==e.OPEN)return;const n=new Fi(o,a,{headers:ii(t.headers,s.host,s.port,r)});!function(e,t,s={}){const n=s.pendingFrameLimit??256;let r=!1,i=Di(t);const o=[],a=[];let d;const c=()=>{d&&(clearTimeout(d),d=void 0)},p=(s,r)=>{if(s.length>=n)return ki(e,1011,"WebSocket bridge pending frame limit exceeded."),void ki(t,1011,"WebSocket bridge pending frame limit exceeded.");s.push(r)};s.upstreamOpenTimeoutMs&&!i&&(d=setTimeout(()=>{i||r||(ki(e,1011,"Upstream websocket did not open."),ki(t))},s.upstreamOpenTimeoutMs)),e.on("open",()=>Pi(e,a)),t.on("open",()=>{c(),i=!0,s.onUpstreamOpen?.(),Pi(t,o)}),e.on("message",(e,s=!1)=>{const n={data:e,isBinary:Boolean(s)};Di(t)?Ci(t,n):p(o,n)}),t.on("message",(t,s=!1)=>{const n={data:t,isBinary:Boolean(s)};Di(e)?Ci(e,n):p(a,n)}),t.on("close",(t,n)=>{c(),s.onUpstreamClose?.(t,n),(i||r||!s.onUpstreamCloseBeforeOpen?.())&&ki(e,t,n)}),t.on("error",t=>{s.onUpstreamError?.(t),(i||r||!s.onUpstreamErrorBeforeOpen?.(t))&&ki(e)}),e.on("close",(e,n)=>{c(),r=!0,s.onClientClose?.(e,n),ki(t,e,n)}),e.on("error",e=>{c(),r=!0,s.onClientError?.(e),ki(t,1011,"WebSocket bridge client failed.")})}(e,n,{onUpstreamCloseBeforeOpen:()=>Date.now()-i<8e3&&(ei(200).then(d),!0),onUpstreamErrorBeforeOpen:e=>ti(e)})};d()},handler:fe});for(const e of["DELETE","OPTIONS","PATCH","POST","PUT"])D.route({method:e,url:"/api/apps/sessions/:id/web/*",handler:fe});return D.get("/api/apps/sessions/:id/novnc/vnc.html",async(e,t)=>{const s=S.getSession(e.params.id);if(!s?.vnc)return t.code(404).send({error:{code:"VNC_SESSION_NOT_FOUND",message:"VNC session not found."}});const n="remote"===e.query.resize?"remote":"scale",r=new URLSearchParams({path:s.vnc.webPath.replace(/^\//,""),autoconnect:"1",resize:n});return t.redirect(`/api/novnc/vnc.html?${r.toString()}`)}),D.patch("/api/settings",async(e,t)=>{try{const s=e.body||{},n=Number(s.defaultConversationId);if(Object.prototype.hasOwnProperty.call(s,"defaultConversationId")){if(!Number.isInteger(n)||n<=0)return t.code(400).send({error:{code:"SETTINGS_INVALID_CONVERSATION",message:"Default conversation id must be a positive integer."}});if(!w.get(n))return t.code(404).send({error:{code:"CONVERSATION_NOT_FOUND",message:"Default conversation does not exist."}})}const r=_(s);return Number.isInteger(n)&&n>0&&w.use(n),{data:r}}catch(e){return t.code(400).send({error:{code:"SETTINGS_UPDATE_FAILED",message:e instanceof Error?e.message:String(e)}})}}),D.get("/api/channels",async()=>({data:[ji(m.channel("telegram").load.bind(m.channel("telegram"))),ji(m.channel("wechat").load.bind(m.channel("wechat"))),ji(m.channel("dingding").load.bind(m.channel("dingding")))]})),D.get("/api/channels/:channel/:instanceId",async(e,t)=>{const s=e.params.channel;if(!["telegram","wechat","dingding"].includes(s))return t.code(404).send({error:{code:"CHANNEL_NOT_FOUND",message:"Channel not found."}});const n=m.channel(s,e.params.instanceId);return{data:ji(n.load.bind(n))}}),D.patch("/api/channels/:channel/:instanceId",async(e,t)=>{const s=e.params.channel;if(!["telegram","wechat","dingding"].includes(s))return t.code(404).send({error:{code:"CHANNEL_NOT_FOUND",message:"Channel not found."}});const n=m.channel(s,e.params.instanceId).patch({...Qi(e.body),channel:s,instanceId:e.params.instanceId,schemaVersion:1});return ir(n,m.paths.configPath),{data:ji(()=>n)}}),D.setNotFoundHandler(async(e,n)=>{if(e.url.startsWith("/api/"))return n.code(404).send({error:{code:"NOT_FOUND",message:"Not found."}});const r=s.join(he,"index.html");return t.existsSync(r)?n.type("text/html").send(t.readFileSync(r,"utf8")):n.type("text/plain").send("TaskHandoff Web UI has not been built yet. Run pnpm web:build.")}),D}function to(e){const t=Number(e);if(!Number.isInteger(t)||t<=0)throw new Error("Conversation id must be a positive integer.");return t}function so(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}(async function(){process.env.TASK_HANDOFF_CLI_PATH||=__filename;const n=new e.Command;var r;n.name("task-handoff-controlled-instance").description("Run a TaskHandoff controlled instance.").version(function(){try{return JSON.parse(t.readFileSync(s.resolve(__dirname,"..","package.json"),"utf8")).version||"unknown"}catch{return"unknown"}}()),n.command("web").description("Run the controlled instance web server.").option("--host <host>","Web server host",process.env.TASK_HANDOFF_WEB_HOST||"127.0.0.1").option("-p, --port <port>","Web server port",so,Number(process.env.TASK_HANDOFF_WEB_PORT)||8080).option("-s, --socket <path>","Unix socket path",N).option("--static-dir <path>","Web UI static directory",process.env.TASK_HANDOFF_WEB_STATIC_DIR||s.resolve(__dirname,"..","ui")).option("--receiver-auto-start","Start the receiver runtime with the web server.").action(async e=>{await async function(e={}){const t=e.host||process.env.TASK_HANDOFF_WEB_HOST||"127.0.0.1",s=Number(e.port||process.env.TASK_HANDOFF_WEB_PORT||8080),n=await eo(e);return function(e){let t=!1;const s=async s=>{if(!t){t=!0;try{await e.close()}finally{process.exitCode=s?0:process.exitCode}}},n=()=>{s("SIGINT")},r=()=>{s("SIGTERM")};process.once("SIGINT",n),process.once("SIGTERM",r),e.addHook("onClose",async()=>{process.off("SIGINT",n),process.off("SIGTERM",r)})}(n),await n.listen({host:t,port:s}),n}({host:e.host,port:e.port,socketPath:e.socket,staticDir:e.staticDir,receiverAutoStart:e.receiverAutoStart})}),n.command("receiver").description("Run the controlled instance receiver.").option("-s, --socket <path>","Unix socket path",N).option("--telegram-token <token>","Telegram bot token",k).option("--telegram-chat-id <id>","Telegram target chat id",D).option("--telegram-allowed-user-ids <ids>","Comma-separated Telegram user ids allowed to control the bot",C.join(",")).option("--telegram-conversation <id>","Telegram passive conversation id",to,P).option("--wechat-token <token>","Wechat iLink bot token",H).option("--wechat-base-url <url>","Wechat iLink base URL",R).option("--wechat-chat-id <id>","Wechat target chat id",M).option("--wechat-conversation <id>","Wechat passive conversation id",to,$).option("--wechat-context-token <token>","Wechat conversation context token",j).option("--wechat-updates-buf <cursor>","Wechat getupdates cursor",L).option("--dingding-client-id <id>","DingDing stream client id",B).option("--dingding-client-secret <secret>","DingDing stream client secret",V).option("--dingding-corp-id <id>","DingDing corp id",G).option("--dingding-robot-code <code>","DingDing robot code",W).option("--dingding-card-template-id <id>","DingDing interactive card template id",X).option("--dingding-card-callback-route-key <key>","DingDing interactive card callback route key",J).option("--dingding-card-user-id-type <type>","DingDing interactive card user id type",Number,Y).option("--dingding-chat-id <id>","DingDing target conversation id",Q).option("--dingding-allowed-user-ids <ids>","Comma-separated DingDing user ids allowed to control the bot",Z.join(",")).option("--dingding-conversation <id>","DingDing passive conversation id",to,ee).option("--headless","Run receiver without interactive terminal input.").action(async e=>{await async function(e){const t=new Function("specifier","return import(specifier)"),{runReceiverInk:n}=await t(v.pathToFileURL(s.join(__dirname,"receiver-ink.mjs")).href);return n(e)}({socketPath:e.socket,telegramToken:e.telegramToken,telegramChatId:e.telegramChatId,telegramAllowedUserIds:e.telegramAllowedUserIds,telegramConversationId:e.telegramConversation,wechatToken:e.wechatToken,wechatBaseUrl:e.wechatBaseUrl,wechatChatId:e.wechatChatId,wechatConversationId:e.wechatConversation,wechatContextToken:e.wechatContextToken,wechatUpdatesBuf:e.wechatUpdatesBuf,dingdingClientId:e.dingdingClientId,dingdingClientSecret:e.dingdingClientSecret,dingdingCorpId:e.dingdingCorpId,dingdingRobotCode:e.dingdingRobotCode,dingdingCardTemplateId:e.dingdingCardTemplateId,dingdingCardCallbackRouteKey:e.dingdingCardCallbackRouteKey,dingdingCardUserIdType:e.dingdingCardUserIdType,dingdingChatId:e.dingdingChatId,dingdingAllowedUserIds:e.dingdingAllowedUserIds,dingdingConversationId:e.dingdingConversation,headless:e.headless})}),void 0===(r=process.argv)[2]&&r.push("web"),await n.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"),s=require("node:path"),n=require("node:os"),r=require("write-file-atomic"),i=require("zod"),o=require("node:net"),a=require("node:stream"),d=require("node:stream/promises"),c=require("@fastify/static"),p=require("@fastify/websocket"),u=require("fastify"),l=require("httpxy"),m=require("node:child_process"),h=require("node:crypto"),g=require("node:events"),f=require("node-pty"),y=require("ws"),v=require("node:url");const S=process.env.TASK_HANDOFF_CONFIG||s.join(process.env.XDG_CONFIG_HOME||s.join(n.homedir(),".config"),"task-handoff","config.json"),I=i.z.record(i.z.string(),i.z.unknown());function A(){try{return I.parse(JSON.parse(t.readFileSync(S,"utf8")))}catch(e){return e&&"object"==typeof e&&"code"in e&&e.code,{}}}function b(e,t){const s={...e};for(const[e,n]of Object.entries(t))if(n&&"object"==typeof n&&!Array.isArray(n)){const t=s[e];s[e]=b(t&&"object"==typeof t&&!Array.isArray(t)?I.parse(t):{},n)}else void 0===n?delete s[e]:s[e]=n;return s}function _(e){const n=b(A(),e);return function(e){t.mkdirSync(s.dirname(S),{recursive:!0}),r.sync(S,`${JSON.stringify(I.parse(e),null,2)}\n`,{mode:384})}(n),n}const w=A(),T=Number(w.defaultConversationId)||1,N=process.env.TASK_HANDOFF_SOCKET||s.join(n.tmpdir(),`task-handoff-${process.getuid?process.getuid():"user"}.sock`),O=w.chatTools?.telegram?.default||{},E=O.defaultChatId,z=E?w.chatBindings?.telegram?.default?.[E]:void 0;function x(e){return Array.isArray(e)?e.map(e=>String(e).trim()).filter(Boolean):String(e||"").split(",").map(e=>e.trim()).filter(Boolean)}const D=E,k=O.token,C=x(O.allowedUserIds),P=Number(z?.conversationId)||T,F=w.wechat||{},R=F.baseUrl,M=F.chatId,j=F.contextToken,H=F.token,L=F.updatesBuf,$=Number(F.conversationId)||T,U=w.chatTools?.dingding?.default||{},q=U.defaultChatId,B=q?w.chatBindings?.dingding?.default?.[q]:void 0,V=U.clientId,K=U.clientSecret,G=U.corpId,W=U.robotCode,X=U.cardTemplateId||"13fc6717-12e4-43ed-8533-111a310d4995.schema",J=U.cardCallbackRouteKey||"bi_workflow_ticket",Y=Number(U.cardUserIdType)||1,Q=q,Z=x(U.allowedUserIds),ee=Number(B?.conversationId)||T,te=/(TOKEN|KEY|SECRET|AUTH|PASSWORD|COOKIE)/i,se=/^(TASK_HANDOFF|CODEX|CLAUDE|PWD$|OLDPWD$|SHELL$|TERM$)/;function ne(e,t){if(void 0!==t)return te.test(e)?"[redacted]":t}function re(e=process.env){return Object.fromEntries(Object.entries(e).filter(([e])=>se.test(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,ne(e,t)]))}function ie(e){if(e)try{return m.execFileSync("ps",["-p",String(e),"-o","pid=,ppid=,comm=,args="],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e3}).trim()||void 0}catch{return}}function oe(e,n){t.mkdirSync(s.dirname(e),{recursive:!0}),t.appendFileSync(e,`${JSON.stringify({time:(new Date).toISOString(),...n})}\n`,{mode:384})}function ae(e){const t=Number(String(e||"").trim());return Number.isInteger(t)&&t>0?t:void 0}function de(e){return"codex"===e||"claude"===e||"passive"===e?e:void 0}function ce(e){const t=Number(e);return Number.isFinite(t)&&t>0?t:void 0}function pe(e){return"codex"===e||"claude"===e?e:void 0}function ue(e,t="open"){return function(e,t="passive",s="open"){const n=(new Date).toISOString();return{id:e,mode:t,status:s,createdAt:n,updatedAt:n,agent:"codex"===t||"claude"===t?t:void 0}}(e,"passive",t)}const le=i.z.record(i.z.string(),i.z.unknown());class me{filePath;options;constructor(e,t){this.filePath=e,this.options=t}path(){return this.filePath}load(){try{const e=JSON.parse(t.readFileSync(this.filePath,"utf8"));return this.options.schema.parse(e)}catch(e){if(e&&"object"==typeof e&&"code"in e&&"ENOENT"===e.code)return this.options.defaultValue();throw e}}save(e){t.mkdirSync(s.dirname(this.filePath),{recursive:!0}),r.sync(this.filePath,`${JSON.stringify(this.options.schema.parse(e),null,2)}\n`,{mode:384})}patch(e){const t=this.load(),s=he(le.parse(t),e),n=this.options.schema.parse(s);return this.save(n),n}}function he(e,t){const s={...e};for(const[e,n]of Object.entries(t))if(n&&"object"==typeof n&&!Array.isArray(n)){const t=s[e];s[e]=he(t&&"object"==typeof t&&!Array.isArray(t)?le.parse(t):{},le.parse(n))}else void 0===n?delete s[e]:s[e]=n;return s}const ge=i.z.enum(["passive","codex","claude"]),fe=i.z.enum(["open","closed"]),ye=i.z.enum(["codex","claude"]),ve=i.z.object({schemaVersion:i.z.literal(1).default(1),id:i.z.number().int().positive(),mode:ge.default("passive"),status:fe.default("open"),title:i.z.string().optional(),cwd:i.z.string().optional(),timeoutMs:i.z.number().positive().optional(),agent:ye.optional(),agentSessionId:i.z.string().optional(),codexSessionId:i.z.string().optional(),createdAt:i.z.string(),updatedAt:i.z.string(),closedAt:i.z.string().optional()}),Se=i.z.object({id:i.z.number().int().positive(),status:fe.default("open"),mode:ge.default("passive"),title:i.z.string().optional(),updatedAt:i.z.string()}),Ie=i.z.object({schemaVersion:i.z.literal(1).default(1),defaultConversationId:i.z.number().int().positive().default(T),nextConversationId:i.z.number().int().positive().default(T+1),items:i.z.array(Se).default([])}),Ae=i.z.object({mode:ge.optional(),status:fe.optional(),title:i.z.string().trim().min(1).optional(),cwd:i.z.string().trim().min(1).optional(),timeoutMs:i.z.number().positive().optional(),agent:ye.optional(),agentSessionId:i.z.string().trim().min(1).optional(),codexSessionId:i.z.string().trim().min(1).optional()});function be(){return(new Date).toISOString()}function _e(e){const t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}function we(e){return Array.isArray(e)?e.map(we):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).filter(([,e])=>null!=e&&""!==e).map(([e,t])=>[e,we(t)])):e}function Te(e){return{id:e.id,status:e.status,mode:e.mode,title:e.title,updatedAt:e.updatedAt}}class Ne{paths;indexStore;constructor(e){this.paths=e,this.indexStore=new me(s.join(e.conversationsDir,"index.json"),{schema:Ie,defaultValue:()=>({schemaVersion:1,defaultConversationId:T,nextConversationId:T+1,items:[]})})}indexPath(){return this.indexStore.path()}list(){const e=this.ensureSeeded(),t=e.items.map(e=>this.loadRecord(e.id)).filter(e=>Boolean(e)).sort((e,t)=>e.id-t.id);return{schemaVersion:1,defaultConversationId:e.defaultConversationId,nextConversationId:e.nextConversationId,indexPath:this.indexStore.path(),items:t}}get(e){return this.ensureSeeded(),this.loadRecord(e)}create(e={}){const t=this.ensureSeeded(),s=be(),n=_e(e.id)||t.nextConversationId;if(this.loadRecord(n))throw Object.assign(new Error(`Conversation ${n} already exists.`),{code:"CONVERSATION_EXISTS"});const r=Ae.parse(we(e)),i=ve.parse({schemaVersion:1,id:n,mode:r.mode||"passive",status:r.status||"open",title:r.title,cwd:r.cwd,timeoutMs:r.timeoutMs,agent:r.agent||("codex"===r.mode||"claude"===r.mode?r.mode:void 0),agentSessionId:r.agentSessionId,codexSessionId:r.codexSessionId,createdAt:s,updatedAt:s});return this.saveRecord(i),this.saveIndex({...t,nextConversationId:Math.max(t.nextConversationId,n+1),items:[...t.items,Te(i)].sort((e,t)=>e.id-t.id)}),i}update(e,t){const s=this.getRequired(e),n=Ae.parse(we(t)),r=be(),i=ve.parse({...s,...n,agent:n.agent||("codex"===n.mode||"claude"===n.mode?n.mode:s.agent),updatedAt:r,closedAt:"closed"===n.status?s.closedAt||r:"open"===n.status?void 0:s.closedAt});return this.saveRecord(i),this.updateIndexItem(i),i}use(e){const t=this.getRequired(e),s=this.ensureSeeded();return this.saveIndex({...s,defaultConversationId:e}),_({defaultConversationId:e}),t}close(e){return this.update(e,{status:"closed"})}reopen(e){return this.update(e,{status:"open"})}delete(e){const s=this.ensureSeeded();if(e===s.defaultConversationId)throw Object.assign(new Error("Default conversation cannot be deleted."),{code:"CONVERSATION_DEFAULT"});const n=this.getRequired(e),r=this.recordPath(e);return t.existsSync(r)&&t.unlinkSync(r),this.saveIndex({...s,items:s.items.filter(t=>t.id!==e)}),n}ensureSeeded(){if(t.existsSync(this.indexStore.path()))return this.indexStore.load();const e=A(),s=function(e){const t=new Map;for(const s of Array.isArray(e.conversations)?e.conversations:[]){const e=ae(s?.id);if(!e)continue;const n=de(s.mode)||"passive",r=pe(s.agent)||("codex"===n||"claude"===n?n:void 0),i="string"==typeof s.agentSessionId&&s.agentSessionId.trim()?s.agentSessionId.trim():"codex"===r&&"string"==typeof s.codexSessionId&&s.codexSessionId.trim()?s.codexSessionId.trim():void 0;t.set(e,{id:e,mode:n,status:"closed"===s.status?"closed":"open",createdAt:s.createdAt||(new Date).toISOString(),updatedAt:s.updatedAt||(new Date).toISOString(),closedAt:s.closedAt,cwd:"string"==typeof s.cwd&&s.cwd.trim()?s.cwd.trim():void 0,timeoutMs:ce(s.timeoutMs),agent:r,aiSessionId:"string"==typeof s.aiSessionId&&s.aiSessionId.trim()?s.aiSessionId.trim():void 0,agentSessionId:i,codexSessionId:"string"==typeof s.codexSessionId&&s.codexSessionId.trim()?s.codexSessionId.trim():"codex"===r&&i?i:void 0})}const s=ae(e.defaultConversationId)||T;t.has(s)||t.set(s,ue(s)),t.has(T)||t.set(T,ue(T));const n=[...t.values()].sort((e,t)=>e.id-t.id),r=Math.max(Number(e.nextConversationId)||1,n.reduce((e,t)=>Math.max(e,t.id+1),1));return{conversations:n,defaultConversationId:s,nextConversationId:r}}(e),n=s.conversations.map(e=>ve.parse({schemaVersion:1,...e,agentSessionId:e.agentSessionId,codexSessionId:e.codexSessionId}));for(const e of n)this.saveRecord(e);const r=_e(e.defaultConversationId)||s.defaultConversationId||T,i=Ie.parse({schemaVersion:1,defaultConversationId:r,nextConversationId:s.nextConversationId,items:n.map(Te)});return this.saveIndex(i),_({defaultConversationId:r}),i}getRequired(e){const t=this.get(e);if(!t)throw Object.assign(new Error("Conversation not found."),{code:"CONVERSATION_NOT_FOUND"});return t}recordPath(e){return s.join(this.paths.conversationsDir,`conversation-${e}.json`)}loadRecord(e){const s=this.recordPath(e);try{return ve.parse(JSON.parse(t.readFileSync(s,"utf8")))}catch(e){if(e&&"object"==typeof e&&"code"in e&&"ENOENT"===e.code)return;throw e}}saveRecord(e){new me(this.recordPath(e.id),{schema:ve,defaultValue:()=>e}).save(e)}saveIndex(e){this.indexStore.save(Ie.parse(e))}updateIndexItem(e){const t=this.ensureSeeded();this.saveIndex({...t,items:t.items.map(t=>t.id===e.id?Te(e):t).sort((e,t)=>e.id-t.id)})}}function Oe(e){const t=_e(e);if(!t)throw Object.assign(new Error("Conversation id must be a positive integer."),{code:"CONVERSATION_ID_INVALID"});return t}class Ee{store;receiverControl;aiSessionController;constructor(e,t,s){this.store=e,this.receiverControl=t,this.aiSessionController=s}async execute(e){const t=this.store.startRun(e.config,e.deployment,e.eventType,e.eventSummary),s=e.promptOverride||(n=e.config.action.promptTemplate,r={trigger:e.config,event:{type:e.eventType,summary:e.eventSummary||""}},n.replaceAll("{{trigger.configHash}}",r.trigger.configHash).replaceAll("{{trigger.name}}",r.trigger.name).replaceAll("{{event.type}}",r.event.type).replaceAll("{{event.summary}}",r.event.summary));var n,r;try{if("ai-session"===e.deployment.target.type){if(!this.aiSessionController)throw Object.assign(new Error("AI session trigger targets are not available."),{code:"TRIGGER_AI_SESSION_TARGET_UNAVAILABLE",statusCode:400});let n;try{n=await this.aiSessionController.sendMessage(e.deployment.target.aiSessionId,{message:s})}catch(t){throw t&&"object"==typeof t&&"code"in t&&"AI_SESSION_NOT_FOUND"===String(t.code)&&this.store.deleteDeployment(e.deployment.configHash,e.deployment.deploymentId||e.deployment.configHash),t}return{run:this.store.completeRun(t),result:n}}const n=await this.receiverControl.message({channel:"web",chatSessionId:`trigger:${e.deployment.deploymentId||e.deployment.configHash}`,userId:"trigger",conversationId:e.deployment.target.conversationId,text:s,attachments:[]});return{run:this.store.completeRun(t),result:n}}catch(e){const s=this.store.completeRun(t,e);throw Object.assign(e instanceof Error?e:new Error(String(e)),{run:s})}}}class ze{store;executor;paths;publish;timers=new Map;watches=new Map;running=new Set;queued=new Map;lastRunAt=new Map;previousAiSessions=new Map;constructor(e,t,s,n){this.store=e,this.executor=t,this.paths=s,this.publish=n}start(){this.stop();const e=this.store.list();for(const t of e.deployments.filter(e=>e.enabled)){const s=e.configs.find(e=>e.configHash===t.configHash);s&&("schedule"===s.source.type&&this.startSchedule(s,t),"file-change"===s.source.type&&this.startFileWatch(s,t))}}restart(){this.start()}stop(){for(const e of this.timers.values())clearInterval(e);this.timers.clear();for(const e of this.watches.values()){for(const t of e.watchers)t.close();e.debounce&&clearTimeout(e.debounce)}this.watches.clear()}handleAiSessions(e){const t=new Map(e.sessions.map(e=>[e.id,e])),s=this.store.pruneMissingAiSessionDeployments(new Set(t.keys()));s.length&&(this.restart(),this.publish?.("trigger.deployment.pruned",{deployments:s}),this.publish?.("trigger.updated",this.store.list()));const n=this.store.list();for(const t of n.deployments.filter(e=>e.enabled)){const s=n.configs.find(e=>e.configHash===t.configHash);if(s&&"ai-session"===s.source.type)for(const n of e.sessions){const e=this.previousAiSessions.get(n.id);if(!e||!this.aiSessionMatches(s,n))continue;const r=e.status!==n.status,i=e.phase!==n.phase;if(!r&&!i)continue;const o=`AI session ${n.id}: ${e.status}/${e.phase} -> ${n.status}/${n.phase}`;this.execute(s,t,"ai-session",o)}}this.previousAiSessions=t}startSchedule(e,t){if("schedule"!==e.source.type)return;const s=e.source,n=xe(t);if("intervalMs"in s)return void this.timers.set(n,setInterval(()=>{this.execute(e,t,"schedule",`Interval ${s.intervalMs}ms`)},s.intervalMs));const r=()=>{const i=function(e){if("intervalMs"in e)return new Date(Date.now()+e.intervalMs);const[t,s]=e.timeOfDay.split(":").map(Number),n=new Date;for(let r=0;r<=14;r+=1){const i=new Date(n.getTime()+864e5*r);if("weekly"===e.scheduleKind&&!e.weekdays.includes(ke(i,e.timezone).weekday))continue;const o=De(i,e.timezone,t,s);if(o.getTime()>n.getTime()+500)return o}return new Date(Date.now()+864e5)}(s),o=Math.max(1e3,i.getTime()-Date.now()),a=setTimeout(()=>{this.execute(e,t,"schedule",function(e){return"intervalMs"in e?`Interval ${e.intervalMs}ms`:"daily"===e.scheduleKind?`Daily at ${e.timeOfDay} ${e.timezone}`:`Weekly on ${e.weekdays.join(",")} at ${e.timeOfDay} ${e.timezone}`}(s)),r()},o);this.timers.set(n,a)};r()}startFileWatch(e,n){if("file-change"!==e.source.type)return;const r=e.source,i=xe(n),o={watchers:[],changed:new Set};for(const i of e.source.roots){const a=s.resolve(i),d=Ce();if(a.startsWith(d)&&t.existsSync(a))for(const i of Re(a)){const a=t.watch(i,(t,a)=>{const c=a?s.join(i,String(a)):i;this.fileMatches(e,c)&&(o.changed.add(s.relative(d,c)),o.debounce&&clearTimeout(o.debounce),o.debounce=setTimeout(()=>{const t=[...o.changed].sort();o.changed.clear(),this.execute(e,n,"file-change",`Changed files:\n${t.join("\n")}`)},r.debounceMs))});o.watchers.push(a)}}o.watchers.length&&this.watches.set(i,o)}fileMatches(e,t){if("file-change"!==e.source.type)return!1;const n=s.relative(Ce(),t).replaceAll(s.sep,"/");return!Pe(n)&&!(e.source.ignore||[]).some(e=>Fe(e,n))&&e.source.globs.some(e=>Fe(e,n))}aiSessionMatches(e,t){return!("ai-session"!==e.source.type||e.source.conversationId&&t.conversationId!==e.source.conversationId||e.source.agent&&t.agent!==e.source.agent||e.source.statuses?.length&&!e.source.statuses.includes(t.status)||e.source.phases?.length&&!e.source.phases.includes(t.phase))}async execute(e,t,s,n){const r=xe(t),i=Date.now(),o=e.policy.cooldownMs||0,a=this.lastRunAt.get(r)||0;if(o&&i-a<o)return this.store.skipRun(e,t,s,"Skipped by cooldown policy."),void this.publish?.("trigger.run.skipped",{configHash:e.configHash,deploymentId:t.deploymentId,reason:"cooldown"});if(this.running.has(r))"queue"===e.policy.whenBusy?this.queued.set(r,{config:e,deployment:t,eventType:s,eventSummary:n}):(this.store.skipRun(e,t,s,"Skipped because trigger is already running."),this.publish?.("trigger.run.skipped",{configHash:e.configHash,deploymentId:t.deploymentId,reason:"busy"}));else{this.running.add(r),this.lastRunAt.set(r,i),this.publish?.("trigger.run.started",{configHash:e.configHash,deploymentId:t.deploymentId,eventType:s});try{const r=await this.executor.execute({config:e,deployment:t,eventType:s,eventSummary:n});this.publish?.("trigger.run.completed",r),this.publish?.("trigger.updated",this.store.list())}catch(t){this.publish?.("trigger.run.failed",{configHash:e.configHash,error:t instanceof Error?t.message:String(t)}),this.publish?.("trigger.updated",this.store.list())}finally{this.running.delete(r);const e=this.queued.get(r);e&&(this.queued.delete(r),setTimeout(()=>{this.execute(e.config,e.deployment,e.eventType,e.eventSummary)},0))}}}}function xe(e){return e.deploymentId||e.configHash}function De(e,t,s,n){const r=ke(e,t),i=Date.UTC(r.year,r.month-1,r.day,s,n,0,0),o=new Date(i),a=ke(o,t),d=(Date.UTC(a.year,a.month-1,a.day,a.hour,a.minute)-o.getTime())/6e4;return new Date(i-6e4*d)}function ke(e,t){const s=new Intl.DateTimeFormat("en-US",{timeZone:t,weekday:"short",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).formatToParts(e),n=e=>s.find(t=>t.type===e)?.value||"";return{year:Number(n("year")),month:Number(n("month")),day:Number(n("day")),hour:Number(n("hour")),minute:Number(n("minute")),weekday:{Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6}[n("weekday")]??0}}function Ce(){return s.resolve(process.env.TASK_HANDOFF_WORKSPACE||process.env.WORKSPACE||"/workspace")}function Pe(e){return/(^|\/)(\.git|node_modules|dist|build)\//.test(e)||/\.(log|tmp|swp)$/.test(e)}function Fe(e,t){if("**/*"===e||"**"===e)return!0;const s=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replaceAll("**",".*").replaceAll("*","[^/]*");return new RegExp(`^${s}$`).test(t)}function Re(e){if("darwin"===process.platform||"win32"===process.platform)return[e];const n=[e],r=[e];for(;r.length;){const e=r.pop();let i=[];try{i=t.readdirSync(e,{withFileTypes:!0})}catch{continue}for(const t of i){if(!t.isDirectory())continue;const i=s.join(e,t.name);Pe(`${s.relative(Ce(),i).replaceAll(s.sep,"/")}/`)||(n.push(i),r.push(i))}}return n}const Me=i.z.union([i.z.object({type:i.z.literal("schedule"),scheduleKind:i.z.literal("interval").default("interval"),intervalMs:i.z.number().int().min(1e3)}).strict(),i.z.object({type:i.z.literal("schedule"),scheduleKind:i.z.literal("daily"),timeOfDay:i.z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/),timezone:i.z.string().trim().min(1).max(120)}).strict(),i.z.object({type:i.z.literal("schedule"),scheduleKind:i.z.literal("weekly"),weekdays:i.z.array(i.z.number().int().min(0).max(6)).min(1).max(7),timeOfDay:i.z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/),timezone:i.z.string().trim().min(1).max(120)}).strict()]),je=i.z.union([Me,i.z.object({type:i.z.literal("file-change"),roots:i.z.array(i.z.string().trim().min(1).max(4096)).min(1).max(50),globs:i.z.array(i.z.string().trim().min(1).max(500)).min(1).max(100),ignore:i.z.array(i.z.string().trim().min(1).max(500)).max(100).optional(),debounceMs:i.z.number().int().min(100).max(6e4).default(1500)}).strict(),i.z.object({type:i.z.literal("ai-session"),conversationId:i.z.number().int().positive().optional(),agent:i.z.string().trim().min(1).max(80).optional(),statuses:i.z.array(i.z.enum(["running","waiting","idle","failed"])).max(20).optional(),phases:i.z.array(i.z.enum(["thinking","tool","editing","approval","responding","unknown"])).max(20).optional()}).strict()]),He=i.z.object({promptTemplate:i.z.string().trim().min(1).max(2e4)}).strict(),Le=i.z.object({cooldownMs:i.z.number().int().min(0).max(864e5).optional(),maxConcurrentRuns:i.z.number().int().min(1).max(20).default(1),whenBusy:i.z.enum(["skip","queue"]).default("skip")}).strict(),$e=i.z.object({configHash:i.z.string().trim().min(8).max(80),name:i.z.string().trim().min(1).max(160),description:i.z.string().trim().max(1e3).optional(),source:je,action:He,policy:Le.default({maxConcurrentRuns:1,whenBusy:"skip"}),createdAt:i.z.string().datetime(),updatedAt:i.z.string().datetime()}).strict(),Ue=i.z.discriminatedUnion("type",[i.z.object({type:i.z.literal("conversation"),conversationId:i.z.number().int().positive()}).strict(),i.z.object({type:i.z.literal("ai-session"),aiSessionId:i.z.string().trim().min(1).max(160)}).strict()]),qe=i.z.object({configHash:i.z.string().trim().min(8).max(80),deploymentId:i.z.string().trim().min(1).max(240).optional(),instanceId:i.z.string().trim().min(1).max(160),origin:i.z.enum(["control-plane","controlled-instance"]).default("controlled-instance"),enabled:i.z.boolean().default(!0),target:Ue,localName:i.z.string().trim().min(1).max(160).optional(),createdAt:i.z.string().datetime(),updatedAt:i.z.string().datetime()}).strict(),Be=i.z.object({configHash:i.z.string().trim().min(8).max(80),deploymentId:i.z.string().trim().min(1).max(240).optional(),instanceId:i.z.string().trim().min(1).max(160),status:i.z.enum(["idle","running","disabled","error"]).default("idle"),lastTriggeredAt:i.z.string().datetime().optional(),lastCompletedAt:i.z.string().datetime().optional(),lastSkippedAt:i.z.string().datetime().optional(),lastError:i.z.string().trim().max(4e3).optional(),runCount:i.z.number().int().min(0).default(0),skippedCount:i.z.number().int().min(0).default(0)}).strict(),Ve=i.z.object({id:i.z.string().trim().min(1).max(160),configHash:i.z.string().trim().min(8).max(80),deploymentId:i.z.string().trim().min(1).max(240).optional(),instanceId:i.z.string().trim().min(1).max(160),eventType:i.z.enum(["manual","schedule","file-change","ai-session"]),status:i.z.enum(["started","completed","failed","skipped"]),target:Ue,promptPreview:i.z.string().trim().max(500),eventSummary:i.z.string().trim().max(1e3).optional(),error:i.z.string().trim().max(4e3).optional(),startedAt:i.z.string().datetime(),completedAt:i.z.string().datetime().optional()}).strict(),Ke=i.z.object({schemaVersion:i.z.literal(1).default(1),configs:i.z.array($e).default([]),deployments:i.z.array(qe).default([]),runtime:i.z.array(Be).default([]),recentRuns:i.z.array(Ve).default([])}).strict();function Ge(e){return Array.isArray(e)?e.map(Ge):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Ge(t)])):e}function We(){return(new Date).toISOString()}function Xe(e){return e.deploymentId||e.configHash}function Je(e){return Be.parse({configHash:e.configHash,deploymentId:e.deploymentId,instanceId:e.instanceId,status:e.enabled?"idle":"disabled",runCount:0,skippedCount:0})}function Ye(e){return e.trim().slice(0,500)}class Qe{indexStore;constructor(e){this.indexStore=new me(s.join(e.triggersDir,"index.json"),{schema:Ke,defaultValue:()=>({schemaVersion:1,configs:[],deployments:[],runtime:[],recentRuns:[]})})}indexPath(){return this.indexStore.path()}list(){return this.indexStore.load()}get(e){const t=this.list(),s=t.configs.find(t=>t.configHash===e),n=t.deployments.filter(t=>t.configHash===e);if(s)return{config:s,deployments:n,runtime:t.runtime.filter(t=>t.configHash===e),recentRuns:t.recentRuns.filter(t=>t.configHash===e)}}create(e){const t=We(),s={maxConcurrentRuns:e.policy?.maxConcurrentRuns??1,whenBusy:e.policy?.whenBusy??"skip",cooldownMs:e.policy?.cooldownMs},n=function(e){const t=Ge({source:e.source,action:e.action,policy:Le.parse(e.policy||{})});return`trg_${h.createHash("sha256").update(JSON.stringify(t)).digest("hex").slice(0,24)}`}({source:e.source,action:e.action,policy:s}),r=$e.parse({configHash:n,name:e.name,description:e.description,source:e.source,action:e.action,policy:s,createdAt:t,updatedAt:t}),i=function(e,t={}){const s=We();return qe.parse({configHash:e,deploymentId:t.deploymentId,instanceId:process.env.TASK_HANDOFF_INSTANCE_ID||"local",origin:t.origin||"controlled-instance",enabled:t.enabled??!0,target:t.target||{type:"conversation",conversationId:1},localName:t.localName,createdAt:s,updatedAt:s})}(n,e.deployment),o=this.list(),a=o.configs.some(e=>e.configHash===n)?o.configs:[...o.configs,r],d=Xe(i),c=[...o.deployments.filter(e=>Xe(e)!==d),i],p=[...o.runtime.filter(e=>Xe(e)!==d),Je(i)];return this.save({...o,configs:a,deployments:c,runtime:p}),{config:r,deployment:i,runtime:Je(i)}}patch(e,t){const s=this.list(),n=s.configs.find(t=>t.configHash===e);if(!n)return;const r=$e.parse({...n,name:t.name??n.name,description:null===t.description?void 0:t.description??n.description,updatedAt:We()});return this.save({...s,configs:s.configs.map(t=>t.configHash===e?r:t)}),r}setEnabled(e,t){const s=this.list(),n=We();let r=!1;const i=s.deployments.map(s=>s.configHash!==e?s:(r=!0,qe.parse({...s,enabled:t,updatedAt:n})));if(!r)return;const o=s.runtime.map(s=>s.configHash===e?Be.parse({...s,status:t?"idle":"disabled"}):s);return this.save({...s,deployments:i,runtime:o}),this.get(e)}delete(e){const t=this.list();return!!t.configs.some(t=>t.configHash===e)&&(this.save({...t,configs:t.configs.filter(t=>t.configHash!==e),deployments:t.deployments.filter(t=>t.configHash!==e),runtime:t.runtime.filter(t=>t.configHash!==e),recentRuns:t.recentRuns.filter(t=>t.configHash!==e)}),!0)}deleteDeployment(e,t){const s=this.list();if(!s.deployments.some(s=>s.configHash===e&&Xe(s)===t))return!1;const n=s.deployments.filter(s=>!(s.configHash===e&&Xe(s)===t)),r=n.some(t=>t.configHash===e);return this.save({...s,configs:r?s.configs:s.configs.filter(t=>t.configHash!==e),deployments:n,runtime:s.runtime.filter(s=>!(s.configHash===e&&Xe(s)===t))}),!0}pruneMissingAiSessionDeployments(e){const t=this.list(),s=t.deployments.filter(t=>"ai-session"===t.target.type&&!e.has(t.target.aiSessionId));if(!s.length)return[];const n=new Set(s.map(e=>Xe(e))),r=t.deployments.filter(e=>!n.has(Xe(e))),i=new Set(r.map(e=>e.configHash));return this.save({...t,configs:t.configs.filter(e=>i.has(e.configHash)),deployments:r,runtime:t.runtime.filter(e=>!n.has(Xe(e)))}),s}startRun(e,t,s,n){const r=We(),i=Ve.parse({id:`run_${Date.now().toString(36)}_${Math.random().toString(16).slice(2)}`,configHash:e.configHash,deploymentId:t.deploymentId,instanceId:t.instanceId,eventType:s,status:"started",target:t.target,promptPreview:Ye(e.action.promptTemplate),eventSummary:n,startedAt:r}),o=this.list(),a=this.upsertRuntime(o,t,{status:"running",lastTriggeredAt:r});return this.save({...o,runtime:a,recentRuns:[i,...o.recentRuns].slice(0,100)}),i}completeRun(e,t){const s=We(),n=Boolean(t),r=this.list(),i=r.recentRuns.map(r=>r.id===e.id?Ve.parse({...r,status:n?"failed":"completed",error:t instanceof Error?t.message:t?String(t):void 0,completedAt:s}):r),o=r.deployments.find(t=>t.configHash===e.configHash&&Xe(t)===(e.deploymentId||e.configHash)),a=o?this.upsertRuntime(r,o,{status:n?"error":o.enabled?"idle":"disabled",lastCompletedAt:s,lastError:n?t instanceof Error?t.message:String(t):void 0,runCount:(r.runtime.find(t=>t.configHash===e.configHash&&Xe(t)===Xe(o))?.runCount||0)+1}):r.runtime;return this.save({...r,runtime:a,recentRuns:i}),i.find(t=>t.id===e.id)}skipRun(e,t,s,n){const r=We(),i=Ve.parse({id:`run_${Date.now().toString(36)}_${Math.random().toString(16).slice(2)}`,configHash:e.configHash,deploymentId:t.deploymentId,instanceId:t.instanceId,eventType:s,status:"skipped",target:t.target,promptPreview:Ye(e.action.promptTemplate),eventSummary:n,startedAt:r,completedAt:r}),o=this.list(),a=this.upsertRuntime(o,t,{status:t.enabled?"idle":"disabled",lastSkippedAt:r,skippedCount:(o.runtime.find(e=>Xe(e)===Xe(t))?.skippedCount||0)+1});return this.save({...o,runtime:a,recentRuns:[i,...o.recentRuns].slice(0,100)}),i}primaryDeployment(e){return this.list().deployments.find(t=>t.configHash===e)}upsertRuntime(e,t,s){const n=Xe(t),r=e.runtime.find(e=>Xe(e)===n)||Je(t),i=Be.parse({...r,...s});return[...e.runtime.filter(e=>Xe(e)!==n),i]}save(e){this.indexStore.save(Ke.parse(e))}}function Ze(e,t){const n=process.env[e];return n&&n.trim()?s.resolve(n.trim()):t}function et(){const e=s.join(process.env.XDG_DATA_HOME||s.join(n.homedir(),".local","share"),"task-handoff"),t=Ze("TASK_HANDOFF_CONFIG",S),r=Ze("TASK_HANDOFF_DATA_DIR",s.dirname(t)||e);return{configPath:t,dataDir:r,channelsDir:Ze("TASK_HANDOFF_CHANNELS_DIR",s.join(r,"channels")),conversationsDir:Ze("TASK_HANDOFF_CONVERSATIONS_DIR",s.join(r,"conversations")),appCatalogDir:Ze("TASK_HANDOFF_APP_CATALOG_DIR",s.join(r,"app-catalog")),appSessionsDir:Ze("TASK_HANDOFF_APP_SESSION_DIR",s.join(r,"app-sessions")),triggersDir:Ze("TASK_HANDOFF_TRIGGERS_DIR",s.join(r,"triggers")),runtimeDir:Ze("TASK_HANDOFF_RUNTIME_DIR",s.join(r,"runtime")),eventsDir:Ze("TASK_HANDOFF_EVENTS_DIR",s.join(r,"events")),artifactDir:Ze("TASK_HANDOFF_ARTIFACT_DIR",s.join(r,"artifacts")),logDir:Ze("TASK_HANDOFF_LOG_DIR",s.join(r,"logs")),webTokenPath:Ze("TASK_HANDOFF_WEB_TOKEN_FILE",s.join(r,"web-token"))}}const tt=i.z.object({schemaVersion:i.z.literal(1).default(1),channel:i.z.enum(["telegram","wechat","dingding"]),instanceId:i.z.string().default("default"),enabled:i.z.boolean().default(!1),defaultChatId:i.z.string().optional(),allowedUserIds:i.z.array(i.z.string()).optional(),bindings:i.z.record(i.z.string(),i.z.object({conversationId:i.z.number(),contextToken:i.z.string().optional()})).optional(),secrets:i.z.record(i.z.string(),i.z.unknown()).optional(),state:i.z.record(i.z.string(),i.z.unknown()).optional()}),st=i.z.object({schemaVersion:i.z.literal(1).default(1),defaultConversationId:i.z.number().default(1),nextConversationId:i.z.number().default(2),items:i.z.array(i.z.record(i.z.string(),i.z.unknown())).default([])}),nt=i.z.object({schemaVersion:i.z.literal(1).default(1),items:i.z.array(i.z.record(i.z.string(),i.z.unknown())).default([])}),rt=/^[a-f0-9]{8}$/;function it(e=process.env){return e.CLAUDE_CONTROL_SOCK||s.join(function(e=process.env){const t=process.getuid?.()??0,r=e.TERMUX_VERSION&&e.PREFIX?s.join(e.PREFIX,"tmp"):"/tmp",i=(e.CLAUDE_CONFIG_DIR??s.join(n.homedir(),".claude")).normalize("NFC"),o=h.createHash("sha256").update(s.resolve(i)).digest("hex").slice(0,8);return s.join(r,`cc-daemon-${t}`,o)}(e),"control.sock")}function ot(e,t={}){const s=t.sockPath||it(),n=t.timeoutMs??5e3;return new Promise(t=>{let r;try{r=o.connect(s)}catch(e){return void t({ok:!1,code:"ENOCONN",error:String(e)})}let i=!1,a="";const d=e=>{i||(i=!0,r.destroy(),t(e))};r.setTimeout(n,()=>d({ok:!1,code:"ETIMEOUT",error:"control socket timeout"})),r.on("error",e=>d({ok:!1,code:"ENOCONN",error:String(e)})),r.once("connect",()=>{r.write(`${JSON.stringify({proto:1,...e})}\n`)}),r.on("data",e=>{a+=e.toString("utf8");const t=a.indexOf("\n");if(t<0)return;const s=a.slice(0,t);try{d(JSON.parse(s))}catch(e){d({ok:!1,code:"EBADJSON",error:String(e),raw:s})}}),r.once("close",()=>{i||d({ok:!1,code:"ENOCONN",error:"connection dropped mid-request"})})})}function at(e,t,s){return pt(e),ot({op:"reply",short:e,text:t},s)}function dt(e,t="SIGTERM",s){return pt(e),ot({op:"kill",short:e,signal:t},s)}function ct(e,{tail:t,onMessage:s,options:n={}}={}){pt(e);const r=o.connect(n.sockPath||it());let i="";return r.on("connect",()=>{r.write(`${JSON.stringify({proto:1,op:"subscribe",short:e,tail:t})}\n`)}),r.on("data",e=>{i+=e.toString("utf8");let t=i.indexOf("\n");for(;t>=0;){const e=i.slice(0,t);if(i=i.slice(t+1),e.trim())try{s?.(JSON.parse(e))}catch{s?.({raw:e})}t=i.indexOf("\n")}}),r.on("error",()=>{}),()=>r.destroy()}function pt(e){if(!rt.test(e))throw new Error(`Claude worker short id must be 8 hex chars: ${e}`)}function ut(e,t=!1){const s=process.env[e];return void 0===s||""===s?t:["1","true","yes","on"].includes(s.toLowerCase())}function lt(...e){for(const t of e){const e=process.env[t]?.trim();if(e)return["--model",e]}return[]}const mt=i.z.string().trim().min(1).max(512).refine(e=>!/\s/.test(e)&&!/[;&|<>`$]/.test(e),"Command must be a single executable path or name."),ht=i.z.object({id:i.z.string().trim().min(1).max(80).regex(/^[a-z0-9][a-z0-9._-]*$/),name:i.z.string().trim().min(1).max(120),kind:i.z.enum(["tty","gui"]),description:i.z.string().max(500).optional(),command:mt,args:i.z.array(i.z.string().max(1024)).max(64).default([]).optional(),cwd:i.z.string().max(512).optional(),env:i.z.record(i.z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),i.z.string().max(4096)).optional(),display:i.z.object({width:i.z.number().int().min(320).max(7680).optional(),height:i.z.number().int().min(240).max(4320).optional(),depth:i.z.union([i.z.literal(16),i.z.literal(24),i.z.literal(32)]).optional()}).optional(),defaultDisplayTarget:i.z.object({mode:i.z.enum(["isolated","shared"]),id:i.z.string().trim().min(1).max(80).regex(/^[a-z0-9][a-z0-9._-]*$/).optional(),autoCreate:i.z.boolean().optional()}).optional(),automation:i.z.object({type:i.z.literal("cdp"),portArg:i.z.string().optional(),endpointPath:i.z.string().optional()}).optional()}),gt=i.z.object({schemaVersion:i.z.literal(1).default(1),items:i.z.array(ht).default([])}).superRefine((e,t)=>{const s=new Set(vt({includeOptional:!0}).map(e=>e.id)),n=new Set;for(const[r,o]of e.items.entries())s.has(o.id)&&t.addIssue({code:i.z.ZodIssueCode.custom,path:["items",r,"id"],message:"Custom apps cannot override built-in app ids."}),n.has(o.id)&&t.addIssue({code:i.z.ZodIssueCode.custom,path:["items",r,"id"],message:"Custom app ids must be unique."}),n.add(o.id)}),ft=[{id:"terminal-tty",name:"Terminal",kind:"tty",description:"Interactive shell in the task workspace.",command:process.env.SHELL||"/bin/bash"},{id:"codex",name:"Codex",kind:"tty",description:"OpenAI Codex CLI in the task workspace.",command:process.env.TASK_HANDOFF_CODEX_COMMAND||"codex"},{id:"claude",name:"Claude",kind:"tty",description:"Claude Code CLI in the task workspace.",command:process.env.TASK_HANDOFF_CLAUDE_COMMAND||"claude"},{id:"terminal-gui",name:"GUI Terminal",kind:"gui",description:"xterm terminal in an isolated virtual desktop with VNC access.",command:process.env.TASK_HANDOFF_XTERM_COMMAND||"xterm",args:["-geometry","120x32"],display:{width:1024,height:768,depth:24}},{id:"chromium",name:"Browser",kind:"gui",description:"Chromium browser with VNC and CDP endpoints.",command:process.env.TASK_HANDOFF_CHROMIUM_COMMAND||"chromium",args:["about:blank"],display:{width:1440,height:900,depth:24},automation:{type:"cdp",portArg:"--remote-debugging-port={port}"}},{id:"vscode-web",name:"VS Code",kind:"web",description:"VS Code Web in the task workspace.",command:process.env.TASK_HANDOFF_VSCODE_WEB_COMMAND||"code-server",args:["--auth","none","--bind-addr","127.0.0.1:{port}","--disable-telemetry","--user-data-dir","{sessionDir}/user-data","--extensions-dir","{sessionDir}/extensions","{cwd}"],web:{readyPath:"/"}}];function yt(e){return"codex"===e.id?{...e,command:process.env.TASK_HANDOFF_CODEX_COMMAND||e.command,args:lt("TASK_HANDOFF_CODEX_MODEL","CODEX_MODEL")}:"claude"===e.id?{...e,command:process.env.TASK_HANDOFF_CLAUDE_COMMAND||e.command,args:[...ut("TASK_HANDOFF_CLAUDE_DANGEROUSLY_SKIP_PERMISSIONS")||ut("TASK_HANDOFF_CLAUDE_SKIP_PERMISSIONS")?["--dangerously-skip-permissions"]:[],...lt("TASK_HANDOFF_CLAUDE_MODEL","CLAUDE_MODEL")]}:"terminal-tty"===e.id?{...e,command:process.env.SHELL||e.command}:"terminal-gui"===e.id?{...e,command:process.env.TASK_HANDOFF_XTERM_COMMAND||e.command}:"chromium"===e.id?{...e,command:process.env.TASK_HANDOFF_CHROMIUM_COMMAND||e.command}:"vscode-web"===e.id?{...e,command:process.env.TASK_HANDOFF_VSCODE_WEB_COMMAND||e.command}:e}function vt(e={}){return[...ft.map(yt),...e.includeOptional||ut("TASK_HANDOFF_ENABLE_CC_SWITCH")?[{id:"cc-switch",name:"CC Switch",kind:"gui",description:"CC Switch desktop app in an isolated virtual desktop.",command:process.env.TASK_HANDOFF_CC_SWITCH_COMMAND||"cc-switch",display:{width:1440,height:900,depth:24}}].map(yt):[]]}function St(e){try{return t.accessSync(e,t.constants.X_OK),t.statSync(e).isFile()}catch{return!1}}function It(e,t=process.env,n=process.cwd()){const r="win32"===process.platform?(t.PATHEXT||".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean):[""],i=e=>{for(const t of r){const n="win32"!==process.platform||s.extname(e)?e:`${e}${t}`;if(St(n))return n}};if(s.isAbsolute(e))return i(e);if(e.includes("/")||e.includes("\\"))return i(s.resolve(n,e));for(const n of(t.PATH||"").split(s.delimiter).filter(Boolean)){const t=i(s.join(n,e));if(t)return t}}function At(e){const t=e.command?.trim();return Boolean(t&&It(t,{...process.env,...e.env},e.cwd))}vt({includeOptional:!0});class bt{customStore;constructor(e){this.customStore=new me(s.join(e.appCatalogDir,"custom.json"),{schema:gt,defaultValue:()=>({schemaVersion:1,items:[]})})}list(){const e=new Map;for(const t of vt())e.set(t.id,t);const t=this.safeCustom();if(t.data)for(const s of t.data.items)e.set(s.id,s);return Array.from(e.values())}available(){return this.list().filter(At)}find(e){return this.list().find(t=>t.id===e)}custom(){return this.customStore.load()}safeCustom(){try{return{data:this.customStore.load(),error:void 0}}catch(e){return{data:void 0,error:{code:"APP_CATALOG_INVALID",message:e instanceof Error?e.message:String(e)}}}}saveCustom(e){return this.customStore.save(gt.parse(e)),this.customStore.load()}customPath(){return this.customStore.path()}}class _t{socketPath;onThreadBound;server;port;stopped=!1;constructor(e,t){this.socketPath=e,this.onThreadBound=t}get endpoint(){return this.port?`ws://127.0.0.1:${this.port}`:void 0}start(e){if(this.server)return;this.port=e;const t=new y.WebSocketServer({host:"127.0.0.1",port:e});this.server=t,t.on("connection",e=>this.attach(e))}stop(){this.stopped=!0,this.server?.close();for(const e of this.server?.clients||[])e.close();this.server=void 0}attach(e){if(this.stopped)return void e.close();const t=new y("ws://localhost/rpc",{createConnection:()=>o.createConnection(this.socketPath),perMessageDeflate:!1}),s=new Map,n=[];e.on("message",(e,r)=>{r||this.observeClientMessage(e.toString(),s),t.readyState===y.OPEN?t.send(e,{binary:r}):t.readyState===y.CONNECTING&&n.push({data:e,isBinary:r})}),t.on("open",()=>{for(;t.readyState===y.OPEN&&n.length>0;){const e=n.shift();e&&t.send(e.data,{binary:e.isBinary})}}),t.on("message",(t,n)=>{n||this.observeServerMessage(t.toString(),s),e.readyState===y.OPEN&&e.send(t,{binary:n})});const r=()=>{e.readyState!==y.OPEN&&e.readyState!==y.CONNECTING||e.close(),t.readyState!==y.OPEN&&t.readyState!==y.CONNECTING||t.close()};e.on("close",r),e.on("error",r),t.on("close",r),t.on("error",r)}observeClientMessage(e,t){const s=wt(e);if(!s)return;const n=Tt(s.id),r="string"==typeof s.method?s.method:"",i=s.params&&"object"==typeof s.params?s.params:{};if(n&&("thread/start"===r||"thread/resume"===r||"thread/fork"===r))return t.set(n,{method:r,threadId:"string"==typeof i.threadId?i.threadId:void 0}),void("string"==typeof i.threadId&&this.onThreadBound(i.threadId));"string"!=typeof i.threadId||"turn/start"!==r&&"turn/steer"!==r&&"turn/interrupt"!==r&&"thread/unsubscribe"!==r||this.onThreadBound(i.threadId)}observeServerMessage(e,t){const s=wt(e);if(!s)return;const n=Tt(s.id);if(!n)return;const r=t.get(n);if(!r)return;if(t.delete(n),s.error)return;const i=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return;const t=e,s=t.thread&&"object"==typeof t.thread&&!Array.isArray(t.thread)?t.thread:void 0;return"string"==typeof s?.id?s.id:"string"==typeof t.threadId?t.threadId:void 0}(s.result)||r.threadId;i&&this.onThreadBound(i)}}function wt(e){try{const t=JSON.parse(e);return t&&"object"==typeof t&&!Array.isArray(t)?t:void 0}catch{return}}function Tt(e){return"string"==typeof e&&e?e:"number"==typeof e&&Number.isFinite(e)?String(e):void 0}function Nt(e){const t=Number(e.TASK_HANDOFF_GUI_SCALE||process.env.TASK_HANDOFF_GUI_SCALE||"1");return Number.isFinite(t)?Math.min(3,Math.max(1,t)):1}function Ot(e){return e.toFixed(2).replace(/\.?0+$/,"")}function Et(){return process.env.TASK_HANDOFF_GUI_APP_HOME||process.env.HOME||n.homedir()}function zt(){return`app_${Date.now().toString(36)}_${Math.random().toString(16).slice(2)}`}function xt(){return(new Date).toISOString()}function Dt(e,t=!1){const s=process.env[e];return void 0===s||""===s?t:["1","true","yes","on"].includes(s.toLowerCase())}const kt=new Set(["stopped","exited","failed"]),Ct={"workbench.colorTheme":"Default Dark Modern","workbench.preferredDarkColorTheme":"Default Dark Modern"};class Pt extends g.EventEmitter{paths;sessions=new Map;persistedSessions=new Map;nextDisplay=101;nextVncPort=6101;nextWebsockifyPort=7101;nextWebPort=8101;nextCdpPort=9201;sharedDisplays=new Map;sharedCodexAppServer;catalogRepository;persistSessionMetadata;constructor(e){super(),this.paths=e,this.catalogRepository=new bt(e),this.persistSessionMetadata=Dt("TASK_HANDOFF_APP_SESSION_PERSIST"),this.persistSessionMetadata&&(this.loadPersistedSessions(),this.cleanupExpiredSessions())}catalog(){return this.catalogRepository.available()}customCatalog(){const e=this.catalogRepository.safeCustom();return e.data?{data:{path:this.catalogRepository.customPath(),...e.data},error:void 0}:{data:void 0,error:e.error}}saveCustomCatalog(e){return{path:this.catalogRepository.customPath(),...this.catalogRepository.saveCustom({schemaVersion:1,items:e})}}listSessions(){return Array.from(this.persistedSessions.values()).sort((e,t)=>t.createdAt.localeCompare(e.createdAt))}sharedCodexAppServerInfo(){const e=this.sharedCodexAppServer;if(e&&!e.child.killed&&null===e.child.exitCode&&t.existsSync(e.socketPath))return{transport:"unix",endpoint:e.endpoint,socketPath:e.socketPath,pid:e.child.pid,command:e.command,args:e.args,logPath:e.logPath,status:"running"}}ensureSharedCodexAppServer(){const e=this.catalogRepository.find("codex"),t=e?.command||process.env.TASK_HANDOFF_CODEX_COMMAND||"codex";if(!this.hasCommand(t))throw Object.assign(new Error(`Missing required command: ${t}`),{code:"APP_DEPENDENCY_MISSING"});const s=e?.cwd||process.env.TASK_HANDOFF_WORKSPACE||process.cwd(),n={...process.env,...e?.env,TERM:"xterm-256color"};return this.acquireSharedCodexAppServer(t,s,n,"__shared_codex_app_server__")}_createCodexAppServerConnectionProxyForTest(e,t){return new _t(e,t)}getSession(e){return this.sessions.get(e)?.metadata||this.persistedSessions.get(e)}runningSessionCount(){return Array.from(this.sessions.values()).filter(e=>"running"===e.metadata.status).length}problemSessionCount(){return Array.from(this.sessions.values()).filter(e=>"failed"===e.metadata.status).length}readLogs(e,n=65536){const r=this.getSession(e);if(!r)throw Object.assign(new Error("App session not found."),{code:"APP_SESSION_NOT_FOUND"});const i=s.resolve(r.paths.logDir),o=(t.existsSync(i)?t.readdirSync(i,{withFileTypes:!0}):[]).filter(e=>e.isFile()&&e.name.endsWith(".log")).sort((e,t)=>e.name.localeCompare(t.name)).map(e=>{const r=s.resolve(i,e.name);if(!r.startsWith(`${i}${s.sep}`))throw Object.assign(new Error("Invalid log path."),{code:"APP_LOG_PATH_INVALID"});const o=t.statSync(r),a=Math.max(0,o.size-n),d=t.openSync(r,"r");try{const s=Buffer.alloc(o.size-a);return t.readSync(d,s,0,s.length,a),{name:e.name,size:o.size,updatedAt:o.mtime.toISOString(),truncated:a>0,content:s.toString("utf8")}}finally{t.closeSync(d)}});return{sessionId:e,logDir:i,maxBytes:n,files:o}}start(e="terminal-tty",n={}){const r=this.catalogRepository.find(e);if(!r)throw Object.assign(new Error("App not found."),{code:"APP_NOT_FOUND"});if(!this.hasCommand(r.command||r.id,{...process.env,...r.env},n.cwd||r.cwd))throw Object.assign(new Error(`Missing required command: ${r.command||r.id}`),{code:"APP_DEPENDENCY_MISSING"});if("gui"===r.kind)return this.startGuiApp(r,n);if("web"===r.kind)return this.startWebApp(r,n);if("tty"!==r.kind)throw Object.assign(new Error("App kind is not implemented yet."),{code:"APP_NOT_IMPLEMENTED"});const i=zt(),o=r.command||process.env.SHELL||"/bin/bash",a=n.cwd||r.cwd||process.env.TASK_HANDOFF_WORKSPACE||process.cwd(),d=this.normalizeLaunchOptions(n);let c=[...r.args||[],...d.args||[]],p={...process.env,...r.env,...d.env,TERM:"xterm-256color"};const u=s.join(this.paths.appSessionsDir,i),l=s.join(this.paths.logDir,"app-sessions",i);t.mkdirSync(u,{recursive:!0}),t.mkdirSync(l,{recursive:!0});const m="codex"!==r.id||Dt("TASK_HANDOFF_CODEX_APP_SERVER_DISABLED")?void 0:this.acquireSharedCodexAppServer(o,a,p,i);let h,g,f,y=m?.endpoint;if(m){const e=this.allocatePort("web");h=new _t(m.socketPath,e=>this.bindCodexThreadToAppSession(i,e)),h.start(e),g=e,y=h.endpoint||m.endpoint,c=[...r.args||[],"--remote",y,"--cd",a,...d.args||[]],p={...p,TASK_HANDOFF_APP_SESSION_ID:i,TASK_HANDOFF_CODEX_APP_SERVER_SOCKET:m.socketPath,TASK_HANDOFF_CODEX_APP_SERVER_URL:m.endpoint,TASK_HANDOFF_CODEX_APP_SERVER_PROXY_URL:y}}"claude"!==r.id||Dt("TASK_HANDOFF_CLAUDE_BG_DISABLED")||(f=this.launchClaudeBackground(o,c,a,p),c=["attach",f.short],p={...p,TASK_HANDOFF_APP_SESSION_ID:i,TASK_HANDOFF_CLAUDE_SHORT:f.short,TASK_HANDOFF_CLAUDE_CONTROL_SOCK:f.controlSock});const v={id:i,appId:e,title:d.title||r.name,kind:"tty",status:"running",createdAt:xt(),updatedAt:xt(),launch:d,tty:{webPath:`/api/apps/sessions/${i}/tty`,shell:o,cwd:a,mode:f?"claude-attach":"pty"},process:{command:o},ai:f?{agent:"claude",claude:{short:f.short,controlSock:f.controlSock,cwd:a}}:m?{agent:"codex",appServer:{transport:"unix",endpoint:m.endpoint,socketPath:m.socketPath,proxyEndpoint:y,proxyPort:g,pid:m.child.pid,command:m.command,args:m.args,logPath:m.logPath,status:"running"}}:void 0,paths:{sessionDir:u,logDir:l}},S=t.createWriteStream(s.join(l,"tty.log"),{flags:"a"}),I={metadata:v,processes:[],codexAppServerProxy:h,ttyDimensions:{cols:120,rows:32},ttyLogStream:S,outputBacklog:"",clients:new Set};S.on("error",()=>{I.ttyLogClosed=!0}),S.on("close",()=>{I.ttyLogClosed=!0});const A=(e,t)=>{I.stopping||(v.status="exited",v.updatedAt=xt(),v.process={...v.process,exitCode:e,signal:void 0===t?void 0:String(t)},this.persist(v),this.emit("updated",v)),"codex"===r.id&&(I.codexAppServerProxy?.stop(),this.releaseSharedCodexAppServer(i)),this.broadcast(I,{type:"exit",code:e,signal:t}),this.closeTtyLog(I)};let b;try{b=this.spawnTerminalPty(o,c,a,p)}catch(e){throw"codex"===r.id&&(h?.stop(),this.releaseSharedCodexAppServer(i)),f&&this.stopClaudeBackgroundLaunch(f.command,f.short,a,p),e}return v.process={...v.process,pid:b.pid},I.pty=b,b.onData(e=>{this.writeTtyLog(I,e),I.outputBacklog=`${I.outputBacklog}${e}`.slice(-65536),this.broadcast(I,{type:"output",data:e})}),b.onExit(({exitCode:e,signal:t})=>A(e,t)),this.sessions.set(i,I),this.persist(v),this.emit("created",v),v}launchClaudeBackground(e,t,s,n){const r=["--bg",...t],i=m.spawnSync(e,r,{cwd:s,env:n,encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:Number(process.env.TASK_HANDOFF_CLAUDE_BG_TIMEOUT_MS)||15e3}),o=`${i.stdout||""}\n${i.stderr||""}`;if(i.error)throw Object.assign(new Error(`Claude background launch failed: ${i.error.message}`),{code:"APP_LAUNCH_FAILED"});if(0!==i.status)throw Object.assign(new Error(`Claude background launch exited with code ${i.status}: ${o.trim()}`),{code:"APP_LAUNCH_FAILED"});const a=function(e){const t=e.match(/\b(?:short|id|worker|session)\D+([a-f0-9]{8})\b/i)?.[1];return t||e.match(/\b([a-f0-9]{8})\b/i)?.[1]}(o);if(!a)throw Object.assign(new Error("Claude background launch did not report a worker id."),{code:"APP_LAUNCH_FAILED"});return{short:a,controlSock:it(n),command:e,bgArgs:r}}stopClaudeBackgroundLaunch(e,t,s,n){try{m.spawnSync(e,["stop",t],{cwd:s,env:n,encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:Number(process.env.TASK_HANDOFF_CLAUDE_BG_TIMEOUT_MS)||15e3})}catch{}}startWebApp(e,n){const r=e.command||e.id;if(!this.hasCommand(r))throw Object.assign(new Error(`Missing required command: ${r}`),{code:"APP_DEPENDENCY_MISSING"});const i=zt(),o=s.join(this.paths.appSessionsDir,i),a=s.join(this.paths.logDir,"app-sessions",i);t.mkdirSync(o,{recursive:!0}),t.mkdirSync(a,{recursive:!0});const d=this.normalizeLaunchOptions(n),c=d.cwd||e.cwd||process.env.TASK_HANDOFF_WORKSPACE||process.cwd(),p=this.allocatePort("web"),u={...process.env,...e.env,...d.env},l=this.webArgs(e,o,c,p,d.args||[]);this.prepareWebAppSession(e,o);const m=this.spawnLogged(r,l,u,a,`${e.id}.log`,c),h={id:i,appId:e.id,title:d.title||e.name,kind:"web",status:"running",createdAt:xt(),updatedAt:xt(),launch:d,web:{host:"127.0.0.1",port:p,webPath:`/api/apps/sessions/${i}/web/`,readyPath:e.web?.readyPath},process:{pid:m.pid,command:r},paths:{sessionDir:o,logDir:a}},g={metadata:h,processes:[m],outputBacklog:"",clients:new Set};return this.sessions.set(i,g),this.persist(h),this.watchLoggedProcess(g,m,e.id,!1),this.emit("created",h),h}startGuiApp(e,n){const r=e.command||e.id,i="kasmvnc"===process.env.TASK_HANDOFF_VNC_BACKEND?"kasmvnc":"novnc",o="kasmvnc"===i?["vncserver","vncpasswd","openssl","xrdb","xrandr","openbox",r]:["Xvfb","openbox","x11vnc","websockify",r];for(const e of o)if(!this.hasCommand(e))throw Object.assign(new Error(`Missing required command: ${e}`),{code:"APP_DEPENDENCY_MISSING"});const a=zt(),d=s.join(this.paths.appSessionsDir,a),c=s.join(this.paths.logDir,"app-sessions",a);t.mkdirSync(d,{recursive:!0}),t.mkdirSync(c,{recursive:!0});const p=this.normalizeLaunchOptions(n),u=p.displayTarget||this.normalizeDisplayTarget(e.defaultDisplayTarget)||{mode:"isolated"};p.displayTarget=u;const l=p.cwd||e.cwd||process.env.TASK_HANDOFF_WORKSPACE||process.cwd(),m=this.allocatePort("cdp"),h=this.guiArgs(e,d,m,p.args||[]);if("shared"===u.mode){const t=this.ensureSharedDisplay(e,p,i,l),s=this.appEnvForDisplay(e,p,t),n=this.spawnLogged(r,h,s,c,`${e.id}.log`,l),o=e.automation?{type:e.automation.type,port:m,endpoint:`http://127.0.0.1:${m}${e.automation.endpointPath||""}`}:void 0,u={id:a,appId:e.id,title:p.title||e.name,kind:"gui",status:"running",createdAt:xt(),updatedAt:xt(),launch:p,display:{display:t.display,mode:"shared",displaySessionId:t.id,width:t.width,height:t.height,depth:t.depth,xPid:t.xPid,wmPid:t.wmPid,compositorPid:t.compositorPid,xauthority:t.xauthority},vnc:{backend:t.backend,host:"127.0.0.1",port:t.vncPort,websockifyPort:t.websockifyPort,webPath:"kasmvnc"===t.backend?`/api/apps/sessions/${a}/web/`:`/api/apps/sessions/${a}/vnc`,noVncPath:"kasmvnc"===t.backend?`/api/apps/sessions/${a}/web/`:`/api/apps/sessions/${a}/novnc/vnc.html`},web:"kasmvnc"===t.backend?{host:"127.0.0.1",port:t.vncPort,webPath:`/api/apps/sessions/${a}/web/`}:void 0,automation:o,process:{pid:n.pid,command:r},paths:{sessionDir:d,logDir:c}},g={metadata:u,processes:[n],outputBacklog:"",clients:new Set};return t.appSessionIds.add(a),this.sessions.set(a,g),this.persist(u),this.watchLoggedProcess(g,n,e.id,!1,()=>this.releaseSharedDisplaySession(t.id,a)),this.emit("created",u),u}const g=`:${this.allocateDisplay()}`,f="kasmvnc"===i?this.allocatePort("web"):this.allocatePort("vnc"),y="novnc"===i?this.allocatePort("websockify"):void 0,v=p.display?.width||e.display?.width||1440,S=p.display?.height||e.display?.height||900,I=p.display?.depth||e.display?.depth||24,A={...process.env,...e.env,...p.env,DISPLAY:g},b=Nt(A),_=s.join(d,"home"),w="kasmvnc"===i?s.join(_,".Xauthority"):void 0,T="kasmvnc"===i?this.startKasmVncDisplay(g,v,S,I,f,A,d,c,b):this.startNoVncDisplay(g,v,S,I,f,y,A,c,l),N="kasmvnc"===i?this.guiScaleEnv({...A,HOME:Et(),XAUTHORITY:w},b):A;try{this.waitForXDisplay(g)}catch(e){for(const e of T)e.killed||e.kill("SIGTERM");throw Object.assign(e instanceof Error?e:new Error(String(e)),{code:"APP_DISPLAY_START_FAILED"})}"kasmvnc"===i&&this.applyGuiScale(N,d,b);const O=this.spawnLogged("openbox",[],N,c,"openbox.log"),E=this.startCompositor(N,c,l),z=this.spawnLogged(r,h,N,c,`${e.id}.log`,l),x=e.automation?{type:e.automation.type,port:m,endpoint:`http://127.0.0.1:${m}${e.automation.endpointPath||""}`}:void 0,D={id:a,appId:e.id,title:p.title||e.name,kind:"gui",status:"running",createdAt:xt(),updatedAt:xt(),launch:p,display:{display:g,mode:"isolated",width:v,height:S,depth:I,xPid:T[0]?.pid,wmPid:O.pid,compositorPid:E?.pid,xauthority:w},vnc:{backend:i,host:"127.0.0.1",port:f,websockifyPort:y,webPath:"kasmvnc"===i?`/api/apps/sessions/${a}/web/`:`/api/apps/sessions/${a}/vnc`,noVncPath:"kasmvnc"===i?`/api/apps/sessions/${a}/web/`:`/api/apps/sessions/${a}/novnc/vnc.html`},web:"kasmvnc"===i?{host:"127.0.0.1",port:f,webPath:`/api/apps/sessions/${a}/web/`}:void 0,automation:x,process:{pid:z.pid,command:r},paths:{sessionDir:d,logDir:c}},k={metadata:D,processes:[z,...T,O,...E?[E]:[]],outputBacklog:"",clients:new Set};this.sessions.set(a,k),this.persist(D);for(const e of T)this.watchLoggedProcess(k,e,"kasmvnc"===i?"kasmvnc":"display",!0);return this.watchLoggedProcess(k,O,"openbox",!0),this.watchLoggedProcess(k,z,e.id,!1),this.emit("created",D),D}ensureSharedDisplay(e,n,r,i){const o="shared"===n.displayTarget?.mode?n.displayTarget:void 0,a=o?.id||"main",d=this.sharedDisplays.get(a);if(d)return d;if(!1===o?.autoCreate)throw Object.assign(new Error(`Shared display session not found: ${a}`),{code:"APP_DISPLAY_SESSION_NOT_FOUND"});const c=a.replace(/[^a-z0-9._-]/gi,"_"),p=s.join(this.paths.appSessionsDir,`display_${c}`),u=s.join(this.paths.logDir,"app-sessions",`display_${c}`);t.mkdirSync(p,{recursive:!0}),t.mkdirSync(u,{recursive:!0});const l=`:${this.allocateDisplay()}`,m="kasmvnc"===r?this.allocatePort("web"):this.allocatePort("vnc"),h="novnc"===r?this.allocatePort("websockify"):void 0,g=n.display?.width||e.display?.width||1440,f=n.display?.height||e.display?.height||900,y=n.display?.depth||e.display?.depth||24,v={...process.env,...e.env,...n.env,DISPLAY:l},S=Nt(v),I=s.join(p,"home"),A="kasmvnc"===r?s.join(I,".Xauthority"):void 0,b="kasmvnc"===r?this.startKasmVncDisplay(l,g,f,y,m,v,p,u,S):this.startNoVncDisplay(l,g,f,y,m,h,v,u,i),_="kasmvnc"===r?this.guiScaleEnv({...v,HOME:Et(),XAUTHORITY:A},S):v;try{this.waitForXDisplay(l)}catch(e){for(const e of b)e.killed||e.kill("SIGTERM");throw Object.assign(e instanceof Error?e:new Error(String(e)),{code:"APP_DISPLAY_START_FAILED"})}"kasmvnc"===r&&this.applyGuiScale(_,p,S);const w=this.spawnLogged("openbox",[],_,u,"openbox.log"),T=this.startCompositor(_,u,i),N={id:a,display:l,width:g,height:f,depth:y,backend:r,vncPort:m,websockifyPort:h,xPid:b[0]?.pid,wmPid:w.pid,compositorPid:T?.pid,xauthority:A,sessionDir:p,logDir:u,processes:[...b,w,...T?[T]:[]],appSessionIds:new Set};this.sharedDisplays.set(a,N);for(const e of[...b,w])this.watchSharedDisplayProcess(N,e);return N}appEnvForDisplay(e,t,s){const n={...process.env,...e.env,...t.env,DISPLAY:s.display},r=Nt(n);return"kasmvnc"===s.backend?this.guiScaleEnv({...n,HOME:Et(),XAUTHORITY:s.xauthority},r):n}releaseSharedDisplaySession(e,t){const s=this.sharedDisplays.get(e);s&&(s.appSessionIds.delete(t),s.appSessionIds.size>0||this.stopSharedDisplay(e))}stopSharedDisplay(e){const t=this.sharedDisplays.get(e);if(t){this.sharedDisplays.delete(e);for(const e of t.processes)e.killed||e.kill("SIGTERM")}}acquireSharedCodexAppServer(e,r,i,o){const a=this.sharedCodexAppServer;if(a&&null===a.child.exitCode&&!a.child.killed&&t.existsSync(a.socketPath))return a.appSessionIds.add(o),a;if(a&&!a.child.killed&&a.child.kill("SIGTERM"),"win32"===process.platform)throw Object.assign(new Error("Codex shared app-server uses unix sockets, which are unavailable on Windows."),{code:"CODEX_APP_SERVER_UNSUPPORTED"});const d=s.join(this.paths.runtimeDir,"codex-app-server"),c=s.join(this.paths.logDir,"app-sessions","codex-app-server"),p=function(e){const r=process.env.TASK_HANDOFF_CODEX_APP_SERVER_SOCKET_DIR?.trim(),i=r?t.realpathSync(r):"darwin"===process.platform?"/private/tmp":t.realpathSync(n.tmpdir()),o=h.createHash("sha256").update(e).digest("hex").slice(0,16);return s.join(i,`task-handoff-codex-${o}`,"app-server.sock")}(d),u=`unix://${p}`,l=process.env.TASK_HANDOFF_CODEX_APP_SERVER_COMMAND||e,m=["app-server","--listen",u];t.mkdirSync(d,{recursive:!0}),t.mkdirSync(c,{recursive:!0}),t.mkdirSync(s.dirname(p),{recursive:!0,mode:448}),t.rmSync(p,{force:!0});const g=this.spawnLogged(l,m,i,c,"codex-app-server.log",r),f={command:l,args:m,socketPath:p,endpoint:u,logPath:s.join(c,"codex-app-server.log"),child:g,appSessionIds:new Set([o])};let y;this.sharedCodexAppServer=f,g.once("error",e=>{y=e}),g.on("exit",(e,t)=>{if(this.sharedCodexAppServer?.child!==g)return;const s=0===e?"exited":"failed";for(const n of f.appSessionIds)this.updateCodexAppServerMetadata(n,s,e,t);this.sharedCodexAppServer=void 0});try{this.waitForUnixSocket(p,5e3,()=>y)}catch(e){throw g.killed||g.kill("SIGTERM"),this.sharedCodexAppServer=void 0,Object.assign(e instanceof Error?e:new Error(String(e)),{code:"CODEX_APP_SERVER_START_FAILED"})}return f}releaseSharedCodexAppServer(e){const s=this.sharedCodexAppServer;s&&(s.appSessionIds.delete(e),s.appSessionIds.size>0||(this.sharedCodexAppServer=void 0,s.child.killed||null!==s.child.exitCode||s.child.kill("SIGTERM"),t.rmSync(s.socketPath,{force:!0})))}stopSharedCodexAppServer(){const e=this.sharedCodexAppServer;e&&(this.sharedCodexAppServer=void 0,e.child.killed||null!==e.child.exitCode||e.child.kill("SIGTERM"),t.rmSync(e.socketPath,{force:!0}))}updateCodexAppServerMetadata(e,t,s,n){const r=this.sessions.get(e);r?.metadata.ai?.appServer&&(r.metadata.ai.appServer={...r.metadata.ai.appServer,status:t,exitCode:s,signal:n},r.metadata.updatedAt=xt(),this.persist(r.metadata),this.emit("updated",r.metadata))}bindCodexThreadToAppSession(e,t){const s=this.sessions.get(e);if(!s?.metadata.ai||"codex"!==s.metadata.appId)return;const n=Array.isArray(s.metadata.ai.threadIds)?s.metadata.ai.threadIds:[];s.metadata.ai={...s.metadata.ai,activeThreadId:t,threadIds:n.includes(t)?n:[...n,t]},s.metadata.updatedAt=xt(),this.persist(s.metadata),this.emit("updated",s.metadata)}watchSharedDisplayProcess(e,t){t.on("exit",(t,s)=>{if(this.sharedDisplays.has(e.id)&&0!==t&&0!==e.appSessionIds.size){this.sharedDisplays.delete(e.id);for(const n of e.appSessionIds){const r=this.sessions.get(n);r&&this.markFailed(r,"APP_DISPLAY_PROCESS_EXITED",`Shared display ${e.id} exited unexpectedly with code ${t??"null"} signal ${s??"null"}.`)}}})}startCompositor(e,t,s){if(this.hasCommand("picom"))return this.spawnLogged("picom",["--config","/dev/null","--backend","xrender"],e,t,"picom.log",s)}startNoVncDisplay(e,t,s,n,r,i,o,a,d){return[this.spawnLogged("Xvfb",[e,"-screen","0",`${t}x${s}x${n}`,"-nolisten","tcp"],o,a,"xvfb.log"),this.spawnLogged("x11vnc",["-display",e,"-localhost","-forever","-shared","-nopw","-xrandr","resize","-rfbport",String(r)],o,a,"x11vnc.log"),this.spawnLogged("websockify",[String(i),`127.0.0.1:${r}`],o,a,"websockify.log",d)]}waitForXDisplay(e,n=5e3){const r=e.replace(/^:/,"").split(".")[0],i=s.join("/tmp/.X11-unix",`X${r}`),o=Date.now();for(;Date.now()-o<n;){if(t.existsSync(i))return;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,50)}throw new Error(`Display ${e} did not become ready within ${n}ms.`)}startKasmVncDisplay(e,t,n,r,i,o,a,d,c){this.prepareKasmVncHome(a,t,n,r,i,c);const p={...o,HOME:s.join(a,"home")},u=this.writeKasmVncLauncher(a,e,t,n,r);return[this.spawnLogged("bash",[u],p,d,"kasmvnc.log")]}guiScaleEnv(e,t){return{...e,TASK_HANDOFF_GUI_SCALE:Ot(t),XCURSOR_SIZE:"24"}}applyGuiScale(e,n,r){if(r<=1)return;const i=s.join(n,"home",".Xresources");if(t.existsSync(i))try{m.execFileSync("xrdb",["-merge",i],{env:e,stdio:"ignore"})}catch{}}writeKasmVncLauncher(e,n,r,i,o){const a=s.join(e,"kasmvnc-launcher.sh");return t.writeFileSync(a,["#!/usr/bin/env bash","set -euo pipefail",`display=${JSON.stringify(n)}`,`geometry=${JSON.stringify(`${r}x${i}`)}`,`depth=${JSON.stringify(String(o))}`,'tail_pid=""',"cleanup() {",' if [ -n "${tail_pid:-}" ]; then',' kill "$tail_pid" >/dev/null 2>&1 || true',' wait "$tail_pid" >/dev/null 2>&1 || true'," fi",' HOME="$HOME" vncserver -kill "$display" >/dev/null 2>&1 || true',"}","trap cleanup EXIT","trap 'cleanup; exit 0' TERM INT",'HOME="$HOME" vncserver "$display" -noxstartup -geometry "$geometry" -depth "$depth" -publicIP 127.0.0.1','log_file=$(ls -t "$HOME/.vnc"/*.log 2>/dev/null | head -n 1 || true)','if [ -z "$log_file" ]; then'," while true; do sleep 3600; done","fi",'tail -F "$log_file" &',"tail_pid=$!",'wait "$tail_pid"',""].join("\n"),{mode:493}),a}prepareKasmVncHome(e,n,r,i,o,a){const d=s.join(e,"home"),c=s.join(d,".vnc"),p=s.join(d,".config","gtk-3.0"),u=s.join(d,".config","fontconfig"),l=Math.round(96*a),h=1024*l,g=process.env.TASK_HANDOFF_KASMVNC_USERNAME||"agent",f=process.env.TASK_HANDOFF_KASMVNC_PASSWORD||"taskhandoff",y=s.join(c,"self.pem");t.mkdirSync(c,{recursive:!0}),t.mkdirSync(p,{recursive:!0}),t.mkdirSync(u,{recursive:!0}),m.execFileSync("openssl",["req","-x509","-nodes","-newkey","rsa:2048","-keyout",y,"-out",y,"-days","3650","-subj","/CN=localhost"],{stdio:"ignore"}),t.writeFileSync(s.join(d,".Xresources"),[`Xft.dpi: ${l}`,"Xft.antialias: 1","Xft.hinting: 1","Xft.hintstyle: hintslight","Xft.rgba: rgb","Xft.lcdfilter: lcddefault","Xcursor.size: 24","XTerm*faceName: Monospace","XTerm*faceSize: 11","XTerm*renderFont: true",""].join("\n")),t.writeFileSync(s.join(p,"settings.ini"),["[Settings]",`gtk-xft-dpi=${h}`,"gtk-xft-antialias=1","gtk-xft-hinting=1","gtk-xft-hintstyle=hintslight","gtk-xft-rgba=rgb","gtk-cursor-theme-size=24",""].join("\n")),t.writeFileSync(s.join(d,".gtkrc-2.0"),[`gtk-xft-dpi = ${h}`,"gtk-xft-antialias = 1","gtk-xft-hinting = 1",'gtk-xft-hintstyle = "hintslight"','gtk-xft-rgba = "rgb"',"gtk-cursor-theme-size = 24",""].join("\n")),t.writeFileSync(s.join(u,"fonts.conf"),['<?xml version="1.0"?>','<!DOCTYPE fontconfig SYSTEM "urn:fontconfig:fonts.dtd">',"<fontconfig>",' <match target="font">',' <edit name="antialias" mode="assign"><bool>true</bool></edit>',' <edit name="hinting" mode="assign"><bool>true</bool></edit>',' <edit name="hintstyle" mode="assign"><const>hintslight</const></edit>',' <edit name="rgba" mode="assign"><const>rgb</const></edit>',' <edit name="lcdfilter" mode="assign"><const>lcddefault</const></edit>'," </match>","</fontconfig>",""].join("\n")),t.writeFileSync(s.join(c,"kasmvnc.yaml"),["desktop:"," resolution:",` width: ${n}`,` height: ${r}`," allow_resize: true",` pixel_depth: ${i}`,"network:"," protocol: http"," interface: 127.0.0.1",` websocket_port: ${o}`," use_ipv4: true"," use_ipv6: false"," ssl:",` pem_certificate: ${y}`,` pem_key: ${y}`," require_ssl: false","user_session:"," session_type: shared"," concurrent_connections_prompt: false"," idle_timeout: never","command_line:"," prompt: false",""].join("\n")),m.execFileSync("vncpasswd",["-u",g,"-w","-r"],{env:{...process.env,HOME:d},input:`${f}\n${f}\n`,stdio:["pipe","ignore","pipe"]})}stop(e){const t=this.sessions.get(e);if(!t){const t=this.persistedSessions.get(e);if(t)return t;throw Object.assign(new Error("App session not found."),{code:"APP_SESSION_NOT_FOUND"})}t.metadata.status="stopping",t.metadata.updatedAt=xt(),t.stopping=!0,this.persist(t.metadata),this.stopClaudeDaemonForSession(t.metadata),t.pty?.kill("SIGTERM"),this.closeTtyLog(t);for(const e of t.clients)e.send(JSON.stringify({type:"exit",code:null,signal:"SIGTERM"})),e.close?.();t.clients.clear();for(const e of t.processes)e.killed||e.kill("SIGTERM");return t.codexAppServerProxy?.stop(),"codex"===t.metadata.appId&&this.releaseSharedCodexAppServer(e),"shared"===t.metadata.display?.mode&&t.metadata.display.displaySessionId&&this.releaseSharedDisplaySession(t.metadata.display.displaySessionId,e),t.metadata.status="stopped",t.metadata.updatedAt=xt(),this.persist(t.metadata),this.sessions.delete(e),this.emit("updated",t.metadata),t.metadata}stopClaudeDaemonForSession(e){const t=e.ai?.claude?.short;t&&dt(t,"SIGTERM",{sockPath:e.ai?.claude?.controlSock,timeoutMs:Number(process.env.TASK_HANDOFF_CLAUDE_CONTROL_TIMEOUT_MS)||5e3})}restart(e){const t=this.getSession(e);if(!t)throw Object.assign(new Error("App session not found."),{code:"APP_SESSION_NOT_FOUND"});const{appId:s,title:n}=t,r={...t.launch,title:n};return this.sessions.has(e)&&this.stop(e),this.start(s,r)}rename(e,t){const s=this.getSession(e);if(!s)throw Object.assign(new Error("App session not found."),{code:"APP_SESSION_NOT_FOUND"});const n="string"==typeof t?t.trim():"";if(!n||n.length>120)throw Object.assign(new Error("App session title must contain between 1 and 120 characters."),{code:"APP_SESSION_TITLE_INVALID"});return s.title=n,s.launch={...s.launch,title:n},s.updatedAt=xt(),this.persist(s),this.emit("updated",s),s}async delete(e){const t=this.getSession(e);if(!t)throw Object.assign(new Error("App session not found."),{code:"APP_SESSION_NOT_FOUND"});const s=this.sessions.get(e);if(s){const t=[...s.processes],n=t.map(e=>this.waitForProcessClose(e,5e3));this.stop(e);const r=await Promise.all(n);let i=t.filter((e,t)=>!r[t]);if(i.length>0){const e=i.map(e=>this.waitForProcessClose(e,1e3));for(const e of i)null===e.exitCode&&null===e.signalCode&&e.kill("SIGKILL");const t=await Promise.all(e);i=i.filter((e,s)=>!t[s])}if(i.length>0)throw Object.assign(new Error(`App session processes did not exit: ${i.map(e=>e.pid??"unknown").join(", ")}.`),{code:"APP_PROCESS_STOP_TIMEOUT"})}return this.sessions.delete(e),this.persistedSessions.delete(e),this.removeSessionFiles(t),this.emit("deleted",t),t}cleanupExpiredSessions(e=new Date){const t=this.sessionRetentionMs();if(!t)return[];const s=e.getTime()-t,n=[];for(const e of this.persistedSessions.values()){if(this.sessions.has(e.id)||!kt.has(e.status))continue;const t=Date.parse(e.updatedAt||e.createdAt);!Number.isFinite(t)||t>s||(this.persistedSessions.delete(e.id),this.removeSessionFiles(e),n.push(e))}return n}screenshot(e){const t=this.sessions.get(e);if(!t)throw Object.assign(new Error("App session not found."),{code:"APP_SESSION_NOT_FOUND"});if(!t.metadata.display)throw Object.assign(new Error("Screenshots are only available for GUI sessions."),{code:"APP_SCREENSHOT_UNAVAILABLE"});if(!this.hasCommand("import"))throw Object.assign(new Error("Missing required command: import. Install ImageMagick in the runtime image."),{code:"APP_DEPENDENCY_MISSING"});try{const e=t.metadata.display.xauthority;return m.execFileSync("import",["-window","root","png:-"],{env:{...process.env,DISPLAY:t.metadata.display.display,...e?{XAUTHORITY:e,HOME:s.dirname(e)}:{}},maxBuffer:20971520})}catch(e){throw Object.assign(new Error(`Screenshot failed: ${e instanceof Error?e.message:String(e)}`),{code:"APP_SCREENSHOT_FAILED"})}}resizeDisplay(e,t){const s=this.sessions.get(e),n=s?.metadata;if(!s||!n?.display)throw Object.assign(new Error("Display session not found."),{code:"APP_DISPLAY_NOT_FOUND"});const r=this.normalizeDisplayOptions(t),i=r.width||n.display.width,o=r.height||n.display.height,a=r.depth||n.display.depth,d=this.displayCommandEnv(n);try{this.resizeDisplayWithXrandr(d,i,o)}catch(e){throw Object.assign(new Error(`Display resize failed: ${e instanceof Error?e.message:String(e)}`),{code:"APP_DISPLAY_RESIZE_FAILED"})}return n.display={...n.display,width:i,height:o,depth:a},this.persist(n),this.emit("updated",n),n}async automationStatus(e){const t=this.sessions.get(e),s=t?.metadata||this.persistedSessions.get(e);if(!s)throw Object.assign(new Error("App session not found."),{code:"APP_SESSION_NOT_FOUND"});if(!s.automation)throw Object.assign(new Error("Automation is not configured for this app session."),{code:"APP_AUTOMATION_UNAVAILABLE"});const n={sessionId:e,type:s.automation.type,endpoint:s.automation.endpoint,port:s.automation.port,ready:!1};if(!t||"running"!==s.status)return{...n,error:{code:"APP_AUTOMATION_NOT_RUNNING",message:"Automation endpoint is only available while the app session is running."}};try{const e=await this.fetchCdpVersion(s.automation.endpoint);return{...n,ready:!0,browser:"string"==typeof e.Browser?e.Browser:void 0,protocolVersion:"string"==typeof e["Protocol-Version"]?e["Protocol-Version"]:void 0,webSocketDebuggerUrl:"string"==typeof e.webSocketDebuggerUrl?e.webSocketDebuggerUrl:void 0}}catch(e){return{...n,error:{code:"APP_AUTOMATION_NOT_READY",message:e instanceof Error?e.message:String(e)}}}}stopAll(){for(const e of this.sessions.values()){e.stopping=!0,e.metadata.status="stopped",e.metadata.updatedAt=xt(),this.persist(e.metadata),this.stopClaudeDaemonForSession(e.metadata),e.pty?.kill("SIGTERM"),this.closeTtyLog(e);for(const t of e.processes)t.kill("SIGTERM")}for(const e of Array.from(this.sharedDisplays.keys()))this.stopSharedDisplay(e);this.stopSharedCodexAppServer(),this.sessions.clear()}vncTarget(e){const t=this.sessions.get(e);if(t?.metadata.vnc)return{host:t.metadata.vnc.host,port:t.metadata.vnc.port}}webTarget(e){const t=this.sessions.get(e);if(t?.metadata.web&&"running"===t.metadata.status)return{host:t.metadata.web.host,port:t.metadata.web.port}}attachTty(e,t){const s=this.sessions.get(e);if(!s||"running"!==s.metadata.status)return t.send(JSON.stringify({type:"error",message:"TTY session not found."})),void t.close?.();s.clients.add(t),t.send(JSON.stringify({type:"connected",session:s.metadata,dimensions:s.ttyDimensions})),s.outputBacklog&&t.send(JSON.stringify({type:"output",data:s.outputBacklog})),t.on("message",e=>{const n=Buffer.isBuffer(e)?e.toString("utf8"):String(e||"");try{const e=JSON.parse(n);if("input"===e.type&&"string"==typeof e.data)s.pty?.write(e.data);else if("resize"===e.type&&Number.isInteger(e.cols)&&Number.isInteger(e.rows)){const n=e.cols,r=e.rows;s.ttyDimensions={cols:n,rows:r},s.pty?.resize(n,r);for(const e of s.clients)e!==t&&e.send(JSON.stringify({type:"resize",cols:n,rows:r}))}}catch{s.pty?.write(n)}}),t.on("close",()=>{s.clients.delete(t)})}broadcast(e,t){const s=JSON.stringify(t);for(const t of e.clients)t.send(s)}writeTtyLog(e,t){const s=e.ttyLogStream;!s||e.ttyLogClosed||s.destroyed||s.closed||s.writableEnded||s.write(t,t=>{t&&(e.ttyLogClosed=!0)})}closeTtyLog(e){const t=e.ttyLogStream;!t||e.ttyLogClosed||t.destroyed||t.closed||t.writableEnded?e.ttyLogClosed=!0:(e.ttyLogClosed=!0,t.end())}persist(e){this.persistedSessions.set(e.id,e),this.persistSessionMetadata&&(t.mkdirSync(e.paths.sessionDir,{recursive:!0}),r.sync(s.join(e.paths.sessionDir,"metadata.json"),`${JSON.stringify(e,null,2)}\n`,{mode:384}))}removeSessionFiles(e){t.rmSync(e.paths.sessionDir,{recursive:!0,force:!0}),t.rmSync(e.paths.logDir,{recursive:!0,force:!0})}sessionRetentionMs(){const e=process.env.TASK_HANDOFF_APP_SESSION_RETENTION_DAYS;if(!e)return;const t=Number(e);return!Number.isFinite(t)||t<=0?void 0:24*t*60*60*1e3}loadPersistedSessions(){if(t.existsSync(this.paths.appSessionsDir))for(const e of t.readdirSync(this.paths.appSessionsDir,{withFileTypes:!0})){if(!e.isDirectory())continue;const n=s.join(this.paths.appSessionsDir,e.name,"metadata.json");if(t.existsSync(n))try{const s=JSON.parse(t.readFileSync(n,"utf8"));if(!s.id||!s.paths?.sessionDir||s.id!==e.name)continue;const r=this.recoverPersistedSession(s);this.persistedSessions.set(r.id,r),r!==s&&this.persist(r)}catch{continue}}}recoverPersistedSession(e){return"running"!==e.status&&"stopping"!==e.status?e:{...e,status:"exited",updatedAt:xt(),error:e.error||{code:"APP_SESSION_RESTORED_WITHOUT_PROCESS",message:"Runtime restarted; previous app processes are not attached. Use restart to launch a new session."},process:{...e.process,exitCode:e.process?.exitCode??null,signal:e.process?.signal??null}}}allocateDisplay(){const e=new Set([...Array.from(this.sessions.values()).map(e=>e.metadata.display?.display),...Array.from(this.sharedDisplays.values()).map(e=>e.display)].filter(e=>Boolean(e)).map(e=>Number(e.replace(/^:/,""))).filter(e=>Number.isInteger(e))),s=this.findAvailableNumber(this.nextDisplay,101,199,s=>!e.has(s)&&!t.existsSync(`/tmp/.X${s}-lock`)&&!t.existsSync(`/tmp/.X11-unix/X${s}`));return this.nextDisplay=this.nextNumber(s,101,199),s}allocatePort(e){const t="vnc"===e?{start:6101,end:6199,next:this.nextVncPort}:"websockify"===e?{start:7101,end:7199,next:this.nextWebsockifyPort}:"web"===e?{start:8101,end:8199,next:this.nextWebPort}:{start:9201,end:9299,next:this.nextCdpPort},s=new Set([...Array.from(this.sessions.values()).flatMap(e=>[e.metadata.vnc?.port,e.metadata.vnc?.websockifyPort,e.metadata.web?.port,e.metadata.automation?.port,e.metadata.ai?.appServer?.proxyPort]),...Array.from(this.sharedDisplays.values()).flatMap(e=>[e.vncPort,e.websockifyPort,"kasmvnc"===e.backend?e.vncPort:void 0])].filter(e=>Number.isInteger(e))),n=this.findAvailableNumber(t.next,t.start,t.end,e=>!s.has(e)&&this.isPortAvailable(e)),r=this.nextNumber(n,t.start,t.end);return"vnc"===e?this.nextVncPort=r:"websockify"===e?this.nextWebsockifyPort=r:"web"===e?this.nextWebPort=r:this.nextCdpPort=r,n}findAvailableNumber(e,t,s,n){const r=s-t+1;for(let s=0;s<r;s+=1){const i=t+(Math.max(e,t)-t+s)%r;if(n(i))return i}throw Object.assign(new Error(`No available allocation in range ${t}-${s}.`),{code:"APP_RESOURCE_EXHAUSTED"})}nextNumber(e,t,s){return e>=s?t:e+1}isPortAvailable(e){const t=["const net=require('node:net');","const server=net.createServer();","server.once('error',()=>process.exit(1));","server.listen(Number(process.argv[1]),'127.0.0.1',()=>server.close(()=>process.exit(0)));"].join("");return 0===m.spawnSync(process.execPath,["-e",t,String(e)],{stdio:"ignore"}).status}waitForUnixSocket(e,s,n){const r=Date.now();for(;Date.now()-r<s;){const s=n?.();if(s)throw s;if(t.existsSync(e)&&this.canConnectUnixSocket(e))return;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,50)}throw new Error(`${e} did not become ready within ${s}ms.`)}canConnectUnixSocket(e){const t=["const net=require('node:net');","const socket=net.createConnection(process.argv[1]);","const done=(code)=>{socket.destroy();process.exit(code);};","socket.once('connect',()=>done(0));","socket.once('error',()=>done(1));","setTimeout(()=>done(1),250);"].join("");return 0===m.spawnSync(process.execPath,["-e",t,e],{stdio:"ignore"}).status}markFailed(e,t,s){e.stopping||"stopped"===e.metadata.status||"failed"===e.metadata.status||(e.metadata.status="failed",e.metadata.updatedAt=xt(),e.metadata.error={code:t,message:s},this.persist(e.metadata),this.emit("updated",e.metadata))}waitForProcessClose(e,t){return null!==e.exitCode||null!==e.signalCode?Promise.resolve(!0):new Promise(s=>{let n=!1;const r=t=>{n||(n=!0,clearTimeout(a),e.off("close",i),e.off("error",o),s(t))},i=()=>r(!0),o=()=>r(!0),a=setTimeout(()=>r(!1),t);e.once("close",i),e.once("error",o)})}watchLoggedProcess(e,t,s,n,r){t.on("error",t=>{this.markFailed(e,"APP_PROCESS_ERROR",`${s} failed: ${t.message}`)}),t.on("exit",(t,i)=>{if(e.stopping)r?.();else{if(n&&0!==t)return this.markFailed(e,"APP_PROCESS_EXITED",`${s} exited unexpectedly with code ${t??"null"} signal ${i??"null"}.`),void r?.();n||(e.metadata.status=0===t?"exited":"failed",e.metadata.updatedAt=xt(),e.metadata.process={...e.metadata.process,exitCode:t,signal:i},0!==t&&(e.metadata.error={code:"APP_PROCESS_EXITED",message:`${s} exited with code ${t??"null"} signal ${i??"null"}.`}),this.persist(e.metadata),this.emit("updated",e.metadata)),r?.()}})}guiArgs(e,t,n,r){const i=[...e.args||[],...r].map(e=>e.replaceAll("{sessionDir}",t).replaceAll("{cdpPort}",String(n)));if("chromium"===e.id){const r=Dt("TASK_HANDOFF_CHROMIUM_NO_SANDBOX")?["--no-sandbox"]:[],o=function(e){const t=process.env.TASK_HANDOFF_CHROMIUM_USER_DATA_DIR?.trim();return t||s.join(e,"profile")}(t);return[...r,"--disable-dev-shm-usage","--no-first-run",...this.chromiumExtensionArgs(),"--remote-debugging-address=127.0.0.1",...o?[`--user-data-dir=${o}`]:[],...e.automation?.portArg?[e.automation.portArg.replaceAll("{port}",String(n))]:[`--remote-debugging-port=${n}`],...i]}return e.automation?.portArg&&i.unshift(e.automation.portArg.replaceAll("{port}",String(n))),this.isXtermApp(e)?["-fa",process.env.TASK_HANDOFF_XTERM_FONT_FAMILY||"Monospace","-fs",process.env.TASK_HANDOFF_XTERM_FONT_SIZE||"11",...i]:i}chromiumExtensionArgs(){const e=this.chromiumExtensionDirs();return e.length>0?[`--load-extension=${e.join(",")}`]:[]}chromiumExtensionDirs(){const e=process.env.TASK_HANDOFF_CHROMIUM_EXTENSION_DIRS;if(e)return e.split(/[,;]/).map(e=>e.trim()).filter(e=>this.isChromiumExtensionDir(e));const n=process.env.TASK_HANDOFF_CHROMIUM_EXTENSION_DIR||"/opt/task-handoff/chromium-extensions";return t.existsSync(n)?t.readdirSync(n,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>s.join(n,e.name)).filter(e=>this.isChromiumExtensionDir(e)).sort():[]}isChromiumExtensionDir(e){return t.existsSync(s.join(e,"manifest.json"))}isXtermApp(e){const t=s.basename(e.command||e.id);return"terminal-gui"===e.id||"xterm"===t}webArgs(e,t,s,n,r){const i=e=>e.replaceAll("{sessionDir}",t).replaceAll("{cwd}",s).replaceAll("{port}",String(n)),o=[...e.args||[],...r].map(i);return e.web?.portArg&&o.unshift(i(e.web.portArg)),o}prepareWebAppSession(e,n){if("vscode-web"!==e.id)return;const i=s.join(n,"user-data","User"),o=s.join(i,"settings.json");let a={};if(t.mkdirSync(i,{recursive:!0}),t.existsSync(o))try{const e=JSON.parse(t.readFileSync(o,"utf8"));e&&"object"==typeof e&&!Array.isArray(e)&&(a=e)}catch{a={}}r.sync(o,`${JSON.stringify({...Ct,...a},null,2)}\n`,{mode:384})}async fetchCdpVersion(e){const t=new URL(e);t.pathname=s.posix.join(t.pathname,"json","version");const n=new AbortController,r=setTimeout(()=>n.abort(),1e3);try{const e=await fetch(t,{signal:n.signal});if(!e.ok)throw new Error(`CDP version endpoint returned HTTP ${e.status}.`);return await e.json()}finally{clearTimeout(r)}}normalizeLaunchOptions(e={}){const t={};"string"==typeof e.title&&e.title.trim()&&(t.title=e.title.trim()),Array.isArray(e.args)&&(t.args=e.args.filter(e=>"string"==typeof e)),"string"==typeof e.cwd&&e.cwd.trim()&&(t.cwd=e.cwd.trim()),e.env&&"object"==typeof e.env&&!Array.isArray(e.env)&&(t.env=Object.fromEntries(Object.entries(e.env).filter(e=>"string"==typeof e[0]&&"string"==typeof e[1]&&e[0].trim().length>0).map(([e,t])=>[e.trim(),t])));const s=this.normalizeDisplayOptions(e.display||{});Object.keys(s).length>0&&(t.display=s);const n=this.normalizeDisplayTarget(e.displayTarget);return n&&(t.displayTarget=n),t}normalizeDisplayTarget(e){if(e&&"object"==typeof e){if("isolated"===e.mode)return{mode:"isolated"};if("shared"===e.mode)return{mode:"shared",id:"string"==typeof e.id&&e.id.trim()?e.id.trim():"main",autoCreate:!1!==e.autoCreate}}}normalizeDisplayOptions(e){const t=Number(e.width),s=Number(e.height),n=Number(e.depth),r={};return Number.isInteger(t)&&t>=320&&t<=7680&&(r.width=t),Number.isInteger(s)&&s>=240&&s<=4320&&(r.height=s),Number.isInteger(n)&&n>=8&&n<=32&&(r.depth=n),r}displayCommandEnv(e){const t=e.paths?.sessionDir,n=e.display?.xauthority?s.dirname(e.display.xauthority):t?s.join(t,"home"):void 0;return{...process.env,DISPLAY:e.display?.display,...n?{HOME:n,XAUTHORITY:e.display?.xauthority||s.join(n,".Xauthority")}:{}}}resizeDisplayWithXrandr(e,t,s){const n=`${t}x${s}`,r=this.connectedDisplayOutput(e),i=r?[["--output",r,"--mode",n],["--fb",n]]:[["--fb",n]];let o;for(const t of i)try{return void m.execFileSync("xrandr",t,{env:e,stdio:"ignore"})}catch(e){o=e}throw o instanceof Error?o:new Error(String(o))}connectedDisplayOutput(e){try{const t=m.execFileSync("xrandr",["--query"],{env:e,encoding:"utf8"});return t.match(/^(\S+)\s+connected\b/m)?.[1]}catch{return}}hasCommand(e,t=process.env,s=process.cwd()){return Boolean(It(e,t,s))}spawnTerminalPty(e,n,r,i){try{return function(){if("darwin"===process.platform||"linux"===process.platform)try{const e=s.resolve(s.dirname(require.resolve("node-pty")),".."),n=s.join(e,"prebuilds",`${process.platform}-${process.arch}`,"spawn-helper"),r=t.statSync(n);73&r.mode||t.chmodSync(n,493|r.mode)}catch{}}(),f.spawn(e,n,{name:"xterm-256color",cols:120,rows:32,cwd:r,env:i})}catch(e){throw Object.assign(new Error(`PTY unavailable: ${e instanceof Error?e.message:String(e)}`),{code:"PTY_UNAVAILABLE"})}}spawnLogged(e,n,r,i,o,a){const d=t.createWriteStream(s.join(i,o),{flags:"a"}),c=m.spawn(e,n,{cwd:a,env:r,stdio:["ignore","pipe","pipe"]});return c.stdout.pipe(d),c.stderr.pipe(d),c}}const Ft={"image/bmp":".bmp","image/gif":".gif","image/jpeg":".jpg","image/png":".png","image/webp":".webp"};function Rt(e=[]){if(!e.length)return[];const r=function(){const e=process.env.TASK_HANDOFF_AI_SESSION_ATTACHMENT_DIR?.trim();return e?s.resolve(e):s.join(n.tmpdir(),"task-handoff-ai-session-attachments")}();return t.mkdirSync(r,{recursive:!0}),function(e){const n=Date.now()-function(){const e=Number(process.env.TASK_HANDOFF_AI_SESSION_ATTACHMENT_RETENTION_MS);return Number.isFinite(e)&&e>0?e:864e5}();try{for(const r of t.readdirSync(e,{withFileTypes:!0})){if(!r.isFile())continue;const i=s.join(e,r.name);try{t.statSync(i).mtimeMs<n&&t.unlinkSync(i)}catch{}}}catch{}}(r),e.map(e=>{const n=Ft[e.mime.toLowerCase()]||s.extname(e.name)||".img",i=`${e.id}-${(o=e.name,s.basename(o).replace(/[^\w.\- ()\u4e00-\u9fff]/g,"_").slice(0,160)||"image").replace(/\.[^.]+$/,"")}${n}`;var o;const a=s.join(r,i);return t.writeFileSync(a,Buffer.from(e.data,"base64")),{...e,path:a}})}async function Mt(e,t=[],s){const n=Rt(t);if(!n.length)return s(e);const r=n.map((e,t)=>`图片${n.length>1?t+1:""}路径:${e.path}`);return s([e.trim(),r.join("\n")].filter(Boolean).join("\n\n"))}class jt{approvals=new Map;register(e){return this.approvals.set(e.id,e),e}latestForSession(e){return[...this.approvals.values()].filter(t=>t.sessionId===e).at(-1)}async resolveForSession(e,t){const s=this.latestForSession(e);if(s)return await s.resolve(t),this.approvals.delete(s.id),s}remove(e){return this.approvals.delete(e)}clearSession(e){for(const t of this.approvals.values())t.sessionId===e&&this.approvals.delete(t.id)}}class Ht{registry;providers=new Map;constructor(e){this.registry=e}register(e){this.providers.set(e.agent,e)}async sendMessage(e,t){const s=this.requireSession(e),n=t.message.trim();if(!n)throw $t("AI_SESSION_MESSAGE_EMPTY","Message is required.");const r=t.mode||"auto";if("queue"===r||"auto"===r&&Lt(s)){const e=this.registry.enqueueMessage(s.id,n,t.attachments||[]);if(!e)throw $t("AI_SESSION_NOT_FOUND","AI session not found.",404);return{session:e.session,provider:s.agent,action:"queue",queueId:e.item.id}}if("steer"===r)return this.steerMessage(s.id,{message:n,attachments:t.attachments||[]});if(Lt(s))throw $t("AI_SESSION_BUSY","AI session is busy. Queue the message or steer it into the running turn.",409);return this.startMessage(s.id,{message:n,attachments:t.attachments||[]})}async startMessage(e,t){const s=this.requireSession(e);if(Lt(s))throw $t("AI_SESSION_BUSY","AI session is busy. Queue the message or steer it into the running turn.",409);const n=this.requireProvider(s),r=n.startMessage||n.sendMessage;if(!r)throw $t("AI_SESSION_SEND_UNSUPPORTED",`${s.agent} sessions do not support starting turns.`,400);return r.call(n,s,t)}async steerMessage(e,t){const s=this.requireSession(e);if(!Lt(s))throw $t("AI_SESSION_NOT_ACTIVE","AI session is not active.",409);const n=this.requireProvider(s),r=n.steerMessage||n.sendMessage;if(!r)throw $t("AI_SESSION_STEER_UNSUPPORTED",`${s.agent} sessions do not support turn steering.`,400);const i="string"==typeof t?{message:t}:t;return r.call(n,s,i)}async sendNextQueuedMessage(e){const t=this.requireSession(e);if(Lt(t))return;const s=this.registry.nextQueuedMessage(t.id);if(s){this.registry.markQueuedMessageSending(t.id,s.id);try{const e=await this.startMessage(t.id,{message:s.message,attachments:this.registry.queuedMessageAttachments(s.id)}),n=this.registry.removeQueuedMessage(t.id,s.id);return{...e,session:n||e.session,queueId:s.id}}catch(e){throw this.registry.markQueuedMessageFailed(t.id,s.id,e),e}}}async steerQueuedMessage(e,t){const s=this.requireSession(e),n=s.queue.items.find(e=>e.id===t);if(!n)throw $t("AI_SESSION_QUEUE_ITEM_NOT_FOUND","Queued message not found.",404);const r=await this.steerMessage(s.id,{message:n.message,attachments:this.registry.queuedMessageAttachments(n.id)}),i=this.registry.removeQueuedMessage(s.id,n.id);return{...r,session:i||r.session,action:"steer",queueId:n.id}}retryQueuedMessage(e,t){const s=this.registry.retryQueuedMessage(e,t);if(!s)throw $t("AI_SESSION_QUEUE_ITEM_NOT_FOUND","Queued message not found.",404);return s}removeQueuedMessage(e,t){const s=this.registry.removeQueuedMessage(e,t);if(!s)throw $t("AI_SESSION_NOT_FOUND","AI session not found.",404);return s}reorderQueuedMessages(e,t){const s=this.registry.reorderQueuedMessages(e,t);if(!s)throw $t("AI_SESSION_NOT_FOUND","AI session not found.",404);return s}async interrupt(e){const t=this.requireSession(e);if("running"!==t.status&&"waiting"!==t.status)throw $t("AI_SESSION_NOT_ACTIVE","AI session is not active.",400);return this.requireProvider(t).interrupt(t)}async resolveApproval(e,t){const s=this.requireSession(e),n=this.requireProvider(s);if(n.resolveApproval)return n.resolveApproval(s,t);throw $t("AI_SESSION_APPROVAL_UNSUPPORTED",`${s.agent} sessions do not expose structured approval control.`,400)}requireSession(e){const t=this.registry.get(e);if(!t)throw $t("AI_SESSION_NOT_FOUND","AI session not found.",404);return t}requireProvider(e){const t=this.providers.get(e.agent);if(!t)throw $t("AI_SESSION_CONTROL_UNSUPPORTED",`${e.agent} sessions do not support direct control yet.`,400);return t}}function Lt(e){return"running"===e.status||"waiting"===e.status}function $t(e,t,s=400){const n=new Error(t);return n.code=e,n.statusCode=s,n}function Ut(e){const t=Qt(e);return/^\[(?:request interrupted by user|user interrupted request)\]$/i.test(t)}function qt(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}function Bt(e){if(e.timestamp)return e;const{timestamp:t,...s}=e;return s}function Vt(e){return Array.isArray(e)?e:[]}function Kt(e){return"tool_use"===e.type}function Gt(e){return"tool_result"===e.type}function Wt(e){return"text"===e.type}function Xt(e){return"text"!==e.type&&"output_text"!==e.type&&"input_text"!==e.type||"string"!=typeof e.text?"":e.text}function Jt(e){if("string"==typeof e)return Qt(e);const t=Vt(e).map(Xt).filter(Boolean).join("\n");return t?Qt(t):""}function Yt(e,t=180){const s=String(e??"").replace(/\s+/g," ").trim();return s.length>t?`${s.slice(0,t-3)}...`:s}function Qt(e){return String(e??"").trim()}function Zt(e){try{const t=qt(JSON.parse(String(e||"{}")));return Yt(t.cmd||t.command||t.path||t.ref_id||t.pattern||"")}catch{return""}}function es(e){if(e&&"object"==typeof e&&!Array.isArray(e)){const t=e;return Yt(t.command||t.cmd||t.file_path||t.filePath||t.path||t.ref_id||t.pattern||t.description||"")}return Zt(e)}function ts(e){return/\b(task-handoff|result-ipc)(\.js)?\b/.test(e)}function ss(e){return["edit","multiedit","write","notebookedit"].includes(e.toLowerCase())}function ns(e,r,i=s.join(n.homedir(),".claude")){const o=Yt(e,200);if(!o)return;const a=s.join(i,"projects"),d=Yt(r);if(d){const e=s.join(a,function(e){return s.resolve(e).split(s.sep).join("-")}(d),`${o}.jsonl`);if(t.existsSync(e))return e}const c=[a];for(;c.length>0;){const e=c.pop();if(!e)continue;let n;try{n=t.readdirSync(e,{withFileTypes:!0})}catch{continue}for(const t of n){const n=s.join(e,t.name);if(t.isDirectory())c.push(n);else if(t.isFile()&&t.name.endsWith(".jsonl")&&t.name.includes(o))return n}}}function rs(e,t){let n;try{n=JSON.parse(e)}catch{return}const r=qt(n),i=qt(r.payload),o="string"==typeof qt(n).timestamp?qt(n).timestamp:void 0;if("turn_context"===r.type)return;if("event_msg"===r.type)return"agent_message"===i.type?Bt({text:Qt(i.message),kind:"assistant",timestamp:o}):void 0;if("assistant"===r.type){const e=Vt(r.message?.content);let s,n;for(const r of e){if(Kt(r)){const e=Yt(r.name||"tool",80),n=es(r.input),i=ts(n),a=ss(e)?"edit":void 0;if(r.id&&t.calls.set(r.id,{tool:e,command:n,ignored:i,action:a}),i)continue;s??=Bt({key:r.id,text:"edit"===a?`Editing ${n||"files"}`:n?`Running ${e}: ${n}`:`Running ${e}`,kind:"tool",timestamp:o});continue}Wt(r)&&r.text&&(n??=Qt(r.text))}return s||(n?Bt({text:n,kind:"assistant",timestamp:o}):void 0)}if("user"===r.type){const e=Jt(r.message?.content);if(e&&!Ut(e))return Bt({text:e,kind:"user",timestamp:o});const s=Vt(r.message?.content);for(const e of s){if(!Gt(e))continue;const s=e.tool_use_id?t.calls.get(e.tool_use_id):void 0;if(!s||s.ignored)continue;const n=Boolean(e.is_error);return Bt({key:e.tool_use_id,text:"edit"===s.action?n?`Edit failed: ${s.command||"files"}`:`Finished editing ${s.command||"files"}`:n?`Failed ${s.tool}${s.command?`: ${s.command}`:""}`:s.command?`Finished ${s.tool}: ${s.command}`:`Finished ${s.tool}`,kind:"tool",timestamp:o})}return}if("response_item"!==r.type)return;const a=r.payload;if(a){if("custom_tool_call"===a.type){const e=Yt(a.name||"custom_tool",80);if("apply_patch"!==e)return;const n=function(e){const t=[...String(e||"").matchAll(/^\*\*\* (?:Add|Delete|Update) File: (.+)$/gm)].map(e=>function(e){if(!s.isAbsolute(e))return e;const t=s.relative(process.cwd(),e);return!t||t.startsWith("..")||s.isAbsolute(t)?e:t}(e[1].trim()));if(0===t.length)return"files";const n=t.slice(0,2).join(", ");return t.length>2?`${n} +${t.length-2} more`:n}(a.input);return a.call_id&&t.calls.set(a.call_id,{tool:e,command:n,ignored:!1,action:"edit"}),Bt({key:a.call_id,text:`Editing ${n}`,kind:"tool",timestamp:o})}if("custom_tool_call_output"===a.type){const e=a.call_id?t.calls.get(a.call_id):void 0;if(!e||e.ignored||"edit"!==e.action)return;const s=Yt(a.output,120),n=/failed|error/i.test(s);return Bt({key:a.call_id,text:n?`Edit failed: ${e.command}`:`Finished editing ${e.command}`,kind:"tool",timestamp:o})}if("function_call"===a.type){const e=Yt(a.name||"tool",80),s=Zt(a.arguments),n="write_stdin"===e||ts(s);if(a.call_id&&t.calls.set(a.call_id,{tool:e,command:s,ignored:n}),n)return;return Bt({key:a.call_id,text:s?`Running ${e}: ${s}`:`Running ${e}`,kind:"tool",timestamp:o})}if("function_call_output"===a.type){const e=a.call_id?t.calls.get(a.call_id):void 0;if(!e||e.ignored)return;return Bt({key:a.call_id,text:e.command?`Finished ${e.tool}: ${e.command}`:`Finished ${e.tool}`,kind:"tool",timestamp:o})}if("message"===a.type){const e=Jt(a.content);if(!e)return;return Bt({text:Qt(e),kind:"user"===a.role?"user":"assistant",timestamp:o})}}}const is=41943040,os="ai-session.snapshot",as=i.z.string().trim().min(1).max(80),ds=i.z.enum(["running","waiting","idle","failed"]),cs=i.z.enum(["thinking","tool","editing","approval","responding","unknown"]),ps=i.z.object({name:i.z.string().trim().min(1).max(120),inputPreview:i.z.string().trim().max(500).optional(),startedAt:i.z.string().datetime().optional()}).strict(),us=i.z.object({toolCalls:i.z.number().int().min(0).default(0),edits:i.z.number().int().min(0).default(0),approvals:i.z.number().int().min(0).default(0)}).strict().default({toolCalls:0,edits:0,approvals:0}),ls=i.z.object({send:i.z.boolean().optional(),interrupt:i.z.boolean().optional(),approval:i.z.boolean().optional()}).strict(),ms=i.z.object({id:i.z.string().trim().min(1).max(120),kind:i.z.enum(["image"]),name:i.z.string().trim().min(1).max(240),mime:i.z.string().trim().min(1).max(120),size:i.z.number().int().min(0).max(20971520),data:i.z.string().min(1).max(31457280)}).strict(),hs=ms.omit({data:!0}),gs=i.z.object({id:i.z.string().trim().min(1).max(120),kind:i.z.enum(["image"]).optional()}).strict(),fs=i.z.enum(["auto","queue","steer","immediate"]),ys=i.z.object({message:i.z.string().trim().min(1).max(2e4),mode:fs.optional()}),vs=ys.extend({attachments:i.z.array(ms).max(6).default([])}).strict().superRefine((e,t)=>{e.attachments.reduce((e,t)=>e+t.size,0)>is&&t.addIssue({code:i.z.ZodIssueCode.custom,path:["attachments"],message:"Images must be 41943040 bytes or less in total."})});ys.extend({attachments:i.z.array(gs).max(6).default([])}).strict();const Ss=i.z.object({decision:i.z.enum(["allow","deny","skip"])}).strict(),Is=i.z.object({queueIds:i.z.array(i.z.string().trim().min(1).max(120)).max(100)}).strict(),As=i.z.object({code:i.z.string().trim().min(1).max(160),message:i.z.string(),instanceId:i.z.string().trim().min(1).max(160).optional(),nodeId:i.z.string().trim().min(1).max(160).optional(),route:i.z.string().trim().min(1).max(4096).optional()}).strict(),bs=i.z.object({id:i.z.string().trim().min(1).max(120),message:i.z.string().trim().min(1).max(2e4),attachments:i.z.array(hs).max(6).default([]),status:i.z.enum(["queued","sending","failed"]).default("queued"),createdAt:i.z.string().datetime(),updatedAt:i.z.string().datetime(),error:i.z.string().trim().max(4e3).optional()}).strict(),_s=i.z.object({pendingCount:i.z.number().int().min(0).default(0),items:i.z.array(bs).max(100).default([])}).strict().default({pendingCount:0,items:[]}),ws=i.z.enum(["control","realtime","adapter-snapshot","transcript-tail","transcript-scan","process-scan","app-session"]),Ts=i.z.object({id:i.z.string().trim().min(1).max(240),providerTurnId:i.z.string().trim().max(240).optional(),source:ws.optional(),userPrompt:i.z.string().trim().optional(),status:i.z.enum(["queued","running","waiting","completed","failed"]).default("running"),phase:cs.optional(),summary:i.z.string().trim().max(1e3).optional(),lastMessage:i.z.string().trim().optional(),revision:i.z.number().int().min(0).default(0),sourcePriority:i.z.number().int().min(0).max(100).optional(),snapshotVersion:i.z.number().int().min(0).optional(),observedAt:i.z.string().datetime().optional(),startedAt:i.z.string().datetime().optional(),updatedAt:i.z.string().datetime().optional(),completedAt:i.z.string().datetime().optional()}).strict(),Ns=i.z.object({id:i.z.string().trim().min(1).max(120),agent:as,appSessionId:i.z.string().trim().max(120).optional(),appId:i.z.string().trim().max(120).optional(),providerSessionId:i.z.string().trim().max(240).optional(),providerMeta:i.z.record(i.z.string(),i.z.unknown()).optional(),appBindingKeys:i.z.array(i.z.string().trim().min(1).max(240)).max(20).optional(),actions:ls.optional(),activeTurnId:i.z.string().trim().max(240).optional(),conversationId:i.z.number().int().positive().optional(),title:i.z.string().trim().max(240).optional(),cwd:i.z.string().trim().max(4096).optional(),userPrompt:i.z.string().trim().optional(),turns:i.z.array(Ts).max(50).optional(),status:ds.default("running"),phase:cs.default("unknown"),summary:i.z.string().trim().max(1e3).optional(),lastMessage:i.z.string().trim().optional(),currentTool:ps.optional(),transcriptPath:i.z.string().trim().max(4096).optional(),transcriptSize:i.z.number().int().min(0).optional(),startedAt:i.z.string().datetime(),updatedAt:i.z.string().datetime(),completedAt:i.z.string().datetime().optional(),error:i.z.string().trim().max(4e3).optional(),counters:us,queue:_s}).strict(),Os=i.z.object({session:Ns,provider:i.z.string().trim().min(1).max(80),action:i.z.enum(["send","queue","steer","interrupt","approval"]),decision:i.z.enum(["allow","deny","skip"]).optional(),turnId:i.z.string().trim().min(1).max(240).optional(),providerTurnId:i.z.string().trim().min(1).max(240).optional(),queueId:i.z.string().trim().min(1).max(120).optional()}).strict(),Es=Ns.pick({id:!0,agent:!0,appSessionId:!0,appId:!0,providerSessionId:!0,providerMeta:!0,appBindingKeys:!0,actions:!0,activeTurnId:!0,conversationId:!0,title:!0,cwd:!0,userPrompt:!0,turns:!0,status:!0,phase:!0,summary:!0,lastMessage:!0,currentTool:!0,queue:!0,startedAt:!0,updatedAt:!0,error:!0}),zs=i.z.object({runningCount:i.z.number().int().min(0).default(0),waitingCount:i.z.number().int().min(0).default(0),staleCount:i.z.number().int().min(0).default(0),sessions:i.z.array(Es).default([]),updatedAt:i.z.string().datetime()}).strict();i.z.object({revision:i.z.number().int().min(0),lastEventAt:i.z.string().datetime(),snapshot:zs}).strict(),zs.pick({runningCount:!0,waitingCount:!0,staleCount:!0,updatedAt:!0}).extend({idleCount:i.z.number().int().min(0).default(0),problemCount:i.z.number().int().min(0).default(0),revision:i.z.number().int().min(0).optional()});const xs=i.z.enum(["provider-event","app-session-created","app-session-updated","app-session-deleted","discovery-scan","control-action","heartbeat-sync","startup"]),Ds=i.z.object({instanceId:i.z.string().trim().min(1).max(160),nodeId:i.z.string().trim().min(1).max(160).optional(),snapshotRevision:i.z.number().int().min(0),previousRevision:i.z.number().int().min(0).optional(),eventSeq:i.z.number().int().min(1),traceId:i.z.string().trim().min(1).max(160),generatedAt:i.z.string().datetime(),reason:xs}).strict(),ks=i.z.object({meta:Ds,snapshot:zs}).strict(),Cs=i.z.object({meta:Ds,upserted:i.z.array(Es).default([]),removed:i.z.array(i.z.string().trim().min(1).max(120)).default([])}).strict(),Ps=i.z.object({meta:Ds,sessionIds:i.z.array(i.z.string().trim().min(1).max(120)).default([]),expiresAt:i.z.string().datetime()}).strict(),Fs=i.z.object({instanceId:i.z.string().trim().min(1).max(160),sinceRevision:i.z.number().int().min(0),latestRevision:i.z.number().int().min(0),syncRequired:i.z.boolean().default(!1),events:i.z.array(i.z.discriminatedUnion("type",[i.z.object({type:i.z.literal(os),payload:ks}).strict(),i.z.object({type:i.z.literal("ai-session.patch"),payload:Cs}).strict(),i.z.object({type:i.z.literal("ai-session.removed"),payload:Ps}).strict()])).default([])}).strict(),Rs=i.z.object({source:ws,sourcePriority:i.z.number().int().min(0).max(100).optional(),observedAt:i.z.string().datetime().optional(),snapshotVersion:i.z.number().int().min(0).optional()}).strict(),Ms=Rs.extend({type:i.z.literal("snapshot"),agent:i.z.string().trim().min(1).max(80),appSessionId:i.z.string().trim().max(120).optional(),appId:i.z.string().trim().max(120).optional(),providerSessionId:i.z.string().trim().max(240).optional(),providerMeta:i.z.record(i.z.string(),i.z.unknown()).optional(),appBindingKeys:i.z.array(i.z.string().trim().min(1).max(240)).max(20).optional(),actions:ls.optional(),conversationId:i.z.number().int().positive().optional(),title:i.z.string().trim().max(240).optional(),cwd:i.z.string().trim().max(4096).optional(),activeTurnId:i.z.string().trim().max(240).optional(),userPrompt:i.z.string().trim().optional(),turns:i.z.array(Ts).max(50).optional(),status:ds.optional(),phase:cs.optional(),summary:i.z.string().trim().max(1e3).optional(),lastMessage:i.z.string().trim().optional(),transcriptPath:i.z.string().trim().max(4096).optional(),transcriptSize:i.z.number().int().min(0).optional(),replaceActivity:i.z.boolean().optional()}).strict(),js=Rs.extend({type:i.z.literal("event"),sessionId:i.z.string().trim().min(1).max(120),kind:i.z.enum(["lifecycle","send-ack","turn-started","user-message","assistant-message","approval-requested","turn-completed"]),activeTurnId:i.z.string().trim().max(240).optional(),providerTurnId:i.z.string().trim().max(240).optional(),userPrompt:i.z.string().trim().optional(),text:i.z.string().optional(),status:ds.optional(),phase:cs.optional(),summary:i.z.string().trim().max(1e3).optional(),error:i.z.string().trim().max(4e3).optional(),counters:i.z.object({toolCalls:i.z.number().int().min(0).optional(),edits:i.z.number().int().min(0).optional(),approvals:i.z.number().int().min(0).optional()}).strict().optional()}).strict();function Hs(e,t=500){const s=String(e??"").replace(/\s+/g," ").trim();return s.length>t?`${s.slice(0,t-3)}...`:s}function Ls(e){return String(e??"").trim()}i.z.discriminatedUnion("type",[Ms,js]);const $s={control:90,realtime:80,"adapter-snapshot":60,"transcript-tail":50,"app-session":40,"process-scan":30,"transcript-scan":20};function Us(e,t){return Math.max(0,Math.min(100,Number.isInteger(t)?Number(t):e?$s[e]:0))}function qs(e){const t={};return e.source&&(t.source=e.source,t.sourcePriority=Us(e.source,e.sourcePriority)),e.providerTurnId&&(t.providerTurnId=Hs(e.providerTurnId,240)),Number.isInteger(e.snapshotVersion)&&(t.snapshotVersion=Number(e.snapshotVersion)),e.observedAt&&(t.observedAt=e.observedAt),t}function Bs(e){const t=Hs(e,120),s=t.replace(/[^a-zA-Z0-9_.:-]+/g,"_").replace(/^_+|_+$/g,""),n=h.createHash("sha1").update(t).digest("hex").slice(0,10);return s?`${s}_${n}`:n}function Vs(e,t){return`turn_${Bs(e)}_${Bs(t)}`}function Ks(e,t,s=1){return Vs(e,t||`${e}:${s}`)}function Gs(e,t){return`turn_legacy_${t}_${Bs(e.userPrompt||e.updatedAt||e.lastMessage||e.summary)}`}function Ws(e,t={}){const s=[];for(const[n,r]of(e||[]).entries()){const e=r&&"object"==typeof r?r:void 0;if(!e)continue;const i={id:e.id?Hs(e.id,240):Gs(e,n),providerTurnId:e.providerTurnId?Hs(e.providerTurnId,240):t.providerTurnId,source:e.source||t.source,userPrompt:e.userPrompt?Ls(e.userPrompt):void 0,status:e.status||"completed",phase:e.phase,summary:e.summary?Hs(e.summary,1e3):void 0,lastMessage:e.lastMessage?Ls(e.lastMessage):void 0,revision:Math.max(0,Number(e.revision)||0),sourcePriority:Number.isInteger(e.sourcePriority)?Number(e.sourcePriority):t.sourcePriority,snapshotVersion:Number.isInteger(e.snapshotVersion)?Number(e.snapshotVersion):t.snapshotVersion,observedAt:e.observedAt||t.observedAt,startedAt:e.startedAt,updatedAt:e.updatedAt,completedAt:e.completedAt};(i.userPrompt||i.summary||i.lastMessage)&&s.push(i)}return s.slice(-50)}function Xs(e,t){if(!e)return!0;const s=Us(e.source,e.sourcePriority),n=Us(t.source,t.sourcePriority);if(n!==s)return n>s||Boolean(t.lastMessage||t.summary)&&!e.lastMessage&&!e.summary;const r=Number(e.snapshotVersion)||0,i=Number(t.snapshotVersion)||0;return i!==r?i>r:(t.revision||0)>=(e.revision||0)||Date.parse(t.observedAt||t.updatedAt||"")>=Date.parse(e.observedAt||e.updatedAt||"")}function Js(e,t){const s=function(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e))}(t);if(!e)return s;const n=e.userPrompt===(t.userPrompt??e.userPrompt)&&e.summary===(t.summary??e.summary)&&e.lastMessage===(t.lastMessage??e.lastMessage),r=e.status===(t.status??e.status)&&e.phase===(t.phase??e.phase);return n&&r&&(delete s.observedAt,delete s.updatedAt,delete s.completedAt),s}function Ys(e){return Boolean(e?.lastMessage||e?.summary)}function Qs(e){if(!e.activeTurnId||"running"!==e.status)return!1;const t=Ws(e.turns).find(t=>t.id===e.activeTurnId);return Boolean(!t||!Ys(t))}function Zs(e,t,s){return s?e.activeTurnId:"idle"!==t.status&&"failed"!==t.status?t.activeTurnId?Hs(t.activeTurnId,240):e.activeTurnId:void 0}function en(e,t,s,n={}){const r=function(e,t,s={}){const n=Ws(e),r=Ws(t,s);function i(e,t){const s=r.slice(0,t).reverse().find(e=>n.some(t=>t.id===e.id));if(s){const t=n.findIndex(e=>e.id===s.id);return void n.splice(t+1,0,e)}const i=r.slice(t+1).find(e=>n.some(t=>t.id===e.id));if(i){const t=n.findIndex(e=>e.id===i.id);return void n.splice(t,0,e)}n.push(e)}for(const[e,t]of r.entries()){let s=!1;for(const[e,r]of n.entries())if(r.id!==t.id&&r.userPrompt&&r.userPrompt===t.userPrompt&&!r.lastMessage&&!r.summary&&(t.lastMessage||t.summary)){const i={...r,...Js(r,t),id:r.id,providerTurnId:t.providerTurnId||t.id,revision:Math.max(r.revision||0,t.revision||0)};Xs(r,i)&&(n[e]=i),s=!0;break}if(s)continue;const r=n.findIndex(e=>e.id===t.id),o=r>=0?n[r]:void 0;if(Xs(o,t)){const s={...o,...Js(o,t),revision:Math.max(o?.revision||0,t.revision||0)};r>=0?n[r]=s:i(s,e)}}return n.slice(-50)}(e,t.turns,n),i=t.userPrompt?Ls(t.userPrompt):"",o=t.activeTurnId?Hs(t.activeTurnId,240):"";if(i){const e=r.at(-1),a=(o?r.find(e=>e.id===o):void 0)||[...r].reverse().find(e=>e.userPrompt===i&&!e.lastMessage&&!e.summary),d=Boolean(t.turns?.some(e=>e.userPrompt&&Ls(e.userPrompt)===i));a?(o&&a.id!==o&&(a.id=o),a.userPrompt=i,a.updatedAt=s,a.status="waiting"===t.status?"waiting":"running",a.phase=t.phase||a.phase||"thinking",Object.assign(a,n),a.revision+=1):!e||e.lastMessage||e.summary||e.userPrompt!==i?d||r.push({id:o||Vs(i,s),...n,userPrompt:i,status:"waiting"===t.status?"waiting":"running",phase:t.phase||"thinking",revision:0,startedAt:s,updatedAt:s}):(e.updatedAt=s,e.status="waiting"===t.status?"waiting":"running",e.phase=t.phase||e.phase||"thinking",Object.assign(e,n),e.revision+=1)}if(t.lastMessage||t.summary){let e=o?r.find(e=>e.id===o):r.at(-1);if(!e&&o){const t=[...r].reverse().find(e=>e.userPrompt&&!e.lastMessage&&!e.summary);t&&(t.id=o,e=t)}!e&&o&&(e={id:o,...n,status:"waiting"===t.status?"waiting":"failed"===t.status?"failed":"running",phase:t.phase||"unknown",revision:0,startedAt:s,updatedAt:s},r.push(e));const i={summary:t.summary?Hs(t.summary,1e3):e?.summary,lastMessage:t.lastMessage?Ls(t.lastMessage):e?.lastMessage,status:"idle"===t.status?"completed":"waiting"===t.status?"waiting":"failed"===t.status?"failed":e?.status||"running",phase:t.phase||e?.phase,updatedAt:s,completedAt:"idle"===t.status||"failed"===t.status?s:e?.completedAt,...n};if(e){const t=e.summary===i.summary&&e.lastMessage===i.lastMessage,s=e.status===i.status&&e.phase===i.phase,n=t&&s;Object.assign(e,{...i,observedAt:n?e.observedAt:i.observedAt,updatedAt:n||t?e.updatedAt:i.updatedAt,completedAt:n?e.completedAt:i.completedAt}),t&&s||(e.revision+=1)}else r.push({id:`turn_${h.randomUUID().replace(/-/g,"").slice(0,20)}`,...i,status:i.status||"running",revision:0,startedAt:s})}else if((t.status||t.phase)&&o){const e=r.find(e=>e.id===o);if(e){const r="idle"===t.status?"completed":"waiting"===t.status?"waiting":"failed"===t.status?"failed":e.status,i=t.phase||e.phase,o="idle"===t.status||"failed"===t.status?s:e.completedAt,a=e.status!==r||e.phase!==i||e.completedAt!==o;Object.assign(e,{status:r,phase:i,completedAt:o,updatedAt:a?s:e.updatedAt,...n}),a&&(e.revision+=1)}}if(("running"===t.status||"waiting"===t.status)&&o){const e=r.findIndex(e=>e.id===o);if(e>=0&&e!==r.length-1){const[t]=r.splice(e,1);r.push(t)}}return Ws(r)}function tn(){return(new Date).toISOString()}function sn(e){t.mkdirSync(e,{recursive:!0})}function nn(e){try{return JSON.parse(t.readFileSync(e,"utf8"))}catch{return}}function rn(e,t,s){if(!Array.isArray(e))return;const n=[...new Set(e.map(e=>Hs(e,s)).filter(Boolean))].slice(0,t);return n.length?n:void 0}function on(e){const t=e&&"object"==typeof e&&!Array.isArray(e)?e:{},s={send:"boolean"==typeof t.send?t.send:void 0,interrupt:"boolean"==typeof t.interrupt?t.interrupt:void 0,approval:"boolean"==typeof t.approval?t.approval:void 0};return void 0===s.send&&void 0===s.interrupt&&void 0===s.approval?void 0:s}function an(e){const t=e.map(cn).filter(e=>Boolean(e)).slice(0,100);return{pendingCount:t.filter(e=>"queued"===e.status||"sending"===e.status).length,items:t}}function dn(e){const t=e&&"object"==typeof e&&!Array.isArray(e)?e:{};return an(Array.isArray(t.items)?t.items:[])}function cn(e){const t=e&&"object"==typeof e&&!Array.isArray(e)?e:void 0;if(!(t?.id&&t.message&&t.createdAt&&t.updatedAt))return;const s="sending"===t.status||"failed"===t.status?t.status:"queued";return{id:Hs(t.id,120),message:Ls(t.message),attachments:pn(t.attachments),status:s,createdAt:t.createdAt,updatedAt:t.updatedAt,error:t.error?Hs(t.error,4e3):void 0}}function pn(e){return Array.isArray(e)?e.map(e=>{const t=hs.safeParse(e);return t.success?t.data:void 0}).filter(e=>Boolean(e)).slice(0,6):[]}function un(e=[]){return e.slice(0,6).map(e=>hs.parse({id:e.id,kind:e.kind,name:e.name,mime:e.mime,size:e.size}))}function ln(e){const t=e&&"object"==typeof e?e:void 0;var s;if(t?.id&&t.agent&&t.startedAt&&t.updatedAt)return{id:Hs(t.id,120),agent:Hs(t.agent,80),appSessionId:t.appSessionId?Hs(t.appSessionId,120):void 0,appId:t.appId?Hs(t.appId,120):void 0,providerSessionId:t.providerSessionId?Hs(t.providerSessionId,240):void 0,providerMeta:t.providerMeta&&"object"==typeof t.providerMeta&&!Array.isArray(t.providerMeta)?t.providerMeta:void 0,appBindingKeys:rn(t.appBindingKeys,20,240),actions:on(t.actions),activeTurnId:t.activeTurnId?Hs(t.activeTurnId,240):void 0,conversationId:Number.isInteger(t.conversationId)&&Number(t.conversationId)>0?Number(t.conversationId):void 0,title:t.title?Hs(t.title,240):void 0,cwd:t.cwd?Hs(t.cwd,4096):void 0,userPrompt:t.userPrompt?Ls(t.userPrompt):void 0,turns:Ws(t.turns),status:mn(t.status),phase:hn(t.phase),summary:t.summary?Hs(t.summary,1e3):void 0,lastMessage:t.lastMessage?Ls(t.lastMessage):void 0,currentTool:t.currentTool?.name?{name:Hs(t.currentTool.name,120),inputPreview:t.currentTool.inputPreview?Hs(t.currentTool.inputPreview,500):void 0,startedAt:t.currentTool.startedAt}:void 0,transcriptPath:t.transcriptPath?Hs(t.transcriptPath,4096):void 0,transcriptSize:Number.isInteger(t.transcriptSize)&&Number(t.transcriptSize)>=0?Number(t.transcriptSize):void 0,startedAt:t.startedAt,updatedAt:t.updatedAt,completedAt:t.completedAt,error:t.error?Hs(t.error,4e3):void 0,counters:(s=t.counters,{toolCalls:Math.max(0,Number(s?.toolCalls)||0),edits:Math.max(0,Number(s?.edits)||0),approvals:Math.max(0,Number(s?.approvals)||0)}),queue:dn(t.queue)}}function mn(e){const t=String(e||"").trim().toLowerCase();return"waiting"===t?"waiting":"failed"===t?"failed":"idle"===t||"completed"===t||"stale"===t||"stopped"===t||"exited"===t?"idle":"running"}function hn(e){return["thinking","tool","editing","approval","responding","unknown"].includes(String(e))?e:"unknown"}function gn(e){return e.appSessionId?`${e.agent}:app:${e.appSessionId}`:e.providerSessionId?`${e.agent}:provider:${e.providerSessionId}`:e.transcriptPath?`${e.agent}:transcript:${e.transcriptPath}`:`${e.agent}:id:${e.id}`}function fn(e,t){const s=Number(Boolean(e.userPrompt))+Number(Boolean(e.summary))+Number(Boolean(e.lastMessage))+(e.turns?.length||0),n=Number(Boolean(t.userPrompt))+Number(Boolean(t.summary))+Number(Boolean(t.lastMessage))+(t.turns?.length||0);return s!==n?s>n?e:t:Date.parse(e.updatedAt)>=Date.parse(t.updatedAt)?e:t}function yn(e){return{id:e.id,agent:e.agent,appSessionId:e.appSessionId,appId:e.appId,providerSessionId:e.providerSessionId,providerMeta:e.providerMeta,appBindingKeys:e.appBindingKeys,actions:vn(e),activeTurnId:e.activeTurnId,conversationId:e.conversationId,title:e.title,cwd:e.cwd,userPrompt:e.userPrompt,turns:e.turns,status:e.status,phase:e.phase,summary:e.summary,lastMessage:e.lastMessage,currentTool:e.currentTool,queue:e.queue,startedAt:e.startedAt,updatedAt:e.updatedAt,error:e.error}}function vn(e){const t="running"===e.status||"waiting"===e.status,s=e.actions||{};return{send:s.send??!0,interrupt:Boolean(t&&!1!==s.interrupt),approval:Boolean("waiting"===e.status&&"approval"===e.phase&&!1!==s.approval)}}function Sn(e,t){const s=Hs(e,1e3);return"user"===t?{userPrompt:Ls(e)}:"assistant"===t?{status:"running",phase:"responding",summary:s,lastMessage:Ls(e)}:/approval|permission|approve|deny/i.test(s)?{status:"waiting",phase:"approval",summary:s,counters:{approvals:1}}:/^Editing\b|Finished editing\b|Edit failed/i.test(s)?{status:"running",phase:"editing",summary:s,counters:{edits:1}}:/^Tool\b|^Running\b|^Finished\b|^Failed\b/i.test(s)?{status:"running",phase:"tool",summary:s,counters:{toolCalls:1}}:s?{status:"running",phase:"responding",summary:s,lastMessage:Ls(e)}:{}}function In(e,t,s){const n=t.activeTurnId?Hs(t.activeTurnId,240):void 0;if("transcript-tail"!==t.source||!n||!e.activeTurnId||n===e.activeTurnId)return n||e.activeTurnId;const r=Ws(e.turns).find(t=>t.id===e.activeTurnId);if(!r||Ys(r))return n;const i=s?Ls(s):"";return i&&r.userPrompt&&r.userPrompt!==i?n:e.activeTurnId}function An(e,r,i){if(r)return"claude"===e?ns(r,i):function(e,r=s.join(n.homedir(),".codex")){const i=Yt(e,200);if(!i)return;const o=[s.join(r,"sessions")];for(;o.length>0;){const e=o.pop();if(!e)continue;let n;try{n=t.readdirSync(e,{withFileTypes:!0})}catch{continue}for(const t of n){const n=s.join(e,t.name);if(t.isDirectory())o.push(n);else if(t.isFile()&&t.name.endsWith(".jsonl")&&t.name.includes(i))return n}}}(r)}class bn{dir;retentionMs;idleAfterMs;staleAfterMs;orphanedAppSessionRetentionMs;orphanedAppSessionAt=new Map;queuedAttachmentPayloads=new Map;changes=new g.EventEmitter;constructor(e={}){this.dir=e.dir||function(){const e=process.env.TASK_HANDOFF_AI_SESSION_DIR;return e?.trim()?s.resolve(e.trim()):s.join(et().dataDir,"ai-sessions")}(),this.retentionMs=e.retentionMs??(Number(process.env.TASK_HANDOFF_AI_SESSION_RETENTION_MS)||864e5),this.idleAfterMs=e.idleAfterMs??(Number(process.env.TASK_HANDOFF_AI_SESSION_IDLE_AFTER_MS)||3e4),this.staleAfterMs=e.staleAfterMs??(Number(process.env.TASK_HANDOFF_AI_SESSION_STALE_AFTER_MS)||3e5),this.orphanedAppSessionRetentionMs=e.orphanedAppSessionRetentionMs??(Number(process.env.TASK_HANDOFF_AI_SESSION_ORPHAN_RETENTION_MS)||3e5)}sessionPath(e){return s.join(this.dir,`${e}.json`)}onChange(e){return this.changes.on("change",e),()=>{this.changes.off("change",e)}}start(e,t={}){const s=t.timestamp||tn(),n=t.meta||qs({source:"control",observedAt:s}),r={id:`ais_${h.randomUUID().replace(/-/g,"").slice(0,20)}`,agent:Hs(e.agent||"unknown",80),appSessionId:e.appSessionId?Hs(e.appSessionId,120):void 0,appId:e.appId?Hs(e.appId,120):void 0,providerSessionId:e.providerSessionId?Hs(e.providerSessionId,240):void 0,providerMeta:void 0,activeTurnId:void 0,conversationId:e.conversationId,title:e.title?Hs(e.title,240):void 0,cwd:e.cwd?Hs(e.cwd,4096):void 0,userPrompt:e.userPrompt?Ls(e.userPrompt):void 0,turns:en(void 0,{userPrompt:t.suppressPromptTurn?void 0:e.userPrompt,turns:e.turns},s,n),status:mn(e.status||"idle"),phase:hn(e.phase||"unknown"),summary:e.summary?Hs(e.summary,1e3):void 0,startedAt:s,updatedAt:s,counters:{toolCalls:0,edits:0,approvals:0},queue:{pendingCount:0,items:[]}};return this.put(r),r}get(e){return ln(nn(this.sessionPath(e)))}put(e){return sn(this.dir),function(e,n){sn(s.dirname(e));const r=`${e}.${process.pid}.${Date.now()}.tmp`;t.writeFileSync(r,`${JSON.stringify(n,null,2)}\n`,"utf8"),t.renameSync(r,e)}(this.sessionPath(e.id),e),this.emitChange("write"),e}update(e,t,s={}){const n=this.get(e);if(!n)return;const r={toolCalls:n.counters.toolCalls+Math.max(0,Number(t.counters?.toolCalls)||0),edits:n.counters.edits+Math.max(0,Number(t.counters?.edits)||0),approvals:n.counters.approvals+Math.max(0,Number(t.counters?.approvals)||0)},i=s.preserveUpdatedAt?n.updatedAt:s.updatedAt||tn(),o=s.suppressPromptTurn?{...t,userPrompt:void 0}:t,a=s.suppressTurnUpdate?Ws(s.replaceTurns?void 0:n.turns):en(s.replaceTurns?void 0:n.turns,o,i,s.meta),d=t.userPrompt?Ls(t.userPrompt):"",c=a.at(-1),p=Boolean(d&&!t.lastMessage&&c?.userPrompt===d&&!c.summary&&!c.lastMessage),u={...n,...t,id:n.id,agent:n.agent,startedAt:n.startedAt,updatedAt:i,status:t.status?mn(t.status):n.status,phase:t.phase?hn(t.phase):n.phase,summary:s.replaceActivity?t.summary?Hs(t.summary,1e3):void 0:s.clearResponse?void 0:t.summary?Hs(t.summary,1e3):p?void 0:n.summary,lastMessage:s.replaceActivity?t.lastMessage?Ls(t.lastMessage):void 0:s.clearResponse?void 0:t.lastMessage?Ls(t.lastMessage):p?void 0:n.lastMessage,userPrompt:s.replaceActivity?t.userPrompt?Ls(t.userPrompt):void 0:t.userPrompt?Ls(t.userPrompt):n.userPrompt,turns:a,error:t.error?Hs(t.error,4e3):n.error,counters:r,queue:t.queue?dn(t.queue):n.queue};return this.put(u)}enqueueMessage(e,t,s=[]){const n=this.get(e);if(!n)return;const r=tn(),i={id:`aiq_${h.randomUUID().replace(/-/g,"").slice(0,20)}`,message:Ls(t),attachments:un(s),status:"queued",createdAt:r,updatedAt:r},o=[...n.queue?.items||[],i],a=this.update(e,{queue:an(o)},{updatedAt:r,suppressTurnUpdate:!0});return a&&s.length&&this.queuedAttachmentPayloads.set(i.id,s.slice(0,6)),a?{session:a,item:i}:void 0}queuedMessages(e){return this.get(e)?.queue||{pendingCount:0,items:[]}}nextQueuedMessage(e){return this.queuedMessages(e).items.find(e=>"queued"===e.status)}queuedMessageAttachments(e){return this.queuedAttachmentPayloads.get(e)||[]}markQueuedMessageSending(e,t){return this.patchQueuedMessage(e,t,{status:"sending",error:void 0})}markQueuedMessageFailed(e,t,s){const n=s instanceof Error?s.message:String(s);return this.patchQueuedMessage(e,t,{status:"failed",error:Hs(n,4e3)})}retryQueuedMessage(e,t){return this.patchQueuedMessage(e,t,{status:"queued",error:void 0})}removeQueuedMessage(e,t){const s=this.get(e);if(!s)return;const n=(s.queue?.items||[]).filter(e=>e.id!==t);return this.queuedAttachmentPayloads.delete(t),this.update(e,{queue:an(n)},{suppressTurnUpdate:!0})}reorderQueuedMessages(e,t){const s=this.get(e);if(!s)return;const n=s.queue?.items||[],r=new Map(n.map(e=>[e.id,e])),i=t.map(e=>r.get(e)).filter(e=>Boolean(e)),o=n.filter(e=>!t.includes(e.id));return this.update(e,{queue:an([...i,...o])},{suppressTurnUpdate:!0})}patchQueuedMessage(e,t,s){const n=this.get(e);if(!n)return;const r=tn();let i=!1;const o=(n.queue?.items||[]).map(e=>e.id!==t?e:(i=!0,{...e,...s,updatedAt:r}));return i?this.update(e,{queue:an(o)},{updatedAt:r,suppressTurnUpdate:!0}):void 0}bindProviderSession(e,t){const s=this.get(e),n=s?An(s.agent,t,s.cwd):void 0;return this.update(e,{providerSessionId:t,transcriptPath:n,status:"running",phase:"thinking",summary:`${s?.agent||"AI"} session ${t} started`})}apply(e){const t=e.observedAt||tn(),s={...e,observedAt:t,sourcePriority:Us(e.source,e.sourcePriority)};return"snapshot"===e.type?this.reduceSnapshotInput(s):this.reduceRealtimeInput(s)}applyRealtimeEvent(e,t){return this.apply({type:"event",sessionId:e,source:t.source||"realtime",...t})}reduceRealtimeInput(e){const t=e.sessionId,s=this.get(t);if(!s)return;const n=qs(e);if("send-ack"===e.kind){const s=e.observedAt||tn(),r=Ls(e.userPrompt);return this.update(t,{activeTurnId:e.activeTurnId||Vs(r,s),status:e.status||"running",phase:e.phase||"thinking",userPrompt:r},{updatedAt:s,meta:n})}if("lifecycle"===e.kind){const r=e.status||s.status;return"idle"!==r&&"failed"!==r||!Qs(s)?this.update(t,{activeTurnId:("running"===r||"waiting"===r)&&e.activeTurnId||s.activeTurnId,status:r,phase:e.phase||s.phase},{updatedAt:e.observedAt,meta:n}):s}if("turn-started"===e.kind)return this.update(t,{activeTurnId:e.activeTurnId||s.activeTurnId,status:e.status||"running",phase:e.phase||"thinking"},{updatedAt:e.observedAt,meta:n});if("user-message"===e.kind){const r=In(s,e,e.userPrompt);return this.update(t,{activeTurnId:r,status:e.status||"running",phase:e.phase||"thinking",userPrompt:e.userPrompt},{updatedAt:e.observedAt,meta:n})}if("assistant-message"===e.kind){const r=In(s,e),i="transcript-tail"===e.source;return this.update(t,{activeTurnId:r,status:e.status||(i?"idle":"running"),phase:e.phase||(i?"unknown":"responding"),summary:e.text,lastMessage:e.text},{updatedAt:e.observedAt,meta:n})}if("approval-requested"===e.kind)return this.update(t,{activeTurnId:e.activeTurnId||s.activeTurnId,status:e.status||"waiting",phase:e.phase||"approval",summary:e.summary||e.text,counters:e.counters||{approvals:1}},{updatedAt:e.observedAt,meta:n});if("turn-completed"===e.kind){const r=e.error?Hs(e.error,4e3):void 0,i=e.text||e.summary||("failed"===e.status?r:void 0),o=Boolean(i);return this.update(t,{activeTurnId:e.activeTurnId&&e.activeTurnId!==s.activeTurnId?s.activeTurnId:void 0,status:e.status||"idle",phase:e.phase||"unknown",summary:i,lastMessage:i,error:r},{updatedAt:e.observedAt,meta:n,clearResponse:!o})}}applyAdapterSnapshot(e){return this.apply({type:"snapshot",source:e.source||"control",...e})}reduceSnapshotInput(e){const t=qs(e),s=this.readSessions().find(t=>e.appSessionId&&t.appSessionId===e.appSessionId||e.providerSessionId&&t.providerSessionId===e.providerSessionId||e.transcriptPath&&t.transcriptPath===e.transcriptPath);if(!s){const s=this.start({agent:e.agent,appSessionId:e.appSessionId,appId:e.appId,providerSessionId:e.providerSessionId,conversationId:e.conversationId,title:e.title,cwd:e.cwd,userPrompt:e.userPrompt,turns:e.turns,status:e.status||"idle",phase:e.phase||"unknown",summary:e.summary},{meta:t,timestamp:e.observedAt,suppressPromptTurn:!e.turns?.length});return this.update(s.id,{providerMeta:e.providerMeta,appBindingKeys:e.appBindingKeys,actions:e.actions,lastMessage:e.lastMessage,transcriptPath:e.transcriptPath,transcriptSize:e.transcriptSize,status:e.status||s.status,phase:e.phase||"unknown"},{updatedAt:e.observedAt,meta:t,suppressTurnUpdate:!e.turns?.length})}return this.orphanedAppSessionAt.delete(s.id),this.reduceSnapshot(s.id,e)}reduceSnapshot(e,t){const s=this.get(e);if(!s)return;const n=qs(t),r=Ws(t.turns,n),i=function(e,t){if(!Qs(e))return!1;const s=Ws(e.turns).find(t=>t.id===e.activeTurnId);return!Ws(t).some(t=>t.id===e.activeTurnId||Boolean(s?.userPrompt&&t.userPrompt===s.userPrompt&&Ys(t)&&!Ys(s)))}(s,r),o=Boolean(s.activeTurnId&&r.some(e=>e.id===s.activeTurnId)),a=s.activeTurnId?r.find(e=>e.id===s.activeTurnId):void 0,d=Boolean(t.replaceActivity&&s.activeTurnId&&o&&!Ys(a)),c=function(e){return"app-session"===e.source||"adapter-snapshot"===e.source&&"codex"===e.agent&&"codex-app-server"===e.appId}(t);return this.update(e,{appSessionId:c?t.appSessionId:t.appSessionId||s.appSessionId,appId:t.appId||s.appId,providerSessionId:t.providerSessionId||s.providerSessionId,providerMeta:t.providerMeta||s.providerMeta,appBindingKeys:c?t.appBindingKeys:t.appBindingKeys||s.appBindingKeys,actions:t.actions||s.actions,activeTurnId:Zs(s,t,i),conversationId:t.conversationId||s.conversationId,title:t.title||s.title,cwd:t.cwd||s.cwd,userPrompt:i?s.userPrompt:t.userPrompt||s.userPrompt,turns:i?s.turns:t.turns,lastMessage:i?s.lastMessage:d?void 0:t.lastMessage||s.lastMessage,transcriptPath:t.transcriptPath||s.transcriptPath,transcriptSize:t.transcriptSize??s.transcriptSize,status:i?s.status:t.status||s.status,phase:i?s.phase:t.phase||s.phase,summary:i?s.summary:d?void 0:t.replaceActivity?t.summary:t.summary||s.summary},{updatedAt:t.observedAt,meta:n,replaceActivity:Boolean(t.replaceActivity),suppressPromptTurn:!r.length,suppressTurnUpdate:!r.length,replaceTurns:Boolean(t.replaceActivity&&!i&&0===r.length&&!t.userPrompt&&!t.summary&&!t.lastMessage)})}attachTranscript(e,t){if(!t){const s=this.get(e);t=s?An(s.agent,s.providerSessionId,s.cwd):void 0}const s=this.get(e);return t&&s?this.applyAdapterSnapshot({source:"transcript-scan",agent:s.agent,appId:s.appId,appSessionId:s.appSessionId,providerSessionId:s.providerSessionId,cwd:s.cwd,transcriptPath:t,status:s.status,phase:s.phase}):s}progress(e,t,s){if("user"===s)return this.applyRealtimeEvent(e,{kind:"user-message",userPrompt:t});if("assistant"===s)return this.applyRealtimeEvent(e,{kind:"assistant-message",text:t});const n=Sn(t,s);return this.applyRealtimeEvent(e,{kind:"waiting"===n.status?"approval-requested":"assistant-message",text:n.summary||t,status:n.status,phase:n.phase,counters:n.counters,source:"realtime"})}complete(e,t){return this.applyRealtimeEvent(e,{kind:"turn-completed",status:"idle",phase:"responding",text:t?Ls(t):"Completed",source:"control"})}fail(e,t){const s=t instanceof Error?t.message:String(t);return this.applyRealtimeEvent(e,{kind:"turn-completed",status:"failed",phase:"unknown",text:`Failed: ${s}`,source:"control"})}markWaitingByConversation(e,t){const s=this.list().filter(t=>t.conversationId===e&&!["idle","failed"].includes(t.status)).sort((e,t)=>Date.parse(t.updatedAt)-Date.parse(e.updatedAt))[0];return s?this.applyRealtimeEvent(s.id,{kind:"approval-requested",status:"waiting",phase:"approval",summary:t,counters:{approvals:1},source:"realtime"}):void 0}list(){return this.canonicalSessions(this.readSessions().filter(e=>!this.orphanedAppSessionAt.has(e.id)))}readSessions(){sn(this.dir);let e=[];try{e=t.readdirSync(this.dir).filter(e=>e.endsWith(".json"))}catch{return[]}const n=Date.now();return e.map(e=>ln(nn(s.join(this.dir,e)))).filter(e=>Boolean(e)).map(e=>this.withDerivedLifecycle(e,n)).sort((e,t)=>Date.parse(t.updatedAt)-Date.parse(e.updatedAt))}canonicalSessions(e){const t=new Map;for(const s of e){const e=gn(s),n=t.get(e);t.set(e,n?fn(n,s):s)}return[...t.values()].sort((e,t)=>Date.parse(t.updatedAt)-Date.parse(e.updatedAt))}reconcileAppSessionBindings(e=[],s=Date.now()){const n=new Set(e.filter(e=>"string"!=typeof e.status||"running"===e.status).map(e=>"string"==typeof e.id?e.id.trim():"").filter(Boolean));let r=0,i=0;for(const e of this.readSessions()){if(!e.appSessionId){this.orphanedAppSessionAt.delete(e.id);continue}if(n.has(e.appSessionId)){this.orphanedAppSessionAt.delete(e.id);continue}const o=this.orphanedAppSessionAt.get(e.id)??s;this.orphanedAppSessionAt.set(e.id,o),r+=1,s-o>=this.orphanedAppSessionRetentionMs&&(t.rmSync(this.sessionPath(e.id),{force:!0}),this.orphanedAppSessionAt.delete(e.id),i+=1,this.emitChange("delete"))}return{hidden:r,deleted:i}}reconcileAdapterSessions(e){const s=e.appSessionIds||new Set,n=e.providerSessionIds||new Set,r=e.providerShorts||new Set;let i=0;for(const o of this.readSessions()){if(o.agent!==e.agent)continue;if(!o.appSessionId&&!o.providerSessionId&&!o.providerMeta?.short)continue;if(o.appSessionId&&s.has(o.appSessionId)){this.orphanedAppSessionAt.delete(o.id);continue}if(o.providerSessionId&&n.has(o.providerSessionId)){this.orphanedAppSessionAt.delete(o.id);continue}const a="string"==typeof o.providerMeta?.short?o.providerMeta.short:"";a&&r.has(a)?this.orphanedAppSessionAt.delete(o.id):(t.rmSync(this.sessionPath(o.id),{force:!0}),this.orphanedAppSessionAt.delete(o.id),i+=1,this.emitChange("delete"))}return{deleted:i}}snapshot(e=20){const t=this.list().slice(0,e);return this.snapshotFromSessions(t)}boundSnapshot(e=[],t=20){const s=new Set(e.filter(e=>"string"!=typeof e.status||"running"===e.status).map(e=>"string"==typeof e.id?e.id.trim():"").filter(Boolean)),n=this.list().filter(e=>Boolean(e.appSessionId&&s.has(e.appSessionId))).slice(0,t);return this.snapshotFromSessions(n)}snapshotFromSessions(e){return{runningCount:e.filter(e=>"running"===e.status).length,waitingCount:e.filter(e=>"waiting"===e.status).length,staleCount:0,sessions:e.map(yn),updatedAt:tn()}}prune(){const e=new Set(this.canonicalSessions(this.readSessions()).map(e=>e.id));for(const s of this.readSessions())e.has(s.id)||(t.rmSync(this.sessionPath(s.id),{force:!0}),this.emitChange("delete"));const s=Date.now()-this.retentionMs;for(const e of this.readSessions())["idle","failed"].includes(e.status)&&Date.parse(e.updatedAt)<s&&t.rm(this.sessionPath(e.id),{force:!0},()=>this.emitChange("delete"))}ingestTranscriptLine(e,t,s){const n=rs(t,s);if(!n?.text)return this.get(e);const r=n.timestamp||tn();if("user"===n.kind){const t=Ls(n.text),i=n.key||n.timestamp;if(i)s.activeTurnId=Ks(t,i);else{s.promptCounts||=new Map;const e=(s.promptCounts.get(t)||0)+1;s.promptCounts.set(t,e),s.activeTurnId=Ks(t,void 0,e)}return this.applyRealtimeEvent(e,{kind:"user-message",activeTurnId:s.activeTurnId,providerTurnId:s.activeTurnId,userPrompt:t,observedAt:r,source:"transcript-tail"})}if("assistant"===n.kind)return this.applyRealtimeEvent(e,{kind:"assistant-message",activeTurnId:s.activeTurnId,providerTurnId:s.activeTurnId,text:n.text,observedAt:r,source:"transcript-tail"});const i=Sn(n.text,n.kind);return this.applyRealtimeEvent(e,{kind:"waiting"===i.status?"approval-requested":"assistant-message",activeTurnId:s.activeTurnId,providerTurnId:s.activeTurnId,text:i.summary||n.text,status:i.status,phase:i.phase,counters:i.counters,observedAt:r,source:"transcript-tail"})}createFromTranscript(e,s,n={}){const r=t.statSync(s),i=r.mtime.toISOString(),o=function(e,s=t.statSync(e)){const n={calls:new Map},r={};let i;const o=new Map;for(const a of function(e,s=t.statSync(e)){const n=Math.max(0,s.size-524288),r=t.openSync(e,"r");try{const e=Buffer.alloc(s.size-n);return t.readSync(r,e,0,e.length,n),e.toString("utf8")}finally{t.closeSync(r)}}(e,s).split(/\r?\n/)){const e=rs(a,n);if(!e?.text)continue;const t=e.timestamp||s.mtime.toISOString();if("user"===e.kind){const s=Ls(e.text);r.userPrompt=s;const n=e.key||e.timestamp;if(n)i=Ks(s,n);else{const e=(o.get(s)||0)+1;o.set(s,e),i=Ks(s,void 0,e)}r.turns=en(r.turns,{activeTurnId:i,userPrompt:s},t);continue}r.summary=Hs(e.text,1e3),r.lastMessage=Ls(e.text),r.turns=en(r.turns,{activeTurnId:i,summary:r.summary,lastMessage:r.lastMessage},t)}return r}(s,r),a=this.readSessions().find(e=>e.transcriptPath===s||n.providerSessionId&&e.providerSessionId===n.providerSessionId);if(a){const t=!a.appSessionId&&!a.conversationId,p=Number.isInteger(a.transcriptSize)&&r.size>Number(a.transcriptSize),u=t&&p?tn():t&&!p?a.updatedAt:(d=a.updatedAt,c=i,Date.parse(d)>=Date.parse(c)?d:c);return this.applyAdapterSnapshot({source:"transcript-scan",agent:e,transcriptPath:s,transcriptSize:r.size,providerSessionId:n.providerSessionId||a.providerSessionId,cwd:n.cwd||a.cwd,userPrompt:a.userPrompt||o.userPrompt,turns:o.turns?.length?o.turns:a.turns,summary:o.summary||a.summary,lastMessage:o.lastMessage||a.lastMessage,status:t&&p?"running":a.status,phase:t&&p&&"unknown"===a.phase?"responding":a.phase,observedAt:u,replaceActivity:Boolean(o.turns?.length)})||a}var d,c;const p=this.start({agent:e,providerSessionId:n.providerSessionId,cwd:n.cwd,userPrompt:o.userPrompt,turns:o.turns,status:this.lifecycleForTranscriptMtime(r.mtimeMs),phase:"unknown",summary:o.summary||`${e} transcript detected`},{meta:qs({source:"transcript-scan",observedAt:i}),timestamp:i,suppressPromptTurn:!o.turns?.length});return this.applyAdapterSnapshot({source:"transcript-scan",agent:p.agent,providerSessionId:p.providerSessionId,cwd:p.cwd,userPrompt:p.userPrompt,turns:p.turns,summary:p.summary,lastMessage:o.lastMessage,transcriptPath:s,transcriptSize:r.size,status:p.status,phase:p.phase,observedAt:i})||p}emitChange(e){this.changes.emit("change",e)}reconcileActiveProcesses(e){const t=new Set;for(const s of e){const e=this.list().find(e=>e.agent===s.agent&&(s.providerSessionId&&e.providerSessionId===s.providerSessionId||s.transcriptPath&&e.transcriptPath===s.transcriptPath));e&&(t.add(e.id),this.applyAdapterSnapshot({source:"process-scan",agent:e.agent,appId:e.appId,appSessionId:e.appSessionId,providerSessionId:s.providerSessionId||e.providerSessionId,cwd:s.cwd||e.cwd,title:e.title,userPrompt:e.userPrompt,turns:e.turns,summary:e.summary,lastMessage:e.lastMessage,status:"running",phase:"unknown"===e.phase?"thinking":e.phase,transcriptPath:s.transcriptPath||e.transcriptPath}))}return t}withDerivedLifecycle(e,t=Date.now()){if(["idle","failed","waiting"].includes(e.status))return e;const s=t-Date.parse(e.updatedAt);return s>this.staleAfterMs&&e.transcriptPath&&!e.conversationId||s>this.idleAfterMs&&"running"===e.status?{...e,status:"idle"}:e}lifecycleForTranscriptMtime(e){const t=Date.now()-e;return t>this.staleAfterMs||t>this.idleAfterMs?"idle":"running"}}function _n(e={}){return new bn(e)}function wn(e){const t=String(e||"").trim().toLowerCase();return t&&"idle"!==t?"stopped"===t||"exited"===t||"failed"===t?"failed"===t?"failed":"idle":["active","busy","running","thinking","working"].includes(t)?"running":"idle":"idle"}class Tn{providers=new Map;register(e){this.providers.set(e.id,e)}async refresh(e){for(const t of this.providers.values())await t.refresh(e)}}class Nn{id="claude-app-session-binding";refresh(e){!function(e=_n(),r=[],i=process.env.CLAUDE_HOME||s.join(n.homedir(),".claude")){const o=function(e){const r=function(e=process.env.CLAUDE_HOME||s.join(n.homedir(),".claude")){return s.join(e,"sessions")}(e);let i=[];try{i=t.readdirSync(r,{withFileTypes:!0})}catch{return new Map}const o=new Map;for(const e of i){if(!e.isFile()||!e.name.endsWith(".json"))continue;const t=nn(s.join(r,e.name)),n=Number(t?.pid||s.basename(e.name,".json"));t?.sessionId&&Number.isInteger(n)&&n>0&&o.set(n,t)}return o}(i);for(const t of r){const s=Hs(t.appId,120),n=Hs(t.id,120),r=Hs(t.status,80).toLowerCase(),a=Number(t.process?.pid);if("claude"!==s||!n||r&&"running"!==r||!Number.isInteger(a)||a<=0)continue;const d=o.get(a),c=Hs(d?.sessionId,240);if(!c)continue;const p=Hs(d?.cwd||t.tty?.cwd||t.launch?.cwd,4096);e.applyAdapterSnapshot({agent:"claude",appId:s,appSessionId:n,providerSessionId:c,title:Hs(t.title,240)||"Claude",cwd:p,transcriptPath:ns(c,p,i),status:wn(d?.status)})}e.snapshot()}(e.registry,e.appSessions)}}class On{id="transcript-tail-discovery";tailState=new Map;refresh(e){!function(e,s){for(const n of e.list()){if(!n.transcriptPath||"failed"===n.status)continue;let r;try{r=t.statSync(n.transcriptPath)}catch{continue}const i=s.get(n.id)||{offset:Math.max(0,r.size-65536),partial:"",calls:new Map,promptCounts:new Map};if(r.size<i.offset&&(i.offset=0,i.partial="",i.calls.clear(),i.promptCounts?.clear(),i.activeTurnId=void 0),r.size===i.offset){s.set(n.id,i);continue}const o=t.readFileSync(n.transcriptPath).subarray(i.offset).toString("utf8");i.offset=r.size,i.partial+=o;const a=i.partial.split(/\r?\n/);i.partial=a.pop()||"";for(const t of a)e.ingestTranscriptLine(n.id,t,i);s.set(n.id,i)}}(e.registry,this.tailState)}}const En=process.env.TASK_HANDOFF_RECEIVER_LOG||(process.env.TASK_HANDOFF_LOG_DIR?`${process.env.TASK_HANDOFF_LOG_DIR}/receiver.log`:void 0)||(zn=S,xn="receiver.log",process.env.CODEX_SANDBOX?s.join(process.cwd(),".task-handoff",xn):s.join(s.dirname(zn),xn));var zn,xn;class Dn{registry;client;id="claude-control-sock";agent="claude";subscriptions=new Map;textByShort=new Map;constructor(e,t={list:()=>ot({op:"list"},{timeoutMs:Number(process.env.TASK_HANDOFF_CLAUDE_CONTROL_TIMEOUT_MS)||5e3}),reply:at,kill:dt,subscribe:ct}){this.registry=e,this.client=t}async refresh(e){if(!Hn("TASK_HANDOFF_AI_SESSION_SCAN",!0)||!Hn("TASK_HANDOFF_CLAUDE_CONTROL_SCAN",!0))return;const t=await this.client.list(),s=t.ok&&Array.isArray(t.jobs)?t.jobs:[],n=e.appSessions.filter(Un),r=new Map;for(const e of n){const t=Fn(e.ai?.claude?.short,80);t&&r.set(t,e)}for(const e of n){const t=Fn(e.ai?.claude?.short,80);if(!t)continue;const n=s.find(e=>e.short===t);this.upsertJob(n||Ln(e)||{short:t},e)}for(const e of s)e.short&&!r.has(e.short)&&this.upsertJob(e);this.reconcileSubscriptions(new Set([...s.map(e=>Fn(e.short,80)).filter(Boolean),...Array.from(r.keys())])),e.registry.reconcileAdapterSessions({agent:this.agent,appSessionIds:new Set(n.map(e=>Fn(e.id,120)).filter(Boolean)),providerSessionIds:new Set(s.map(e=>Fn(e.sessionId,240)).filter(Boolean)),providerShorts:new Set([...s.map(e=>Fn(e.short,80)).filter(Boolean),...Array.from(r.keys())])})}async sendMessage(e,t){return this.startMessage(e,t)}async startMessage(e,t){const s=this.requireShort(e),n=await Mt(t.message,t.attachments,t=>this.client.reply(s,t.endsWith("\n")?t:`${t}\n`,{sockPath:this.controlSockForSession(e),timeoutMs:Number(process.env.TASK_HANDOFF_CLAUDE_CONTROL_TIMEOUT_MS)||5e3}));if(!n.ok)throw $t("AI_SESSION_SEND_FAILED",n.error||`Claude reply failed: ${n.code||"unknown"}`);const r=this.registry.applyRealtimeEvent(e.id,{kind:"send-ack",userPrompt:t.message,source:"control"})||e;return{session:r,provider:this.agent,action:"send",turnId:r.activeTurnId}}async steerMessage(e,t){return{...await this.startMessage(e,t),action:"steer"}}async interrupt(e){const t=this.requireShort(e),s=await this.client.kill(t,"SIGTERM",{sockPath:this.controlSockForSession(e),timeoutMs:Number(process.env.TASK_HANDOFF_CLAUDE_CONTROL_TIMEOUT_MS)||5e3});if(!s.ok)throw $t("AI_SESSION_INTERRUPT_FAILED",s.error||`Claude interrupt failed: ${s.code||"unknown"}`);return{session:this.registry.applyRealtimeEvent(e.id,{kind:"lifecycle",status:"running",phase:"unknown",source:"control"})||e,provider:this.agent,action:"interrupt"}}async resolveApproval(e,t){throw $t("AI_SESSION_APPROVAL_UNSUPPORTED","Claude daemon sessions do not expose structured approval control.",400)}stop(){for(const e of this.subscriptions.values())e();this.subscriptions.clear(),this.textByShort.clear()}upsertJob(e,t){const s=Fn(e.short,80);if(!s)return;const n=Fn(e.sessionId||t?.ai?.claude?.providerSessionId,240),r=Fn(e.cwd||t?.ai?.claude?.cwd||t?.tty?.cwd||t?.launch?.cwd,4096),i=this.sessionForShort(s),o=kn(e.state||t?.ai?.claude?.state,{hasWorkSignal:Pn(e),isAppSession:Boolean(t||i?.appSessionId)}),a=Fn(t?.ai?.claude?.controlSock,4096)||it();this.registry.applyAdapterSnapshot({source:"adapter-snapshot",agent:"claude",appId:Fn(t?.appId,120)||(t?"claude":"claude-daemon"),appSessionId:Fn(t?.id,120),providerSessionId:n,appBindingKeys:$n(t,s),actions:Cn(o),providerMeta:{short:s,controlSock:a,pid:Number(e.pid||t?.ai?.claude?.pid)||void 0,state:Fn(e.state||t?.ai?.claude?.state,80),tempo:Fn(e.tempo||t?.ai?.claude?.tempo,80),cliVersion:Fn(e.cliVersion||t?.ai?.claude?.cliVersion,80),source:Fn(e.source||t?.ai?.claude?.source,80)},title:Fn(t?.title,240)||"Claude",cwd:r,transcriptPath:ns(n,r),status:o.status,phase:o.phase})&&this.ensureSubscription(s,a)}reconcileSubscriptions(e){for(const[t,s]of this.subscriptions)e.has(t)||(s(),this.subscriptions.delete(t),this.textByShort.delete(t))}ensureSubscription(e,t){if(this.subscriptions.has(e))return;this.subscriptions.set(e,()=>{});const s=this.client.subscribe(e,{tail:Number(process.env.TASK_HANDOFF_CLAUDE_SUBSCRIBE_TAIL_BYTES)||4096,options:{sockPath:t},onMessage:s=>this.applySubscribeMessage(e,t,s)});this.subscriptions.set(e,s)}applySubscribeMessage(e,t,s){const n=Rn(s.record);n&&this.upsertJob(n);const r=this.textFromSubscribeMessage(e,s);if(r){const t=this.sessionForShort(e);t&&this.registry.applyRealtimeEvent(t.id,{kind:"assistant-message",text:r,source:"realtime"})}const i=this.stateFromSubscribeMessage(s,n);if(i.observedState){const r=this.sessionForShort(e),o=i.lifecycleState?kn(i.lifecycleState,{hasWorkSignal:!1,isAppSession:Boolean(r?.appSessionId)}):void 0;this.logSubscribeMessage(e,t,s,n,i,r,o),r&&this.registry.applyAdapterSnapshot({source:"adapter-snapshot",agent:r.agent,appId:r.appId,appSessionId:r.appSessionId,providerSessionId:r.providerSessionId,appBindingKeys:r.appBindingKeys,actions:Cn(o),providerMeta:{...r.providerMeta||{},short:e,controlSock:t,state:i.observedState,stateSource:i.source},status:o?.status,phase:o?.phase,cwd:r.cwd,title:r.title})}else this.logSubscribeMessage(e,t,s,n,i,this.sessionForShort(e))}sessionForShort(e){return this.registry.list().find(t=>"claude"===t.agent&&t.providerMeta?.short===e)}stateFromSubscribeMessage(e,t){const s=Rn(e.patch),n="settled"===Fn(e.type,80)?e.outcome:void 0,r=[{source:"message.state",value:e.state},{source:"patch.state",value:s?.state},{source:"record.state",value:t?.state},{source:"settled.outcome",value:n}].find(e=>Fn(e.value,80));return{observedState:Fn(r?.value,80),lifecycleState:Fn(n,80),source:r?.source,patch:s}}logSubscribeMessage(e,t,s,n,r,i,o){if(Hn("TASK_HANDOFF_DIAGNOSTIC_LOGS"))try{oe(En,{event:"claude_control_subscribe",short:e,controlSock:t,messageType:Fn(s.type,80)||void 0,state:r.observedState||void 0,lifecycleState:r.lifecycleState||void 0,stateSource:r.source,recordState:Fn(n?.state,80)||void 0,patchKeys:r.patch?Object.keys(r.patch).sort():void 0,outcome:Fn(s.outcome,80)||void 0,streamLineBytes:"string"==typeof s.line?Buffer.byteLength(s.line):void 0,streamTailCount:Mn(s.streamTail).length||void 0,aiSessionId:i?.id,appSessionId:i?.appSessionId,providerSessionId:i?.providerSessionId,mappedStatus:o?.status,mappedPhase:o?.phase})}catch{}}textFromSubscribeMessage(e,t){const s=[...Mn(t.streamTail).map(e=>String(e||"")),...Mn(t.output).map(e=>String(e||"")),jn(t.data),jn(t.text),jn(t.delta),jn(t.raw)].filter(Boolean);if(0===s.length)return"";const n=(r=s.join("\n"),String(r).replace(/\x1B\][^\x07]*(?:\x07|\x1B\\)?/g,"").replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,"").replace(/\x1B[\x30-\x7E]/g,"").replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g,"")).replace(/\u0007/g,"").split(/\r?\n/).map(e=>e.trim()).filter(Boolean).filter(e=>!function(e){const t=e.replace(/[─━═_\-]{3,}/g,"").replace(/[⏺●•·]/g,"").replace(/\s+/g," ").trim();return!t||[/^claude code\b/i,/\bapi usage billing\b/i,/\/effort\b/i,/\bauto mode on\b/i,/\bshift\+tab to cycle\b/i,/\bfor agents\b/i,/^log an error\??"?$/i,/^~\/\S+/,/^\S+\s+·\s+\S+.*\b\/project\/work\b/i,/^\S+\s+·\s+\/?(?:workspace|project|Users|home)\b/i,/^(?:high|medium|low)\s*·\s*\/?effort\b/i,/^[›>]\s*try\s+["'`]/i,/^try\s+["'`]/i].some(e=>e.test(t))}(e)).slice(-8).join("\n").trim();var r;return n&&this.textByShort.get(e)!==n?(this.textByShort.set(e,n),n):""}requireShort(e){const t="string"==typeof e.providerMeta?.short?e.providerMeta.short:void 0;if(!t)throw $t("AI_SESSION_CLAUDE_SHORT_NOT_FOUND","Claude session is not bound to a daemon worker.");return t}controlSockForSession(e){return"string"==typeof e.providerMeta?.controlSock?e.providerMeta.controlSock:void 0}}function kn(e,t={}){const s=String(e||"").trim().toLowerCase();return s&&"idle"!==s?"blocked"===s?{status:"idle",phase:"unknown"}:"waiting"===s?{status:"waiting",phase:"unknown"}:"failed"===s?{status:"failed",phase:"unknown"}:["stopped","exited","completed","done"].includes(s)?{status:"idle",phase:"unknown"}:["active","busy","running","thinking","working"].includes(s)?t.isAppSession&&!t.hasWorkSignal?{status:"idle",phase:"unknown"}:{status:"running",phase:"thinking"}:{status:"idle",phase:"unknown"}:{status:"idle",phase:"unknown"}}function Cn(e){return{send:!0,interrupt:"running"===e?.status||"waiting"===e?.status,approval:!1}}function Pn(e){return Boolean(Fn(e.detail,500)||Fn(e.intent,500)||Fn(e.needs,500))}function Fn(e,t=500){const s=String(e??"").replace(/\s+/g," ").trim();return s.length>t?`${s.slice(0,t-3)}...`:s}function Rn(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:void 0}function Mn(e){return Array.isArray(e)?e:[]}function jn(e){return"string"==typeof e?e:""}function Hn(e,t=!1){const s=process.env[e];return void 0===s||""===s?t:!["0","false","no","off"].includes(String(s).toLowerCase())}function Ln(e){const t=e.ai?.claude,s=Fn(t?.short,80);if(s)return{short:s,sessionId:Fn(t?.providerSessionId,240)||void 0,pid:Number(t?.pid)||void 0,cwd:Fn(t?.cwd||e.tty?.cwd||e.launch?.cwd,4096)||void 0,state:Fn(t?.state,80)||void 0,tempo:Fn(t?.tempo,80)||void 0,cliVersion:Fn(t?.cliVersion,80)||void 0,source:Fn(t?.source,80)||void 0}}function $n(e,t){const s=[e?.id?`app:${Fn(e.id,120)}`:"",t?`claude-short:${t}`:""].filter(Boolean);return s.length?s:void 0}function Un(e){const t=Fn(e.status,80).toLowerCase();return!t||"running"===t}function qn(e){return"allow"===e?"allowed":"deny"===e?"denied":"skipped"}function Bn(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}function Vn(e){const t=e.turn&&"object"==typeof e.turn?e.turn:void 0;return"string"==typeof t?.id?t.id:void 0}function Kn(e){return e instanceof Error&&/no active turn/i.test(e.message)}function Gn(e){if(e instanceof Error)return e.message.match(/expected active turn id `[^`]+` but found `([^`]+)`/i)?.[1]}function Wn(e){const t=String(e.type||""),s=Array.isArray(e.activeFlags)?e.activeFlags.map(String):[];return"active"===t&&s.includes("waitingOnApproval")?{status:"waiting",phase:"approval"}:"active"===t&&s.includes("waitingOnUserInput")?{status:"waiting",phase:"thinking"}:"active"===t?{status:"running",phase:"thinking"}:"systemError"===t?{status:"failed",phase:"unknown"}:{status:"idle",phase:"unknown"}}function Xn(e,t){const s=e[t];return"string"==typeof s&&s.trim()?s:void 0}function Jn(e){const t=Bn(e);return"text"===t.type&&"string"==typeof t.text?t.text.trim():""}function Yn(e){return(Array.isArray(e.content)?e.content:[]).map(Jn).filter(Boolean).join("\n").trim()}class Qn extends g.EventEmitter{child;proxyChild;socket;buffer="";nextId=1;pending=new Map;mode;requestTimeoutMs;constructor(e={}){super(),this.mode=e.socketPath?{type:"unix",command:e.command||process.env.TASK_HANDOFF_CODEX_APP_SERVER_COMMAND||process.env.TASK_HANDOFF_CODEX_COMMAND||"codex",socketPath:e.socketPath}:{type:"stdio",command:e.command||process.env.TASK_HANDOFF_CODEX_APP_SERVER_COMMAND||process.env.TASK_HANDOFF_CODEX_COMMAND||"codex"},this.requestTimeoutMs=e.requestTimeoutMs||Number(process.env.TASK_HANDOFF_CODEX_APP_SERVER_TIMEOUT_MS)||5e3}get connected(){return Boolean(this.child&&!this.child.killed||this.proxyChild&&!this.proxyChild.killed||this.socket?.readyState===y.OPEN)}async start(){if(this.connected)return;if("unix"===this.mode.type)return void await this.startUnixSocket(this.mode.command,this.mode.socketPath);const e=m.spawn(this.mode.command,["app-server","--listen","stdio://"],{stdio:["pipe","pipe","ignore"],env:process.env});this.child=e,e.stdout.on("data",e=>this.onData(e)),e.once("exit",()=>{this.child=void 0;for(const[e,t]of this.pending)clearTimeout(t.timer),t.reject(new Error("Codex app-server exited.")),this.pending.delete(e);this.emit("disconnect")}),await this.initialize()}stop(){this.child&&!this.child.killed&&(this.child.removeAllListeners(),this.child.kill("SIGTERM")),this.socket&&this.socket.readyState===y.OPEN&&(this.socket.removeAllListeners(),this.socket.close()),this.proxyChild&&!this.proxyChild.killed&&(this.proxyChild.removeAllListeners(),this.proxyChild.kill("SIGTERM"));for(const[e,t]of this.pending)clearTimeout(t.timer),t.reject(new Error("Codex app-server stopped.")),this.pending.delete(e);this.child=void 0,this.proxyChild=void 0,this.socket=void 0}async listLoadedThreadIds(){const e=[];let t;for(let s=0;s<20;s+=1){const s=await this.request("thread/loaded/list",{cursor:t,limit:100});if(Array.isArray(s.data)&&e.push(...s.data.filter(e=>"string"==typeof e)),t="string"==typeof s.nextCursor&&s.nextCursor?s.nextCursor:null,!t)break}return e}async readThread(e,t={}){const s=await this.request("thread/read",{threadId:e,includeTurns:Boolean(t.includeTurns)});return s.thread&&"object"==typeof s.thread?s.thread:void 0}async listThreads(){const e=[];let t;for(let s=0;s<10;s+=1){const s=await this.request("thread/list",{cursor:t,limit:100,sortKey:null,sortDirection:null,modelProviders:null,sourceKinds:[],archived:!1,cwd:null,useStateDbOnly:!1,searchTerm:null});if(Array.isArray(s.data)?e.push(...s.data.filter(e=>Boolean(e&&"object"==typeof e&&!Array.isArray(e)))):Array.isArray(s.threads)&&e.push(...s.threads.filter(e=>Boolean(e&&"object"==typeof e&&!Array.isArray(e)))),t="string"==typeof s.nextCursor?s.nextCursor:null,!t)break}return e}async startTurn(e,t){return{turnId:Vn(await this.request("turn/start",{threadId:e,input:[{type:"text",text:t,text_elements:[]}]}))}}async steerTurn(e,t,s){const n=await this.request("turn/steer",{threadId:e,expectedTurnId:t,input:[{type:"text",text:s,text_elements:[]}]});return{turnId:"string"==typeof n.turnId?n.turnId:t}}async interruptTurn(e,t){await this.request("turn/interrupt",{threadId:e,turnId:t})}async resumeThread(e){const t=await this.request("thread/resume",{threadId:e});return t.thread&&"object"==typeof t.thread?t.thread:void 0}async respondToApproval(e,t){this.sendResponse(e.id,function(e,t){if("command"===e.kind)return{decision:"allow"===t?"accept":"skip"===t?"cancel":"decline"};if("file-change"===e.kind)return{decision:"allow"===t?"accept":"skip"===t?"cancel":"decline"};if("allow"!==t)return{permissions:{},scope:"turn"};const s=Bn(e.params.permissions),n=Bn(s.fileSystem);return{permissions:{...s.network?{network:s.network}:{},...Object.keys(n).length?{fileSystem:{...Array.isArray(n.read)?{read:n.read}:{},...Array.isArray(n.write)?{write:n.write}:{},...Array.isArray(n.entries)?{entries:n.entries}:{},...n.globScanMaxDepth?{globScanMaxDepth:n.globScanMaxDepth}:{}}}:{}},scope:"turn"}}(e,t))}request(e,t){const s=this.child?.stdin.writable,n=this.socket?.readyState===y.OPEN;if(!s&&!n)return Promise.reject(new Error("Codex app-server is not connected."));const r=this.nextId++,i=JSON.stringify({id:r,method:e,params:t});return new Promise((t,s)=>{const o=setTimeout(()=>{this.pending.delete(r),s(new Error(`Codex app-server request timed out: ${e}`))},this.requestTimeoutMs);this.pending.set(r,{resolve:t,reject:s,timer:o}),n?this.socket?.send(i):this.child?.stdin.write(`${i}\n`)})}async initialize(){await this.request("initialize",{clientInfo:{name:"task-handoff",version:"1.0.0"},capabilities:{experimentalApi:!0}}),this.notify("initialized",{})}notify(e,t){const s=JSON.stringify({method:e,params:t});this.socket?.readyState!==y.OPEN?this.child?.stdin.writable&&this.child.stdin.write(`${s}\n`):this.socket.send(s)}sendResponse(e,t){const s=JSON.stringify({id:e,result:t});this.socket?.readyState!==y.OPEN?this.child?.stdin.writable&&this.child.stdin.write(`${s}\n`):this.socket.send(s)}startUnixSocket(e,t){return new Promise((s,n)=>{const r=m.spawn(e,["app-server","proxy","--sock",t],{stdio:["pipe","pipe","ignore"],env:process.env});this.proxyChild=r;const i=new y("ws://localhost/rpc",{createConnection:()=>function(e){const t=new a.Duplex({read(){e.stdout.resume()},write(t,s,n){e.stdin.write(t,n)},final(t){e.stdin.end(t)},destroy(t,s){e.killed||e.kill("SIGTERM"),s(t)}});e.stdout.on("data",s=>{t.push(s)||e.stdout.pause()}),e.stdout.on("end",()=>t.push(null)),e.stdout.on("error",e=>t.destroy(e)),e.stdin.on("error",e=>t.destroy(e));const s=t;return s.setTimeout=()=>t,s.setNoDelay=()=>t,s.setKeepAlive=()=>t,s}(r),perMessageDeflate:!1});this.socket=i;let o=!1;const d=e=>{o||(o=!0,this.socket=void 0,this.proxyChild=void 0,r.killed||r.kill("SIGTERM"),n(e))};r.once("error",d),r.once("exit",(e,t)=>{o?this.proxyChild===r&&(this.proxyChild=void 0,this.emit("disconnect")):d(new Error(`Codex app-server proxy exited before connect: code=${e??"null"} signal=${t??"null"}.`))}),i.once("error",d),i.once("open",()=>{o=!0,r.off("error",d),i.off("error",d),i.on("message",e=>this.handleLine(e.toString())),i.once("close",()=>{this.socket=void 0,this.proxyChild===r&&(this.proxyChild=void 0),r.killed||r.kill("SIGTERM");for(const[e,t]of this.pending)clearTimeout(t.timer),t.reject(new Error("Codex app-server disconnected.")),this.pending.delete(e);this.emit("disconnect")}),this.initialize().then(()=>s()).catch(e=>{i.close(),n(e)})})})}onData(e){this.buffer+=e.toString("utf8");let t=this.buffer.indexOf("\n");for(;t>=0;){const e=this.buffer.slice(0,t).trim();this.buffer=this.buffer.slice(t+1),e&&this.handleLine(e),t=this.buffer.indexOf("\n")}this.buffer.length>8388608&&(this.buffer="")}handleLine(e){let t;try{t=JSON.parse(e)}catch{return}const s=Number(t.id);if(Number.isInteger(s)){const e=this.pending.get(s);if(e){clearTimeout(e.timer),this.pending.delete(s);const n=t.error&&"object"==typeof t.error?t.error:void 0;return void(n?e.reject(new Error(String(n.message||"Codex app-server error."))):e.resolve(t.result&&"object"==typeof t.result?t.result:{}))}}const n=String(t.method||""),r=t.params&&"object"==typeof t.params?t.params:{};if(Number.isInteger(s)){const e=function(e,t,s){if("item/commandExecution/requestApproval"===t){const n=Xn(s,"threadId");if(!n)return;const r=Xn(s,"command"),i=Xn(s,"reason");return{id:e,method:t,kind:"command",threadId:n,turnId:Xn(s,"turnId"),itemId:Xn(s,"itemId"),summary:i||(r?`Approve command: ${r}`:"Codex is requesting command approval."),params:s}}if("item/fileChange/requestApproval"===t){const n=Xn(s,"threadId");if(!n)return;const r=Xn(s,"grantRoot");return{id:e,method:t,kind:"file-change",threadId:n,turnId:Xn(s,"turnId"),itemId:Xn(s,"itemId"),summary:Xn(s,"reason")||(r?`Approve file changes under ${r}`:"Codex is requesting file change approval."),params:s}}if("item/permissions/requestApproval"===t){const n=Xn(s,"threadId");if(!n)return;return{id:e,method:t,kind:"permissions",threadId:n,turnId:Xn(s,"turnId"),itemId:Xn(s,"itemId"),summary:Xn(s,"reason")||"Codex is requesting additional permissions.",params:s}}}(s,n,r);return void(e&&this.emit("event",{type:"approval-request",request:e}))}const i=function(e,t){if("thread/started"===e){const e=t.thread&&"object"==typeof t.thread?t.thread:void 0;return e?{type:"thread",thread:e}:void 0}if("thread/status/changed"===e&&"string"==typeof t.threadId)return{type:"thread-status",threadId:t.threadId,status:t.status||{}};if("thread/closed"===e&&"string"==typeof t.threadId)return{type:"thread-closed",threadId:t.threadId};if("turn/started"===e&&"string"==typeof t.threadId){const e=t.turn&&"object"==typeof t.turn?t.turn:{};return{type:"turn-started",threadId:t.threadId,turnId:"string"==typeof e.id?e.id:void 0}}if("turn/completed"===e&&"string"==typeof t.threadId){const e=t.turn&&"object"==typeof t.turn?t.turn:{},s=function(e){const t=Bn(e),s="string"==typeof t.message?t.message.trim():"",n="string"==typeof t.additionalDetails?t.additionalDetails.trim():"";return s&&n?`${s}\n\n${n}`:s||n||void 0}(e.error);return{type:"turn-completed",threadId:t.threadId,turnId:"string"==typeof e.id?e.id:void 0,status:"string"==typeof e.status?e.status:void 0,error:s}}if(("item/started"===e||"item/completed"===e)&&"string"==typeof t.threadId){const e=t.item&&"object"==typeof t.item?t.item:{};if("userMessage"===e.type){const s=Yn(e);return s?{type:"user-message",threadId:t.threadId,turnId:"string"==typeof t.turnId?t.turnId:void 0,text:s}:void 0}}if("item/agentMessage/delta"===e&&"string"==typeof t.threadId&&"string"==typeof t.delta)return{type:"agent-message-delta",threadId:t.threadId,turnId:"string"==typeof t.turnId?t.turnId:void 0,itemId:"string"==typeof t.itemId?t.itemId:void 0,delta:t.delta};if("item/completed"===e&&"string"==typeof t.threadId){const e=t.item&&"object"==typeof t.item?t.item:{};if("agentMessage"===e.type&&"string"==typeof e.text)return{type:"agent-message-completed",threadId:t.threadId,turnId:"string"==typeof t.turnId?t.turnId:void 0,text:e.text}}}(n,r);i&&this.emit("event",i)}}class Zn{registry;id="codex-app-server";agent="codex";client;started=!1;retryAfter=0;activeSocketPath;appSessions=[];agentMessageBuffers=new Map;approvals=new jt;injectedClient;options;constructor(e,t={}){this.registry=e,"start"in t&&"listLoadedThreadIds"in t?(this.injectedClient=t,this.options={allowSpawn:!0},this.attachClient(this.injectedClient)):this.options=t}async sync(e=[]){const t=this.setAppSessions(e),s=this.activeSocketPath;if(!this.injectedClient&&!t&&!this.options.allowSpawn)return void this.stop();this.injectedClient||this.client&&s===t||(this.stop(),this.client=this.createClient(t?{socketPath:t}:{}),this.attachClient(this.client)),this.activeSocketPath=t;const n=this.client;if(n){if(!this.started){if(Date.now()<this.retryAfter)return;try{await n.start(),this.started=!0}catch{return void(this.retryAfter=Date.now()+3e4)}}try{const e=await n.listLoadedThreadIds(),t=new Map;if(n.listThreads)for(const e of await n.listThreads()){const s="string"==typeof e.id?e.id:void 0;s&&t.set(s,e)}for(const s of e){let e=t.get(s);if(n.readThread)try{e={...e||{},...await n.readThread(s,{includeTurns:!0})}}catch{e||={id:s}}this.upsertThread(e||{id:s},{bindAppSession:!0})}}catch{this.started=!1,n.stop()}}}async refresh(e){await this.sync(e.appSessions)}stop(){this.client?.stop(),this.injectedClient||(this.client=void 0),this.started=!1,this.activeSocketPath=void 0,this.agentMessageBuffers.clear(),this.retryAfter=0}async sendMessage(e,t){const s=await this.requireReadyClient(),n=this.requireThreadId(e),r=await Mt(t.message,t.attachments,t=>this.steerOrStartTurnForCompatibility(s,n,e,t)),i=this.registry.applyRealtimeEvent(e.id,{kind:r.started?"send-ack":"user-message",activeTurnId:r.turnId,providerTurnId:r.turnId,userPrompt:t.message,source:"control"})||e;return{session:i,provider:this.agent,action:r.started?"send":"steer",turnId:i.activeTurnId,providerTurnId:r.turnId}}async startMessage(e,t){const s=await this.requireReadyClient(),n=this.requireThreadId(e),r=await Mt(t.message,t.attachments,e=>this.startTurn(s,n,e)),i=this.registry.applyRealtimeEvent(e.id,{kind:"send-ack",activeTurnId:r.turnId,providerTurnId:r.turnId,userPrompt:t.message,source:"control"})||e;return{session:i,provider:this.agent,action:"send",turnId:i.activeTurnId,providerTurnId:r.turnId}}async steerMessage(e,t){const s=await this.requireReadyClient(),n=this.requireThreadId(e),r=await Mt(t.message,t.attachments,t=>this.steerTurn(s,n,e,t)),i=this.registry.applyRealtimeEvent(e.id,{kind:"user-message",activeTurnId:r.turnId,providerTurnId:r.turnId,userPrompt:t.message,source:"control"})||e;return{session:i,provider:this.agent,action:"steer",turnId:i.activeTurnId,providerTurnId:r.turnId}}async steerTurn(e,t,s,n){if(!s.activeTurnId)throw $t("AI_SESSION_NO_ACTIVE_TURN","AI session has no active turn to steer.",409);if(!e.steerTurn)throw $t("AI_SESSION_STEER_UNSUPPORTED","Codex app-server client does not support turn steering.");try{return{turnId:(await e.steerTurn(t,s.activeTurnId,n)).turnId||s.activeTurnId}}catch(s){const r=Gn(s);if(r)return{turnId:(await e.steerTurn(t,r,n)).turnId||r};throw s}}async steerOrStartTurnForCompatibility(e,t,s,n){if(!Boolean(s.activeTurnId&&("running"===s.status||"waiting"===s.status)))return this.startTurn(e,t,n);try{return{...await this.steerTurn(e,t,s,n),started:!1}}catch(s){if(!Kn(s))throw s;return this.startTurn(e,t,n)}}async startTurn(e,t,s){if(!e.startTurn)throw $t("AI_SESSION_SEND_UNSUPPORTED","Codex app-server client does not support starting turns.");return{turnId:(await e.startTurn(t,s)).turnId,started:!0}}async interrupt(e){const t=await this.requireReadyClient(),s=this.requireThreadId(e),n=e.activeTurnId;if(!n)throw $t("AI_SESSION_NO_ACTIVE_TURN","AI session has no active turn to interrupt.");if(!t.interruptTurn)throw $t("AI_SESSION_INTERRUPT_UNSUPPORTED","Codex app-server client does not support turn interruption.");try{await t.interruptTurn(s,n)}catch(r){const i=Gn(r);if(i)return await t.interruptTurn(s,i),{session:this.registry.applyRealtimeEvent(e.id,{kind:"lifecycle",activeTurnId:i,status:"running",phase:"unknown",source:"control"})||e,provider:this.agent,action:"interrupt",providerTurnId:i};if(!Kn(r))throw r;return{session:this.registry.applyRealtimeEvent(e.id,{kind:"turn-completed",activeTurnId:void 0,status:"idle",phase:"unknown",text:"Codex turn is no longer active.",source:"control"})||e,provider:this.agent,action:"interrupt",providerTurnId:n}}return{session:this.registry.applyRealtimeEvent(e.id,{kind:"lifecycle",status:"running",phase:"unknown",source:"control"})||e,provider:this.agent,action:"interrupt",providerTurnId:n}}async resolveApproval(e,t){if(await this.resolveAttachedApproval(e,t))return{session:this.registry.applyRealtimeEvent(e.id,{kind:"assistant-message",status:"skip"===t?"idle":"running",phase:"skip"===t?"unknown":"thinking",text:`Codex approval ${qn(t)}.`,source:"control"})||e,provider:this.agent,action:"approval",decision:t};throw $t("AI_SESSION_APPROVAL_NOT_ATTACHED","Codex approval request is not attached to this control connection. The app-server did not replay a pending approval request for this session.",409)}async resolveAttachedApproval(e,t){return await this.approvals.resolveForSession(e.id,t)||(await this.attachPendingApprovalRequest(e),this.approvals.resolveForSession(e.id,t))}async attachPendingApprovalRequest(e){const t=await this.requireReadyClient();if(!t.resumeThread||this.approvals.latestForSession(e.id))return;const s=this.requireThreadId(e),n=await t.resumeThread(s);n&&this.upsertThread(n,{bindAppSession:!0}),await async function(e){const t=Date.now()+1e3;for(;Date.now()<t;){if(e())return!0;await new Promise(e=>setTimeout(e,25))}return e()}(()=>Boolean(this.approvals.latestForSession(e.id)))}attachClient(e){e.on("event",e=>this.applyProviderEvent(e)),e.on("disconnect",()=>{this.started=!1,this.retryAfter=Date.now()+3e4}),this.client=e}createClient(e){return this.options.createClient?this.options.createClient(e):new Qn(e)}codexAppServerSocketPath(e){return e.map(e=>e.ai?.appServer?.socketPath).find(e=>"string"==typeof e&&e.trim().length>0)}setAppSessions(e){return this.appSessions=e,this.codexAppServerSocketPath(e)}appSessionIdForThread(e){if(this.activeSocketPath)for(const t of this.appSessions)if("string"==typeof t.id&&"codex"===t.appId&&t.ai?.appServer?.socketPath===this.activeSocketPath&&"running"===t.status){if(t.ai?.activeThreadId===e)return t.id;if(Array.isArray(t.ai?.threadIds)&&t.ai.threadIds.includes(e))return t.id}}applyProviderEvent(e){if("thread"===e.type)return void this.upsertThread(e.thread,{bindAppSession:!0});if("approval-request"===e.type)return void this.applyApprovalRequest(e.request);const t=this.registry.list().find(t=>"codex"===t.agent&&t.providerSessionId===e.threadId);if(t)if("thread-closed"!==e.type){if("thread-status"===e.type){const s=Wn(e.status);return void this.registry.applyRealtimeEvent(t.id,{kind:"lifecycle",activeTurnId:t.activeTurnId,status:s.status,phase:s.phase,source:"realtime"})}if("turn-started"!==e.type)if("user-message"!==e.type)if("turn-completed"!==e.type){if("agent-message-delta"===e.type){const s=`${e.threadId}:${e.turnId||""}:${e.itemId||""}`,n=`${this.agentMessageBuffers.get(s)||""}${e.delta}`;return this.agentMessageBuffers.set(s,n),void this.registry.applyRealtimeEvent(t.id,{kind:"assistant-message",activeTurnId:e.turnId||t.activeTurnId,providerTurnId:e.turnId||t.activeTurnId,text:n,source:"realtime"})}"agent-message-completed"===e.type&&this.registry.applyRealtimeEvent(t.id,{kind:"assistant-message",activeTurnId:e.turnId||t.activeTurnId,providerTurnId:e.turnId||t.activeTurnId,text:e.text,status:t.status,source:"realtime"})}else this.registry.applyRealtimeEvent(t.id,{kind:"turn-completed",activeTurnId:e.turnId,providerTurnId:e.turnId,status:"failed"===e.status?"failed":"idle",error:"failed"===e.status?e.error:void 0,source:"realtime"});else this.registry.applyRealtimeEvent(t.id,{kind:"user-message",activeTurnId:e.turnId||t.activeTurnId,providerTurnId:e.turnId||t.activeTurnId,userPrompt:e.text,source:"realtime"});else this.registry.applyRealtimeEvent(t.id,{kind:"turn-started",activeTurnId:e.turnId,providerTurnId:e.turnId,source:"realtime"})}else this.registry.applyRealtimeEvent(t.id,{kind:"turn-completed",activeTurnId:t.activeTurnId,status:"idle",phase:"unknown",text:"Codex thread closed.",source:"realtime"})}upsertThread(e,t){const s="string"==typeof e.id?e.id:void 0;if(!s||!0===e.ephemeral)return;const n=Wn(e.status||{}),r=t.bindAppSession?this.appSessionIdForThread(s):void 0,i=function(e){let t,s;const n=[],r=Array.isArray(e.turns)?e.turns:[];for(const[e,i]of r.entries()){const r=Bn(i),o={id:"string"==typeof r.id&&r.id.trim()?r.id.trim():`turn_${e}`,status:"completed",revision:0},a=Array.isArray(r.items)?r.items:[];for(const e of a){const n=Bn(e);if("userMessage"===n.type){const e=Yn(n);e&&!Ut(e)&&(t=e,o.userPrompt=e)}else"agentMessage"===n.type&&"string"==typeof n.text&&n.text.trim()&&(s=n.text.trim(),o.lastMessage=s,o.summary=s.length>1e3?`${s.slice(0,997)}...`:s)}(o.userPrompt||o.lastMessage||o.summary)&&n.push(o)}return{userPrompt:t,turns:n,summary:s,lastMessage:s}}(e);this.registry.applyAdapterSnapshot({source:"adapter-snapshot",agent:"codex",appId:r?"codex":"codex-app-server",appSessionId:r,providerSessionId:s,appBindingKeys:r?[`app:${r}`]:void 0,actions:{send:!0,interrupt:"running"===n.status||"waiting"===n.status,approval:"waiting"===n.status&&"approval"===n.phase},title:"string"==typeof e.name?e.name:void 0,cwd:"string"==typeof e.cwd?e.cwd:void 0,userPrompt:i.userPrompt,turns:i.turns,summary:i.summary,lastMessage:i.lastMessage,status:n.status,phase:n.phase,replaceActivity:!0})}applyApprovalRequest(e){const t=this.registry.list().find(t=>"codex"===t.agent&&t.providerSessionId===e.threadId);if(!t)return;const s=this.client;s?.respondToApproval&&(this.approvals.register({id:`${e.threadId}:${e.id}`,sessionId:t.id,provider:this.agent,summary:e.summary,metadata:{kind:e.kind,requestId:e.id,itemId:e.itemId},resolve:t=>s.respondToApproval?.(e,t)}),this.registry.applyRealtimeEvent(t.id,{kind:"approval-requested",activeTurnId:e.turnId||t.activeTurnId,providerTurnId:e.turnId||t.activeTurnId,status:"waiting",phase:"approval",summary:e.summary,counters:{approvals:1},source:"realtime"}))}async requireReadyClient(){const e=this.client;if(!e)throw $t("AI_SESSION_CONTROL_NOT_CONNECTED","Codex app-server is not connected.",503);return this.started||(await e.start(),this.started=!0),e}requireThreadId(e){if(!e.providerSessionId)throw $t("AI_SESSION_THREAD_NOT_FOUND","AI session is not bound to a Codex thread.");return e.providerSessionId}}class er{registeredInstanceId="";timer;config;snapshotProvider;fetchImpl;constructor(e,t,s=fetch){this.config=e,this.snapshotProvider=t,this.fetchImpl=s}enabled(){return Boolean("controlled"===this.config.controlMode&&this.config.nodeAgentUrl&&this.config.registrationToken&&this.config.instanceId)}async start(){this.enabled()&&(await this.register(),this.timer=setInterval(()=>{this.heartbeat().catch(e=>{console.warn(`node agent heartbeat failed: ${e instanceof Error?e.message:String(e)}`)})},this.config.heartbeatIntervalMs))}stop(){this.timer&&(clearInterval(this.timer),this.timer=void 0)}async register(){const e=await this.snapshotProvider(),t=this.requiredInstanceId(),s=await this.request(`node-agent/instances/${encodeURIComponent(t)}/register`,{instanceId:this.config.instanceId,name:this.config.instanceName,projectId:this.config.projectId,nodeId:this.config.nodeId,runtimeId:this.config.runtimeId,imageId:this.config.imageId,instanceVersion:e.instanceVersion,protocolVersion:e.protocolVersion,build:e.build,controlMode:"controlled",capabilities:e.capabilities,target:e.target,workspace:e.workspace});this.registeredInstanceId=String(s.id||t),await this.heartbeat()}async heartbeat(){const e=this.registeredInstanceId||this.config.instanceId;if(!e)return;const t=await this.snapshotProvider();await this.request(`node-agent/instances/${encodeURIComponent(e)}/heartbeat`,{status:t.status,health:t.health,protocolVersion:t.protocolVersion,build:t.build,capabilities:t.capabilities,receiver:t.receiver,apps:t.apps,aiSessions:t.aiSessions,workspace:t.workspace,target:t.target})}async request(e,t){const s=this.config.nodeAgentUrl?.replace(/\/$/,"");if(!s)throw new Error("Node agent URL is required.");const n=await this.fetchImpl(`${s}/api/${e}`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${this.config.registrationToken}`},body:JSON.stringify((r=t,Object.fromEntries(Object.entries(r).filter(([,e])=>void 0!==e))))});var r;const i=await n.json().catch(()=>({}));if(!n.ok)throw new Error(i.error?.message||`Node agent request failed with HTTP ${n.status}`);return i.data||{}}requiredInstanceId(){if(!this.config.instanceId)throw new Error("Instance id is required for controlled mode registration.");return this.config.instanceId}}function tr(e,t){return e&&"object"==typeof e&&"code"in e?String(e.code):t}function sr(e){return e instanceof Error?e.message:String(e)}const nr=/^(telegram|wechat|dingding)\.([^.]+)\.json$/;function rr(e){return("string"==typeof e?e.trim():"")||void 0}function ir(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e))}function or(e){const t=e.secrets||{};return"telegram"===e.channel?ir({enabled:e.enabled,token:rr(t.botToken),allowedUserIds:e.allowedUserIds,defaultChatId:rr(e.defaultChatId)}):"wechat"===e.channel?ir({enabled:e.enabled,token:rr(t.token)||rr(t.webhookUrl),baseUrl:rr(t.baseUrl),contextToken:rr(t.contextToken),updatesBuf:rr(e.state?.updatesBuf),defaultChatId:rr(e.defaultChatId)}):ir({enabled:e.enabled,clientId:rr(t.clientId),clientSecret:rr(t.clientSecret),corpId:rr(t.corpId),robotCode:rr(t.robotCode),cardTemplateId:rr(t.cardTemplateId),cardCallbackRouteKey:rr(t.cardCallbackRouteKey),cardUserIdType:t.cardUserIdType,allowedUserIds:e.allowedUserIds,defaultChatId:rr(e.defaultChatId)})}function ar(e){try{const s=JSON.parse(t.readFileSync(e,"utf8"));return s&&"object"==typeof s&&!Array.isArray(s)?s:{}}catch{return{}}}function dr(e,n){const i=ar(n),o=i.chatTools&&"object"==typeof i.chatTools&&!Array.isArray(i.chatTools)?i.chatTools:{},a=i.chatBindings&&"object"==typeof i.chatBindings&&!Array.isArray(i.chatBindings)?i.chatBindings:{},d={...o,[e.channel]:{...o[e.channel]||{},[e.instanceId]:or(e)}},c=function(e){const t=rr(e.defaultChatId),s=e.bindings||{},n={};for(const[e,t]of Object.entries(s))n[e]=ir({conversationId:t.conversationId,contextToken:rr(t.contextToken)});return t&&!n[t]&&(n[t]={conversationId:1}),Object.keys(n).length>0?n:void 0}(e),p={...a,[e.channel]:{...a[e.channel]||{},...c?{[e.instanceId]:c}:{}}},u={...i,chatTools:d,chatBindings:p};return function(e,n){t.mkdirSync(s.dirname(e),{recursive:!0}),r.sync(e,`${JSON.stringify(n,null,2)}\n`,{mode:384})}(n,u),u}function cr(e,n){if(!t.existsSync(e))return ar(n);let r=ar(n);for(const i of t.readdirSync(e,{withFileTypes:!0})){if(!i.isFile())continue;const o=i.name.match(nr);if(o)try{const a=JSON.parse(t.readFileSync(s.join(e,i.name),"utf8"));if(a.channel!==o[1]||a.instanceId!==o[2])continue;r=dr(a,n)}catch{continue}}return r}function pr(e){return e.startsWith("ai-session.")||e.startsWith("ai.session.")?"ai.sessions":e.startsWith("app-session.")?"app.sessions":e.startsWith("receiver.")?"receiver":e.startsWith("conversation.")?"conversations":e.startsWith("trigger.")?"triggers":e.startsWith("channel.")?"channels":e.startsWith("instance.")?"instances":e.startsWith("node.")?"nodes":e.startsWith("project.")?"projects":e.startsWith("model.")?"models":e.startsWith("image.")?"images":"system"}class ur{clients=new Set;seq=0;connect(e){const t=e;t.topics=new Set(["*"]),this.clients.add(e),e.on("close",()=>{this.clients.delete(e)}),e.on("message",e=>{const s=function(e){try{const t=JSON.parse(String(e||"{}"));return t&&"object"==typeof t?t:void 0}catch{return}}(e);"subscribe"===s?.type&&(t.topics=new Set(s.topics?.length?s.topics:["*"]))})}publish(e,t){const s=this.createEvent(e,t),n=s.topic,r=JSON.stringify(s);for(const t of this.clients)t.readyState===t.OPEN&&lr(t.topics,n,e)&&t.send(r);return s}send(e,t,s){const n=this.createEvent(t,s);return e.send(JSON.stringify(n)),n}createEvent(e,t){return{v:1,id:`evt_${Date.now().toString(36)}_${Math.random().toString(16).slice(2)}`,seq:++this.seq,type:e,topic:pr(e),createdAt:(new Date).toISOString(),payload:t}}}function lr(e,t,s){return!e||e.has("*")||e.has(t)||e.has(s)}const mr=i.z.object({type:i.z.literal("result"),result:i.z.unknown(),attachments:i.z.array(i.z.object({id:i.z.string(),kind:i.z.enum(["image","file"]),path:i.z.string(),name:i.z.string(),mime:i.z.string().optional(),size:i.z.number().nonnegative().optional()})).optional(),conversationId:i.z.number().int().positive().optional(),timeoutMs:i.z.number().positive().optional(),source:i.z.enum(["cli","mcp"]).optional(),kind:i.z.enum(["task","approval"]).optional(),cwd:i.z.string().optional(),sessionIds:i.z.record(i.z.string(),i.z.string()).optional()}),hr=i.z.discriminatedUnion("action",[i.z.object({type:i.z.literal("control"),action:i.z.literal("pending.list"),requestId:i.z.string().optional()}),i.z.object({type:i.z.literal("control"),action:i.z.literal("pending.reply"),requestId:i.z.string().optional(),id:i.z.number().int().positive(),markdown:i.z.string()}),i.z.object({type:i.z.literal("control"),action:i.z.literal("pending.drop"),requestId:i.z.string().optional(),id:i.z.number().int().positive()}),i.z.object({type:i.z.literal("control"),action:i.z.literal("pending.approval"),requestId:i.z.string().optional(),id:i.z.number().int().positive(),decision:i.z.enum(["allow","deny","skip"])}),i.z.object({type:i.z.literal("control"),action:i.z.literal("receiver.message"),requestId:i.z.string().optional(),channel:i.z.string().trim().min(1).max(80),chatSessionId:i.z.string().trim().min(1).max(240),userId:i.z.string().trim().max(240).optional(),text:i.z.string().trim().min(1).max(2e4),attachments:i.z.array(i.z.record(i.z.string(),i.z.unknown())).default([]),conversationId:i.z.number().int().positive().optional()})]);i.z.union([mr,hr]);const gr=i.z.object({type:i.z.literal("reply"),value:i.z.string()}),fr=i.z.object({type:i.z.literal("error"),message:i.z.string()}),yr=i.z.object({type:i.z.literal("control.response"),requestId:i.z.string().optional(),ok:i.z.boolean(),data:i.z.unknown().optional(),error:i.z.object({code:i.z.string(),message:i.z.string()}).optional()});function vr(e){return`${JSON.stringify(e)}\n`}i.z.union([gr,fr,yr]);class Sr{socketPath;constructor(e){this.socketPath=e}pendingList(){return this.request({type:"control",action:"pending.list"})}reply(e,t){return this.request({type:"control",action:"pending.reply",id:e,markdown:t})}drop(e){return this.request({type:"control",action:"pending.drop",id:e})}approval(e,t){return this.request({type:"control",action:"pending.approval",id:e,decision:t})}message(e){return this.request({type:"control",action:"receiver.message",channel:e.channel,chatSessionId:e.chatSessionId,userId:e.userId,text:e.text,attachments:e.attachments||[],conversationId:e.conversationId})}request(e){const t=h.randomUUID();return new Promise((s,n)=>{const r=o.createConnection(this.socketPath),i=setTimeout(()=>{r.destroy(),n(Object.assign(new Error("Receiver control request timed out."),{code:"RECEIVER_CONTROL_TIMEOUT"}))},5e3),a=e=>{clearTimeout(i),r.end(),e()};r.once("connect",()=>{r.write(vr({...e,requestId:t}))}),function(e,t,s){let n="";e.on("data",r=>{n+=r.toString("utf8");let i=n.indexOf("\n");for(;-1!==i;){const r=n.slice(0,i);if(n=n.slice(i+1),i=n.indexOf("\n"),r.trim())try{const n=t.safeParse(JSON.parse(r));if(!n.success){e.write(vr({type:"error",message:"Invalid message shape."}));continue}s(n.data)}catch(t){e.write(vr({type:"error",message:"Invalid JSON message."}))}}})}(r,yr,e=>{e.requestId===t&&a(()=>{if(e.ok)s(e.data);else{const t=Object.assign(new Error(e.error?.message||"Receiver control request failed."),{code:e.error?.code||"RECEIVER_CONTROL_FAILED"});n(t)}})}),r.once("error",e=>{a(()=>{n(Object.assign(new Error(`Receiver is not available at ${this.socketPath}: ${e.message}`),{code:"RECEIVER_UNAVAILABLE"}))})}),r.once("close",()=>{clearTimeout(i)})})}}class Ir extends g.EventEmitter{socketPath;child;statusValue={running:!1};logPath;exitPromise;constructor(e,t){super(),this.socketPath=e,this.logPath=t?s.join(t,"receiver.log"):void 0}status(){return{...this.statusValue}}start(){if(this.child&&!this.child.killed&&this.statusValue.running)return this.status();const e=process.env.TASK_HANDOFF_CLI_PATH||s.resolve(__dirname,"cli.js");let t;return this.child=m.spawn(process.execPath,[e,"receiver","--headless","--socket",this.socketPath],{env:{...process.env,TASK_HANDOFF_RECEIVER_HEADLESS:"1"},stdio:["ignore","pipe","pipe"]}),this.statusValue={running:!0,pid:this.child.pid,startedAt:(new Date).toISOString(),exitedAt:void 0,exitCode:void 0,signal:void 0},this.appendLog(`\n[${this.statusValue.startedAt}] receiver started pid=${this.child.pid}\n`),this.child.stdout?.on("data",e=>this.handleLog(e)),this.child.stderr?.on("data",e=>this.handleLog(e)),this.exitPromise=new Promise(e=>{t=e}),this.child.on("exit",(e,s)=>{const n=(new Date).toISOString();this.statusValue={...this.statusValue,running:!1,exitedAt:n,exitCode:e,signal:s},this.appendLog(`[${n}] receiver exited code=${e??"null"} signal=${s??"null"}\n`),this.emit("exit",this.status()),this.child=void 0,t?.(this.status())}),this.emit("start",this.status()),this.status()}stop(){return this.child&&this.statusValue.running?(this.child.kill("SIGTERM"),this.status()):this.status()}async stopAndWait(e=2e3){if(!this.child||!this.statusValue.running)return this.status();const t=this.exitPromise;return this.stop(),t?await Promise.race([t,new Promise(t=>{setTimeout(()=>t(this.status()),e)})]):this.status()}readLogs(e=65536){const s=this.logPath;if(!s||!t.existsSync(s))return{logPath:s,maxBytes:e,size:0,truncated:!1,content:""};const n=t.statSync(s),r=Math.max(0,n.size-e),i=t.openSync(s,"r");try{const o=Buffer.alloc(n.size-r);return t.readSync(i,o,0,o.length,r),{logPath:s,maxBytes:e,size:n.size,updatedAt:n.mtime.toISOString(),truncated:r>0,content:o.toString("utf8")}}finally{t.closeSync(i)}}handleLog(e){const t=String(e);this.appendLog(t),this.emit("log",t)}appendLog(e){this.logPath&&(t.mkdirSync(s.dirname(this.logPath),{recursive:!0}),t.appendFileSync(this.logPath,e))}}function Ar(){return process.env.HOME||n.homedir()||"/home/agent"}function br(){return process.env.TASK_HANDOFF_WORKSPACE||process.env.WORKSPACE||"/workspace"}function _r(){const e=Ar(),t=function(){const e=[s.join(Ar(),".config","chromium")],t=process.env.TASK_HANDOFF_CHROMIUM_USER_DATA_DIR?.trim();return t&&!e.includes(t)&&e.push(t),e}().map((e,t)=>({id:0===t?"chromium-profile":`chromium-profile-${t+1}`,type:"dir",projectPath:0===t?"chromium":`chromium-${t+1}`,containerPath:e}));return[{id:"codex",label:"Codex",projectRoot:".task-handoff/configs/codex",items:[{id:"config",type:"file",projectPath:"config.toml",containerPath:s.join(e,".codex","config.toml")},{id:"auth",type:"file",projectPath:"auth.json",containerPath:s.join(e,".codex","auth.json")},{id:"agents",type:"file",projectPath:"AGENTS.md",containerPath:s.join(e,".codex","AGENTS.md")},{id:"skills",type:"dir",projectPath:"skills",containerPath:s.join(e,".codex","skills")}]},{id:"claude",label:"Claude",projectRoot:".task-handoff/configs/claude",items:[{id:"claude-json",type:"file",projectPath:".claude.json",containerPath:s.join(e,".claude.json")},{id:"settings",type:"file",projectPath:"settings.json",containerPath:s.join(e,".claude","settings.json")},{id:"claude-md",type:"file",projectPath:"CLAUDE.md",containerPath:s.join(e,".claude","CLAUDE.md")},{id:"commands",type:"dir",projectPath:"commands",containerPath:s.join(e,".claude","commands")},{id:"agents",type:"dir",projectPath:"agents",containerPath:s.join(e,".claude","agents")},{id:"skills",type:"dir",projectPath:"skills",containerPath:s.join(e,".claude","skills")}]},{id:"browser",label:"Browser",projectRoot:".task-handoff/configs/browser",items:t}]}function wr(e,n,r){return t.existsSync(n)?(t.mkdirSync(s.dirname(r),{recursive:!0}),"dir"===e?t.cpSync(n,r,{recursive:!0,force:!0}):t.copyFileSync(n,r),"copied"):"skipped_missing_source"}function Tr(e,t,n){const r=n||_r().find(e=>e.id===t);if(!r){const e=new Error(`Config sync preset ${t} was not found.`);throw Object.assign(e,{statusCode:404,code:"CONFIG_SYNC_PRESET_NOT_FOUND"}),e}const i=r.items.map(t=>{const n=function(e,t){const n=s.resolve(br(),e),r=s.resolve(n,t);if(r!==n&&!r.startsWith(`${n}${s.sep}`)){const e=new Error(`Config sync path escapes project root: ${t}`);throw Object.assign(e,{statusCode:400,code:"CONFIG_SYNC_PATH_INVALID"}),e}return r}(r.projectRoot,t.projectPath),i=function(e){const t=s.resolve(function(e){const t={HOME:Ar(),WORKSPACE:br(),CODEX_HOME:process.env.CODEX_HOME||s.join(Ar(),".codex"),CLAUDE_HOME:process.env.CLAUDE_HOME||s.join(Ar(),".claude")};return e.replace(/\$\{([A-Z_]+)\}/g,(e,s)=>t[s]||e)}(e));if(![s.resolve(Ar()),s.resolve(br()),s.resolve(process.env.TASK_HANDOFF_DATA_DIR||"/data/task-handoff"),s.resolve(process.env.TASK_HANDOFF_LOG_DIR||"/data/logs"),s.resolve(process.env.TASK_HANDOFF_ARTIFACT_DIR||"/data/artifacts")].some(e=>t===e||t.startsWith(`${e}${s.sep}`))){const t=new Error(`Config sync target path is not allowed: ${e}`);throw Object.assign(t,{statusCode:400,code:"CONFIG_SYNC_CONTAINER_PATH_INVALID"}),t}return t}(t.containerPath),o="import"===e?n:i,a="import"===e?i:n;try{return{...t,source:o,target:a,status:wr(t.type,o,a)}}catch(e){return{...t,source:o,target:a,status:"failed",error:e instanceof Error?e.message:String(e)}}});return{preset:{id:r.id,label:r.label,projectRoot:r.projectRoot},direction:e,items:i}}const Nr="2026-06-23",Or=i.z.string().trim().min(1).max(120).regex(/^[a-zA-Z0-9][a-zA-Z0-9_.:-]*$/),Er=i.z.string().datetime(),zr=i.z.record(i.z.string(),i.z.string()).default({}),xr=i.z.record(i.z.string(),i.z.string()).default({}),Dr=i.z.object({codexModelId:Or.optional(),claudeModelId:Or.optional()}).strict().default({}),kr=i.z.object({component:i.z.enum(["control-plane","node-agent","controlled-instance"]),packageName:i.z.string().trim().max(160).optional(),packageVersion:i.z.string().trim().max(80).optional(),protocolVersion:i.z.string().trim().max(80).optional(),buildId:i.z.string().trim().max(160).optional(),builtAt:i.z.string().trim().max(120).optional(),gitCommit:i.z.string().trim().max(120).optional(),imageRef:i.z.string().trim().max(512).optional(),imageDigest:i.z.string().trim().max(240).optional()}).strict(),Cr=i.z.enum(["stable","beta","alpha"]),Pr=i.z.discriminatedUnion("component",[i.z.object({component:i.z.literal("node-agent")}).strict(),i.z.object({component:i.z.literal("controlled-instance"),instanceId:Or}).strict()]);i.z.object({target:Pr,channel:Cr.default("stable")}).strict(),i.z.object({target:Pr,source:i.z.enum(["npm","docker-registry"]),channel:Cr,currentVersion:i.z.string().trim().max(240).optional(),availableVersion:i.z.string().trim().min(1).max(240),artifactRef:i.z.string().trim().min(1).max(512).optional(),updateAvailable:i.z.boolean(),supported:i.z.boolean().default(!0),reason:i.z.string().trim().max(2048).optional(),checkedAt:Er}).strict(),i.z.object({id:Or,nodeId:Or,target:Pr,source:i.z.enum(["npm","docker-registry"]),channel:Cr,fromVersion:i.z.string().trim().max(240).optional(),toVersion:i.z.string().trim().min(1).max(240),artifactRef:i.z.string().trim().min(1).max(512).optional(),status:i.z.enum(["queued","updating","restarting","succeeded","failed"]),error:i.z.string().trim().max(4096).optional(),startedAt:Er.optional(),completedAt:Er.optional(),createdAt:Er,updatedAt:Er}).strict();const Fr=i.z.object({type:i.z.enum(["branch","tag","commit"]),name:i.z.string().trim().min(1).max(240).optional(),commit:i.z.string().trim().max(80).optional()}).strict(),Rr=i.z.object({type:i.z.enum(["none","ssh-key","https-token"]).default("none"),secretId:i.z.string().trim().min(1).max(120).optional()}).strict(),Mr=i.z.object({depth:i.z.number().int().positive().max(1e5).optional(),submodules:i.z.boolean().default(!1),lfs:i.z.boolean().default(!1),subdirectory:i.z.string().trim().max(240).default("")}).strict();i.z.object({id:Or,name:i.z.string().trim().min(1).max(160),url:i.z.string().trim().min(1).max(2048),provider:i.z.string().trim().max(80).optional(),ref:Fr.default({type:"branch",name:"main"}),auth:Rr.default({type:"none"}),clone:Mr.default({submodules:!1,lfs:!1,subdirectory:""}),defaultImageId:Or.optional(),modelSelection:Dr,labels:zr,createdAt:Er,updatedAt:Er}).strict(),i.z.object({id:Or,nodeId:Or,name:i.z.string().trim().min(1).max(160),path:i.z.string().trim().min(1).max(4096),defaultImageId:Or.optional(),modelSelection:Dr,labels:zr,createdAt:Er,updatedAt:Er}).strict();const jr=i.z.discriminatedUnion("type",[i.z.object({type:i.z.literal("git-repository"),repositoryId:Or.optional(),url:i.z.string().trim().min(1).max(2048),provider:i.z.string().trim().max(80).optional(),ref:Fr.default({type:"branch",name:"main"}),auth:Rr.default({type:"none"}),clone:Mr.default({submodules:!1,lfs:!1,subdirectory:""})}).strict(),i.z.object({type:i.z.literal("git-template"),url:i.z.string().trim().min(1).max(2048),templateId:i.z.string().trim().min(1).max(120).optional(),ref:Fr.default({type:"branch",name:"main"}),auth:Rr.default({type:"none"}),clone:Mr.default({submodules:!1,lfs:!1,subdirectory:""})}).strict(),i.z.object({type:i.z.literal("local-folder"),localFolderId:Or.optional(),path:i.z.string().trim().min(1).max(4096),ownerNodeId:Or.optional()}).strict()]),Hr=i.z.object({mode:i.z.enum(["local-bind","git-clone","empty-volume","persistent-volume"]),path:i.z.string().trim().min(1).max(4096).default("/workspace"),volumeName:i.z.string().trim().max(240).optional(),readOnly:i.z.boolean().default(!1)}).strict(),Lr=i.z.enum(["codex","claude"]);i.z.object({id:Or,name:i.z.string().trim().min(1).max(160),source:jr,defaultImageId:Or.optional(),defaultNodeId:Or.optional(),defaultRuntimeId:Or.optional(),modelSelection:Dr,workspacePolicy:Hr,labels:zr,createdAt:Er,updatedAt:Er}).strict(),i.z.object({id:Or,name:i.z.string().trim().min(1).max(160),endpoint:i.z.string().trim().min(1).max(2048),key:i.z.string().trim().min(1).max(4096),model:i.z.string().trim().min(1).max(240),app:Lr,enabled:i.z.boolean().default(!0),order:i.z.number().int().min(0).max(1e6).default(0),labels:zr,createdAt:Er,updatedAt:Er}).strict();const $r=i.z.object({id:Or,name:i.z.string().trim().min(1).max(160),image:i.z.string().trim().min(1).max(512),registry:i.z.string().trim().min(1).max(160).default("local"),capabilities:i.z.array(i.z.string().trim().min(1).max(80)).default([]),optionalApps:i.z.array(i.z.string().trim().min(1).max(120)).default([]),defaultEnv:xr,labels:zr,createdAt:Er,updatedAt:Er}).strict();i.z.object({id:Or,name:i.z.string().trim().min(1).max(160),connectionMode:i.z.enum(["local-ipc","local-loopback","direct-http","reverse-wss"]).default("direct-http"),auth:i.z.object({mode:i.z.enum(["local-static-key","paired-hmac"]).default("local-static-key"),keyId:Or.optional(),secret:i.z.string().trim().max(4096).optional(),pairedAt:Er.optional(),pairing:i.z.object({status:i.z.enum(["pending","paired","expired"]).default("pending"),joinToken:i.z.string().trim().max(4096).optional(),expiresAt:Er.optional()}).strict().optional()}).strict().default({mode:"local-static-key"}),endpoint:i.z.string().trim().max(2048).optional(),controlEndpoint:i.z.string().trim().max(2048).optional(),containerEndpoint:i.z.string().trim().max(2048).optional(),publicWebBase:i.z.string().trim().max(2048).optional(),status:i.z.enum(["unknown","online","offline","degraded"]).default("unknown"),health:i.z.enum(["unknown","ok","degraded","failed"]).default("unknown"),capabilities:i.z.record(i.z.string(),i.z.unknown()).default({}),labels:zr,lastSeenAt:Er.optional(),createdAt:Er,updatedAt:Er}).strict(),i.z.object({id:Or,nodeId:Or,name:i.z.string().trim().min(1).max(160),type:i.z.enum(["docker","kubernetes","local"]),status:i.z.enum(["unknown","online","offline","degraded"]).default("unknown"),accessStrategy:i.z.enum(["node-proxy","direct-port","kubernetes-ingress","kubernetes-port-forward"]).default("node-proxy"),capabilities:i.z.record(i.z.string(),i.z.unknown()).default({}),labels:zr,createdAt:Er,updatedAt:Er}).strict(),i.z.object({ok:i.z.boolean().optional(),role:i.z.string().optional(),nodeId:Or.optional()}).passthrough(),i.z.object({nodeId:Or,joinToken:i.z.string().trim().min(1),expiresAt:Er}).passthrough(),i.z.object({id:Or,keyId:Or,url:i.z.string().trim().min(1).max(2048).optional(),name:i.z.string().trim().min(1).max(160).optional(),pairedAt:Er,updatedAt:Er.optional(),active:i.z.boolean().optional(),current:i.z.boolean().optional()}).passthrough(),i.z.object({remote:i.z.object({id:Or,url:i.z.string().trim().min(1).max(2048).optional(),keyId:Or,pairedAt:Er,active:i.z.boolean()}).passthrough(),tunnel:i.z.object({status:i.z.enum(["disabled","saved","connecting","connected","failed"]),error:i.z.string().trim().max(2048).optional()}).passthrough()}).passthrough(),i.z.object({deleted:i.z.boolean().optional()}).passthrough(),i.z.object({repository:i.z.string().trim().optional(),tag:i.z.string().trim().optional(),id:i.z.string().trim(),createdSince:i.z.string().trim().optional(),size:i.z.string().trim().optional(),reference:i.z.string().trim().min(1)}).passthrough();const Ur=i.z.lazy(()=>i.z.object({name:i.z.string().trim().min(1),path:i.z.string().trim().min(1).max(4096),children:i.z.array(Ur)}).passthrough());i.z.object({status:i.z.number().int().min(100).max(599).optional(),headers:i.z.record(i.z.string(),i.z.string()).optional(),bodyBase64:i.z.string().optional()}).passthrough();const qr=i.z.object({strategy:i.z.enum(["node-proxy","direct-port","kubernetes-ingress","kubernetes-port-forward"]).default("node-proxy"),web:i.z.string().trim().max(2048).optional(),api:i.z.string().trim().max(2048).optional(),vnc:i.z.string().trim().max(2048).optional(),tty:i.z.string().trim().max(2048).optional(),logs:i.z.string().trim().max(2048).optional(),status:i.z.enum(["unknown","reachable","endpoint-unreachable"]).default("unknown")}).strict(),Br=i.z.object({strategy:i.z.enum(["control-plane-proxy","direct-port","node-proxy","kubernetes-ingress","kubernetes-port-forward"]).default("control-plane-proxy"),web:i.z.string().trim().max(2048).optional(),api:i.z.string().trim().max(2048).optional(),ws:i.z.string().trim().max(2048).optional(),status:i.z.enum(["unknown","reachable","endpoint-unreachable"]).default("unknown")}).strict().default({strategy:"control-plane-proxy",status:"unknown"}),Vr=i.z.object({mode:i.z.enum(["local-bind","git-clone","empty-volume","persistent-volume"]).optional(),status:i.z.enum(["unknown","pending","ready","failed"]).default("unknown"),path:i.z.string().trim().max(4096).optional(),resolvedCommit:i.z.string().trim().max(120).optional(),error:i.z.string().trim().max(2048).optional()}).passthrough(),Kr=i.z.object({id:Or,name:i.z.string().trim().min(1).max(160),projectId:Or.optional(),source:jr,sourceSnapshot:i.z.record(i.z.string(),i.z.unknown()).default({}),nodeId:Or,runtimeId:Or,imageId:Or.optional(),imageSnapshot:$r.optional(),status:i.z.enum(["created","provisioning","starting","registering","registered","running","stopping","stopped","failed","unhealthy"]).default("created"),health:i.z.enum(["unknown","ok","degraded","failed"]).default("unknown"),connectionStatus:i.z.enum(["unknown","online","offline","endpoint-unreachable"]).default("unknown"),agentStatus:i.z.enum(["unknown","online","offline"]).default("unknown"),targetStatus:i.z.enum(["unknown","reachable","endpoint-unreachable"]).default("unknown"),uiAccessStatus:i.z.enum(["unknown","reachable","endpoint-unreachable"]).default("unknown"),controlMode:i.z.enum(["standalone","controlled"]).default("controlled"),protocolVersion:i.z.string().trim().max(80).optional(),instanceVersion:i.z.string().trim().max(80).optional(),build:kr.optional(),capabilities:i.z.record(i.z.string(),i.z.unknown()).default({}),config:i.z.object({autoImportAgentConfigs:i.z.boolean().default(!0)}).strict().default({autoImportAgentConfigs:!0}),workspace:Vr.default({status:"unknown"}),target:qr.default({strategy:"direct-port",status:"unknown"}),access:Br,receiver:i.z.object({status:i.z.string().trim().max(80).default("unknown"),pendingCount:i.z.number().int().min(0).default(0)}).strict().default({status:"unknown",pendingCount:0}),apps:i.z.object({runningCount:i.z.number().int().min(0).default(0),problemCount:i.z.number().int().min(0).default(0),updatedAt:Er.optional(),revision:i.z.number().int().min(0).optional()}).strict().default({runningCount:0,problemCount:0}),aiSessions:zs.default(()=>({runningCount:0,waitingCount:0,staleCount:0,sessions:[],updatedAt:(new Date).toISOString()})),triggers:i.z.object({enabledCount:i.z.number().int().min(0).default(0),runningCount:i.z.number().int().min(0).default(0),errorCount:i.z.number().int().min(0).default(0),configs:i.z.array(i.z.object({configHash:i.z.string().trim().min(1),config:$e,deployments:i.z.array(qe).default([]),runtime:i.z.array(Be).default([])}).strict()).default([]),recentRuns:i.z.array(Ve).default([])}).strict().optional(),runtime:i.z.object({kind:i.z.string().trim().max(80).optional(),containerName:i.z.string().trim().max(240).optional(),containerId:i.z.string().trim().max(240).optional(),workspacePath:i.z.string().trim().max(4096).optional(),pid:i.z.number().int().positive().optional(),port:i.z.number().int().positive().max(65535).optional(),labels:i.z.record(i.z.string(),i.z.string()).default({})}).strict().default({labels:{}}),registrationToken:i.z.string().trim().min(1).max(240).optional(),lastHeartbeatAt:Er.optional(),createdAt:Er,updatedAt:Er}).strict();i.z.object({instanceId:Or.optional(),name:i.z.string().trim().min(1).max(160),projectId:Or.optional(),source:jr.optional(),nodeId:Or.optional(),runtimeId:Or.optional(),imageId:Or.optional(),instanceVersion:i.z.string().trim().max(80).optional(),protocolVersion:i.z.string().trim().max(80),build:kr.optional(),controlMode:i.z.enum(["standalone","controlled"]).default("controlled"),capabilities:i.z.record(i.z.string(),i.z.unknown()).default({}),target:qr.default({strategy:"direct-port",status:"unknown"}),workspace:Vr.default({status:"unknown"}),registrationToken:i.z.string().trim().max(240).optional()}).strict(),i.z.object({status:Kr.shape.status.optional(),health:Kr.shape.health.optional(),protocolVersion:i.z.string().trim().max(80),build:kr.optional(),capabilities:Kr.shape.capabilities.optional(),receiver:Kr.shape.receiver.optional(),apps:Kr.shape.apps.optional(),aiSessions:Kr.shape.aiSessions.optional(),triggers:Kr.shape.triggers.optional(),workspace:Vr.optional(),target:qr.partial().optional()}).strict();const Gr=i.z.enum(["web","telegram","wechat","dingding"]);function Wr(){try{const e=s.resolve(__dirname,"..","package.json");return JSON.parse(t.readFileSync(e,"utf8")).version||"unknown"}catch{return"unknown"}}function Xr(e){const t=process.env[e]?.trim();return t||void 0}function Jr(){return"controlled"===process.env.TASK_HANDOFF_CONTROL_MODE}function Yr(e,r){const i=[{name:"Xvfb",requiredFor:["gui-display"]},{name:"openbox",requiredFor:["gui-window-manager"]},{name:"picom",requiredFor:["gui-compositor"]},{name:"x11vnc",requiredFor:["vnc"]},{name:"websockify",requiredFor:["novnc-proxy"]},{name:"vncserver",requiredFor:["kasmvnc"]},{name:"vncpasswd",requiredFor:["kasmvnc-auth"]},{name:"openssl",requiredFor:["kasmvnc-cert"]},{name:"xrdb",requiredFor:["kasmvnc-hidpi"]},{name:"xrandr",requiredFor:["kasmvnc-resize"]},{name:process.env.TASK_HANDOFF_CHROMIUM_COMMAND||"chromium",label:"chromium",requiredFor:["browser"]},{name:process.env.TASK_HANDOFF_VSCODE_WEB_COMMAND||"code-server",label:"code-server",requiredFor:["vscode-web"]},{name:process.env.TASK_HANDOFF_XTERM_COMMAND||"xterm",label:"xterm",requiredFor:["gui-terminal"]},{name:"import",requiredFor:["screenshot"]},{name:process.env.TASK_HANDOFF_CODEX_COMMAND||"codex",label:"codex",requiredFor:["active-codex-agent"]},{name:process.env.TASK_HANDOFF_CLAUDE_COMMAND||process.env.CLAUDE_CLI_PATH||"claude",label:"claude",requiredFor:["active-claude-agent"]}].map(e=>{const t=It(e.name);return{name:e.label||e.name,command:e.name,available:Boolean(t),path:t,requiredFor:e.requiredFor}}),o=function(e){return Object.entries(e).map(([e,n])=>{const r=s.resolve(n),i=e.endsWith("Path"),o=i?s.dirname(r):r;let a=!1,d=!1,c="missing";try{const e=t.existsSync(r)?t.statSync(r):void 0;a=Boolean(e),c=e?.isFile()?"file":e?.isDirectory()?"directory":"missing";const n=a?i?r:o:(e=>{let n=e;for(;!t.existsSync(n);){const e=s.dirname(n);if(e===n)return n;n=e}return t.statSync(n).isDirectory()?n:s.dirname(n)})(o);t.accessSync(n,t.constants.W_OK),d=!0}catch{d=!1}return{key:e,path:r,exists:a,type:c,writable:d}})}(e),a="linux"===process.platform;return{ok:a&&i.every(e=>e.available)&&Boolean(r)&&o.every(e=>e.writable),runtime:{platform:process.platform,arch:process.arch,linuxRuntime:a,node:process.version,pid:process.pid,hostname:n.hostname(),uptimeSeconds:Math.round(process.uptime())},noVnc:{available:Boolean(r),root:r},commands:i,storage:o}}async function Qr(e){try{const t=await e.pendingList();if(t&&"object"==typeof t&&"pending"in t&&Array.isArray(t.pending))return t.pending.length}catch{return 0}return 0}function Zr(){const e=process.env.TASK_HANDOFF_INSTANCE_WEB_URL||process.env.TASK_HANDOFF_PUBLIC_WEB_URL,t=process.env.TASK_HANDOFF_INSTANCE_API_URL||(e?`${e.replace(/\/$/,"")}/api`:void 0);return{strategy:process.env.TASK_HANDOFF_INSTANCE_ENDPOINT_STRATEGY||"direct-port",web:e,api:t,status:e||t?"reachable":"unknown"}}function ei(e){const s=process.env.TASK_HANDOFF_WORKSPACE||process.env.WORKSPACE||"/workspace",n=t.existsSync(s);return{mode:process.env.TASK_HANDOFF_WORKSPACE_MODE||(process.env.TASK_HANDOFF_GIT_URL?"git-clone":"local-bind"),status:n?"ready":"unknown",path:s,exists:n,git:{url:process.env.TASK_HANDOFF_GIT_URL,ref:process.env.TASK_HANDOFF_GIT_REF,resolvedCommit:process.env.TASK_HANDOFF_GIT_COMMIT},storage:{dataDir:e.dataDir,logDir:e.logDir}}}function ti(e){const t=e.catalog();return{protocolVersion:Nr,apps:t.map(e=>({id:e.id,name:e.name,kind:e.kind,automation:e.automation})),features:{receiver:!0,appRuntime:!0,tty:t.some(e=>"tty"===e.kind),gui:t.some(e=>"gui"===e.kind),browser:t.some(e=>"browser"===e.id||"chromium"===e.id),screenshots:!0,logs:!0}}}function si(e){const t=e.list();return{enabledCount:t.deployments.filter(e=>e.enabled).length,runningCount:t.runtime.filter(e=>"running"===e.status).length,errorCount:t.runtime.filter(e=>"error"===e.status).length,configs:t.configs.map(e=>({configHash:e.configHash,config:e,deployments:t.deployments.filter(t=>t.configHash===e.configHash),runtime:t.runtime.filter(t=>t.configHash===e.configHash)})),recentRuns:t.recentRuns.slice(0,20)}}async function ni(e,t,s,n,r=_n(),i){const o=t.status(),a=e.listSessions();return{status:"running",health:"ok",instanceVersion:Wr(),protocolVersion:Nr,build:{component:"controlled-instance",packageName:"@task-handoff/controlled-instance",packageVersion:Wr(),protocolVersion:Nr,buildId:Xr("TASK_HANDOFF_BUILD_ID"),builtAt:Xr("TASK_HANDOFF_BUILT_AT"),gitCommit:Xr("TASK_HANDOFF_GIT_COMMIT"),imageRef:Xr("TASK_HANDOFF_IMAGE_REF"),imageDigest:Xr("TASK_HANDOFF_IMAGE_DIGEST")},controlMode:Jr()?"controlled":"standalone",capabilities:ti(e),receiver:{status:o.running?"running":"stopped",pendingCount:await Qr(s)},apps:{runningCount:e.runningSessionCount(),problemCount:e.problemSessionCount()},aiSessions:r.boundSnapshot(a),triggers:i?si(i):void 0,workspace:ei(n),target:Zr()}}i.z.object({id:Or,channel:Gr,name:i.z.string().trim().min(1).max(160),enabled:i.z.boolean().default(!1),token:i.z.string().trim().max(4096).optional(),defaultChatId:i.z.string().trim().max(240).optional(),allowedUserIds:i.z.array(i.z.string().trim().min(1).max(240)).default([]),pollIntervalMs:i.z.number().int().positive().max(6e4).default(3e3),settings:i.z.record(i.z.string(),i.z.unknown()).default({}),createdAt:Er,updatedAt:Er}).strict(),i.z.object({id:Or,channel:Gr,bridgeId:Or.optional(),chatSessionId:i.z.string().trim().min(1).max(240),userId:i.z.string().trim().max(240).optional(),activeProjectId:Or.optional(),activeInstanceId:Or.optional(),activeAiSessionId:i.z.string().trim().min(1).max(120).optional(),lastUsedAt:Er,createdAt:Er,updatedAt:Er}).strict(),i.z.object({source:i.z.object({type:i.z.literal("chat-gateway").default("chat-gateway"),channel:Gr,bridgeId:Or.optional(),chatSessionId:i.z.string().trim().min(1).max(240),userId:i.z.string().trim().max(240).optional()}).strict(),message:i.z.object({text:i.z.string().trim().max(2e4).default(""),attachments:i.z.array(ms).max(6).default([])}).strict().superRefine((e,t)=>{e.attachments.reduce((e,t)=>e+t.size,0)>is&&t.addIssue({code:i.z.ZodIssueCode.custom,path:["attachments"],message:"Images must be 41943040 bytes or less in total."})}),target:i.z.object({instanceId:Or,aiSessionId:i.z.string().trim().min(1).max(120)}).strict().optional()}).strict(),i.z.object({id:Or,instanceId:Or,projectId:Or.optional(),aiSessionId:i.z.string().trim().min(1).max(120),providerSessionId:i.z.string().trim().max(240).optional(),result:i.z.string().default(""),timeoutMs:i.z.number().positive().optional(),source:i.z.string().trim().max(120).optional(),kind:i.z.enum(["task","approval"]).default("task"),status:i.z.enum(["pending","unreachable"]).default("pending"),error:i.z.string().trim().max(2048).optional(),lastSeenAt:Er}).strict();const ri=new Set(["ECONNREFUSED","ECONNRESET","EHOSTUNREACH"]);function ii(e){return new Promise(t=>setTimeout(t,e))}function oi(e){const t=e?.code;return Boolean(t&&ri.has(t))}function ai(e,t="/"){const s=new URL(t,"http://task-handoff.local"),n=`/api/apps/sessions/${e}/web`,r=s.pathname.startsWith(n)?s.pathname.slice(n.length):"/";return`${r.startsWith("/")?r:`/${r}`}${s.search}`}function di(){const e=process.env.TASK_HANDOFF_KASMVNC_USERNAME||"agent",t=process.env.TASK_HANDOFF_KASMVNC_PASSWORD||"taskhandoff";return`Basic ${Buffer.from(`${e}:${t}`).toString("base64")}`}function ci(e,t,s,n={}){const r=new Set(["connection","content-length","host","keep-alive","proxy-authenticate","proxy-authorization","referer","referrer","te","trailer","transfer-encoding","upgrade"]);return{...Object.fromEntries(Object.entries(e).filter(([e,t])=>!(e=>{const t=e.toLowerCase();return r.has(t)||t.startsWith("sec-ch-")||t.startsWith("sec-fetch-")})(e)&&void 0!==t).map(([e,t])=>[e,Array.isArray(t)?t.join(", "):String(t)])),...Object.fromEntries(Object.entries(n).filter(([,e])=>void 0!==e).map(([e,t])=>[e,Array.isArray(t)?t.join(", "):String(t)])),host:`${t}:${s}`}}function pi(e,t,s,n={}){return Object.fromEntries(Object.entries(ci(e,t,s,n)).filter(([e])=>{const t=e.toLowerCase();return!t.startsWith("sec-websocket-")||"sec-websocket-origin"===t}))}function ui(e,t){const s=e[t];return Array.isArray(s)?s.join(","):s||""}function li(e){if(ui(e,"content-encoding"))return!1;const t=ui(e,"content-type").toLowerCase();return t.includes("text/css")||t.includes("text/html")}function mi(e,t){const s=ui(t,"content-type").toLowerCase(),n=e.toString("utf8");if(s.includes("text/css"))return n.replace(/(#noVNC_transition\s*\{[\s\S]*?background\s*:\s*)#fff(\s+url\()/g,"$1#05090b$2").replace(/(#noVNC_transition\s*\{[\s\S]*?background-color\s*:\s*)#fff\b/g,"$1#05090b");if(s.includes("text/html")){const e=['<style id="task-handoff-kasm-loading-theme">',"html,body{background:#05090b!important;}","#noVNC_transition{background-color:#05090b!important;color:#31c6b6!important;}","#noVNC_transition::after{color:#9fb4bc!important;}","html.task-handoff-kasm-quiet-start #noVNC_control_bar{transition:none!important;}","html.task-handoff-kasm-quiet-start #noVNC_control_bar.noVNC_open{left:-100%!important;}","html.task-handoff-kasm-quiet-start.noVNC_right #noVNC_control_bar.noVNC_open{left:100%!important;}","html.task-handoff-kasm-quiet-start #noVNC_control_bar_handle::after,html.task-handoff-kasm-quiet-start .noVNC_panel{transition:none!important;}","</style>",'<script id="task-handoff-kasm-quiet-start">',"(function(){","var root=document.documentElement;","root.classList.add('task-handoff-kasm-quiet-start');","var attempts=0;","var timer=window.setInterval(function(){","var bar=document.getElementById('noVNC_control_bar');","if(bar){bar.classList.remove('noVNC_open');}","attempts+=1;","if(attempts>=20){window.clearInterval(timer);root.classList.remove('task-handoff-kasm-quiet-start');}","},100);","})();","<\/script>"].join("");return n.includes("</head>")?n.replace("</head>",`${e}</head>`):`${e}${n}`}return n}function hi(e){const t={};e.forEach((e,s)=>{t[s]=e});const s=e.getSetCookie?.();return s?.length&&(t["set-cookie"]=s),t}function gi(e){const t={};e.forEach((e,s)=>{t[s]=e});const s=e.getSetCookie?.();return s?.length&&(t["set-cookie"]=s),t}const fi="app-session.snapshot",yi="app-session.patch",vi="app-session.removed",Si=36e5,Ii=i.z.enum(["created","starting","running","stopping","stopped","exited","failed","closed","terminated","unknown"]),Ai=i.z.object({type:i.z.enum(["app-session","provider-session","adapter-key"]),id:i.z.string().trim().min(1).max(240),agent:i.z.string().trim().min(1).max(80).optional(),adapter:i.z.string().trim().min(1).max(80).optional(),key:i.z.string().trim().min(1).max(240).optional()}).strict(),bi=i.z.record(i.z.string(),i.z.unknown()).and(i.z.object({id:i.z.string().trim().min(1).max(160),appId:i.z.string().trim().min(1).max(160).optional(),title:i.z.string().trim().max(240).optional(),kind:i.z.string().trim().max(80).optional(),status:Ii.default("unknown"),bindings:i.z.array(Ai).max(40).default([]),workspace:i.z.object({cwd:i.z.string().trim().max(4096).optional()}).strict().optional(),createdAt:i.z.string().datetime().optional(),updatedAt:i.z.string().datetime().optional()})),_i=i.z.object({runningCount:i.z.number().int().min(0).default(0),problemCount:i.z.number().int().min(0).default(0),sessions:i.z.array(bi).default([]),updatedAt:i.z.string().datetime()}).strict();i.z.object({revision:i.z.number().int().min(0),lastEventAt:i.z.string().datetime(),snapshot:_i}).strict(),_i.pick({runningCount:!0,problemCount:!0,updatedAt:!0}).extend({revision:i.z.number().int().min(0).optional()});const wi=i.z.enum(["app-session-created","app-session-updated","app-session-deleted","app-session-recovered","control-action","heartbeat-sync","startup"]),Ti=i.z.object({instanceId:i.z.string().trim().min(1).max(160),nodeId:i.z.string().trim().min(1).max(160).optional(),snapshotRevision:i.z.number().int().min(0),previousRevision:i.z.number().int().min(0).optional(),eventSeq:i.z.number().int().min(1),traceId:i.z.string().trim().min(1).max(160),generatedAt:i.z.string().datetime(),reason:wi}).strict(),Ni=i.z.object({meta:Ti,snapshot:_i}).strict(),Oi=i.z.object({meta:Ti,session:bi}).strict(),Ei=i.z.object({meta:Ti,sessionId:i.z.string().trim().min(1).max(160),tombstone:bi.optional(),expiresAt:i.z.string().datetime().optional()}).strict(),zi=i.z.object({instanceId:i.z.string().trim().min(1).max(160),sinceRevision:i.z.number().int().min(0),latestRevision:i.z.number().int().min(0),syncRequired:i.z.boolean().default(!1),events:i.z.array(i.z.discriminatedUnion("type",[i.z.object({type:i.z.literal(fi),payload:Ni}).strict(),i.z.object({type:i.z.literal(yi),payload:Oi}).strict(),i.z.object({type:i.z.literal(vi),payload:Ei}).strict()])).default([])}).strict();function xi(e,t=(new Date).toISOString()){const s=e.map(e=>function(e){const t=function(e){const t=(e||"unknown").trim().toLowerCase();return"ended"===t?"closed":"terminating"===t?"stopping":Ii.options.includes(t)?t:"unknown"}("string"==typeof e.status?e.status:void 0),s="string"==typeof e.id?e.id:"",n=function(e){const t=Pi(e.workspace),s=Pi(e.tty),n=Pi(e.launch),r=Pi(e.ai),i=Pi(r.claude),o=Fi(t.cwd)||Fi(s.cwd)||Fi(i.cwd)||Fi(n.cwd);return o?{cwd:o}:void 0}(e),{workspace:r,...i}=e;return bi.parse({...i,status:t,bindings:Ci([...(o=e.bindings,Array.isArray(o)?o.flatMap(e=>{const t=Ai.safeParse(e);return t.success?[t.data]:[]}):[]),...s?[{type:"app-session",id:s}]:[],...ki(e)]),...n?{workspace:n}:{}});var o}(e));return _i.parse({runningCount:s.filter(e=>"running"===e.status).length,problemCount:s.filter(e=>"failed"===e.status).length,sessions:s,updatedAt:t})}function Di(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 ki(e){const t=Pi(e.ai),s=Pi(t.claude),n=Pi(t.appServer),r=[],i=Fi(s.short);i&&r.push({type:"adapter-key",adapter:"claude",agent:"claude",id:`short:${i}`,key:`short:${i}`});const o=Fi(s.providerSessionId);o&&r.push({type:"provider-session",agent:"claude",id:o});const a=Array.isArray(t.threadIds)?t.threadIds.filter(e=>"string"==typeof e&&Boolean(e.trim())):[],d=Fi(t.activeThreadId);for(const e of[...new Set([d,...a].filter(Boolean))])r.push({type:"provider-session",agent:"codex",id:e});const c=Fi(n.socketPath);return c&&r.push({type:"adapter-key",adapter:"codex-app-server",agent:"codex",id:`socket:${c}`,key:`socket:${c}`}),r}function Ci(e){const t=new Map;for(const s of e)t.set(Di(s),s);return[...t.values()]}function Pi(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}function Fi(e){return"string"==typeof e&&e.trim()?e.trim():""}function Ri(e){return e.readyState===(e.OPEN??1)}function Mi(e,t,s){e.close(function(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}(t),function(e){const t=Buffer.isBuffer(e)?e.toString("utf8"):"string"==typeof e?e:"";if(Buffer.byteLength(t,"utf8")<=123)return t;let s="";for(const e of t){const t=`${s}${e}`;if(Buffer.byteLength(t,"utf8")>123)break;s=t}return s}(s)||void 0)}function ji(e,t){e.send(t.data,{binary:t.isBinary})}function Hi(e,t){if(Ri(e))for(const s of t.splice(0))ji(e,s)}const Li=require("ws");function $i(e){return{method:e.method,headers:e.headers,body:e.streamRawRequest?e.rawRequest:e.requestBody,...e.streamRawRequest?{duplex:"half"}:{}}}function Ui(e){return a.Readable.fromWeb(e)}function qi(e){const t=e();return{...t,secrets:t.secrets?Object.fromEntries(Object.entries(t.secrets).map(([e,t])=>[e,{configured:void 0!==t&&""!==t,preview:"string"==typeof t?`${t.slice(0,6)}***`:void 0}])):void 0}}const Bi=i.z.object({id:i.z.string().trim().min(1).max(120),label:i.z.string().trim().min(1).max(120),projectRoot:i.z.string().trim().min(1).max(500),items:i.z.array(i.z.object({id:i.z.string().trim().min(1).max(120),type:i.z.enum(["file","dir"]),projectPath:i.z.string().trim().min(1).max(500),containerPath:i.z.string().trim().min(1).max(500)}).strip()).min(1).max(50)}).strip(),Vi=i.z.object({preset:Bi.optional()}).strip().default({}),Ki=i.z.object({appId:i.z.string().min(1).max(80).regex(/^[a-z0-9][a-z0-9_.-]*$/).optional(),title:i.z.string().trim().min(1).max(120).optional(),args:i.z.array(i.z.string().max(4096)).max(64).optional(),cwd:i.z.string().trim().min(1).max(512).optional(),env:i.z.record(i.z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),i.z.string().max(4096)).optional(),display:i.z.object({width:i.z.number().int().min(320).max(7680).optional(),height:i.z.number().int().min(240).max(4320).optional(),depth:i.z.union([i.z.literal(16),i.z.literal(24),i.z.literal(32)]).optional()}).optional(),displayTarget:i.z.object({mode:i.z.enum(["isolated","shared"]),id:i.z.string().trim().min(1).max(80).regex(/^[a-z0-9][a-z0-9._-]*$/).optional(),autoCreate:i.z.boolean().optional()}).optional()}).strict(),Gi=i.z.object({width:i.z.number().int().min(320).max(7680).optional(),height:i.z.number().int().min(240).max(4320).optional(),depth:i.z.number().int().min(8).max(32).optional()}).strip(),Wi=i.z.object({title:i.z.string().trim().min(1).max(120)}).strict(),Xi=i.z.object({source:i.z.object({type:i.z.literal("chat-gateway").default("chat-gateway"),channel:i.z.enum(["web","telegram","wechat","dingding"]),chatSessionId:i.z.string().trim().min(1).max(240),userId:i.z.string().trim().max(240).optional()}).strict(),message:i.z.object({text:i.z.string().trim().max(2e4).default(""),attachments:i.z.array(i.z.record(i.z.string(),i.z.unknown())).default([])}).strict(),routing:i.z.object({projectId:i.z.string().trim().min(1).max(120),instanceId:i.z.string().trim().min(1).max(120),conversationId:i.z.number().int().positive().optional()}).strict()}).strict(),Ji=i.z.object({name:i.z.string().trim().min(1).max(160),description:i.z.string().trim().max(1e3).optional(),source:je,action:He,policy:Le.partial().optional(),deployment:i.z.object({deploymentId:i.z.string().trim().min(1).max(240).optional(),origin:i.z.enum(["control-plane","controlled-instance"]).optional(),enabled:i.z.boolean().optional(),target:Ue.optional(),localName:i.z.string().trim().min(1).max(160).optional()}).strict().optional()}).strict(),Yi=i.z.object({name:i.z.string().trim().min(1).max(160).optional(),description:i.z.string().trim().max(1e3).nullable().optional()}).strict(),Qi=i.z.object({promptOverride:i.z.string().trim().min(1).max(2e4).optional(),eventSummary:i.z.string().trim().max(1e3).optional(),deploymentId:i.z.string().trim().min(1).max(240).optional()}).strict().default({});function Zi(e){return e instanceof i.z.ZodError?e.issues.map(e=>`${e.path.join(".")||"body"}: ${e.message}`).join("; "):e instanceof Error?e.message:String(e)}function eo(e,t){if(t instanceof i.z.ZodError)return e.code(400).send({error:As.parse({code:"AI_SESSION_CONTROL_INVALID",message:t.issues.map(e=>`${e.path.join(".")||"body"}: ${e.message}`).join("; ")})});const s=t&&"object"==typeof t?t:{},n="string"==typeof s.code?s.code:"AI_SESSION_CONTROL_FAILED",r="number"==typeof s.statusCode?s.statusCode:"AI_SESSION_NOT_FOUND"===n?404:400;return e.code(r).send({error:As.parse({code:n,message:t instanceof Error?t.message:String(t)})})}function to(e,t=!1){const s=process.env[e];return void 0===s||""===s?t:["1","true","yes","on"].includes(s.toLowerCase())}function so(e){return process.env.TASK_HANDOFF_RECEIVER_LOG||s.join(e,"receiver.log")}function no(e){return Array.isArray(e)?e.map(no):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,null===t?void 0:no(t)])):e}function ro(e,s=200){const n=Math.min(Math.max(1,Number(s)||200),1e3),r=t.readFileSync(e,"utf8").split(/\r?\n/);return{path:e,lineCount:r.length,tail:r.slice(-n).join("\n")}}async function io(e={}){const r=e.socketPath||N,a=(new Date).toISOString(),m=function(){const e=et();return{paths:e,channel:(t,n="default")=>new me(s.join(e.channelsDir,`${t}.${n}.json`),{schema:tt,defaultValue:()=>({schemaVersion:1,channel:t,instanceId:n,enabled:!1})}),conversationIndex:()=>new me(s.join(e.conversationsDir,"index.json"),{schema:st,defaultValue:()=>({schemaVersion:1,defaultConversationId:1,nextConversationId:2,items:[]})}),appSessionIndex:()=>new me(s.join(e.appSessionsDir,"index.json"),{schema:nt,defaultValue:()=>({schemaVersion:1,items:[]})})}}();!function(e,t){if(to("TASK_HANDOFF_DIAGNOSTIC_LOGS"))try{oe(so(e),{event:"controlled_instance_start",component:"controlled-instance",controlMode:process.env.TASK_HANDOFF_CONTROL_MODE,diagnosticLogs:process.env.TASK_HANDOFF_DIAGNOSTIC_LOGS,dataDir:t,logDir:e,receiverLog:so(e),process:{pid:process.pid,ppid:process.ppid,cwd:process.cwd(),argv:process.argv,parent:ie(process.ppid),env:re()}})}catch{}}(m.paths.logDir,m.paths.dataDir);const g=function(e){if("off"===process.env.TASK_HANDOFF_WEB_AUTH)return{enabled:!1};const n=process.env.TASK_HANDOFF_WEB_TOKEN?.trim();if(n)return{enabled:!0,source:"env",token:n};const r=function(e){try{return t.readFileSync(e,"utf8").trim()||void 0}catch(e){if(e&&"object"==typeof e&&"code"in e&&"ENOENT"===e.code)return;throw e}}(e.webTokenPath);if(r)return{enabled:!0,source:"file",token:r,tokenFile:e.webTokenPath};if("required"===process.env.TASK_HANDOFF_WEB_AUTH){const n=h.randomBytes(24).toString("base64url");return function(e,n){t.mkdirSync(s.dirname(e),{recursive:!0}),t.writeFileSync(e,`${n}\n`,{mode:384})}(e.webTokenPath,n),{enabled:!0,source:"generated",token:n,tokenFile:e.webTokenPath}}return{enabled:!1,tokenFile:e.webTokenPath}}(m.paths),f=new ur,y=e.receiverProcess||new Ir(r,m.paths.logDir),v=new Sr(r),S=e.appRuntime||new Pt(m.paths),I=_n(),b=new Ht(I),w=new Ne(m.paths),O=new Qe(m.paths),E=new Ee(O,v,b),z=new ze(O,E,m.paths,(e,t)=>f.publish(e,t)),x=new er(function(e=process.env){return{controlMode:"controlled"===e.TASK_HANDOFF_CONTROL_MODE?"controlled":"standalone",nodeAgentUrl:e.TASK_HANDOFF_NODE_AGENT_URL,registrationToken:e.TASK_HANDOFF_REGISTRATION_TOKEN,instanceId:e.TASK_HANDOFF_INSTANCE_ID,instanceName:e.TASK_HANDOFF_INSTANCE_NAME||e.HOSTNAME||"controlled-instance",projectId:e.TASK_HANDOFF_PROJECT_ID,nodeId:e.TASK_HANDOFF_NODE_ID,runtimeId:e.TASK_HANDOFF_RUNTIME_ID,imageId:e.TASK_HANDOFF_IMAGE_ID,heartbeatIntervalMs:Number(e.TASK_HANDOFF_HEARTBEAT_INTERVAL_MS)||1e4}}(),()=>ni(S,y,v,m.paths,I,O)),D=u({logger:e.logger??!0,bodyLimit:67108864});await D.register(p),function(e,t){e.addHook("preHandler",async(e,s)=>{if(t.enabled&&"/api/health"!==e.url&&"/api/auth/status"!==e.url&&e.url.startsWith("/api/")&&function(e){const t=(e.headers.authorization||"").match(/^Bearer\s+(.+)$/i);if(t?.[1])return t[1];try{return new URL(e.url,"http://localhost").searchParams.get("token")||void 0}catch{return}}(e)!==t.token)return s.code(401).send({error:{code:"UNAUTHORIZED",message:"Missing or invalid web token."}})})}(D,g),y.on("start",e=>f.publish("receiver.started",e)),y.on("exit",e=>f.publish("receiver.exited",e)),D.addHook("onReady",async()=>{x.enabled()&&await x.start()}),D.addHook("onClose",async()=>{x.stop(),z.stop()});let k="",C=0,P=0;const F=[],R=new Set,M=new Map;let j,H="",L=0,$=0;const U=[];let q=xi([]);const B=new Tn,V=new Zn(I),K=new Dn(I);b.register(V),b.register(K),B.register(new Nn),B.register(K),B.register(new On),B.register(V);const G=()=>{const e=S.sharedCodexAppServerInfo();return e?[...S.listSessions(),{id:"__shared_codex_app_server__",appId:"codex",title:"Codex app-server",status:"running",createdAt:a,ai:{appServer:e}}]:S.listSessions()};let W;const X=async(e="discovery-scan")=>{W||(W=(async()=>{const e=G();I.reconcileAppSessionBindings(e),await B.refresh({registry:I,appSessions:e})})().finally(()=>{W=void 0})),await W,Y(e)},J=()=>{const e=Date.now()-36e5;for(;F.length&&F[0].createdAtMs<e;)F.shift()},Y=(e="provider-event")=>{const t=I.boundSnapshot(G()),s=JSON.stringify(t.sessions);if(s!==k){k=s,C+=1;const n=((e,t)=>({meta:{instanceId:process.env.TASK_HANDOFF_INSTANCE_ID||"standalone",nodeId:process.env.TASK_HANDOFF_NODE_ID,snapshotRevision:C,previousRevision:C>0?C-1:void 0,eventSeq:++P,traceId:`ais_evt_${Date.now().toString(36)}_${Math.random().toString(16).slice(2,10)}`,generatedAt:(new Date).toISOString(),reason:t},snapshot:e}))(t,e);(e=>{F.push({type:os,payload:e,createdAtMs:Date.now()}),J()})(n),f.publish(os,n),D.log.info({traceId:n.meta.traceId,instanceId:n.meta.instanceId,snapshotRevision:n.meta.snapshotRevision,eventSeq:n.meta.eventSeq,reason:e,sessionCount:t.sessions.length,runningCount:t.runningCount,waitingCount:t.waitingCount},"ai-session.snapshot.published"),z.handleAiSessions(t)}},Q=()=>{const e=Date.now()-Si;for(;U.length&&U[0].createdAtMs<e;)U.shift()},Z=e=>({instanceId:process.env.TASK_HANDOFF_INSTANCE_ID||"standalone",nodeId:process.env.TASK_HANDOFF_NODE_ID,snapshotRevision:L,previousRevision:L>0?L-1:void 0,eventSeq:++$,traceId:`aps_evt_${Date.now().toString(36)}_${Math.random().toString(16).slice(2,10)}`,generatedAt:(new Date).toISOString(),reason:e}),ee=(e,t)=>({meta:Z(t),session:e}),te=(e,t,s)=>({meta:Z(s),sessionId:e,tombstone:t,expiresAt:new Date(Date.now()+Si).toISOString()}),se=(e,t,s)=>{(e=>{U.push({...e,createdAtMs:Date.now()}),Q()})(e),f.publish(e.type,e.payload),D.log.info({traceId:e.payload.meta.traceId,instanceId:e.payload.meta.instanceId,snapshotRevision:e.payload.meta.snapshotRevision,eventSeq:e.payload.meta.eventSeq,reason:s,eventType:e.type,sessionCount:t.sessions.length,runningCount:t.runningCount,problemCount:t.problemCount},"app-session.event.published")},ne=e=>{Q();const t=L,s=process.env.TASK_HANDOFF_INSTANCE_ID||"standalone";if(e>t)return zi.parse({instanceId:s,sinceRevision:e,latestRevision:t,syncRequired:!0,events:[]});if(e===t)return zi.parse({instanceId:s,sinceRevision:e,latestRevision:t,syncRequired:!1,events:[]});const n=U.filter(t=>t.payload.meta.snapshotRevision>e),r=n[0]?.payload.meta.snapshotRevision,i=!n.length||r!==e+1;return zi.parse({instanceId:s,sinceRevision:e,latestRevision:t,syncRequired:i,events:i?[]:n.map(e=>({type:e.type,payload:e.payload}))})},ae=e=>{J();const t=C;if(e>t)return Fs.parse({instanceId:process.env.TASK_HANDOFF_INSTANCE_ID||"standalone",sinceRevision:e,latestRevision:t,syncRequired:!0,events:[]});if(e===t)return Fs.parse({instanceId:process.env.TASK_HANDOFF_INSTANCE_ID||"standalone",sinceRevision:e,latestRevision:t,syncRequired:!1,events:[]});const s=F.filter(t=>t.payload.meta.snapshotRevision>e),n=s[0]?.payload.meta.snapshotRevision,r=!s.length||n!==e+1;return Fs.parse({instanceId:process.env.TASK_HANDOFF_INSTANCE_ID||"standalone",sinceRevision:e,latestRevision:t,syncRequired:r,events:r?[]:s.map(e=>({type:e.type,payload:e.payload}))})},de=async e=>{if(R.has(e))return;const t=I.get(e);if(t&&"idle"===t.status&&I.nextQueuedMessage(e)){R.add(e);try{await b.sendNextQueuedMessage(e)}catch(t){D.log.warn({err:t,sessionId:e},"failed to drain AI session message queue")}finally{R.delete(e),Y("control-action")}}};let ce;const pe=I.onChange(()=>{ce||(ce=setTimeout(()=>{ce=void 0,Y()},Number(process.env.TASK_HANDOFF_AI_SESSION_PUBLISH_DEBOUNCE_MS)||50));for(const e of I.list()){const t=M.get(e.id);M.set(e.id,e.status),t&&"idle"!==t&&"idle"===e.status&&e.queue.pendingCount>0&&de(e.id)}});D.addHook("onReady",async()=>{if(z.start(),to("TASK_HANDOFF_CODEX_APP_SERVER",!1))try{S.ensureSharedCodexAppServer()}catch(e){D.log.warn({err:e},"failed to start shared Codex app-server")}}),D.addHook("onReady",async()=>{await X("startup"),j=setInterval(()=>{X()},Number(process.env.TASK_HANDOFF_AI_SESSION_SCAN_INTERVAL_MS)||5e3)}),D.addHook("onClose",async()=>{pe(),ce&&(clearTimeout(ce),ce=void 0),j&&(clearInterval(j),j=void 0),V.stop(),K.stop()});const ue=(e,t)=>{(e=>{const t=xi(S.listSessions()),s=JSON.stringify(t.sessions);if(s===H)return void D.log.info({instanceId:process.env.TASK_HANDOFF_INSTANCE_ID||"standalone",snapshotRevision:L,reason:e,sessionCount:t.sessions.length},"app-session.snapshot.skipped-unchanged");H=s;const n=function(e,t){const s=new Map(e.sessions.map(e=>[e.id,e])),n=new Map(t.sessions.map(e=>[e.id,e])),r=[];for(const e of t.sessions){const t=s.get(e.id);t&&JSON.stringify(t)===JSON.stringify(e)||r.push({type:"upsert",session:e})}for(const t of e.sessions)n.has(t.id)||r.push({type:"removed",sessionId:t.id,tombstone:t});return r}(q,t);if(0===L||1!==n.length){L+=1;const s=((e,t)=>({meta:{instanceId:process.env.TASK_HANDOFF_INSTANCE_ID||"standalone",nodeId:process.env.TASK_HANDOFF_NODE_ID,snapshotRevision:L,previousRevision:L>0?L-1:void 0,eventSeq:++$,traceId:`aps_evt_${Date.now().toString(36)}_${Math.random().toString(16).slice(2,10)}`,generatedAt:(new Date).toISOString(),reason:t},snapshot:e}))(t,e);se({type:fi,payload:s},t,e)}else{L+=1;const s=n[0],r="removed"===s.type?{type:vi,payload:te(s.sessionId,s.tombstone,e)}:{type:yi,payload:ee(s.session,e)};se(r,t,e)}q=t})(e),X("app-session-recovered"===e?"discovery-scan":e).catch(s=>{D.log.warn({err:s,reason:e,sessionId:t.id},"failed to refresh AI sessions after app session event")})};y.on("log",e=>f.publish("receiver.log",{message:e})),S.on("created",e=>ue("app-session-created",e)),S.on("updated",e=>ue("app-session-updated",e)),S.on("deleted",e=>ue("app-session-deleted",e)),D.addHook("onClose",async()=>{await y.stopAndWait(),S.stopAll()}),!Jr()&&(e.receiverAutoStart??to("TASK_HANDOFF_RECEIVER_AUTO_START"))&&D.addHook("onReady",async()=>{cr(m.paths.channelsDir,m.paths.configPath),y.start()});const le=function(){const e=process.env.TASK_HANDOFF_NOVNC_ROOT?.trim();if(e){const n=s.resolve(e);return t.existsSync(s.join(n,"vnc.html"))?n:void 0}const n=["/usr/share/novnc","/usr/share/noVNC","/usr/local/share/novnc","/usr/local/share/noVNC"].filter(e=>Boolean(e));for(const e of n){const n=s.resolve(e);if(t.existsSync(s.join(n,"vnc.html")))return n}}();le?await D.register(c,{root:le,prefix:"/api/novnc/",decorateReply:!1}):D.get("/api/novnc/*",async(e,t)=>t.code(404).send({error:{code:"NOVNC_NOT_FOUND",message:"noVNC static files were not found. Install noVNC or set TASK_HANDOFF_NOVNC_ROOT to a directory containing vnc.html."}}));const he=s.resolve(e.staticDir||process.env.TASK_HANDOFF_WEB_STATIC_DIR||function(){const e=[s.resolve(process.cwd(),"packages","controlled-instance-ui","dist"),s.resolve(__dirname,"..","packages","controlled-instance-ui","dist"),s.resolve(__dirname,"..","..","..","controlled-instance-ui","dist"),s.resolve(__dirname,"..","..","..","..","packages","controlled-instance-ui","dist")];return e.find(e=>t.existsSync(e))||e[0]}());t.existsSync(he)&&await D.register(c,{root:he,prefix:"/"}),D.get("/api/health",async()=>({data:{ok:!0,version:Wr(),startedAt:a}})),D.get("/api/auth/status",async()=>({data:{enabled:g.enabled,source:g.source,tokenFile:g.tokenFile}})),D.get("/api/events",{websocket:!0},e=>{f.connect(e),f.send(e,"events.connected",{});const t=I.boundSnapshot(G()),s={meta:{instanceId:process.env.TASK_HANDOFF_INSTANCE_ID||"standalone",nodeId:process.env.TASK_HANDOFF_NODE_ID,snapshotRevision:C,eventSeq:P,traceId:`ais_evt_${Date.now().toString(36)}_${Math.random().toString(16).slice(2,10)}`,generatedAt:(new Date).toISOString(),reason:"startup"},snapshot:t};f.send(e,os,s)}),D.get("/api/status",async()=>{const e=A();return{data:{receiverReady:y.status().running,receiver:y.status(),socketPath:r,defaultConversationId:Number(e.defaultConversationId)||T,pendingTaskCount:await Qr(v),runningAppCount:S.runningSessionCount(),storage:m.paths}}}),D.get("/api/instance/status",async()=>{const e=A(),t=await ni(S,y,v,m.paths,I,O);return{data:{id:process.env.TASK_HANDOFF_INSTANCE_ID,name:process.env.TASK_HANDOFF_INSTANCE_NAME||n.hostname(),...t,defaultConversationId:Number(e.defaultConversationId)||T,startedAt:a}}}),D.get("/api/instance/capabilities",async()=>({data:ti(S)})),D.get("/api/workspace/status",async()=>({data:ei(m.paths)})),D.get("/api/ai-sessions",async e=>{const t=void 0===e.query.sinceRevision?void 0:Number(e.query.sinceRevision);return Number.isInteger(t)&&t>=0?{data:ae(t)}:{data:I.boundSnapshot(G(),100)}}),D.get("/api/ai-sessions/state",async()=>({data:{revision:C,lastEventAt:F.at(-1)?.payload.meta.generatedAt||a,snapshot:I.boundSnapshot(G(),100)}})),D.get("/api/triggers",async()=>({data:O.list()})),D.get("/api/triggers/:configHash",async(e,t)=>{const s=O.get(e.params.configHash);return s?{data:s}:t.code(404).send({error:{code:"TRIGGER_NOT_FOUND",message:"Trigger not found."}})}),D.post("/api/triggers",async(e,t)=>{try{const t=Ji.parse(e.body||{}),s=O.create(t);return z.restart(),f.publish("trigger.created",s),f.publish("trigger.updated",si(O)),{data:s}}catch(e){return t.code(400).send({error:{code:"TRIGGER_INVALID",message:Zi(e)}})}}),D.patch("/api/triggers/:configHash",async(e,t)=>{try{const s=Yi.parse(e.body||{}),n=O.patch(e.params.configHash,s);return n?(z.restart(),f.publish("trigger.updated",O.get(e.params.configHash)),{data:n}):t.code(404).send({error:{code:"TRIGGER_NOT_FOUND",message:"Trigger not found."}})}catch(e){return t.code(400).send({error:{code:"TRIGGER_INVALID",message:Zi(e)}})}}),D.delete("/api/triggers/:configHash",async(e,t)=>{const s=O.delete(e.params.configHash);return s?(z.restart(),f.publish("trigger.deleted",{configHash:e.params.configHash}),f.publish("trigger.updated",si(O)),{data:{deleted:s}}):t.code(404).send({error:{code:"TRIGGER_NOT_FOUND",message:"Trigger not found."}})}),D.delete("/api/triggers/:configHash/deployments/:deploymentId",async(e,t)=>{const s=O.deleteDeployment(e.params.configHash,e.params.deploymentId);return s?(z.restart(),f.publish("trigger.deployment.deleted",{configHash:e.params.configHash,deploymentId:e.params.deploymentId}),f.publish("trigger.updated",si(O)),{data:{deleted:s}}):t.code(404).send({error:{code:"TRIGGER_DEPLOYMENT_NOT_FOUND",message:"Trigger deployment not found."}})}),D.post("/api/triggers/:configHash/enable",async(e,t)=>{const s=O.setEnabled(e.params.configHash,!0);return s?(z.restart(),f.publish("trigger.enabled",s),f.publish("trigger.updated",si(O)),{data:s}):t.code(404).send({error:{code:"TRIGGER_NOT_FOUND",message:"Trigger not found."}})}),D.post("/api/triggers/:configHash/disable",async(e,t)=>{const s=O.setEnabled(e.params.configHash,!1);return s?(z.restart(),f.publish("trigger.disabled",s),f.publish("trigger.updated",si(O)),{data:s}):t.code(404).send({error:{code:"TRIGGER_NOT_FOUND",message:"Trigger not found."}})}),D.post("/api/triggers/:configHash/run",async(e,t)=>{try{f.publish("trigger.run.started",{configHash:e.params.configHash});const t=await async function(e,t,s,n={}){const r=Qi.parse(n||{}),i=e.get(s);if(!i)throw Object.assign(new Error("Trigger not found."),{code:"TRIGGER_NOT_FOUND",statusCode:404});const o=r.deploymentId?i.deployments.find(e=>(e.deploymentId||e.configHash)===r.deploymentId):i.deployments[0];if(!o)throw Object.assign(new Error("Trigger has no deployment."),{code:"TRIGGER_DEPLOYMENT_NOT_FOUND",statusCode:404});return t.execute({config:i.config,deployment:o,eventType:"manual",eventSummary:r.eventSummary,promptOverride:r.promptOverride})}(O,E,e.params.configHash,e.body||{});return f.publish("trigger.run.completed",t),f.publish("trigger.updated",si(O)),{data:t}}catch(s){const n=s&&"object"==typeof s&&"code"in s?String(s.code):"TRIGGER_RUN_FAILED";return f.publish("trigger.run.failed",{configHash:e.params.configHash,error:Zi(s)}),t.code("TRIGGER_NOT_FOUND"===n?404:"RECEIVER_UNAVAILABLE"===n?503:400).send({error:{code:n,message:Zi(s)}})}}),D.get("/api/triggers/runs",async()=>({data:O.list().recentRuns})),D.get("/api/ai-sessions/:id",async(e,t)=>{const s=I.get(e.params.id);return s?{data:s}:t.code(404).send({error:{code:"AI_SESSION_NOT_FOUND",message:"AI session not found."}})}),D.get("/api/ai-sessions/:id/turns",async(e,t)=>{const s=I.get(e.params.id);if(!s)return t.code(404).send({error:{code:"AI_SESSION_NOT_FOUND",message:"AI session not found."}});const n=String(e.query.afterTurnId||"").trim(),r=Number(e.query.afterRevision),i=s.turns||[],o=n?i.findIndex(e=>e.id===n):-1,a=i.filter(e=>!n||o<0||(e.id!==n?i.findIndex(t=>t.id===e.id)>o:!!Number.isFinite(r)&&e.revision>r)),d=a.at(-1);return{data:{sessionId:s.id,turns:a,nextCursor:d?{turnId:d.id,revision:d.revision}:n?{turnId:n,revision:Number.isFinite(r)?r:0}:void 0}}}),D.get("/api/ai-sessions/:id/transcript",async(e,t)=>{const s=I.get(e.params.id);if(!s?.transcriptPath)return t.code(404).send({error:{code:"AI_SESSION_TRANSCRIPT_NOT_FOUND",message:"AI session transcript not found."}});try{return{data:ro(s.transcriptPath,Number(e.query.tail)||200)}}catch(e){return t.code(404).send({error:{code:"AI_SESSION_TRANSCRIPT_NOT_READABLE",message:e instanceof Error?e.message:String(e)}})}}),D.post("/api/ai-sessions/:id/messages",async(e,t)=>{try{const t=vs.parse(e.body||{}),s=Os.parse(await b.sendMessage(e.params.id,t));return Y("control-action"),{data:s}}catch(e){return eo(t,e)}}),D.get("/api/ai-sessions/:id/queue",async(e,t)=>{const s=I.get(e.params.id);return s?{data:s.queue}:t.code(404).send({error:{code:"AI_SESSION_NOT_FOUND",message:"AI session not found."}})}),D.post("/api/ai-sessions/:id/queue/:queueId/steer",async(e,t)=>{try{const t=Os.parse(await b.steerQueuedMessage(e.params.id,e.params.queueId));return Y("control-action"),{data:t}}catch(e){return eo(t,e)}}),D.post("/api/ai-sessions/:id/queue/:queueId/retry",async(e,t)=>{try{const t=b.retryQueuedMessage(e.params.id,e.params.queueId);return Y("control-action"),{data:t}}catch(e){return eo(t,e)}}),D.delete("/api/ai-sessions/:id/queue/:queueId",async(e,t)=>{try{const t=b.removeQueuedMessage(e.params.id,e.params.queueId);return Y("control-action"),{data:t}}catch(e){return eo(t,e)}}),D.patch("/api/ai-sessions/:id/queue/reorder",async(e,t)=>{try{const t=Is.parse(e.body||{}),s=b.reorderQueuedMessages(e.params.id,t.queueIds);return Y("control-action"),{data:s}}catch(e){return eo(t,e)}}),D.post("/api/ai-sessions/:id/interrupt",async(e,t)=>{try{const t=Os.parse(await b.interrupt(e.params.id));return Y("control-action"),{data:t}}catch(e){return eo(t,e)}}),D.post("/api/ai-sessions/:id/approval",async(e,t)=>{try{const t=Ss.parse(e.body||{}),s=Os.parse(await b.resolveApproval(e.params.id,t.decision));return Y("control-action"),{data:s}}catch(e){return eo(t,e)}}),D.get("/api/diagnostics",async()=>({data:Yr(m.paths,le)})),D.get("/api/settings",async()=>({data:A()})),function(e,{conversations:t,events:s}){e.get("/api/conversations",async()=>({data:t.list()})),e.post("/api/conversations",async(e,n)=>{try{const n=t.create(e.body||{});return s.publish("conversation.created",n),{data:n}}catch(e){const t=tr(e,"CONVERSATION_CREATE_FAILED");return n.code("CONVERSATION_EXISTS"===t?409:400).send({error:{code:t,message:sr(e)}})}}),e.get("/api/conversations/:id",async(e,s)=>{try{const n=t.get(Oe(e.params.id));return n?{data:n}:s.code(404).send({error:{code:"CONVERSATION_NOT_FOUND",message:"Conversation not found."}})}catch(e){const t=tr(e,"CONVERSATION_GET_FAILED");return s.code("CONVERSATION_ID_INVALID"===t?400:404).send({error:{code:t,message:sr(e)}})}}),e.patch("/api/conversations/:id",async(e,n)=>{try{const n=t.update(Oe(e.params.id),e.body||{});return s.publish("conversation.updated",n),{data:n}}catch(e){const t=tr(e,"CONVERSATION_UPDATE_FAILED");return n.code("CONVERSATION_NOT_FOUND"===t?404:400).send({error:{code:t,message:sr(e)}})}}),e.post("/api/conversations/:id/use",async(e,n)=>{try{const n=t.use(Oe(e.params.id));return s.publish("conversation.default.updated",n),{data:n}}catch(e){const t=tr(e,"CONVERSATION_USE_FAILED");return n.code("CONVERSATION_NOT_FOUND"===t?404:400).send({error:{code:t,message:sr(e)}})}}),e.post("/api/conversations/:id/close",async(e,n)=>{try{const n=t.close(Oe(e.params.id));return s.publish("conversation.closed",n),{data:n}}catch(e){const t=tr(e,"CONVERSATION_CLOSE_FAILED");return n.code("CONVERSATION_NOT_FOUND"===t?404:400).send({error:{code:t,message:sr(e)}})}}),e.post("/api/conversations/:id/reopen",async(e,n)=>{try{const n=t.reopen(Oe(e.params.id));return s.publish("conversation.reopened",n),{data:n}}catch(e){const t=tr(e,"CONVERSATION_REOPEN_FAILED");return n.code("CONVERSATION_NOT_FOUND"===t?404:400).send({error:{code:t,message:sr(e)}})}}),e.delete("/api/conversations/:id",async(e,n)=>{try{const n=t.delete(Oe(e.params.id));return s.publish("conversation.deleted",n),{data:n}}catch(e){const t=tr(e,"CONVERSATION_DELETE_FAILED"),s="CONVERSATION_NOT_FOUND"===t?404:"CONVERSATION_DEFAULT"===t?409:400;return n.code(s).send({error:{code:t,message:sr(e)}})}})}(D,{conversations:w,events:f}),D.post("/api/receiver/start",async(e,t)=>Jr()?t.code(409).send({error:{code:"RECEIVER_MANAGED_BY_CONTROL_PLANE",message:"Receiver chat bindings are managed by the control plane while this instance is node-agent controlled."}}):(cr(m.paths.channelsDir,m.paths.configPath),{data:y.start()})),D.post("/api/receiver/stop",async()=>({data:y.stop()})),D.get("/api/receiver/logs",async e=>{const t=Number(e.query.maxBytes||65536),s=Number.isFinite(t)?Math.min(Math.max(1024,t),524288):65536;return{data:y.readLogs(s)}}),D.get("/api/receiver/status",async()=>({data:{...y.status(),pendingCount:await Qr(v)}})),D.post("/api/receiver/messages",async(e,t)=>{try{const s=Xi.parse(e.body);return s.message.text.trim()?{data:await v.message({channel:s.source.channel,chatSessionId:s.source.chatSessionId,userId:s.source.userId,text:s.message.text,attachments:s.message.attachments,conversationId:s.routing.conversationId})}:t.code(400).send({error:{code:"RECEIVER_MESSAGE_INVALID",message:"Message text is required."}})}catch(e){const s=e&&"object"==typeof e&&"code"in e?String(e.code):"RECEIVER_MESSAGE_INVALID";return t.code("RECEIVER_UNAVAILABLE"===s?503:400).send({error:{code:s,message:Zi(e)}})}});const ge=async(e,t)=>{try{return{data:await v.pendingList()}}catch(e){const s=e&&"object"==typeof e&&"code"in e?String(e.code):"RECEIVER_CONTROL_FAILED";return t.code("RECEIVER_UNAVAILABLE"===s?503:400).send({error:{code:s,message:e instanceof Error?e.message:String(e)}})}};D.get("/api/tasks/pending",ge),D.get("/api/receiver/pending",ge),D.post("/api/tasks/:id/reply",async(e,t)=>{const s=Number(e.params.id),n=e.body?.markdown;if(!Number.isInteger(s)||s<=0||!n?.trim())return t.code(400).send({error:{code:"TASK_REPLY_INVALID",message:"Task id and markdown are required."}});try{return{data:await v.reply(s,n)}}catch(e){const s=e&&"object"==typeof e&&"code"in e?String(e.code):"RECEIVER_CONTROL_FAILED";return t.code("PENDING_TASK_NOT_FOUND"===s?404:"RECEIVER_UNAVAILABLE"===s?503:400).send({error:{code:s,message:e instanceof Error?e.message:String(e)}})}}),D.post("/api/receiver/pending/:id/reply",async(e,t)=>{const s=Number(e.params.id),n=e.body?.markdown;if(!Number.isInteger(s)||s<=0||!n?.trim())return t.code(400).send({error:{code:"TASK_REPLY_INVALID",message:"Task id and markdown are required."}});try{return{data:await v.reply(s,n)}}catch(e){const s=e&&"object"==typeof e&&"code"in e?String(e.code):"RECEIVER_CONTROL_FAILED";return t.code("PENDING_TASK_NOT_FOUND"===s?404:"RECEIVER_UNAVAILABLE"===s?503:400).send({error:{code:s,message:e instanceof Error?e.message:String(e)}})}}),D.post("/api/tasks/:id/drop",async(e,t)=>{const s=Number(e.params.id);if(!Number.isInteger(s)||s<=0)return t.code(400).send({error:{code:"TASK_ID_INVALID",message:"Task id must be a positive integer."}});try{return{data:await v.drop(s)}}catch(e){const s=e&&"object"==typeof e&&"code"in e?String(e.code):"RECEIVER_CONTROL_FAILED";return t.code("PENDING_TASK_NOT_FOUND"===s?404:"RECEIVER_UNAVAILABLE"===s?503:400).send({error:{code:s,message:e instanceof Error?e.message:String(e)}})}});for(const[e,t]of[["approve","allow"],["deny","deny"],["skip","skip"]])D.post(`/api/tasks/:id/${e}`,async(e,s)=>{const n=Number(e.params.id);if(!Number.isInteger(n)||n<=0)return s.code(400).send({error:{code:"TASK_ID_INVALID",message:"Task id must be a positive integer."}});try{return{data:await v.approval(n,t)}}catch(e){const t=e&&"object"==typeof e&&"code"in e?String(e.code):"RECEIVER_CONTROL_FAILED";return s.code("PENDING_TASK_NOT_FOUND"===t?404:"RECEIVER_UNAVAILABLE"===t?503:400).send({error:{code:t,message:e instanceof Error?e.message:String(e)}})}}),D.post(`/api/receiver/pending/:id/${e}`,async(e,s)=>{const n=Number(e.params.id);if(!Number.isInteger(n)||n<=0)return s.code(400).send({error:{code:"TASK_ID_INVALID",message:"Task id must be a positive integer."}});try{return{data:await v.approval(n,t)}}catch(e){const t=e&&"object"==typeof e&&"code"in e?String(e.code):"RECEIVER_CONTROL_FAILED";return s.code("PENDING_TASK_NOT_FOUND"===t?404:"RECEIVER_UNAVAILABLE"===t?503:400).send({error:{code:t,message:e instanceof Error?e.message:String(e)}})}});D.post("/api/receiver/pending/:id/approval",async(e,t)=>{const s=Number(e.params.id),n=e.body?.decision;if(!Number.isInteger(s)||s<=0||!n)return t.code(400).send({error:{code:"TASK_APPROVAL_INVALID",message:"Task id and approval decision are required."}});try{return{data:await v.approval(s,n)}}catch(e){const s=e&&"object"==typeof e&&"code"in e?String(e.code):"RECEIVER_CONTROL_FAILED";return t.code("PENDING_TASK_NOT_FOUND"===s?404:"RECEIVER_UNAVAILABLE"===s?503:400).send({error:{code:s,message:e instanceof Error?e.message:String(e)}})}}),D.get("/api/apps/catalog",async()=>({data:S.catalog()})),D.get("/api/config-sync/presets",async()=>({data:_r()})),D.post("/api/config-sync/:direction/:preset",async(e,t)=>{const s=e.params.direction;if("import"!==s&&"export"!==s)return t.code(400).send({error:{code:"CONFIG_SYNC_DIRECTION_INVALID",message:"Config sync direction must be import or export."}});try{const t=Vi.parse(e.body||{});return{data:Tr(s,e.params.preset,t.preset)}}catch(e){const s=e&&"object"==typeof e?e:{};return t.code("number"==typeof s.statusCode?s.statusCode:500).send({error:{code:"string"==typeof s.code?s.code:"CONFIG_SYNC_FAILED",message:e instanceof Error?e.message:String(e)}})}}),D.get("/api/apps/catalog/custom",async(e,t)=>{const s=S.customCatalog();return s.error||!s.data?t.code(400).send({error:s.error||{code:"APP_CATALOG_INVALID",message:"Custom app catalog is invalid."}}):{data:s.data}}),D.patch("/api/apps/catalog/custom",async(e,t)=>{try{return{data:S.saveCustomCatalog(e.body?.items||[])}}catch(e){return t.code(400).send({error:{code:"APP_CATALOG_INVALID",message:e instanceof Error?e.message:String(e)}})}}),D.get("/api/apps/sessions",async(e,t)=>{if(void 0!==e.query.sinceRevision){const s=Number(e.query.sinceRevision);return!Number.isInteger(s)||s<0?t.code(400).send({error:{code:"APP_SESSION_DELTA_INVALID",message:"sinceRevision must be a non-negative integer."}}):{data:ne(s)}}return{data:S.listSessions()}}),D.get("/api/apps/sessions/state",async()=>({data:{revision:L,lastEventAt:U.at(-1)?.payload.meta.generatedAt||a,snapshot:xi(S.listSessions())}})),D.post("/api/apps/sessions",async(e,t)=>{try{const t=function(e={}){const t=Ki.parse(e||{}),s={};return t.title&&(s.title=t.title),t.args&&(s.args=t.args),t.cwd&&(s.cwd=t.cwd),t.env&&(s.env=t.env),t.display&&(s.display=t.display),t.displayTarget&&(s.displayTarget=t.displayTarget),{appId:t.appId||"terminal-tty",options:s}}(e.body);return{data:S.start(t.appId,t.options)}}catch(e){if(e instanceof i.z.ZodError)return t.code(400).send({error:{code:"APP_LAUNCH_INVALID",message:Zi(e)}});const s=e&&"object"==typeof e&&"code"in e?String(e.code):"APP_LAUNCH_FAILED";return t.code("APP_NOT_FOUND"===s?404:400).send({error:{code:s,message:e instanceof Error?e.message:String(e)}})}}),D.get("/api/apps/sessions/:id",async(e,t)=>{const s=S.getSession(e.params.id);return s?{data:s}:t.code(404).send({error:{code:"APP_SESSION_NOT_FOUND",message:"App session not found."}})}),D.patch("/api/apps/sessions/:id",async(e,t)=>{try{const{title:t}=Wi.parse(e.body||{});return{data:S.rename(e.params.id,t)}}catch(e){if(e instanceof i.z.ZodError)return t.code(400).send({error:{code:"APP_SESSION_UPDATE_INVALID",message:Zi(e)}});const s=e&&"object"==typeof e&&"code"in e?String(e.code):"APP_SESSION_UPDATE_FAILED";return t.code("APP_SESSION_NOT_FOUND"===s?404:400).send({error:{code:s,message:e instanceof Error?e.message:String(e)}})}}),D.post("/api/apps/sessions/:id/stop",async(e,t)=>{try{return{data:S.stop(e.params.id)}}catch(e){return t.code(404).send({error:{code:"APP_SESSION_NOT_FOUND",message:e instanceof Error?e.message:String(e)}})}}),D.post("/api/apps/sessions/:id/restart",async(e,t)=>{try{return{data:S.restart(e.params.id)}}catch(e){const s=e&&"object"==typeof e&&"code"in e?String(e.code):"APP_RESTART_FAILED";return t.code("APP_SESSION_NOT_FOUND"===s?404:400).send({error:{code:s,message:e instanceof Error?e.message:String(e)}})}}),D.post("/api/apps/sessions/:id/display",async(e,t)=>{try{return{data:S.resizeDisplay(e.params.id,Gi.parse(e.body||{}))}}catch(e){const s=e&&"object"==typeof e&&"code"in e?String(e.code):"APP_DISPLAY_RESIZE_FAILED";return e instanceof i.z.ZodError?t.code(400).send({error:{code:"APP_DISPLAY_INVALID",message:Zi(e)}}):t.code("APP_DISPLAY_NOT_FOUND"===s?404:400).send({error:{code:s,message:e instanceof Error?e.message:String(e)}})}}),D.delete("/api/apps/sessions/:id",async(e,t)=>{try{return{data:await S.delete(e.params.id)}}catch(e){const s=e&&"object"==typeof e&&"code"in e?String(e.code):"APP_DELETE_FAILED";return t.code("APP_SESSION_NOT_FOUND"===s?404:400).send({error:{code:s,message:e instanceof Error?e.message:String(e)}})}}),D.get("/api/apps/sessions/:id/logs",async(e,t)=>{try{const t=Number(e.query.maxBytes||65536),s=Number.isFinite(t)?Math.min(Math.max(1024,t),524288):65536;return{data:S.readLogs(e.params.id,s)}}catch(e){const s=e&&"object"==typeof e&&"code"in e?String(e.code):"APP_LOGS_FAILED";return t.code("APP_SESSION_NOT_FOUND"===s?404:400).send({error:{code:s,message:e instanceof Error?e.message:String(e)}})}}),D.get("/api/apps/sessions/:id/screenshot",async(e,t)=>{try{const s=S.screenshot(e.params.id);return t.header("Cache-Control","no-store").type("image/png").send(s)}catch(e){const s=e&&"object"==typeof e&&"code"in e?String(e.code):"APP_SCREENSHOT_FAILED",n="APP_SESSION_NOT_FOUND"===s?404:"APP_SCREENSHOT_UNAVAILABLE"===s?409:400;return t.code(n).send({error:{code:s,message:e instanceof Error?e.message:String(e)}})}}),D.get("/api/apps/sessions/:id/snapshot",async(e,t)=>{try{const s=S.screenshot(e.params.id);return t.header("Cache-Control","no-store").type("image/png").send(s)}catch(e){const s=e&&"object"==typeof e&&"code"in e?String(e.code):"APP_SNAPSHOT_FAILED",n="APP_SESSION_NOT_FOUND"===s?404:"APP_SCREENSHOT_UNAVAILABLE"===s?409:400;return t.code(n).send({error:{code:s,message:e instanceof Error?e.message:String(e)}})}}),D.get("/api/apps/sessions/:id/automation",async(e,t)=>{try{return{data:await S.automationStatus(e.params.id)}}catch(e){const s=e&&"object"==typeof e&&"code"in e?String(e.code):"APP_AUTOMATION_FAILED",n="APP_SESSION_NOT_FOUND"===s?404:"APP_AUTOMATION_UNAVAILABLE"===s?409:400;return t.code(n).send({error:{code:s,message:e instanceof Error?e.message:String(e)}})}}),D.get("/api/apps/sessions/:id/tty",{websocket:!0},(e,t)=>{S.attachTty(t.params.id,e)}),D.get("/api/apps/sessions/:id/vnc",{websocket:!0},(e,t)=>{const s=S.vncTarget(t.params.id);if(!s)return e.send(JSON.stringify({error:{code:"VNC_SESSION_NOT_FOUND",message:"VNC session not found."}})),void e.close();const n=o.connect(s.port,s.host);n.on("data",t=>{e.readyState===e.OPEN&&e.send(t)}),n.on("close",()=>e.close()),n.on("error",()=>e.close()),e.on("message",e=>{n.write(function(e){return Buffer.isBuffer(e)?e:Array.isArray(e)?Buffer.concat(e):Buffer.from(e)}(e))}),e.on("close",()=>n.destroy())});const fe=async(e,t)=>{const s=S.webTarget(e.params.id);if(!s)return function(e,t,s,n=502){return e.code(n).send({error:{code:t,message:s}})}(t,"WEB_SESSION_NOT_FOUND","Web session not found.",404);const n="kasmvnc"===S.getSession(e.params.id)?.vnc?.backend,r=n?{authorization:di()}:{};t.hijack();const i=function(e){if(void 0!==e)return Buffer.isBuffer(e)||"string"==typeof e?e:JSON.stringify(e)}(e.body),o=void 0!==i||"GET"===e.method||"HEAD"===e.method||"OPTIONS"===e.method,a=Date.now(),c=`http://${s.host}:${s.port}`,p=new URL(ai(e.params.id,e.raw.url),`${c}/`).toString();for(;;)try{const a=await l.proxyFetch(c,p,$i({method:e.method,headers:ci(e.headers,s.host,s.port,r),requestBody:i,rawRequest:e.raw,streamRawRequest:void 0===i&&!o})),u=hi(a.headers);if("HEAD"!==e.method&&n&&li(u)){const e=Buffer.from(mi(Buffer.from(await a.arrayBuffer()),u),"utf8"),s={...u,"content-length":String(e.byteLength)};delete s.etag,t.raw.writeHead(a.status||502,a.statusText,s),t.raw.end(e);break}if(t.raw.writeHead(a.status||502,a.statusText,gi(a.headers)),!a.body||"HEAD"===e.method){t.raw.end();break}await d.pipeline(Ui(a.body),t.raw);break}catch(e){if(o&&oi(e)&&Date.now()-a<8e3){await ii(200);continue}if(t.raw.headersSent||t.raw.destroyed){t.raw.destroyed||t.raw.destroy(e instanceof Error?e:void 0);break}t.raw.headersSent||t.raw.writeHead(502,{"content-type":"application/json"}),t.raw.end(JSON.stringify({error:{code:"WEB_PROXY_FAILED",message:e instanceof Error?e.message:String(e)}}));break}return t};D.route({method:"GET",url:"/api/apps/sessions/:id/web/*",wsHandler:(e,t)=>{const s=S.webTarget(t.params.id);if(!s)return e.send(JSON.stringify({error:{code:"WEB_SESSION_NOT_FOUND",message:"Web session not found."}})),void e.close();const n=`http://${s.host}:${s.port}`,r="kasmvnc"===S.getSession(t.params.id)?.vnc?.backend?{authorization:di(),origin:n,"sec-websocket-origin":t.headers.origin||n}:{origin:n},i=Date.now(),o=`ws://${s.host}:${s.port}${ai(t.params.id,t.raw.url)}`,a=function(e){const t=e["sec-websocket-protocol"],s=(Array.isArray(t)?t:t?[t]:[]).flatMap(e=>e.split(",").map(e=>e.trim()).filter(Boolean));return s.length?s:void 0}(t.headers)||("kasmvnc"===S.getSession(t.params.id)?.vnc?.backend?["binary"]:void 0),d=()=>{if(e.readyState!==e.OPEN)return;const n=new Li(o,a,{headers:pi(t.headers,s.host,s.port,r)});!function(e,t,s={}){const n=s.pendingFrameLimit??256;let r=!1,i=Ri(t);const o=[],a=[];let d;const c=()=>{d&&(clearTimeout(d),d=void 0)},p=(s,r)=>{if(s.length>=n)return Mi(e,1011,"WebSocket bridge pending frame limit exceeded."),void Mi(t,1011,"WebSocket bridge pending frame limit exceeded.");s.push(r)};s.upstreamOpenTimeoutMs&&!i&&(d=setTimeout(()=>{i||r||(Mi(e,1011,"Upstream websocket did not open."),Mi(t))},s.upstreamOpenTimeoutMs)),e.on("open",()=>Hi(e,a)),t.on("open",()=>{c(),i=!0,s.onUpstreamOpen?.(),Hi(t,o)}),e.on("message",(e,s=!1)=>{const n={data:e,isBinary:Boolean(s)};Ri(t)?ji(t,n):p(o,n)}),t.on("message",(t,s=!1)=>{const n={data:t,isBinary:Boolean(s)};Ri(e)?ji(e,n):p(a,n)}),t.on("close",(t,n)=>{c(),s.onUpstreamClose?.(t,n),(i||r||!s.onUpstreamCloseBeforeOpen?.())&&Mi(e,t,n)}),t.on("error",t=>{s.onUpstreamError?.(t),(i||r||!s.onUpstreamErrorBeforeOpen?.(t))&&Mi(e)}),e.on("close",(e,n)=>{c(),r=!0,s.onClientClose?.(e,n),Mi(t,e,n)}),e.on("error",e=>{c(),r=!0,s.onClientError?.(e),Mi(t,1011,"WebSocket bridge client failed.")})}(e,n,{onUpstreamCloseBeforeOpen:()=>Date.now()-i<8e3&&(ii(200).then(d),!0),onUpstreamErrorBeforeOpen:e=>oi(e)})};d()},handler:fe});for(const e of["DELETE","OPTIONS","PATCH","POST","PUT"])D.route({method:e,url:"/api/apps/sessions/:id/web/*",handler:fe});return D.get("/api/apps/sessions/:id/novnc/vnc.html",async(e,t)=>{const s=S.getSession(e.params.id);if(!s?.vnc)return t.code(404).send({error:{code:"VNC_SESSION_NOT_FOUND",message:"VNC session not found."}});const n="remote"===e.query.resize?"remote":"scale",r=new URLSearchParams({path:s.vnc.webPath.replace(/^\//,""),autoconnect:"1",resize:n});return t.redirect(`/api/novnc/vnc.html?${r.toString()}`)}),D.patch("/api/settings",async(e,t)=>{try{const s=e.body||{},n=Number(s.defaultConversationId);if(Object.prototype.hasOwnProperty.call(s,"defaultConversationId")){if(!Number.isInteger(n)||n<=0)return t.code(400).send({error:{code:"SETTINGS_INVALID_CONVERSATION",message:"Default conversation id must be a positive integer."}});if(!w.get(n))return t.code(404).send({error:{code:"CONVERSATION_NOT_FOUND",message:"Default conversation does not exist."}})}const r=_(s);return Number.isInteger(n)&&n>0&&w.use(n),{data:r}}catch(e){return t.code(400).send({error:{code:"SETTINGS_UPDATE_FAILED",message:e instanceof Error?e.message:String(e)}})}}),D.get("/api/channels",async()=>({data:[qi(m.channel("telegram").load.bind(m.channel("telegram"))),qi(m.channel("wechat").load.bind(m.channel("wechat"))),qi(m.channel("dingding").load.bind(m.channel("dingding")))]})),D.get("/api/channels/:channel/:instanceId",async(e,t)=>{const s=e.params.channel;if(!["telegram","wechat","dingding"].includes(s))return t.code(404).send({error:{code:"CHANNEL_NOT_FOUND",message:"Channel not found."}});const n=m.channel(s,e.params.instanceId);return{data:qi(n.load.bind(n))}}),D.patch("/api/channels/:channel/:instanceId",async(e,t)=>{const s=e.params.channel;if(!["telegram","wechat","dingding"].includes(s))return t.code(404).send({error:{code:"CHANNEL_NOT_FOUND",message:"Channel not found."}});const n=m.channel(s,e.params.instanceId).patch({...no(e.body),channel:s,instanceId:e.params.instanceId,schemaVersion:1});return dr(n,m.paths.configPath),{data:qi(()=>n)}}),D.setNotFoundHandler(async(e,n)=>{if(e.url.startsWith("/api/"))return n.code(404).send({error:{code:"NOT_FOUND",message:"Not found."}});const r=s.join(he,"index.html");return t.existsSync(r)?n.type("text/html").send(t.readFileSync(r,"utf8")):n.type("text/plain").send("TaskHandoff Web UI has not been built yet. Run pnpm web:build.")}),D}function oo(e){const t=Number(e);if(!Number.isInteger(t)||t<=0)throw new Error("Conversation id must be a positive integer.");return t}function ao(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}(async function(){process.env.TASK_HANDOFF_CLI_PATH||=__filename;const n=new e.Command;var r;n.name("task-handoff-controlled-instance").description("Run a TaskHandoff controlled instance.").version(function(){try{return JSON.parse(t.readFileSync(s.resolve(__dirname,"..","package.json"),"utf8")).version||"unknown"}catch{return"unknown"}}()),n.command("web").description("Run the controlled instance web server.").option("--host <host>","Web server host",process.env.TASK_HANDOFF_WEB_HOST||"127.0.0.1").option("-p, --port <port>","Web server port",ao,Number(process.env.TASK_HANDOFF_WEB_PORT)||8080).option("-s, --socket <path>","Unix socket path",N).option("--static-dir <path>","Web UI static directory",process.env.TASK_HANDOFF_WEB_STATIC_DIR||s.resolve(__dirname,"..","ui")).option("--receiver-auto-start","Start the receiver runtime with the web server.").action(async e=>{await async function(e={}){const t=e.host||process.env.TASK_HANDOFF_WEB_HOST||"127.0.0.1",s=Number(e.port||process.env.TASK_HANDOFF_WEB_PORT||8080),n=await io(e);return function(e){let t=!1;const s=async s=>{if(!t){t=!0;try{await e.close()}finally{process.exitCode=s?0:process.exitCode}}},n=()=>{s("SIGINT")},r=()=>{s("SIGTERM")};process.once("SIGINT",n),process.once("SIGTERM",r),e.addHook("onClose",async()=>{process.off("SIGINT",n),process.off("SIGTERM",r)})}(n),await n.listen({host:t,port:s}),n}({host:e.host,port:e.port,socketPath:e.socket,staticDir:e.staticDir,receiverAutoStart:e.receiverAutoStart})}),n.command("receiver").description("Run the controlled instance receiver.").option("-s, --socket <path>","Unix socket path",N).option("--telegram-token <token>","Telegram bot token",k).option("--telegram-chat-id <id>","Telegram target chat id",D).option("--telegram-allowed-user-ids <ids>","Comma-separated Telegram user ids allowed to control the bot",C.join(",")).option("--telegram-conversation <id>","Telegram passive conversation id",oo,P).option("--wechat-token <token>","Wechat iLink bot token",H).option("--wechat-base-url <url>","Wechat iLink base URL",R).option("--wechat-chat-id <id>","Wechat target chat id",M).option("--wechat-conversation <id>","Wechat passive conversation id",oo,$).option("--wechat-context-token <token>","Wechat conversation context token",j).option("--wechat-updates-buf <cursor>","Wechat getupdates cursor",L).option("--dingding-client-id <id>","DingDing stream client id",V).option("--dingding-client-secret <secret>","DingDing stream client secret",K).option("--dingding-corp-id <id>","DingDing corp id",G).option("--dingding-robot-code <code>","DingDing robot code",W).option("--dingding-card-template-id <id>","DingDing interactive card template id",X).option("--dingding-card-callback-route-key <key>","DingDing interactive card callback route key",J).option("--dingding-card-user-id-type <type>","DingDing interactive card user id type",Number,Y).option("--dingding-chat-id <id>","DingDing target conversation id",Q).option("--dingding-allowed-user-ids <ids>","Comma-separated DingDing user ids allowed to control the bot",Z.join(",")).option("--dingding-conversation <id>","DingDing passive conversation id",oo,ee).option("--headless","Run receiver without interactive terminal input.").action(async e=>{await async function(e){const t=new Function("specifier","return import(specifier)"),{runReceiverInk:n}=await t(v.pathToFileURL(s.join(__dirname,"receiver-ink.mjs")).href);return n(e)}({socketPath:e.socket,telegramToken:e.telegramToken,telegramChatId:e.telegramChatId,telegramAllowedUserIds:e.telegramAllowedUserIds,telegramConversationId:e.telegramConversation,wechatToken:e.wechatToken,wechatBaseUrl:e.wechatBaseUrl,wechatChatId:e.wechatChatId,wechatConversationId:e.wechatConversation,wechatContextToken:e.wechatContextToken,wechatUpdatesBuf:e.wechatUpdatesBuf,dingdingClientId:e.dingdingClientId,dingdingClientSecret:e.dingdingClientSecret,dingdingCorpId:e.dingdingCorpId,dingdingRobotCode:e.dingdingRobotCode,dingdingCardTemplateId:e.dingdingCardTemplateId,dingdingCardCallbackRouteKey:e.dingdingCardCallbackRouteKey,dingdingCardUserIdType:e.dingdingCardUserIdType,dingdingChatId:e.dingdingChatId,dingdingAllowedUserIds:e.dingdingAllowedUserIds,dingdingConversationId:e.dingdingConversation,headless:e.headless})}),void 0===(r=process.argv)[2]&&r.push("web"),await n.parseAsync(process.argv)})().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});
|