@task-handoff/controlled-instance 0.0.5 → 0.0.7

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.
Files changed (64) hide show
  1. package/dist/controlled-instance-cli.js +1 -1
  2. package/package.json +6 -5
  3. package/ui/assets/{abnfDiagram-VRR7QNED-BFiN2Q76.js → abnfDiagram-VRR7QNED-194RX9IN.js} +1 -1
  4. package/ui/assets/{arc-Dq--sBDV.js → arc-BYVGqC5t.js} +1 -1
  5. package/ui/assets/{architectureDiagram-ZJ3FMSHR-Db4PxmuE.js → architectureDiagram-ZJ3FMSHR-CoPwwXUU.js} +1 -1
  6. package/ui/assets/{blockDiagram-677ZJIJ3-BFrzsRE9.js → blockDiagram-677ZJIJ3-H5JZC7U7.js} +1 -1
  7. package/ui/assets/{c4Diagram-LMCZKHZV-CUMWfjX6.js → c4Diagram-LMCZKHZV-Dqpl6_qm.js} +1 -1
  8. package/ui/assets/channel-TJVIu1MF.js +1 -0
  9. package/ui/assets/{chunk-2Q5K7J3B-CB1EgF5j.js → chunk-2Q5K7J3B-2ZgtL6n7.js} +1 -1
  10. package/ui/assets/{chunk-32BRIVSS-BpsgCkbk.js → chunk-32BRIVSS-CEXm1EXp.js} +1 -1
  11. package/ui/assets/{chunk-5VM5RSS4-D2CmjJTK.js → chunk-5VM5RSS4-CKW6FEMJ.js} +1 -1
  12. package/ui/assets/{chunk-EX3LRPZG-B6a-4QdQ.js → chunk-EX3LRPZG-VzxnJ2kg.js} +1 -1
  13. package/ui/assets/{chunk-JWPE2WC7-CaAhbnco.js → chunk-JWPE2WC7-BdTmpgW9.js} +1 -1
  14. package/ui/assets/{chunk-MOJQB5TN-BVrVauq9.js → chunk-MOJQB5TN-BLlSyuQM.js} +1 -1
  15. package/ui/assets/{chunk-RYQCIY6F-floPzgi_.js → chunk-RYQCIY6F-Czfbwt0J.js} +1 -1
  16. package/ui/assets/{chunk-V7JOEXUC-CsI-g__8.js → chunk-V7JOEXUC-DgEZ8h5T.js} +1 -1
  17. package/ui/assets/{chunk-VR4S4FIN-D8Y1VI2b.js → chunk-VR4S4FIN-wwqUN6xL.js} +1 -1
  18. package/ui/assets/{chunk-XXDRQBXY-Cekf3q84.js → chunk-XXDRQBXY-BtkUWghn.js} +1 -1
  19. package/ui/assets/classDiagram-OUVF2IWQ-C_xTyyn8.js +1 -0
  20. package/ui/assets/classDiagram-v2-EOCWNBFH-C_xTyyn8.js +1 -0
  21. package/ui/assets/{cose-bilkent-JH36ORCC-RBmo63PX.js → cose-bilkent-JH36ORCC-Y6TPLTfA.js} +1 -1
  22. package/ui/assets/{cynefin-VYW2F7L2-BN3xSlwd.js → cynefin-VYW2F7L2-D3jVfkZt.js} +1 -1
  23. package/ui/assets/{cynefinDiagram-TSTJHNR4-3l4UENpc.js → cynefinDiagram-TSTJHNR4-BV1b-Dw3.js} +1 -1
  24. package/ui/assets/{dagre-VKFMJZFB-COl79Q4K.js → dagre-VKFMJZFB-Cw3pgElI.js} +1 -1
  25. package/ui/assets/{diagram-FQU43EPY-CdXE7bBS.js → diagram-FQU43EPY-Bld95cRm.js} +1 -1
  26. package/ui/assets/{diagram-G47NLZAW-DFA0Bju6.js → diagram-G47NLZAW-Dgt_Uu2j.js} +1 -1
  27. package/ui/assets/{diagram-NH7WQ7WH-Dy9tUKxS.js → diagram-NH7WQ7WH-CsntZLnK.js} +1 -1
  28. package/ui/assets/{diagram-OA4YK3LP-D1FLe4Ab.js → diagram-OA4YK3LP-guLqo7vh.js} +1 -1
  29. package/ui/assets/{diagram-WEI45ONY-BUQTU_sh.js → diagram-WEI45ONY-EUJW_XG6.js} +1 -1
  30. package/ui/assets/{ebnfDiagram-CCIWWBDH-DE_ci1oj.js → ebnfDiagram-CCIWWBDH-CxNJI1wE.js} +1 -1
  31. package/ui/assets/{erDiagram-Q63AITRT-ChWjJ4b9.js → erDiagram-Q63AITRT-DvSwLDNK.js} +1 -1
  32. package/ui/assets/{flowDiagram-23GEKE2U-LF29m1FZ.js → flowDiagram-23GEKE2U-B57VXksl.js} +1 -1
  33. package/ui/assets/{ganttDiagram-NO4QXBWP-C6b_JCSo.js → ganttDiagram-NO4QXBWP-Bx3NUsJ8.js} +1 -1
  34. package/ui/assets/{gitGraphDiagram-IHSO6WYX-xE_MdkYR.js → gitGraphDiagram-IHSO6WYX-BwWO6wZD.js} +1 -1
  35. package/ui/assets/{index-BIbw48nC.js → index-CAyLlqvU.js} +44 -44
  36. package/ui/assets/{infoDiagram-FWYZ7A6U-CEtNx7ws.js → infoDiagram-FWYZ7A6U-BlYPDsx5.js} +1 -1
  37. package/ui/assets/{ishikawaDiagram-FXEZZL3T-DW7bDtHL.js → ishikawaDiagram-FXEZZL3T-taYae6-F.js} +1 -1
  38. package/ui/assets/{journeyDiagram-5HDEW3XC-DCxHm0_Y.js → journeyDiagram-5HDEW3XC-D9Z3ppAv.js} +1 -1
  39. package/ui/assets/{kanban-definition-HUTT4EX6-lVRMOBLe.js → kanban-definition-HUTT4EX6-CDz4GDAr.js} +1 -1
  40. package/ui/assets/{linear-BIwYlsDY.js → linear-BMUuNGHb.js} +1 -1
  41. package/ui/assets/{mermaid.core-B01IBkDW.js → mermaid.core-gfnF-ku-.js} +4 -4
  42. package/ui/assets/{mindmap-definition-LN4V7U3C-BErgcbhL.js → mindmap-definition-LN4V7U3C-MLqyslko.js} +1 -1
  43. package/ui/assets/{pegDiagram-2B236MQR-Cus1G4uH.js → pegDiagram-2B236MQR-DQw26N-J.js} +1 -1
  44. package/ui/assets/{pieDiagram-ENE6RG2P-Cy8c84gb.js → pieDiagram-ENE6RG2P-BwJ_0N3w.js} +1 -1
  45. package/ui/assets/{quadrantDiagram-ABIIQ3AL-DfxzIOIK.js → quadrantDiagram-ABIIQ3AL-BbC5ekO2.js} +1 -1
  46. package/ui/assets/{railroadDiagram-RFXS5EU6-DPZcn8Wr.js → railroadDiagram-RFXS5EU6-H--1M5II.js} +1 -1
  47. package/ui/assets/{requirementDiagram-TGXJPOKE-CaIpeFc_.js → requirementDiagram-TGXJPOKE-C_WPtNqV.js} +1 -1
  48. package/ui/assets/{sankeyDiagram-HTMAVEWB-CrGNRaMm.js → sankeyDiagram-HTMAVEWB-BOeIIkMZ.js} +1 -1
  49. package/ui/assets/{sequenceDiagram-DBY2YBRQ-C18kcqQK.js → sequenceDiagram-DBY2YBRQ-SZTI3gGz.js} +1 -1
  50. package/ui/assets/{sizeCapture-X5ZJPWSS-CerMxLH-.js → sizeCapture-X5ZJPWSS-U9XCGYy3.js} +1 -1
  51. package/ui/assets/{stateDiagram-2N3HPSRC-BohrrPCg.js → stateDiagram-2N3HPSRC-B367gct6.js} +1 -1
  52. package/ui/assets/stateDiagram-v2-6OUMAXLB-DbhC1BXL.js +1 -0
  53. package/ui/assets/{swimlanes-5IMT3BWC-DsNmdb0L.js → swimlanes-5IMT3BWC-QynZ-lcF.js} +2 -2
  54. package/ui/assets/swimlanesDiagram-G3AALYLV-DakkM0R8.js +8 -0
  55. package/ui/assets/{timeline-definition-FHXFAJF6-BgshrCBA.js → timeline-definition-FHXFAJF6-DpC7yOkh.js} +1 -1
  56. package/ui/assets/{vennDiagram-L72KCM5P-B6hkO7gb.js → vennDiagram-L72KCM5P-CEZJ5J_R.js} +1 -1
  57. package/ui/assets/{wardleyDiagram-EHGQE667-ChCeQ23d.js → wardleyDiagram-EHGQE667-DFcdE-GT.js} +1 -1
  58. package/ui/assets/{xychartDiagram-FW5EYKEG-VLWto9yh.js → xychartDiagram-FW5EYKEG-CDna5jg7.js} +1 -1
  59. package/ui/index.html +1 -1
  60. package/ui/assets/channel-D6D-Wcdm.js +0 -1
  61. package/ui/assets/classDiagram-OUVF2IWQ-B5JBH9Fz.js +0 -1
  62. package/ui/assets/classDiagram-v2-EOCWNBFH-B5JBH9Fz.js +0 -1
  63. package/ui/assets/stateDiagram-v2-6OUMAXLB-D8nDa8ho.js +0 -1
  64. package/ui/assets/swimlanesDiagram-G3AALYLV-BvmD64a2.js +0 -8
@@ -1 +1 @@
1
- "use strict";var e=require("commander"),t=require("node:fs"),s=require("node:path"),n=require("node:crypto"),r=require("node:net"),i=require("node:os"),o=require("node:stream"),a=require("node:stream/promises"),d=require("@fastify/static"),c=require("@fastify/websocket"),p=require("fastify"),u=require("httpxy"),l=require("zod"),m=require("node:child_process"),h=require("write-file-atomic"),g=require("node:events"),f=require("node-pty"),y=require("ws"),v=require("@iarna/toml");const S=/(TOKEN|KEY|SECRET|AUTH|PASSWORD|COOKIE)/i,A=/^(TASK_HANDOFF|CODEX|CLAUDE|PWD$|OLDPWD$|SHELL$|TERM$)/;function I(e,t){if(void 0!==t)return S.test(e)?"[redacted]":t}function b(e=process.env){return Object.fromEntries(Object.entries(e).filter(([e])=>A.test(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,I(e,t)]))}function _(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 w(e,n){t.mkdirSync(s.dirname(e),{recursive:!0}),t.appendFileSync(e,`${JSON.stringify({time:(new Date).toISOString(),...n})}\n`,{mode:384})}class T{store;aiSessionController;constructor(e,t){this.store=e,this.aiSessionController=t}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{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}}catch(e){const s=this.store.completeRun(t,e);throw Object.assign(e instanceof Error?e:new Error(String(e)),{run:s})}}}class O{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=z(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(x(i,e.timezone).weekday))continue;const o=N(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=z(n),o={watchers:[],changed:new Set};for(const i of e.source.roots){const a=s.resolve(i),d=E();if(a.startsWith(d)&&t.existsSync(a))for(const i of P(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(E(),t).replaceAll(s.sep,"/");return!k(n)&&!(e.source.ignore||[]).some(e=>D(e,n))&&e.source.globs.some(e=>D(e,n))}aiSessionMatches(e,t){return!("ai-session"!==e.source.type||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=z(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 z(e){return e.deploymentId||e.configHash}function N(e,t,s,n){const r=x(e,t),i=Date.UTC(r.year,r.month-1,r.day,s,n,0,0),o=new Date(i),a=x(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 x(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 E(){return s.resolve(process.env.TASK_HANDOFF_WORKSPACE||process.env.WORKSPACE||"/workspace")}function k(e){return/(^|\/)(\.git|node_modules|dist|build)\//.test(e)||/\.(log|tmp|swp)$/.test(e)}function D(e,t){if("**/*"===e||"**"===e)return!0;const s=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replaceAll("**",".*").replaceAll("*","[^/]*");return new RegExp(`^${s}$`).test(t)}function P(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);k(`${s.relative(E(),i).replaceAll(s.sep,"/")}/`)||(n.push(i),r.push(i))}}return n}const C=l.z.union([l.z.object({type:l.z.literal("schedule"),scheduleKind:l.z.literal("interval").default("interval"),intervalMs:l.z.number().int().min(1e3)}).strict(),l.z.object({type:l.z.literal("schedule"),scheduleKind:l.z.literal("daily"),timeOfDay:l.z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/),timezone:l.z.string().trim().min(1).max(120)}).strict(),l.z.object({type:l.z.literal("schedule"),scheduleKind:l.z.literal("weekly"),weekdays:l.z.array(l.z.number().int().min(0).max(6)).min(1).max(7),timeOfDay:l.z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/),timezone:l.z.string().trim().min(1).max(120)}).strict()]),F=l.z.union([C,l.z.object({type:l.z.literal("file-change"),roots:l.z.array(l.z.string().trim().min(1).max(4096)).min(1).max(50),globs:l.z.array(l.z.string().trim().min(1).max(500)).min(1).max(100),ignore:l.z.array(l.z.string().trim().min(1).max(500)).max(100).optional(),debounceMs:l.z.number().int().min(100).max(6e4).default(1500)}).strict(),l.z.object({type:l.z.literal("ai-session"),agent:l.z.string().trim().min(1).max(80).optional(),statuses:l.z.array(l.z.enum(["running","waiting","idle","failed"])).max(20).optional(),phases:l.z.array(l.z.enum(["thinking","tool","editing","approval","responding","unknown"])).max(20).optional()}).strict()]),M=l.z.object({promptTemplate:l.z.string().trim().min(1).max(2e4)}).strict(),R=l.z.object({cooldownMs:l.z.number().int().min(0).max(864e5).optional(),maxConcurrentRuns:l.z.number().int().min(1).max(20).default(1),whenBusy:l.z.enum(["skip","queue"]).default("skip")}).strict(),j=l.z.object({configHash:l.z.string().trim().min(8).max(80),name:l.z.string().trim().min(1).max(160),description:l.z.string().trim().max(1e3).optional(),source:F,action:M,policy:R.default({maxConcurrentRuns:1,whenBusy:"skip"}),createdAt:l.z.string().datetime(),updatedAt:l.z.string().datetime()}).strict(),H=l.z.object({type:l.z.literal("ai-session"),aiSessionId:l.z.string().trim().min(1).max(160)}).strict(),$=l.z.object({configHash:l.z.string().trim().min(8).max(80),deploymentId:l.z.string().trim().min(1).max(240).optional(),instanceId:l.z.string().trim().min(1).max(160),origin:l.z.enum(["control-plane","controlled-instance"]).default("controlled-instance"),enabled:l.z.boolean().default(!0),target:H,localName:l.z.string().trim().min(1).max(160).optional(),createdAt:l.z.string().datetime(),updatedAt:l.z.string().datetime()}).strict(),L=l.z.object({configHash:l.z.string().trim().min(8).max(80),deploymentId:l.z.string().trim().min(1).max(240).optional(),instanceId:l.z.string().trim().min(1).max(160),status:l.z.enum(["idle","running","disabled","error"]).default("idle"),lastTriggeredAt:l.z.string().datetime().optional(),lastCompletedAt:l.z.string().datetime().optional(),lastSkippedAt:l.z.string().datetime().optional(),lastError:l.z.string().trim().max(4e3).optional(),runCount:l.z.number().int().min(0).default(0),skippedCount:l.z.number().int().min(0).default(0)}).strict(),U=l.z.object({id:l.z.string().trim().min(1).max(160),configHash:l.z.string().trim().min(8).max(80),deploymentId:l.z.string().trim().min(1).max(240).optional(),instanceId:l.z.string().trim().min(1).max(160),eventType:l.z.enum(["manual","schedule","file-change","ai-session"]),status:l.z.enum(["started","completed","failed","skipped"]),target:H,promptPreview:l.z.string().trim().max(500),eventSummary:l.z.string().trim().max(1e3).optional(),error:l.z.string().trim().max(4e3).optional(),startedAt:l.z.string().datetime(),completedAt:l.z.string().datetime().optional()}).strict(),q=l.z.object({schemaVersion:l.z.literal(1).default(1),configs:l.z.array(j).default([]),deployments:l.z.array($).default([]),runtime:l.z.array(L).default([]),recentRuns:l.z.array(U).default([])}).strict();function B(e){return Array.isArray(e)?e.map(B):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,B(t)])):e}const K=l.z.record(l.z.string(),l.z.unknown());class V{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(this.options.sanitize?this.options.sanitize(e):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}),h.sync(this.filePath,`${JSON.stringify(this.options.schema.parse(e),null,2)}\n`,{mode:384})}patch(e){const t=this.load(),s=G(K.parse(t),e),n=this.options.schema.parse(s);return this.save(n),n}}function G(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]=G(t&&"object"==typeof t&&!Array.isArray(t)?K.parse(t):{},K.parse(n))}else void 0===n?delete s[e]:s[e]=n;return s}function W(){return(new Date).toISOString()}function X(e){return e.deploymentId||e.configHash}function J(e){return L.parse({configHash:e.configHash,deploymentId:e.deploymentId,instanceId:e.instanceId,status:e.enabled?"idle":"disabled",runCount:0,skippedCount:0})}function Y(e){return e.trim().slice(0,500)}class Q{indexStore;constructor(e){const t=new Set;this.indexStore=new V(s.join(e.triggersDir,"index.json"),{schema:q,defaultValue:()=>({schemaVersion:1,configs:[],deployments:[],runtime:[],recentRuns:[]}),sanitize:e=>function(e,t){const s=ee(e);if(!s)return t?.({kind:"index",id:"index",reason:"invalid index replaced with an empty index"}),q.parse({});const n=te(s.configs).flatMap((e,s)=>{const n=ee(e),r=se(n?.configHash)||`config[${s}]`;if(!n)return t?.({kind:"config",id:r,reason:"invalid config removed"}),[];const i=function(e){const t=ne(e,["configHash","name","description","createdAt","updatedAt"]),s=ee(e.source);s&&("schedule"===s.type?t.source=ne(s,["type","scheduleKind","intervalMs","timeOfDay","timezone","weekdays"]):"file-change"===s.type?t.source=ne(s,["type","roots","globs","ignore","debounceMs"]):"ai-session"===s.type?t.source=ne(s,["type","agent","statuses","phases"]):t.source=s);const n=ee(e.action);t.action=n?ne(n,["promptTemplate"]):n;const r=ee(e.policy);return t.policy=r?ne(r,["cooldownMs","maxConcurrentRuns","whenBusy"]):r,t}(n);return Z(j,i,n,"config",r,t)}),r=te(s.deployments).flatMap((e,s)=>{const n=ee(e),r=se(n?.deploymentId)||se(n?.configHash)||`deployment[${s}]`,i=ee(n?.target);if("conversation"===i?.type)return t?.({kind:"deployment",id:r,reason:"conversation target removed"}),[];if(!n)return t?.({kind:"deployment",id:r,reason:"invalid deployment removed"}),[];const o=ne(n,["configHash","deploymentId","instanceId","origin","enabled","localName","createdAt","updatedAt"]);return o.target=i?ne(i,["type","aiSessionId"]):i,Z($,o,n,"deployment",r,t)}),i=new Set(r.map(e=>X(e))),o=te(s.runtime).flatMap((e,s)=>{const n=ee(e),r=se(n?.deploymentId)||se(n?.configHash)||`runtime[${s}]`;return n&&i.has(r)?Z(L,ne(n,["configHash","deploymentId","instanceId","status","lastTriggeredAt","lastCompletedAt","lastSkippedAt","lastError","runCount","skippedCount"]),n,"runtime",r,t):(t?.({kind:"runtime",id:r,reason:"orphaned or conversation runtime removed"}),[])}),a=te(s.recentRuns).flatMap((e,s)=>{const n=ee(e),r=se(n?.id)||`recentRun[${s}]`,i=ee(n?.target);if("conversation"===i?.type)return t?.({kind:"recent-run",id:r,reason:"conversation target run removed"}),[];if(!n)return t?.({kind:"recent-run",id:r,reason:"invalid run removed"}),[];const o=ne(n,["id","configHash","deploymentId","instanceId","eventType","status","promptPreview","eventSummary","error","startedAt","completedAt"]);return o.target=i?ne(i,["type","aiSessionId"]):i,Z(U,o,n,"recent-run",r,t)}),d=ne(s,["schemaVersion","configs","deployments","runtime","recentRuns"]);return Object.keys(s).some(e=>!(e in d))&&t?.({kind:"index",id:"index",reason:"unknown index fields ignored"}),q.parse({schemaVersion:1,configs:n,deployments:r,runtime:o,recentRuns:a})}(e,e=>{const s=`${e.kind}:${e.id}:${e.reason}`;t.has(s)||(t.add(s),console.warn(JSON.stringify({message:"historical trigger entry was sanitized",...e})))})})}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=W(),s={maxConcurrentRuns:e.policy?.maxConcurrentRuns??1,whenBusy:e.policy?.whenBusy??"skip",cooldownMs:e.policy?.cooldownMs},r=function(e){const t=B({source:e.source,action:e.action,policy:R.parse(e.policy||{})});return`trg_${n.createHash("sha256").update(JSON.stringify(t)).digest("hex").slice(0,24)}`}({source:e.source,action:e.action,policy:s}),i=j.parse({configHash:r,name:e.name,description:e.description,source:e.source,action:e.action,policy:s,createdAt:t,updatedAt:t}),o=function(e,t){const s=W();return $.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,localName:t.localName,createdAt:s,updatedAt:s})}(r,e.deployment),a=this.list(),d=a.configs.some(e=>e.configHash===r)?a.configs:[...a.configs,i],c=X(o),p=[...a.deployments.filter(e=>X(e)!==c),o],u=[...a.runtime.filter(e=>X(e)!==c),J(o)];return this.save({...a,configs:d,deployments:p,runtime:u}),{config:i,deployment:o,runtime:J(o)}}patch(e,t){const s=this.list(),n=s.configs.find(t=>t.configHash===e);if(!n)return;const r=j.parse({...n,name:t.name??n.name,description:null===t.description?void 0:t.description??n.description,updatedAt:W()});return this.save({...s,configs:s.configs.map(t=>t.configHash===e?r:t)}),r}setEnabled(e,t){const s=this.list(),n=W();let r=!1;const i=s.deployments.map(s=>s.configHash!==e?s:(r=!0,$.parse({...s,enabled:t,updatedAt:n})));if(!r)return;const o=s.runtime.map(s=>s.configHash===e?L.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&&X(s)===t))return!1;const n=s.deployments.filter(s=>!(s.configHash===e&&X(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&&X(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=>X(e))),r=t.deployments.filter(e=>!n.has(X(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(X(e)))}),s}startRun(e,t,s,n){const r=W(),i=U.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:Y(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=W(),n=Boolean(t),r=this.list(),i=r.recentRuns.map(r=>r.id===e.id?U.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&&X(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&&X(t)===X(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=W(),i=U.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:Y(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=>X(e)===X(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=X(t),r=e.runtime.find(e=>X(e)===n)||J(t),i=L.parse({...r,...s});return[...e.runtime.filter(e=>X(e)!==n),i]}save(e){this.indexStore.save(q.parse(e))}}function Z(e,t,s,n,r,i){const o=e.safeParse(t);return o.success?(JSON.stringify(t)!==JSON.stringify(s)&&i?.({kind:n,id:r,reason:"unknown or legacy fields ignored"}),[o.data]):(i?.({kind:n,id:r,reason:"entry failed current schema and was removed"}),[])}function ee(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:void 0}function te(e){return Array.isArray(e)?e:[]}function se(e){return"string"==typeof e?e:""}function ne(e,t){return Object.fromEntries(t.filter(t=>Object.prototype.hasOwnProperty.call(e,t)).map(t=>[t,e[t]]))}const re=process.env.TASK_HANDOFF_CONFIG||s.join(process.env.XDG_CONFIG_HOME||s.join(i.homedir(),".config"),"task-handoff","config.json"),ie=l.z.record(l.z.string(),l.z.unknown());function oe(e,t){const n=process.env[e];return n&&n.trim()?s.resolve(n.trim()):t}function ae(){const e=s.join(process.env.XDG_DATA_HOME||s.join(i.homedir(),".local","share"),"task-handoff"),t=oe("TASK_HANDOFF_CONFIG",re),n=oe("TASK_HANDOFF_DATA_DIR",s.dirname(t)||e);return{configPath:t,dataDir:n,appCatalogDir:oe("TASK_HANDOFF_APP_CATALOG_DIR",s.join(n,"app-catalog")),appSessionsDir:oe("TASK_HANDOFF_APP_SESSION_DIR",s.join(n,"app-sessions")),triggersDir:oe("TASK_HANDOFF_TRIGGERS_DIR",s.join(n,"triggers")),runtimeDir:oe("TASK_HANDOFF_RUNTIME_DIR",s.join(n,"runtime")),eventsDir:oe("TASK_HANDOFF_EVENTS_DIR",s.join(n,"events")),artifactDir:oe("TASK_HANDOFF_ARTIFACT_DIR",s.join(n,"artifacts")),logDir:oe("TASK_HANDOFF_LOG_DIR",s.join(n,"logs")),webTokenPath:oe("TASK_HANDOFF_WEB_TOKEN_FILE",s.join(n,"web-token"))}}const de=/^[a-f0-9]{8}$/;function ce(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",o=(e.CLAUDE_CONFIG_DIR??s.join(i.homedir(),".claude")).normalize("NFC"),a=n.createHash("sha256").update(s.resolve(o)).digest("hex").slice(0,8);return s.join(r,`cc-daemon-${t}`,a)}(e),"control.sock")}function pe(e,t={}){const s=t.sockPath||ce(),n=t.timeoutMs??5e3;return new Promise(t=>{let i;try{i=r.connect(s)}catch(e){return void t({ok:!1,code:"ENOCONN",error:String(e)})}let o=!1,a="";const d=e=>{o||(o=!0,i.destroy(),t(e))};i.setTimeout(n,()=>d({ok:!1,code:"ETIMEOUT",error:"control socket timeout"})),i.on("error",e=>d({ok:!1,code:"ENOCONN",error:String(e)})),i.once("connect",()=>{i.write(`${JSON.stringify({proto:1,...e})}\n`)}),i.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})}}),i.once("close",()=>{o||d({ok:!1,code:"ENOCONN",error:"connection dropped mid-request"})})})}function ue(e,t,s){return he(e),pe({op:"reply",short:e,text:t},s)}function le(e,t="SIGTERM",s){return he(e),pe({op:"kill",short:e,signal:t},s)}function me(e,{tail:t,onMessage:s,options:n={}}={}){he(e);const i=r.connect(n.sockPath||ce());let o="";return i.on("connect",()=>{i.write(`${JSON.stringify({proto:1,op:"subscribe",short:e,tail:t})}\n`)}),i.on("data",e=>{o+=e.toString("utf8");let t=o.indexOf("\n");for(;t>=0;){const e=o.slice(0,t);if(o=o.slice(t+1),e.trim())try{s?.(JSON.parse(e))}catch{s?.({raw:e})}t=o.indexOf("\n")}}),i.on("error",()=>{}),()=>i.destroy()}function he(e){if(!de.test(e))throw new Error(`Claude worker short id must be 8 hex chars: ${e}`)}function ge(e,t=!1){const s=process.env[e];return void 0===s||""===s?t:["1","true","yes","on"].includes(s.toLowerCase())}function fe(...e){for(const t of e){const e=process.env[t]?.trim();if(e)return["--model",e]}return[]}const ye=l.z.string().trim().min(1).max(512).refine(e=>!/\s/.test(e)&&!/[;&|<>`$]/.test(e),"Command must be a single executable path or name."),ve=l.z.object({id:l.z.string().trim().min(1).max(80).regex(/^[a-z0-9][a-z0-9._-]*$/),name:l.z.string().trim().min(1).max(120),kind:l.z.enum(["tty","gui","web"]),description:l.z.string().max(500).optional(),command:ye,args:l.z.array(l.z.string().max(1024)).max(64).default([]).optional(),cwd:l.z.string().max(512).optional(),env:l.z.record(l.z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),l.z.string().max(4096)).optional(),display:l.z.object({width:l.z.number().int().min(320).max(7680).optional(),height:l.z.number().int().min(240).max(4320).optional(),depth:l.z.union([l.z.literal(16),l.z.literal(24),l.z.literal(32)]).optional()}).strict().optional(),defaultDisplayTarget:l.z.object({mode:l.z.enum(["isolated","shared"]),id:l.z.string().trim().min(1).max(80).regex(/^[a-z0-9][a-z0-9._-]*$/).optional(),autoCreate:l.z.boolean().optional()}).strict().optional(),automation:l.z.object({type:l.z.literal("cdp"),portArg:l.z.string().optional(),endpointPath:l.z.string().optional()}).strict().optional(),web:l.z.object({portArg:l.z.string().optional(),readyPath:l.z.string().optional()}).strict().optional()}).strict(),Se=l.z.object({schemaVersion:l.z.literal(1).default(1),items:l.z.array(ve).default([])}).strict().superRefine((e,t)=>{const s=new Set(_e({includeOptional:!0}).map(e=>e.id)),n=new Set;for(const[r,i]of e.items.entries())s.has(i.id)&&t.addIssue({code:l.z.ZodIssueCode.custom,path:["items",r,"id"],message:"Custom apps cannot override built-in app ids."}),n.has(i.id)&&t.addIssue({code:l.z.ZodIssueCode.custom,path:["items",r,"id"],message:"Custom app ids must be unique."}),n.add(i.id)}),Ae=new Set(["terminal-tty","codex","claude"]),Ie=[{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 be(e){return"codex"===e.id?{...e,command:process.env.TASK_HANDOFF_CODEX_COMMAND||e.command,args:fe("TASK_HANDOFF_CODEX_MODEL","CODEX_MODEL")}:"claude"===e.id?{...e,command:process.env.TASK_HANDOFF_CLAUDE_COMMAND||e.command,args:[...ge("TASK_HANDOFF_CLAUDE_DANGEROUSLY_SKIP_PERMISSIONS")||ge("TASK_HANDOFF_CLAUDE_SKIP_PERMISSIONS")?["--dangerously-skip-permissions"]:[],...fe("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 _e(e={}){return[...Ie.map(be),...e.includeOptional||ge("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(be):[]]}function we(e){try{return t.accessSync(e,t.constants.X_OK),t.statSync(e).isFile()}catch{return!1}}function Te(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(we(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 Oe(e){const t=e.command?.trim();return Boolean(t&&Te(t,{...process.env,...e.env},e.cwd))}_e({includeOptional:!0});class ze{customStore;inventoryCache;constructor(e){this.customStore=new V(s.join(e.appCatalogDir,"custom.json"),{schema:Se,defaultValue:()=>({schemaVersion:1,items:[]}),sanitize:Ne})}list(){const e=new Map;for(const t of _e())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(Oe)}inventory(e=(new Date).toISOString()){const t=_e().map(e=>({app:e,source:"builtin"})),s=this.safeCustom(),n=new Map;for(const e of t)n.set(e.app.id,e);for(const e of s.data?.items||[])n.set(e.id,{app:e,source:"custom"});const r=[...n.values()].map(({app:e,source:t})=>({app:e,source:t,executable:e.command?.trim()?Te(e.command.trim(),{...process.env,...e.env},e.cwd):void 0})),i=JSON.stringify(r.map(({app:e,source:t,executable:s})=>({id:e.id,name:e.name,kind:e.kind,source:t,executable:s,automation:e.automation?.type,cwd:e.cwd})));return this.inventoryCache&&this.inventoryCache.fingerprint===i||(this.inventoryCache={fingerprint:i,items:r.map(({app:e,source:t,executable:s})=>({id:e.id,name:e.name,kind:e.kind,source:t,availability:s?"available":"missing-dependency",capabilities:{automation:e.automation?.type,supportsCwdSelection:Ae.has(e.id)},diagnosticCode:s?void 0:"APP_EXECUTABLE_NOT_FOUND"}))}),{items:this.inventoryCache.items,observedAt:e,issues:s.error?[{code:"APP_CATALOG_INVALID",message:"Custom app catalog could not be read completely; valid catalog entries remain available."}]:[]}}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:function(e){try{const s=JSON.parse(t.readFileSync(e,"utf8")),n=s&&"object"==typeof s&&!Array.isArray(s)?s:{};if(!Array.isArray(n.items))return;const r=new Set(_e({includeOptional:!0}).map(e=>e.id)),i=new Set,o=[];for(const e of n.items){const t=ve.safeParse(xe(e));!t.success||r.has(t.data.id)||i.has(t.data.id)||(i.add(t.data.id),o.push(t.data))}return{schemaVersion:1,items:o}}catch{return}}(this.customStore.path()),error:{code:"APP_CATALOG_INVALID",message:"Custom app catalog is invalid."}}}}saveCustom(e){return this.customStore.save(Se.parse(e)),this.inventoryCache=void 0,this.customStore.load()}customPath(){return this.customStore.path()}}function Ne(e){if(!e||"object"!=typeof e||Array.isArray(e))return e;const t=e;return{schemaVersion:t.schemaVersion,items:Array.isArray(t.items)?t.items.map(xe):t.items}}function xe(e){if(!e||"object"!=typeof e||Array.isArray(e))return e;const t=e;return{...Ee(t,["id","name","kind","description","command","args","cwd","env"]),display:Ee(t.display,["width","height","depth"]),defaultDisplayTarget:Ee(t.defaultDisplayTarget,["mode","id","autoCreate"]),automation:Ee(t.automation,["type","portArg","endpointPath"]),web:Ee(t.web,["portArg","readyPath"])}}function Ee(e,t){if(!e||"object"!=typeof e||Array.isArray(e))return;const s=e;return Object.fromEntries(t.filter(e=>Object.prototype.hasOwnProperty.call(s,e)).map(e=>[e,s[e]]))}class ke{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:()=>r.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 i=()=>{e.readyState!==y.OPEN&&e.readyState!==y.CONNECTING||e.close(),t.readyState!==y.OPEN&&t.readyState!==y.CONNECTING||t.close()};e.on("close",i),e.on("error",i),t.on("close",i),t.on("error",i)}observeClientMessage(e,t){const s=De(e);if(!s)return;const n=Pe(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=De(e);if(!s)return;const n=Pe(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 De(e){try{const t=JSON.parse(e);return t&&"object"==typeof t&&!Array.isArray(t)?t:void 0}catch{return}}function Pe(e){return"string"==typeof e&&e?e:"number"==typeof e&&Number.isFinite(e)?String(e):void 0}function Ce(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 Fe(e){return e.toFixed(2).replace(/\.?0+$/,"")}function Me(){return process.env.TASK_HANDOFF_GUI_APP_HOME||process.env.HOME||i.homedir()}function Re(){return`app_${Date.now().toString(36)}_${Math.random().toString(16).slice(2)}`}function je(){return(new Date).toISOString()}function He(e,t=!1){const s=process.env[e];return void 0===s||""===s?t:["1","true","yes","on"].includes(s.toLowerCase())}const $e=new Set(["stopped","exited","failed"]),Le={"workbench.colorTheme":"Default Dark Modern","workbench.preferredDarkColorTheme":"Default Dark Modern"};class Ue 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;managedEnvironment={};constructor(e){super(),this.paths=e,this.catalogRepository=new ze(e),this.persistSessionMetadata=He("TASK_HANDOFF_APP_SESSION_PERSIST"),this.persistSessionMetadata&&(this.loadPersistedSessions(),this.cleanupExpiredSessions())}catalog(){return this.catalogRepository.available()}appInventory(e){return this.catalogRepository.inventory(e)}customCatalog(){const e=this.catalogRepository.safeCustom();return e.data?{data:{path:this.catalogRepository.customPath(),...e.data},error:e.error}:{data:void 0,error:e.error}}saveCustomCatalog(e){return{path:this.catalogRepository.customPath(),...this.catalogRepository.saveCustom({schemaVersion:1,items:e})}}replaceManagedEnvironment(e){const t=JSON.stringify(this.managedEnvironment)!==JSON.stringify(e);this.managedEnvironment={...e},t&&this.stopSharedCodexAppServer()}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,...this.managedEnvironment,TERM:"xterm-256color"};return this.acquireSharedCodexAppServer(t,s,n,"__shared_codex_app_server__")}_createCodexAppServerConnectionProxyForTest(e,t){return new ke(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=Re(),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,...this.managedEnvironment,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||He("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 ke(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||He("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:je(),updatedAt:je(),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"}),A={metadata:v,processes:[],codexAppServerProxy:h,ttyDimensions:{cols:120,rows:32},ttyLogStream:S,outputBacklog:"",clients:new Set};S.on("error",()=>{A.ttyLogClosed=!0}),S.on("close",()=>{A.ttyLogClosed=!0});const I=(e,t)=>{A.stopping||(v.status="exited",v.updatedAt=je(),v.process={...v.process,exitCode:e,signal:void 0===t?void 0:String(t)},this.persist(v),this.emit("updated",v)),"codex"===r.id&&(A.codexAppServerProxy?.stop(),this.releaseSharedCodexAppServer(i)),this.broadcast(A,{type:"exit",code:e,signal:t}),this.closeTtyLog(A)};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},A.pty=b,b.onData(e=>{this.writeTtyLog(A,e),A.outputBacklog=`${A.outputBacklog}${e}`.slice(-65536),this.broadcast(A,{type:"output",data:e})}),b.onExit(({exitCode:e,signal:t})=>I(e,t)),this.sessions.set(i,A),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:ce(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=Re(),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,...this.managedEnvironment},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:je(),updatedAt:je(),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=Re(),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:je(),updatedAt:je(),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,A=p.display?.depth||e.display?.depth||24,I={...process.env,...e.env,...p.env,...this.managedEnvironment,DISPLAY:g},b=Ce(I),_=s.join(d,"home"),w="kasmvnc"===i?s.join(_,".Xauthority"):void 0,T="kasmvnc"===i?this.startKasmVncDisplay(g,v,S,A,f,I,d,c,b):this.startNoVncDisplay(g,v,S,A,f,y,I,c,l),O="kasmvnc"===i?this.guiScaleEnv({...I,HOME:Me(),XAUTHORITY:w},b):I;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(O,d,b);const z=this.spawnLogged("openbox",[],O,c,"openbox.log"),N=this.startCompositor(O,c,l),x=this.spawnLogged(r,h,O,c,`${e.id}.log`,l),E=e.automation?{type:e.automation.type,port:m,endpoint:`http://127.0.0.1:${m}${e.automation.endpointPath||""}`}:void 0,k={id:a,appId:e.id,title:p.title||e.name,kind:"gui",status:"running",createdAt:je(),updatedAt:je(),launch:p,display:{display:g,mode:"isolated",width:v,height:S,depth:A,xPid:T[0]?.pid,wmPid:z.pid,compositorPid:N?.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:E,process:{pid:x.pid,command:r},paths:{sessionDir:d,logDir:c}},D={metadata:k,processes:[x,...T,z,...N?[N]:[]],outputBacklog:"",clients:new Set};this.sessions.set(a,D),this.persist(k);for(const e of T)this.watchLoggedProcess(D,e,"kasmvnc"===i?"kasmvnc":"display",!0);return this.watchLoggedProcess(D,z,"openbox",!0),this.watchLoggedProcess(D,x,e.id,!1),this.emit("created",k),k}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,...this.managedEnvironment,DISPLAY:l},S=Ce(v),A=s.join(p,"home"),I="kasmvnc"===r?s.join(A,".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:Me(),XAUTHORITY:I},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),O={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:I,sessionDir:p,logDir:u,processes:[...b,w,...T?[T]:[]],appSessionIds:new Set};this.sharedDisplays.set(a,O);for(const e of[...b,w])this.watchSharedDisplayProcess(O,e);return O}appEnvForDisplay(e,t,s){const n={...process.env,...e.env,...t.env,...this.managedEnvironment,DISPLAY:s.display},r=Ce(n);return"kasmvnc"===s.backend?this.guiScaleEnv({...n,HOME:Me(),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,o,a){const d=this.sharedCodexAppServer;if(d&&null===d.child.exitCode&&!d.child.killed&&t.existsSync(d.socketPath))return d.appSessionIds.add(a),d;if(d&&!d.child.killed&&d.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 c=s.join(this.paths.runtimeDir,"codex-app-server"),p=s.join(this.paths.logDir,"app-sessions","codex-app-server"),u=function(e){const r=process.env.TASK_HANDOFF_CODEX_APP_SERVER_SOCKET_DIR?.trim(),o=r?t.realpathSync(r):"darwin"===process.platform?"/private/tmp":t.realpathSync(i.tmpdir()),a=n.createHash("sha256").update(e).digest("hex").slice(0,16);return s.join(o,`task-handoff-codex-${a}`,"app-server.sock")}(c),l=`unix://${u}`,m=process.env.TASK_HANDOFF_CODEX_APP_SERVER_COMMAND||e,h=["app-server","--listen",l];t.mkdirSync(c,{recursive:!0}),t.mkdirSync(p,{recursive:!0}),t.mkdirSync(s.dirname(u),{recursive:!0,mode:448}),t.rmSync(u,{force:!0});const g=this.spawnLogged(m,h,o,p,"codex-app-server.log",r),f={command:m,args:h,socketPath:u,endpoint:l,logPath:s.join(p,"codex-app-server.log"),child:g,appSessionIds:new Set([a])};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(u,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=je(),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=je(),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:Fe(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=je(),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=je(),this.persist(t.metadata),this.sessions.delete(e),this.emit("updated",t.metadata),t.metadata}stopClaudeDaemonForSession(e){const t=e.ai?.claude?.short;t&&le(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=je(),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)||!$e.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=je(),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}),h.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:je(),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=je(),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=je(),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=He("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 r=s.join(n,"user-data","User"),i=s.join(r,"settings.json");let o={};if(t.mkdirSync(r,{recursive:!0}),t.existsSync(i))try{const e=JSON.parse(t.readFileSync(i,"utf8"));e&&"object"==typeof e&&!Array.isArray(e)&&(o=e)}catch{o={}}h.sync(i,`${JSON.stringify({...Le,...o},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(Te(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 qe={"image/bmp":".bmp","image/gif":".gif","image/jpeg":".jpg","image/png":".png","image/webp":".webp"};function Be(e=[]){if(!e.length)return[];const n=function(){const e=process.env.TASK_HANDOFF_AI_SESSION_ATTACHMENT_DIR?.trim();return e?s.resolve(e):s.join(i.tmpdir(),"task-handoff-ai-session-attachments")}();return t.mkdirSync(n,{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{}}(n),e.map(e=>{const r=qe[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(/\.[^.]+$/,"")}${r}`;var o;const a=s.join(n,i);return t.writeFileSync(a,Buffer.from(e.data,"base64")),{...e,path:a}})}async function Ke(e,t=[],s){const n=Be(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 Ve{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 Ge{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 Xe("AI_SESSION_MESSAGE_EMPTY","Message is required.");const r=t.mode||"auto";if("queue"===r||"auto"===r&&We(s)){const e=this.registry.enqueueMessage(s.id,n,t.attachments||[]);if(!e)throw Xe("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(We(s))throw Xe("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(We(s))throw Xe("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 Xe("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(!We(s))throw Xe("AI_SESSION_NOT_ACTIVE","AI session is not active.",409);const n=this.requireProvider(s),r=n.steerMessage||n.sendMessage;if(!r)throw Xe("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(We(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 Xe("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 Xe("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 Xe("AI_SESSION_NOT_FOUND","AI session not found.",404);return s}reorderQueuedMessages(e,t){const s=this.registry.reorderQueuedMessages(e,t);if(!s)throw Xe("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 Xe("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 Xe("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 Xe("AI_SESSION_NOT_FOUND","AI session not found.",404);return t}requireProvider(e){const t=this.providers.get(e.agent);if(!t)throw Xe("AI_SESSION_CONTROL_UNSUPPORTED",`${e.agent} sessions do not support direct control yet.`,400);return t}}function We(e){return"running"===e.status||"waiting"===e.status}function Xe(e,t,s=400){const n=new Error(t);return n.code=e,n.statusCode=s,n}function Je(e){const t=ot(e);return/^\[(?:request interrupted by user|user interrupted request)\]$/i.test(t)}function Ye(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}function Qe(e){if(e.timestamp)return e;const{timestamp:t,...s}=e;return s}function Ze(e){return Array.isArray(e)?e:[]}function et(e){return"tool_use"===e.type}function tt(e){return"tool_result"===e.type}function st(e){return"text"===e.type}function nt(e){return"text"!==e.type&&"output_text"!==e.type&&"input_text"!==e.type||"string"!=typeof e.text?"":e.text}function rt(e){if("string"==typeof e)return ot(e);const t=Ze(e).map(nt).filter(Boolean).join("\n");return t?ot(t):""}function it(e,t=180){const s=String(e??"").replace(/\s+/g," ").trim();return s.length>t?`${s.slice(0,t-3)}...`:s}function ot(e){return String(e??"").trim()}function at(e){try{const t=Ye(JSON.parse(String(e||"{}")));return it(t.cmd||t.command||t.path||t.ref_id||t.pattern||"")}catch{return""}}function dt(e){if(e&&"object"==typeof e&&!Array.isArray(e)){const t=e;return it(t.command||t.cmd||t.file_path||t.filePath||t.path||t.ref_id||t.pattern||t.description||"")}return at(e)}function ct(e){return/\b(task-handoff|result-ipc)(\.js)?\b/.test(e)}function pt(e){return["edit","multiedit","write","notebookedit"].includes(e.toLowerCase())}function ut(e,n,r=s.join(i.homedir(),".claude")){const o=it(e,200);if(!o)return;const a=s.join(r,"projects"),d=it(n);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 lt(e,t){let n;try{n=JSON.parse(e)}catch{return}const r=Ye(n),i=Ye(r.payload),o="string"==typeof Ye(n).timestamp?Ye(n).timestamp:void 0;if("turn_context"===r.type)return;if("event_msg"===r.type)return"agent_message"===i.type?Qe({text:ot(i.message),kind:"assistant",timestamp:o}):void 0;if("assistant"===r.type){const e=Ze(r.message?.content);let s,n;for(const r of e){if(et(r)){const e=it(r.name||"tool",80),n=dt(r.input),i=ct(n),a=pt(e)?"edit":void 0;if(r.id&&t.calls.set(r.id,{tool:e,command:n,ignored:i,action:a}),i)continue;s??=Qe({key:r.id,text:"edit"===a?`Editing ${n||"files"}`:n?`Running ${e}: ${n}`:`Running ${e}`,kind:"tool",timestamp:o});continue}st(r)&&r.text&&(n??=ot(r.text))}return s||(n?Qe({text:n,kind:"assistant",timestamp:o}):void 0)}if("user"===r.type){const e=rt(r.message?.content);if(e&&!Je(e))return Qe({text:e,kind:"user",timestamp:o});const s=Ze(r.message?.content);for(const e of s){if(!tt(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 Qe({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=it(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"}),Qe({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=it(a.output,120),n=/failed|error/i.test(s);return Qe({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=it(a.name||"tool",80),s=at(a.arguments),n="write_stdin"===e||ct(s);if(a.call_id&&t.calls.set(a.call_id,{tool:e,command:s,ignored:n}),n)return;return Qe({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 Qe({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=rt(a.content);if(!e)return;return Qe({text:ot(e),kind:"user"===a.role?"user":"assistant",timestamp:o})}}}const mt=41943040,ht="ai-session.snapshot",gt=l.z.string().trim().min(1).max(80),ft=l.z.enum(["running","waiting","idle","failed"]),yt=l.z.enum(["thinking","tool","editing","approval","responding","unknown"]),vt=l.z.object({name:l.z.string().trim().min(1).max(120),inputPreview:l.z.string().trim().max(500).optional(),startedAt:l.z.string().datetime().optional()}).strict(),St=l.z.object({toolCalls:l.z.number().int().min(0).default(0),edits:l.z.number().int().min(0).default(0),approvals:l.z.number().int().min(0).default(0)}).strict().default({toolCalls:0,edits:0,approvals:0}),At=l.z.object({send:l.z.boolean().optional(),interrupt:l.z.boolean().optional(),approval:l.z.boolean().optional()}).strict(),It=l.z.object({id:l.z.string().trim().min(1).max(120),kind:l.z.enum(["image"]),name:l.z.string().trim().min(1).max(240),mime:l.z.string().trim().min(1).max(120),size:l.z.number().int().min(0).max(20971520),data:l.z.string().min(1).max(31457280)}).strict(),bt=It.omit({data:!0}),_t=l.z.object({id:l.z.string().trim().min(1).max(120),kind:l.z.enum(["image"]).optional()}).strict(),wt=l.z.enum(["auto","queue","steer","immediate"]),Tt=l.z.object({message:l.z.string().trim().min(1).max(2e4),mode:wt.optional()}),Ot=Tt.extend({attachments:l.z.array(It).max(6).default([])}).strict().superRefine((e,t)=>{e.attachments.reduce((e,t)=>e+t.size,0)>mt&&t.addIssue({code:l.z.ZodIssueCode.custom,path:["attachments"],message:"Images must be 41943040 bytes or less in total."})});Tt.extend({attachments:l.z.array(_t).max(6).default([])}).strict();const zt=l.z.object({decision:l.z.enum(["allow","deny","skip"])}).strict(),Nt=l.z.object({queueIds:l.z.array(l.z.string().trim().min(1).max(120)).max(100)}).strict(),xt=l.z.object({code:l.z.string().trim().min(1).max(160),message:l.z.string(),instanceId:l.z.string().trim().min(1).max(160).optional(),nodeId:l.z.string().trim().min(1).max(160).optional(),route:l.z.string().trim().min(1).max(4096).optional()}).strict(),Et=l.z.object({id:l.z.string().trim().min(1).max(120),message:l.z.string().trim().min(1).max(2e4),attachments:l.z.array(bt).max(6).default([]),status:l.z.enum(["queued","sending","failed"]).default("queued"),createdAt:l.z.string().datetime(),updatedAt:l.z.string().datetime(),error:l.z.string().trim().max(4e3).optional()}).strict(),kt=l.z.object({pendingCount:l.z.number().int().min(0).default(0),items:l.z.array(Et).max(100).default([])}).strict().default({pendingCount:0,items:[]}),Dt=l.z.enum(["control","realtime","adapter-snapshot","transcript-tail","transcript-scan","process-scan","app-session"]),Pt=l.z.object({id:l.z.string().trim().min(1).max(240),providerTurnId:l.z.string().trim().max(240).optional(),source:Dt.optional(),userPrompt:l.z.string().trim().optional(),status:l.z.enum(["queued","running","waiting","completed","failed"]).default("running"),phase:yt.optional(),summary:l.z.string().trim().max(1e3).optional(),lastMessage:l.z.string().trim().optional(),revision:l.z.number().int().min(0).default(0),sourcePriority:l.z.number().int().min(0).max(100).optional(),snapshotVersion:l.z.number().int().min(0).optional(),observedAt:l.z.string().datetime().optional(),startedAt:l.z.string().datetime().optional(),updatedAt:l.z.string().datetime().optional(),completedAt:l.z.string().datetime().optional()}).strict(),Ct=l.z.object({id:l.z.string().trim().min(1).max(120),agent:gt,appSessionId:l.z.string().trim().max(120).optional(),appId:l.z.string().trim().max(120).optional(),providerSessionId:l.z.string().trim().max(240).optional(),providerMeta:l.z.record(l.z.string(),l.z.unknown()).optional(),appBindingKeys:l.z.array(l.z.string().trim().min(1).max(240)).max(20).optional(),actions:At.optional(),activeTurnId:l.z.string().trim().max(240).optional(),conversationId:l.z.number().int().positive().optional(),title:l.z.string().trim().max(240).optional(),cwd:l.z.string().trim().max(4096).optional(),userPrompt:l.z.string().trim().optional(),turns:l.z.array(Pt).max(50).optional(),status:ft.default("running"),phase:yt.default("unknown"),summary:l.z.string().trim().max(1e3).optional(),lastMessage:l.z.string().trim().optional(),currentTool:vt.optional(),transcriptPath:l.z.string().trim().max(4096).optional(),transcriptSize:l.z.number().int().min(0).optional(),startedAt:l.z.string().datetime(),updatedAt:l.z.string().datetime(),completedAt:l.z.string().datetime().optional(),error:l.z.string().trim().max(4e3).optional(),counters:St,queue:kt}).strict(),Ft=l.z.object({session:Ct,provider:l.z.string().trim().min(1).max(80),action:l.z.enum(["send","queue","steer","interrupt","approval"]),decision:l.z.enum(["allow","deny","skip"]).optional(),turnId:l.z.string().trim().min(1).max(240).optional(),providerTurnId:l.z.string().trim().min(1).max(240).optional(),queueId:l.z.string().trim().min(1).max(120).optional()}).strict(),Mt=Ct.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}),Rt=l.z.object({runningCount:l.z.number().int().min(0).default(0),waitingCount:l.z.number().int().min(0).default(0),staleCount:l.z.number().int().min(0).default(0),sessions:l.z.array(Mt).default([]),updatedAt:l.z.string().datetime()}).strict();l.z.object({streamId:l.z.string().trim().min(1).max(240),revision:l.z.number().int().min(0),lastEventAt:l.z.string().datetime(),snapshot:Rt}).strict(),Rt.pick({runningCount:!0,waitingCount:!0,staleCount:!0,updatedAt:!0}).extend({idleCount:l.z.number().int().min(0).default(0),problemCount:l.z.number().int().min(0).default(0),revision:l.z.number().int().min(0).optional()});const jt=l.z.enum(["provider-event","app-session-created","app-session-updated","app-session-deleted","discovery-scan","control-action","heartbeat-sync","startup"]),Ht=l.z.object({streamId:l.z.string().trim().min(1).max(240),instanceId:l.z.string().trim().min(1).max(160),nodeId:l.z.string().trim().min(1).max(160).optional(),revision:l.z.number().int().min(0),previousRevision:l.z.number().int().min(0).optional(),traceId:l.z.string().trim().min(1).max(160),generatedAt:l.z.string().datetime(),reason:jt}).strict(),$t=l.z.object({meta:Ht,snapshot:Rt}).strict(),Lt=l.z.object({meta:Ht,upserted:l.z.array(Mt).default([]),removed:l.z.array(l.z.string().trim().min(1).max(120)).default([])}).strict(),Ut=l.z.object({meta:Ht,sessionIds:l.z.array(l.z.string().trim().min(1).max(120)).default([]),expiresAt:l.z.string().datetime()}).strict(),qt=l.z.object({streamId:l.z.string().trim().min(1).max(240),instanceId:l.z.string().trim().min(1).max(160),sinceRevision:l.z.number().int().min(0),latestRevision:l.z.number().int().min(0),earliestRetainedRevision:l.z.number().int().min(0),syncRequired:l.z.boolean().default(!1),events:l.z.array(l.z.discriminatedUnion("type",[l.z.object({type:l.z.literal(ht),payload:$t}).strict(),l.z.object({type:l.z.literal("ai-session.patch"),payload:Lt}).strict(),l.z.object({type:l.z.literal("ai-session.removed"),payload:Ut}).strict()])).default([])}).strict(),Bt=l.z.object({source:Dt,sourcePriority:l.z.number().int().min(0).max(100).optional(),observedAt:l.z.string().datetime().optional(),snapshotVersion:l.z.number().int().min(0).optional()}).strict(),Kt=Bt.extend({type:l.z.literal("snapshot"),agent:l.z.string().trim().min(1).max(80),appSessionId:l.z.string().trim().max(120).optional(),appId:l.z.string().trim().max(120).optional(),providerSessionId:l.z.string().trim().max(240).optional(),providerMeta:l.z.record(l.z.string(),l.z.unknown()).optional(),appBindingKeys:l.z.array(l.z.string().trim().min(1).max(240)).max(20).optional(),actions:At.optional(),conversationId:l.z.number().int().positive().optional(),title:l.z.string().trim().max(240).optional(),cwd:l.z.string().trim().max(4096).optional(),activeTurnId:l.z.string().trim().max(240).optional(),userPrompt:l.z.string().trim().optional(),turns:l.z.array(Pt).max(50).optional(),status:ft.optional(),phase:yt.optional(),summary:l.z.string().trim().max(1e3).optional(),lastMessage:l.z.string().trim().optional(),transcriptPath:l.z.string().trim().max(4096).optional(),transcriptSize:l.z.number().int().min(0).optional(),replaceActivity:l.z.boolean().optional()}).strict(),Vt=Bt.extend({type:l.z.literal("event"),sessionId:l.z.string().trim().min(1).max(120),kind:l.z.enum(["lifecycle","send-ack","turn-started","user-message","assistant-message","approval-requested","turn-completed"]),activeTurnId:l.z.string().trim().max(240).optional(),providerTurnId:l.z.string().trim().max(240).optional(),userPrompt:l.z.string().trim().optional(),text:l.z.string().optional(),status:ft.optional(),phase:yt.optional(),summary:l.z.string().trim().max(1e3).optional(),error:l.z.string().trim().max(4e3).optional(),counters:l.z.object({toolCalls:l.z.number().int().min(0).optional(),edits:l.z.number().int().min(0).optional(),approvals:l.z.number().int().min(0).optional()}).strict().optional()}).strict();function Gt(e,t=500){const s=String(e??"").replace(/\s+/g," ").trim();return s.length>t?`${s.slice(0,t-3)}...`:s}function Wt(e){return String(e??"").trim()}l.z.discriminatedUnion("type",[Kt,Vt]);const Xt={control:90,realtime:80,"adapter-snapshot":60,"transcript-tail":50,"app-session":40,"process-scan":30,"transcript-scan":20};function Jt(e,t){return Math.max(0,Math.min(100,Number.isInteger(t)?Number(t):e?Xt[e]:0))}function Yt(e){const t={};return e.source&&(t.source=e.source,t.sourcePriority=Jt(e.source,e.sourcePriority)),e.providerTurnId&&(t.providerTurnId=Gt(e.providerTurnId,240)),Number.isInteger(e.snapshotVersion)&&(t.snapshotVersion=Number(e.snapshotVersion)),e.observedAt&&(t.observedAt=e.observedAt),t}function Qt(e){const t=Gt(e,120),s=t.replace(/[^a-zA-Z0-9_.:-]+/g,"_").replace(/^_+|_+$/g,""),r=n.createHash("sha1").update(t).digest("hex").slice(0,10);return s?`${s}_${r}`:r}function Zt(e,t){return`turn_${Qt(e)}_${Qt(t)}`}function es(e,t,s=1){return Zt(e,t||`${e}:${s}`)}function ts(e,t){return`turn_legacy_${t}_${Qt(e.userPrompt||e.updatedAt||e.lastMessage||e.summary)}`}function ss(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?Gt(e.id,240):ts(e,n),providerTurnId:e.providerTurnId?Gt(e.providerTurnId,240):t.providerTurnId,source:e.source||t.source,userPrompt:e.userPrompt?Wt(e.userPrompt):void 0,status:e.status||"completed",phase:e.phase,summary:e.summary?Gt(e.summary,1e3):void 0,lastMessage:e.lastMessage?Wt(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 ns(e,t){if(!e)return!0;const s=Jt(e.source,e.sourcePriority),n=Jt(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 rs(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 is(e){return Boolean(e?.lastMessage||e?.summary)}function os(e){if(!e.activeTurnId||"running"!==e.status)return!1;const t=ss(e.turns).find(t=>t.id===e.activeTurnId);return Boolean(!t||!is(t))}function as(e,t,s){return s?e.activeTurnId:"idle"!==t.status&&"failed"!==t.status?t.activeTurnId?Gt(t.activeTurnId,240):e.activeTurnId:void 0}function ds(e,t,s,r={}){const i=function(e,t,s={}){const n=ss(e),r=ss(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,...rs(r,t),id:r.id,providerTurnId:t.providerTurnId||t.id,revision:Math.max(r.revision||0,t.revision||0)};ns(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(ns(o,t)){const s={...o,...rs(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,r),o=t.userPrompt?Wt(t.userPrompt):"",a=t.activeTurnId?Gt(t.activeTurnId,240):"";if(o){const e=i.at(-1),n=(a?i.find(e=>e.id===a):void 0)||[...i].reverse().find(e=>e.userPrompt===o&&!e.lastMessage&&!e.summary),d=Boolean(t.turns?.some(e=>e.userPrompt&&Wt(e.userPrompt)===o));n?(a&&n.id!==a&&(n.id=a),n.userPrompt=o,n.updatedAt=s,n.status="waiting"===t.status?"waiting":"running",n.phase=t.phase||n.phase||"thinking",Object.assign(n,r),n.revision+=1):!e||e.lastMessage||e.summary||e.userPrompt!==o?d||i.push({id:a||Zt(o,s),...r,userPrompt:o,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,r),e.revision+=1)}if(t.lastMessage||t.summary){let e=a?i.find(e=>e.id===a):i.at(-1);if(!e&&a){const t=[...i].reverse().find(e=>e.userPrompt&&!e.lastMessage&&!e.summary);t&&(t.id=a,e=t)}!e&&a&&(e={id:a,...r,status:"waiting"===t.status?"waiting":"failed"===t.status?"failed":"running",phase:t.phase||"unknown",revision:0,startedAt:s,updatedAt:s},i.push(e));const o={summary:t.summary?Gt(t.summary,1e3):e?.summary,lastMessage:t.lastMessage?Wt(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,...r};if(e){const t=e.summary===o.summary&&e.lastMessage===o.lastMessage,s=e.status===o.status&&e.phase===o.phase,n=t&&s;Object.assign(e,{...o,observedAt:n?e.observedAt:o.observedAt,updatedAt:n||t?e.updatedAt:o.updatedAt,completedAt:n?e.completedAt:o.completedAt}),t&&s||(e.revision+=1)}else i.push({id:`turn_${n.randomUUID().replace(/-/g,"").slice(0,20)}`,...o,status:o.status||"running",revision:0,startedAt:s})}else if((t.status||t.phase)&&a){const e=i.find(e=>e.id===a);if(e){const n="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!==n||e.phase!==i||e.completedAt!==o;Object.assign(e,{status:n,phase:i,completedAt:o,updatedAt:a?s:e.updatedAt,...r}),a&&(e.revision+=1)}}if(("running"===t.status||"waiting"===t.status)&&a){const e=i.findIndex(e=>e.id===a);if(e>=0&&e!==i.length-1){const[t]=i.splice(e,1);i.push(t)}}return ss(i)}function cs(){return(new Date).toISOString()}function ps(e){t.mkdirSync(e,{recursive:!0})}function us(e){try{return JSON.parse(t.readFileSync(e,"utf8"))}catch{return}}function ls(e,t,s){if(!Array.isArray(e))return;const n=[...new Set(e.map(e=>Gt(e,s)).filter(Boolean))].slice(0,t);return n.length?n:void 0}function ms(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 hs(e){const t=e.map(fs).filter(e=>Boolean(e)).slice(0,100);return{pendingCount:t.filter(e=>"queued"===e.status||"sending"===e.status).length,items:t}}function gs(e){const t=e&&"object"==typeof e&&!Array.isArray(e)?e:{};return hs(Array.isArray(t.items)?t.items:[])}function fs(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:Gt(t.id,120),message:Wt(t.message),attachments:ys(t.attachments),status:s,createdAt:t.createdAt,updatedAt:t.updatedAt,error:t.error?Gt(t.error,4e3):void 0}}function ys(e){return Array.isArray(e)?e.map(e=>{const t=bt.safeParse(e);return t.success?t.data:void 0}).filter(e=>Boolean(e)).slice(0,6):[]}function vs(e=[]){return e.slice(0,6).map(e=>bt.parse({id:e.id,kind:e.kind,name:e.name,mime:e.mime,size:e.size}))}function Ss(e){const t=e&&"object"==typeof e?e:void 0;var s;if(t?.id&&t.agent&&t.startedAt&&t.updatedAt)return{id:Gt(t.id,120),agent:Gt(t.agent,80),appSessionId:t.appSessionId?Gt(t.appSessionId,120):void 0,appId:t.appId?Gt(t.appId,120):void 0,providerSessionId:t.providerSessionId?Gt(t.providerSessionId,240):void 0,providerMeta:t.providerMeta&&"object"==typeof t.providerMeta&&!Array.isArray(t.providerMeta)?t.providerMeta:void 0,appBindingKeys:ls(t.appBindingKeys,20,240),actions:ms(t.actions),activeTurnId:t.activeTurnId?Gt(t.activeTurnId,240):void 0,conversationId:Number.isInteger(t.conversationId)&&Number(t.conversationId)>0?Number(t.conversationId):void 0,title:t.title?Gt(t.title,240):void 0,cwd:t.cwd?Gt(t.cwd,4096):void 0,userPrompt:t.userPrompt?Wt(t.userPrompt):void 0,turns:ss(t.turns),status:As(t.status),phase:Is(t.phase),summary:t.summary?Gt(t.summary,1e3):void 0,lastMessage:t.lastMessage?Wt(t.lastMessage):void 0,currentTool:t.currentTool?.name?{name:Gt(t.currentTool.name,120),inputPreview:t.currentTool.inputPreview?Gt(t.currentTool.inputPreview,500):void 0,startedAt:t.currentTool.startedAt}:void 0,transcriptPath:t.transcriptPath?Gt(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?Gt(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:gs(t.queue)}}function As(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 Is(e){return["thinking","tool","editing","approval","responding","unknown"].includes(String(e))?e:"unknown"}function bs(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 _s(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 ws(e){return{id:e.id,agent:e.agent,appSessionId:e.appSessionId,appId:e.appId,providerSessionId:e.providerSessionId,providerMeta:e.providerMeta,appBindingKeys:e.appBindingKeys,actions:Ts(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 Ts(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 Os(e,t){const s=Gt(e,1e3);return"user"===t?{userPrompt:Wt(e)}:"assistant"===t?{status:"running",phase:"responding",summary:s,lastMessage:Wt(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:Wt(e)}:{}}function zs(e,t,s){const n=t.activeTurnId?Gt(t.activeTurnId,240):void 0;if("transcript-tail"!==t.source||!n||!e.activeTurnId||n===e.activeTurnId)return n||e.activeTurnId;const r=ss(e.turns).find(t=>t.id===e.activeTurnId);if(!r||is(r))return n;const i=s?Wt(s):"";return i&&r.userPrompt&&r.userPrompt!==i?n:e.activeTurnId}function Ns(e,n,r){if(n)return"claude"===e?ut(n,r):function(e,n=s.join(i.homedir(),".codex")){const r=it(e,200);if(!r)return;const o=[s.join(n,"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(r))return n}}}(n)}class xs{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(ae().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||cs(),r=t.meta||Yt({source:"control",observedAt:s}),i={id:`ais_${n.randomUUID().replace(/-/g,"").slice(0,20)}`,agent:Gt(e.agent||"unknown",80),appSessionId:e.appSessionId?Gt(e.appSessionId,120):void 0,appId:e.appId?Gt(e.appId,120):void 0,providerSessionId:e.providerSessionId?Gt(e.providerSessionId,240):void 0,providerMeta:void 0,activeTurnId:void 0,conversationId:e.conversationId,title:e.title?Gt(e.title,240):void 0,cwd:e.cwd?Gt(e.cwd,4096):void 0,userPrompt:e.userPrompt?Wt(e.userPrompt):void 0,turns:ds(void 0,{userPrompt:t.suppressPromptTurn?void 0:e.userPrompt,turns:e.turns},s,r),status:As(e.status||"idle"),phase:Is(e.phase||"unknown"),summary:e.summary?Gt(e.summary,1e3):void 0,startedAt:s,updatedAt:s,counters:{toolCalls:0,edits:0,approvals:0},queue:{pendingCount:0,items:[]}};return this.put(i),i}get(e){return Ss(us(this.sessionPath(e)))}put(e){var t,n;return ps(this.dir),t=this.sessionPath(e.id),n=e,ps(s.dirname(t)),h.sync(t,`${JSON.stringify(n,null,2)}\n`,{encoding:"utf8"}),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||cs(),o=s.suppressPromptTurn?{...t,userPrompt:void 0}:t,a=s.suppressTurnUpdate?ss(s.replaceTurns?void 0:n.turns):ds(s.replaceTurns?void 0:n.turns,o,i,s.meta),d=t.userPrompt?Wt(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?As(t.status):n.status,phase:t.phase?Is(t.phase):n.phase,summary:s.replaceActivity?t.summary?Gt(t.summary,1e3):void 0:s.clearResponse?void 0:t.summary?Gt(t.summary,1e3):p?void 0:n.summary,lastMessage:s.replaceActivity?t.lastMessage?Wt(t.lastMessage):void 0:s.clearResponse?void 0:t.lastMessage?Wt(t.lastMessage):p?void 0:n.lastMessage,userPrompt:s.replaceActivity?t.userPrompt?Wt(t.userPrompt):void 0:t.userPrompt?Wt(t.userPrompt):n.userPrompt,turns:a,error:t.error?Gt(t.error,4e3):n.error,counters:r,queue:t.queue?gs(t.queue):n.queue};return this.put(u)}enqueueMessage(e,t,s=[]){const r=this.get(e);if(!r)return;const i=cs(),o={id:`aiq_${n.randomUUID().replace(/-/g,"").slice(0,20)}`,message:Wt(t),attachments:vs(s),status:"queued",createdAt:i,updatedAt:i},a=[...r.queue?.items||[],o],d=this.update(e,{queue:hs(a)},{updatedAt:i,suppressTurnUpdate:!0});return d&&s.length&&this.queuedAttachmentPayloads.set(o.id,s.slice(0,6)),d?{session:d,item:o}: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:Gt(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:hs(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:hs([...i,...o])},{suppressTurnUpdate:!0})}patchQueuedMessage(e,t,s){const n=this.get(e);if(!n)return;const r=cs();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:hs(o)},{updatedAt:r,suppressTurnUpdate:!0}):void 0}bindProviderSession(e,t){const s=this.get(e),n=s?Ns(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||cs(),s={...e,observedAt:t,sourcePriority:Jt(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=Yt(e);if("send-ack"===e.kind){const s=e.observedAt||cs(),r=Wt(e.userPrompt);return this.update(t,{activeTurnId:e.activeTurnId||Zt(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||!os(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=zs(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=zs(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?Gt(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=Yt(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=Yt(t),r=ss(t.turns,n),i=function(e,t){if(!os(e))return!1;const s=ss(e.turns).find(t=>t.id===e.activeTurnId);return!ss(t).some(t=>t.id===e.activeTurnId||Boolean(s?.userPrompt&&t.userPrompt===s.userPrompt&&is(t)&&!is(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&&!is(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:as(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?Ns(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=Os(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?Wt(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(){ps(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=>Ss(us(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=bs(s),n=t.get(e);t.set(e,n?_s(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(ws),updatedAt:cs()}}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=lt(t,s);if(!n?.text)return this.get(e);const r=n.timestamp||cs();if("user"===n.kind){const t=Wt(n.text),i=n.key||n.timestamp;if(i)s.activeTurnId=es(t,i);else{s.promptCounts||=new Map;const e=(s.promptCounts.get(t)||0)+1;s.promptCounts.set(t,e),s.activeTurnId=es(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=Os(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=lt(a,n);if(!e?.text)continue;const t=e.timestamp||s.mtime.toISOString();if("user"===e.kind){const s=Wt(e.text);r.userPrompt=s;const n=e.key||e.timestamp;if(n)i=es(s,n);else{const e=(o.get(s)||0)+1;o.set(s,e),i=es(s,void 0,e)}r.turns=ds(r.turns,{activeTurnId:i,userPrompt:s},t);continue}r.summary=Gt(e.text,1e3),r.lastMessage=Wt(e.text),r.turns=ds(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?cs():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:Yt({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 Es(e={}){return new xs(e)}function ks(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 Ds{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 Ps{id="claude-app-session-binding";refresh(e){!function(e=Es(),n=[],r=process.env.CLAUDE_HOME||s.join(i.homedir(),".claude")){const o=function(e){const n=function(e=process.env.CLAUDE_HOME||s.join(i.homedir(),".claude")){return s.join(e,"sessions")}(e);let r=[];try{r=t.readdirSync(n,{withFileTypes:!0})}catch{return new Map}const o=new Map;for(const e of r){if(!e.isFile()||!e.name.endsWith(".json"))continue;const t=us(s.join(n,e.name)),r=Number(t?.pid||s.basename(e.name,".json"));t?.sessionId&&Number.isInteger(r)&&r>0&&o.set(r,t)}return o}(r);for(const t of n){const s=Gt(t.appId,120),n=Gt(t.id,120),i=Gt(t.status,80).toLowerCase(),a=Number(t.process?.pid);if("claude"!==s||!n||i&&"running"!==i||!Number.isInteger(a)||a<=0)continue;const d=o.get(a),c=Gt(d?.sessionId,240);if(!c)continue;const p=Gt(d?.cwd||t.tty?.cwd||t.launch?.cwd,4096);e.applyAdapterSnapshot({agent:"claude",appId:s,appSessionId:n,providerSessionId:c,title:Gt(t.title,240)||"Claude",cwd:p,transcriptPath:ut(c,p,r),status:ks(d?.status)})}e.snapshot()}(e.registry,e.appSessions)}}class Cs{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 Fs=function(){try{return ie.parse(JSON.parse(t.readFileSync(re,"utf8")))}catch(e){return e&&"object"==typeof e&&"code"in e&&e.code,{}}}();Number(Fs.defaultConversationId),process.env.TASK_HANDOFF_SOCKET||s.join(i.tmpdir(),`task-handoff-${process.getuid?process.getuid():"user"}.sock`);const Ms=Fs.chatTools?.telegram?.default||{},Rs=Ms.defaultChatId,js=Rs?Fs.chatBindings?.telegram?.default?.[Rs]:void 0;function Hs(e){return Array.isArray(e)?e.map(e=>String(e).trim()).filter(Boolean):String(e||"").split(",").map(e=>e.trim()).filter(Boolean)}Ms.token,Hs(Ms.allowedUserIds),Number(js?.conversationId);const $s=Fs.wechat||{};$s.baseUrl,$s.chatId,$s.contextToken,$s.token,$s.updatesBuf,Number($s.conversationId);const Ls=Fs.chatTools?.dingding?.default||{},Us=Ls.defaultChatId,qs=Us?Fs.chatBindings?.dingding?.default?.[Us]:void 0;Ls.clientId,Ls.clientSecret,Ls.corpId,Ls.robotCode,Ls.cardTemplateId,Ls.cardCallbackRouteKey,Number(Ls.cardUserIdType),Hs(Ls.allowedUserIds),Number(qs?.conversationId);const Bs=process.env.TASK_HANDOFF_RECEIVER_LOG||(process.env.TASK_HANDOFF_LOG_DIR?`${process.env.TASK_HANDOFF_LOG_DIR}/receiver.log`:void 0)||(Ks=re,Vs="receiver.log",process.env.CODEX_SANDBOX?s.join(process.cwd(),".task-handoff",Vs):s.join(s.dirname(Ks),Vs));var Ks,Vs;class Gs{registry;client;id="claude-control-sock";agent="claude";subscriptions=new Map;textByShort=new Map;constructor(e,t={list:()=>pe({op:"list"},{timeoutMs:Number(process.env.TASK_HANDOFF_CLAUDE_CONTROL_TIMEOUT_MS)||5e3}),reply:ue,kill:le,subscribe:me}){this.registry=e,this.client=t}async refresh(e){if(!tn("TASK_HANDOFF_AI_SESSION_SCAN",!0)||!tn("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(rn),r=new Map;for(const e of n){const t=Ys(e.ai?.claude?.short,80);t&&r.set(t,e)}for(const e of n){const t=Ys(e.ai?.claude?.short,80);if(!t)continue;const n=s.find(e=>e.short===t);this.upsertJob(n||sn(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=>Ys(e.short,80)).filter(Boolean),...Array.from(r.keys())])),e.registry.reconcileAdapterSessions({agent:this.agent,appSessionIds:new Set(n.map(e=>Ys(e.id,120)).filter(Boolean)),providerSessionIds:new Set(s.map(e=>Ys(e.sessionId,240)).filter(Boolean)),providerShorts:new Set([...s.map(e=>Ys(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 Ke(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 Xe("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 Xe("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 Xe("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=Ys(e.short,80);if(!s)return;const n=Ys(e.sessionId||t?.ai?.claude?.providerSessionId,240),r=Ys(e.cwd||t?.ai?.claude?.cwd||t?.tty?.cwd||t?.launch?.cwd,4096),i=this.sessionForShort(s),o=Ws(e.state||t?.ai?.claude?.state,{hasWorkSignal:Js(e),isAppSession:Boolean(t||i?.appSessionId)}),a=Ys(t?.ai?.claude?.controlSock,4096)||ce();this.registry.applyAdapterSnapshot({source:"adapter-snapshot",agent:"claude",appId:Ys(t?.appId,120)||(t?"claude":"claude-daemon"),appSessionId:Ys(t?.id,120),providerSessionId:n,appBindingKeys:nn(t,s),actions:Xs(o),providerMeta:{short:s,controlSock:a,pid:Number(e.pid||t?.ai?.claude?.pid)||void 0,state:Ys(e.state||t?.ai?.claude?.state,80),tempo:Ys(e.tempo||t?.ai?.claude?.tempo,80),cliVersion:Ys(e.cliVersion||t?.ai?.claude?.cliVersion,80),source:Ys(e.source||t?.ai?.claude?.source,80)},title:Ys(t?.title,240)||"Claude",cwd:r,transcriptPath:ut(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=Qs(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?Ws(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:Xs(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=Qs(e.patch),n="settled"===Ys(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=>Ys(e.value,80));return{observedState:Ys(r?.value,80),lifecycleState:Ys(n,80),source:r?.source,patch:s}}logSubscribeMessage(e,t,s,n,r,i,o){if(tn("TASK_HANDOFF_DIAGNOSTIC_LOGS"))try{w(Bs,{event:"claude_control_subscribe",short:e,controlSock:t,messageType:Ys(s.type,80)||void 0,state:r.observedState||void 0,lifecycleState:r.lifecycleState||void 0,stateSource:r.source,recordState:Ys(n?.state,80)||void 0,patchKeys:r.patch?Object.keys(r.patch).sort():void 0,outcome:Ys(s.outcome,80)||void 0,streamLineBytes:"string"==typeof s.line?Buffer.byteLength(s.line):void 0,streamTailCount:Zs(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=[...Zs(t.streamTail).map(e=>String(e||"")),...Zs(t.output).map(e=>String(e||"")),en(t.data),en(t.text),en(t.delta),en(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 Xe("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 Ws(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 Xs(e){return{send:!0,interrupt:"running"===e?.status||"waiting"===e?.status,approval:!1}}function Js(e){return Boolean(Ys(e.detail,500)||Ys(e.intent,500)||Ys(e.needs,500))}function Ys(e,t=500){const s=String(e??"").replace(/\s+/g," ").trim();return s.length>t?`${s.slice(0,t-3)}...`:s}function Qs(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:void 0}function Zs(e){return Array.isArray(e)?e:[]}function en(e){return"string"==typeof e?e:""}function tn(e,t=!1){const s=process.env[e];return void 0===s||""===s?t:!["0","false","no","off"].includes(String(s).toLowerCase())}function sn(e){const t=e.ai?.claude,s=Ys(t?.short,80);if(s)return{short:s,sessionId:Ys(t?.providerSessionId,240)||void 0,pid:Number(t?.pid)||void 0,cwd:Ys(t?.cwd||e.tty?.cwd||e.launch?.cwd,4096)||void 0,state:Ys(t?.state,80)||void 0,tempo:Ys(t?.tempo,80)||void 0,cliVersion:Ys(t?.cliVersion,80)||void 0,source:Ys(t?.source,80)||void 0}}function nn(e,t){const s=[e?.id?`app:${Ys(e.id,120)}`:"",t?`claude-short:${t}`:""].filter(Boolean);return s.length?s:void 0}function rn(e){const t=Ys(e.status,80).toLowerCase();return!t||"running"===t}function on(e){return"allow"===e?"allowed":"deny"===e?"denied":"skipped"}function an(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}function dn(e){const t=e.turn&&"object"==typeof e.turn?e.turn:void 0;return"string"==typeof t?.id?t.id:void 0}function cn(e){return e instanceof Error&&/no active turn/i.test(e.message)}function pn(e){if(e instanceof Error)return e.message.match(/expected active turn id `[^`]+` but found `([^`]+)`/i)?.[1]}function un(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 ln(e,t){const s=e[t];return"string"==typeof s&&s.trim()?s:void 0}function mn(e){const t=an(e);return"text"===t.type&&"string"==typeof t.text?t.text.trim():""}function hn(e){return(Array.isArray(e.content)?e.content:[]).map(mn).filter(Boolean).join("\n").trim()}class gn 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:dn(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=an(e.params.permissions),n=an(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 o.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 a=!1;const d=e=>{a||(a=!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)=>{a?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",()=>{a=!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=ln(s,"threadId");if(!n)return;const r=ln(s,"command"),i=ln(s,"reason");return{id:e,method:t,kind:"command",threadId:n,turnId:ln(s,"turnId"),itemId:ln(s,"itemId"),summary:i||(r?`Approve command: ${r}`:"Codex is requesting command approval."),params:s}}if("item/fileChange/requestApproval"===t){const n=ln(s,"threadId");if(!n)return;const r=ln(s,"grantRoot");return{id:e,method:t,kind:"file-change",threadId:n,turnId:ln(s,"turnId"),itemId:ln(s,"itemId"),summary:ln(s,"reason")||(r?`Approve file changes under ${r}`:"Codex is requesting file change approval."),params:s}}if("item/permissions/requestApproval"===t){const n=ln(s,"threadId");if(!n)return;return{id:e,method:t,kind:"permissions",threadId:n,turnId:ln(s,"turnId"),itemId:ln(s,"itemId"),summary:ln(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=an(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=hn(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 fn{registry;id="codex-app-server";agent="codex";client;started=!1;retryAfter=0;activeSocketPath;appSessions=[];agentMessageBuffers=new Map;approvals=new Ve;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 Ke(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 Ke(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 Ke(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 Xe("AI_SESSION_NO_ACTIVE_TURN","AI session has no active turn to steer.",409);if(!e.steerTurn)throw Xe("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=pn(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(!cn(s))throw s;return this.startTurn(e,t,n)}}async startTurn(e,t,s){if(!e.startTurn)throw Xe("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 Xe("AI_SESSION_NO_ACTIVE_TURN","AI session has no active turn to interrupt.");if(!t.interruptTurn)throw Xe("AI_SESSION_INTERRUPT_UNSUPPORTED","Codex app-server client does not support turn interruption.");try{await t.interruptTurn(s,n)}catch(r){const i=pn(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(!cn(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 ${on(t)}.`,source:"control"})||e,provider:this.agent,action:"approval",decision:t};throw Xe("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 gn(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=un(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=un(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=an(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=an(e);if("userMessage"===n.type){const e=hn(n);e&&!Je(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 Xe("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 Xe("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,appInventory:e.appInventory,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,appInventory:t.appInventory,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 vn(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"}const Sn=l.z.enum(["ai.sessions","app.sessions"]),An=l.z.object({topic:Sn,instanceId:l.z.string().trim().min(1).max(160),streamId:l.z.string().trim().min(1).max(240),latestRevision:l.z.number().int().min(0),earliestRetainedRevision:l.z.number().int().min(0)}).strict();l.z.object({protocolVersion:l.z.literal(1),streams:l.z.array(An)}).strict();class In{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&&bn(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:vn(e),createdAt:(new Date).toISOString(),payload:t}}}function bn(e,t,s){return!e||e.has("*")||e.has(t)||e.has(s)}function _n(){return process.env.HOME||i.homedir()||"/home/agent"}function wn(){return process.env.TASK_HANDOFF_WORKSPACE||process.env.WORKSPACE||"/workspace"}function Tn(){const e=_n(),t=function(){const e=[s.join(_n(),".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 On(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 zn(e,t,n){const r=n||Tn().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(wn(),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:_n(),WORKSPACE:wn(),CODEX_HOME:process.env.CODEX_HOME||s.join(_n(),".codex"),CLAUDE_HOME:process.env.CLAUDE_HOME||s.join(_n(),".claude")};return e.replace(/\$\{([A-Z_]+)\}/g,(e,s)=>t[s]||e)}(e));if(![s.resolve(_n()),s.resolve(wn()),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:On(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}}function Nn(e,r){const i=s.dirname(e);t.mkdirSync(i,{recursive:!0,mode:448});const o=s.join(i,`.${s.basename(e)}.${process.pid}.${n.randomUUID()}.tmp`);try{t.writeFileSync(o,r,{encoding:"utf8",mode:384}),t.renameSync(o,e),t.chmodSync(e,384)}finally{t.rmSync(o,{force:!0})}}function xn(e=process.env){if("controlled"!==e.TASK_HANDOFF_CONTROL_MODE)return{applied:!1};const n=(e.TASK_HANDOFF_CODEX_MODEL||e.CODEX_MODEL||"").trim(),r=(e.TASK_HANDOFF_CODEX_BASE_URL||e.OPENAI_BASE_URL||"").trim(),o=(e.OPENAI_API_KEY||"").trim(),a=function(e){const t=e.CODEX_HOME?.trim();return s.resolve(t||s.join(e.HOME||i.homedir(),".codex"))}(e),d=s.join(a,"config.toml"),c=s.join(a,"auth.json");let p=!1;if(o){let e="";try{const s=JSON.parse(t.readFileSync(c,"utf8"));e="apikey"===s.auth_mode&&"string"==typeof s.OPENAI_API_KEY?s.OPENAI_API_KEY:""}catch{e=""}e!==o&&(Nn(c,`${JSON.stringify({auth_mode:"apikey",OPENAI_API_KEY:o},null,2)}\n`),p=!0)}else t.existsSync(c)&&(t.rmSync(c,{force:!0}),p=!0);if(!n||!r)return{applied:p,authPath:c};const u=function(e){try{const n=t.readFileSync(e,"utf8");return{contents:n,config:(s=n.trim()?v.parse(n):{},s&&"object"==typeof s&&!Array.isArray(s)?s:{})}}catch(t){if(t&&"object"==typeof t&&"code"in t&&"ENOENT"===t.code)return{contents:"",config:{}};throw Object.assign(new Error(`Codex config could not be read or parsed at ${e}: ${t instanceof Error?t.message:String(t)}`),{code:"CODEX_MODEL_CONFIG_INVALID"})}var s}(d);if(u.config.model===n&&"openai"===u.config.model_provider&&u.config.openai_base_url===r)return{applied:p,configPath:d,authPath:c};const l={...u.config,model:n,model_provider:"openai",openai_base_url:r};let m;return u.contents&&(m=`${d}.bak.${(new Date).toISOString().replace(/[:.]/g,"-")}`,t.copyFileSync(d,m),t.chmodSync(m,384)),Nn(d,v.stringify(l)),{applied:!0,configPath:d,authPath:c,backupPath:m}}const En="2026-07-15",kn=l.z.string(),Dn=l.z.string().trim().min(1).max(120).regex(/^[a-zA-Z0-9][a-zA-Z0-9_.:-]*$/),Pn=l.z.string().datetime(),Cn=l.z.record(l.z.string(),l.z.string()).default({}),Fn=l.z.record(l.z.string(),l.z.string()).default({}),Mn=l.z.object({codexModelHash:Dn.optional(),claudeModelHash:Dn.optional()}).strict().default({}),Rn=l.z.object({id:Dn,name:l.z.string().trim().min(1).max(120),kind:l.z.enum(["tty","gui","web"]),source:l.z.enum(["builtin","custom"]),availability:l.z.enum(["available","missing-dependency"]),capabilities:l.z.object({automation:l.z.enum(["cdp"]).optional(),supportsCwdSelection:l.z.boolean().default(!1)}).strict().default({supportsCwdSelection:!1}),diagnosticCode:l.z.enum(["APP_EXECUTABLE_NOT_FOUND"]).optional()}).strict(),jn=l.z.object({code:l.z.enum(["APP_CATALOG_INVALID"]),message:l.z.string().trim().min(1).max(500)}).strict(),Hn=l.z.object({items:l.z.array(Rn).max(256),observedAt:Pn,issues:l.z.array(jn).max(32).default([])}).strict(),$n=l.z.object({component:l.z.enum(["control-plane","node-agent","controlled-instance"]),packageName:l.z.string().trim().max(160).optional(),packageVersion:l.z.string().trim().max(80).optional(),protocolVersion:kn.optional(),buildId:l.z.string().trim().max(160).optional(),builtAt:l.z.string().trim().max(120).optional(),gitCommit:l.z.string().trim().max(120).optional(),imageRef:l.z.string().trim().max(512).optional(),imageDigest:l.z.string().trim().max(240).optional()}).strict(),Ln=l.z.enum(["stable","beta","alpha"]),Un=l.z.discriminatedUnion("component",[l.z.object({component:l.z.literal("node-agent")}).strict(),l.z.object({component:l.z.literal("controlled-instance"),instanceId:Dn}).strict()]);l.z.object({target:Un,channel:Ln.default("stable")}).strict(),l.z.object({target:Un,source:l.z.enum(["npm","docker-registry"]),channel:Ln,currentVersion:l.z.string().trim().max(240).optional(),availableVersion:l.z.string().trim().min(1).max(240),artifactRef:l.z.string().trim().min(1).max(512).optional(),updateAvailable:l.z.boolean(),supported:l.z.boolean().default(!0),reason:l.z.string().trim().max(2048).optional(),checkedAt:Pn}).strict(),l.z.object({id:Dn,nodeId:Dn,target:Un,source:l.z.enum(["npm","docker-registry"]),channel:Ln,fromVersion:l.z.string().trim().max(240).optional(),toVersion:l.z.string().trim().min(1).max(240),artifactRef:l.z.string().trim().min(1).max(512).optional(),status:l.z.enum(["queued","updating","restarting","succeeded","failed"]),error:l.z.string().trim().max(4096).optional(),startedAt:Pn.optional(),completedAt:Pn.optional(),createdAt:Pn,updatedAt:Pn}).strict();const qn=l.z.object({type:l.z.enum(["branch","tag","commit"]),name:l.z.string().trim().min(1).max(240).optional(),commit:l.z.string().trim().max(80).optional()}).strict(),Bn=l.z.object({type:l.z.enum(["none","ssh-key","https-token"]).default("none"),secretId:l.z.string().trim().min(1).max(120).optional()}).strict(),Kn=l.z.object({depth:l.z.number().int().positive().max(1e5).optional(),submodules:l.z.boolean().default(!1),lfs:l.z.boolean().default(!1),subdirectory:l.z.string().trim().max(240).default("")}).strict();l.z.object({id:Dn,name:l.z.string().trim().min(1).max(160),url:l.z.string().trim().min(1).max(2048),provider:l.z.string().trim().max(80).optional(),ref:qn.default({type:"branch",name:"main"}),auth:Bn.default({type:"none"}),clone:Kn.default({submodules:!1,lfs:!1,subdirectory:""}),defaultImageId:Dn.optional(),labels:Cn,createdAt:Pn,updatedAt:Pn}).strict(),l.z.object({id:Dn,nodeId:Dn,name:l.z.string().trim().min(1).max(160),path:l.z.string().trim().min(1).max(4096),defaultImageId:Dn.optional(),labels:Cn,createdAt:Pn,updatedAt:Pn}).strict();const Vn=l.z.discriminatedUnion("type",[l.z.object({type:l.z.literal("git-repository"),repositoryId:Dn.optional(),url:l.z.string().trim().min(1).max(2048),provider:l.z.string().trim().max(80).optional(),ref:qn.default({type:"branch",name:"main"}),auth:Bn.default({type:"none"}),clone:Kn.default({submodules:!1,lfs:!1,subdirectory:""})}).strict(),l.z.object({type:l.z.literal("git-template"),url:l.z.string().trim().min(1).max(2048),templateId:l.z.string().trim().min(1).max(120).optional(),ref:qn.default({type:"branch",name:"main"}),auth:Bn.default({type:"none"}),clone:Kn.default({submodules:!1,lfs:!1,subdirectory:""})}).strict(),l.z.object({type:l.z.literal("local-folder"),localFolderId:Dn.optional(),path:l.z.string().trim().min(1).max(4096),ownerNodeId:Dn.optional()}).strict()]),Gn=l.z.object({mode:l.z.enum(["local-bind","git-clone","empty-volume","persistent-volume"]),path:l.z.string().trim().min(1).max(4096).default("/workspace"),volumeName:l.z.string().trim().max(240).optional(),readOnly:l.z.boolean().default(!1)}).strict(),Wn=l.z.enum(["codex","claude"]);l.z.object({id:Dn,name:l.z.string().trim().min(1).max(160),source:Vn,defaultImageId:Dn.optional(),defaultNodeId:Dn.optional(),defaultRuntimeId:Dn.optional(),workspacePolicy:Gn,labels:Cn,createdAt:Pn,updatedAt:Pn}).strict();const Xn=l.z.object({id:Dn,name:l.z.string().trim().min(1).max(160),endpoint:l.z.string().trim().min(1).max(2048),key:l.z.string().trim().min(1).max(4096),model:l.z.string().trim().min(1).max(240),app:Wn,enabled:l.z.boolean().default(!0),order:l.z.number().int().min(0).max(1e6).default(0),labels:Cn,createdAt:Pn,updatedAt:Pn}).strict(),Jn=Xn.omit({key:!0}).extend({keyPreview:l.z.string().trim().min(1).max(160),keySet:l.z.boolean()}).strict();Jn.extend({referenceCount:l.z.number().int().min(0)}).strict(),l.z.object({instanceId:Dn,codexModelHash:Dn.optional(),claudeModelHash:Dn.optional(),updatedAt:Pn}).strict();const Yn=l.z.discriminatedUnion("type",[l.z.object({type:l.z.literal("control-plane"),name:Xn.shape.name,enabled:Xn.shape.enabled,order:Xn.shape.order}).strict(),l.z.object({type:l.z.literal("node"),nodeId:Dn,name:Xn.shape.name,enabled:Xn.shape.enabled,order:Xn.shape.order,referenceCount:l.z.number().int().min(0)}).strict()]),Qn=l.z.object({id:Dn,model:Jn,locations:l.z.array(Yn).min(1),referenceCount:l.z.number().int().min(0).default(0)}).strict(),Zn=l.z.object({nodeId:Dn,code:l.z.string().trim().min(1).max(120),message:l.z.string().trim().min(1).max(2e3)}).strict();l.z.object({models:l.z.array(Qn),nodeDiagnostics:l.z.array(Zn).default([]),updatedAt:Pn}).strict(),Xn.omit({id:!0,createdAt:!0,updatedAt:!0}).strict().partial().strict(),l.z.object({modelSelection:Mn,codexModelHash:Dn.optional(),claudeModelHash:Dn.optional()}).strict();const er=l.z.object({id:Dn,name:l.z.string().trim().min(1).max(160),image:l.z.string().trim().min(1).max(512),registry:l.z.string().trim().min(1).max(160).default("local"),capabilities:l.z.array(l.z.string().trim().min(1).max(80)).default([]),optionalApps:l.z.array(l.z.string().trim().min(1).max(120)).default([]),defaultEnv:Fn,labels:Cn,createdAt:Pn,updatedAt:Pn}).strict();l.z.object({id:Dn,name:l.z.string().trim().min(1).max(160),connectionMode:l.z.enum(["local-ipc","local-loopback","direct-http","reverse-wss"]).default("direct-http"),auth:l.z.object({mode:l.z.enum(["local-static-key","paired-hmac"]).default("local-static-key"),keyId:Dn.optional(),secret:l.z.string().trim().max(4096).optional(),pairedAt:Pn.optional(),pairing:l.z.object({status:l.z.enum(["pending","paired","expired"]).default("pending"),joinToken:l.z.string().trim().max(4096).optional(),expiresAt:Pn.optional()}).strict().optional()}).strict().default({mode:"local-static-key"}),endpoint:l.z.string().trim().max(2048).optional(),controlEndpoint:l.z.string().trim().max(2048).optional(),containerEndpoint:l.z.string().trim().max(2048).optional(),publicWebBase:l.z.string().trim().max(2048).optional(),status:l.z.enum(["unknown","online","offline","degraded"]).default("unknown"),health:l.z.enum(["unknown","ok","degraded","failed"]).default("unknown"),capabilities:l.z.record(l.z.string(),l.z.unknown()).default({}),appInventory:Hn.optional(),labels:Cn,lastSeenAt:Pn.optional(),createdAt:Pn,updatedAt:Pn}).strict(),l.z.object({id:Dn,nodeId:Dn,name:l.z.string().trim().min(1).max(160),type:l.z.enum(["docker","kubernetes","local"]),status:l.z.enum(["unknown","online","offline","degraded"]).default("unknown"),accessStrategy:l.z.enum(["node-proxy","direct-port","kubernetes-ingress","kubernetes-port-forward"]).default("node-proxy"),capabilities:l.z.record(l.z.string(),l.z.unknown()).default({}),labels:Cn,createdAt:Pn,updatedAt:Pn}).strict(),l.z.object({ok:l.z.boolean().optional(),role:l.z.string().optional(),nodeId:Dn.optional()}).passthrough(),l.z.object({bindScope:l.z.enum(["loopback","all-ipv4"]),port:l.z.number().int().min(1).max(65535)}).strict().extend({host:l.z.enum(["127.0.0.1","0.0.0.0"]),status:l.z.enum(["listening","error"]),source:l.z.enum(["bootstrap","persisted"]),error:l.z.string().trim().max(2048).optional()}).strict(),l.z.object({nodeId:Dn,joinToken:l.z.string().trim().min(1),expiresAt:Pn}).passthrough(),l.z.object({id:Dn,keyId:Dn,url:l.z.string().trim().min(1).max(2048).optional(),name:l.z.string().trim().min(1).max(160).optional(),pairedAt:Pn,updatedAt:Pn.optional(),active:l.z.boolean().optional(),current:l.z.boolean().optional()}).passthrough(),l.z.object({remote:l.z.object({id:Dn,url:l.z.string().trim().min(1).max(2048).optional(),keyId:Dn,pairedAt:Pn,active:l.z.boolean()}).passthrough(),tunnel:l.z.object({status:l.z.enum(["disabled","saved","connecting","connected","failed"]),error:l.z.string().trim().max(2048).optional()}).passthrough()}).passthrough(),l.z.object({deleted:l.z.boolean().optional()}).passthrough(),l.z.object({repository:l.z.string().trim().optional(),tag:l.z.string().trim().optional(),id:l.z.string().trim(),createdSince:l.z.string().trim().optional(),size:l.z.string().trim().optional(),reference:l.z.string().trim().min(1)}).passthrough();const tr=l.z.lazy(()=>l.z.object({name:l.z.string().trim().min(1),path:l.z.string().trim().min(1).max(4096),children:l.z.array(tr)}).passthrough());l.z.object({status:l.z.number().int().min(100).max(599).optional(),headers:l.z.record(l.z.string(),l.z.string()).optional(),bodyBase64:l.z.string().optional()}).passthrough();const sr=l.z.object({strategy:l.z.enum(["node-proxy","direct-port","kubernetes-ingress","kubernetes-port-forward"]).default("node-proxy"),web:l.z.string().trim().max(2048).optional(),api:l.z.string().trim().max(2048).optional(),vnc:l.z.string().trim().max(2048).optional(),tty:l.z.string().trim().max(2048).optional(),logs:l.z.string().trim().max(2048).optional(),status:l.z.enum(["unknown","reachable","endpoint-unreachable"]).default("unknown")}).strict(),nr=l.z.object({strategy:l.z.enum(["control-plane-proxy","direct-port","node-proxy","kubernetes-ingress","kubernetes-port-forward"]).default("control-plane-proxy"),web:l.z.string().trim().max(2048).optional(),api:l.z.string().trim().max(2048).optional(),ws:l.z.string().trim().max(2048).optional(),status:l.z.enum(["unknown","reachable","endpoint-unreachable"]).default("unknown")}).strict().default({strategy:"control-plane-proxy",status:"unknown"}),rr=l.z.object({mode:l.z.enum(["local-bind","git-clone","empty-volume","persistent-volume"]).optional(),status:l.z.enum(["unknown","pending","ready","failed"]).default("unknown"),path:l.z.string().trim().max(4096).optional(),resolvedCommit:l.z.string().trim().max(120).optional(),error:l.z.string().trim().max(2048).optional()}).passthrough(),ir=l.z.object({id:Dn,name:l.z.string().trim().min(1).max(160),projectId:Dn.optional(),source:Vn,sourceSnapshot:l.z.record(l.z.string(),l.z.unknown()).default({}),modelSelection:Mn,nodeId:Dn,runtimeId:Dn,imageId:Dn.optional(),imageSnapshot:er.optional(),status:l.z.enum(["created","provisioning","starting","registering","registered","running","stopping","stopped","failed","unhealthy"]).default("created"),health:l.z.enum(["unknown","ok","degraded","failed"]).default("unknown"),connectionStatus:l.z.enum(["unknown","online","offline","endpoint-unreachable"]).default("unknown"),agentStatus:l.z.enum(["unknown","online","offline"]).default("unknown"),targetStatus:l.z.enum(["unknown","reachable","endpoint-unreachable"]).default("unknown"),uiAccessStatus:l.z.enum(["unknown","reachable","endpoint-unreachable"]).default("unknown"),controlMode:l.z.enum(["standalone","controlled"]).default("controlled"),protocolVersion:kn.optional(),instanceVersion:l.z.string().trim().max(80).optional(),build:$n.optional(),capabilities:l.z.record(l.z.string(),l.z.unknown()).default({}),appInventory:Hn.optional(),config:l.z.object({autoImportAgentConfigs:l.z.boolean().default(!0)}).strict().default({autoImportAgentConfigs:!0}),workspace:rr.default({status:"unknown"}),target:sr.default({strategy:"direct-port",status:"unknown"}),access:nr,apps:l.z.object({runningCount:l.z.number().int().min(0).default(0),problemCount:l.z.number().int().min(0).default(0),updatedAt:Pn.optional(),revision:l.z.number().int().min(0).optional()}).strict().default({runningCount:0,problemCount:0}),aiSessions:Rt.default(()=>({runningCount:0,waitingCount:0,staleCount:0,sessions:[],updatedAt:(new Date).toISOString()})),triggers:l.z.object({enabledCount:l.z.number().int().min(0).default(0),runningCount:l.z.number().int().min(0).default(0),errorCount:l.z.number().int().min(0).default(0),configs:l.z.array(l.z.object({configHash:l.z.string().trim().min(1),config:j,deployments:l.z.array($).default([]),runtime:l.z.array(L).default([])}).strict()).default([]),recentRuns:l.z.array(U).default([])}).strict().optional(),runtime:l.z.object({kind:l.z.string().trim().max(80).optional(),containerName:l.z.string().trim().max(240).optional(),containerId:l.z.string().trim().max(240).optional(),workspacePath:l.z.string().trim().max(4096).optional(),pid:l.z.number().int().positive().optional(),port:l.z.number().int().positive().max(65535).optional(),labels:l.z.record(l.z.string(),l.z.string()).default({})}).strict().default({labels:{}}),registrationToken:l.z.string().trim().min(1).max(240).optional(),lastHeartbeatAt:Pn.optional(),createdAt:Pn,updatedAt:Pn}).strict();l.z.object({instanceId:Dn.optional(),name:l.z.string().trim().min(1).max(160),projectId:Dn.optional(),source:Vn.optional(),nodeId:Dn.optional(),runtimeId:Dn.optional(),imageId:Dn.optional(),instanceVersion:l.z.string().trim().max(80).optional(),protocolVersion:kn,build:$n.optional(),controlMode:l.z.enum(["standalone","controlled"]).default("controlled"),capabilities:l.z.record(l.z.string(),l.z.unknown()).default({}),appInventory:Hn.optional(),target:sr.default({strategy:"direct-port",status:"unknown"}),workspace:rr.default({status:"unknown"}),registrationToken:l.z.string().trim().max(240).optional()}).strict().superRefine((e,t)=>{e.protocolVersion!==En||e.appInventory||t.addIssue({code:"custom",path:["appInventory"],message:"Current protocol register payload requires appInventory."})}),l.z.object({status:ir.shape.status.optional(),health:ir.shape.health.optional(),protocolVersion:kn,build:$n.optional(),capabilities:ir.shape.capabilities.optional(),appInventory:Hn.optional(),apps:ir.shape.apps.optional(),aiSessions:ir.shape.aiSessions.optional(),triggers:ir.shape.triggers.optional(),workspace:rr.optional(),target:sr.partial().optional()}).strict().superRefine((e,t)=>{e.protocolVersion!==En||e.appInventory||t.addIssue({code:"custom",path:["appInventory"],message:"Current protocol heartbeat payload requires appInventory."})});const or=l.z.enum(["web","telegram","wechat","dingding"]);function ar(){try{const e=s.resolve(__dirname,"..","package.json");return JSON.parse(t.readFileSync(e,"utf8")).version||"unknown"}catch{return"unknown"}}function dr(e){const t=process.env[e]?.trim();return t||void 0}function cr(e,n){const r=[{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=Te(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&&r.every(e=>e.available)&&Boolean(n)&&o.every(e=>e.writable),runtime:{platform:process.platform,arch:process.arch,linuxRuntime:a,node:process.version,pid:process.pid,hostname:i.hostname(),uptimeSeconds:Math.round(process.uptime())},noVnc:{available:Boolean(n),root:n},commands:r,storage:o}}function pr(){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 ur(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 lr(e){const t=e.catalog();return{protocolVersion:En,features:{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 mr(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 hr(e,t,s=Es(),n){const r=e.listSessions();return{status:"running",health:"ok",instanceVersion:ar(),protocolVersion:En,build:{component:"controlled-instance",packageName:"@task-handoff/controlled-instance",packageVersion:ar(),protocolVersion:En,buildId:dr("TASK_HANDOFF_BUILD_ID"),builtAt:dr("TASK_HANDOFF_BUILT_AT"),gitCommit:dr("TASK_HANDOFF_GIT_COMMIT"),imageRef:dr("TASK_HANDOFF_IMAGE_REF"),imageDigest:dr("TASK_HANDOFF_IMAGE_DIGEST")},controlMode:"controlled"===process.env.TASK_HANDOFF_CONTROL_MODE?"controlled":"standalone",capabilities:lr(e),appInventory:e.appInventory(),apps:{runningCount:e.runningSessionCount(),problemCount:e.problemSessionCount()},aiSessions:s.boundSnapshot(r),triggers:n?mr(n):void 0,workspace:ur(t),target:pr()}}l.z.object({id:Dn,channel:or,name:l.z.string().trim().min(1).max(160),enabled:l.z.boolean().default(!1),token:l.z.string().trim().max(4096).optional(),defaultChatId:l.z.string().trim().max(240).optional(),allowedUserIds:l.z.array(l.z.string().trim().min(1).max(240)).default([]),pollIntervalMs:l.z.number().int().positive().max(6e4).default(3e3),settings:l.z.record(l.z.string(),l.z.unknown()).default({}),createdAt:Pn,updatedAt:Pn}).strict(),l.z.object({id:Dn,channel:or,bridgeId:Dn.optional(),chatSessionId:l.z.string().trim().min(1).max(240),userId:l.z.string().trim().max(240).optional(),activeProjectId:Dn.optional(),activeInstanceId:Dn.optional(),activeAiSessionId:l.z.string().trim().min(1).max(120).optional(),lastUsedAt:Pn,createdAt:Pn,updatedAt:Pn}).strict(),l.z.object({source:l.z.object({type:l.z.literal("chat-gateway").default("chat-gateway"),channel:or,bridgeId:Dn.optional(),chatSessionId:l.z.string().trim().min(1).max(240),userId:l.z.string().trim().max(240).optional()}).strict(),message:l.z.object({text:l.z.string().trim().max(2e4).default(""),attachments:l.z.array(It).max(6).default([])}).strict().superRefine((e,t)=>{e.attachments.reduce((e,t)=>e+t.size,0)>mt&&t.addIssue({code:l.z.ZodIssueCode.custom,path:["attachments"],message:"Images must be 41943040 bytes or less in total."})}),target:l.z.object({instanceId:Dn,aiSessionId:l.z.string().trim().min(1).max(120)}).strict().optional()}).strict(),l.z.object({id:Dn,instanceId:Dn,projectId:Dn.optional(),aiSessionId:l.z.string().trim().min(1).max(120),providerSessionId:l.z.string().trim().max(240).optional(),result:l.z.string().default(""),timeoutMs:l.z.number().positive().optional(),source:l.z.string().trim().max(120).optional(),kind:l.z.enum(["task","approval"]).default("task"),status:l.z.enum(["pending","unreachable"]).default("pending"),error:l.z.string().trim().max(2048).optional(),lastSeenAt:Pn}).strict();const gr=new Set(["ECONNREFUSED","ECONNRESET","EHOSTUNREACH"]);function fr(e){return new Promise(t=>setTimeout(t,e))}function yr(e){const t=e?.code;return Boolean(t&&gr.has(t))}function vr(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 Sr(){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 Ar(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 Ir(e,t,s,n={}){return Object.fromEntries(Object.entries(Ar(e,t,s,n)).filter(([e])=>{const t=e.toLowerCase();return!t.startsWith("sec-websocket-")||"sec-websocket-origin"===t}))}function br(e,t){const s=e[t];return Array.isArray(s)?s.join(","):s||""}function _r(e){if(br(e,"content-encoding"))return!1;const t=br(e,"content-type").toLowerCase();return t.includes("text/css")||t.includes("text/html")}function wr(e,t){const s=br(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 Tr(e){const t={};e.forEach((e,s)=>{t[s]=e});const s=e.getSetCookie?.();return s?.length&&(t["set-cookie"]=s),t}function Or(e){const t={};e.forEach((e,s)=>{t[s]=e});const s=e.getSetCookie?.();return s?.length&&(t["set-cookie"]=s),t}const zr="app-session.snapshot",Nr="app-session.patch",xr="app-session.removed",Er=36e5,kr=l.z.enum(["created","starting","running","stopping","stopped","exited","failed","closed","terminated","unknown"]),Dr=l.z.object({type:l.z.enum(["app-session","provider-session","adapter-key"]),id:l.z.string().trim().min(1).max(240),agent:l.z.string().trim().min(1).max(80).optional(),adapter:l.z.string().trim().min(1).max(80).optional(),key:l.z.string().trim().min(1).max(240).optional()}).strict(),Pr=l.z.record(l.z.string(),l.z.unknown()).and(l.z.object({id:l.z.string().trim().min(1).max(160),appId:l.z.string().trim().min(1).max(160).optional(),title:l.z.string().trim().max(240).optional(),kind:l.z.string().trim().max(80).optional(),status:kr.default("unknown"),bindings:l.z.array(Dr).max(40).default([]),workspace:l.z.object({cwd:l.z.string().trim().max(4096).optional()}).strict().optional(),createdAt:l.z.string().datetime().optional(),updatedAt:l.z.string().datetime().optional()})),Cr=l.z.object({runningCount:l.z.number().int().min(0).default(0),problemCount:l.z.number().int().min(0).default(0),sessions:l.z.array(Pr).default([]),updatedAt:l.z.string().datetime()}).strict();l.z.object({streamId:l.z.string().trim().min(1).max(240),revision:l.z.number().int().min(0),lastEventAt:l.z.string().datetime(),snapshot:Cr}).strict(),Cr.pick({runningCount:!0,problemCount:!0,updatedAt:!0}).extend({revision:l.z.number().int().min(0).optional()});const Fr=l.z.enum(["app-session-created","app-session-updated","app-session-deleted","app-session-recovered","control-action","heartbeat-sync","startup"]),Mr=l.z.object({streamId:l.z.string().trim().min(1).max(240),instanceId:l.z.string().trim().min(1).max(160),nodeId:l.z.string().trim().min(1).max(160).optional(),revision:l.z.number().int().min(0),previousRevision:l.z.number().int().min(0).optional(),traceId:l.z.string().trim().min(1).max(160),generatedAt:l.z.string().datetime(),reason:Fr}).strict(),Rr=l.z.object({meta:Mr,snapshot:Cr}).strict(),jr=l.z.object({meta:Mr,session:Pr}).strict(),Hr=l.z.object({meta:Mr,sessionId:l.z.string().trim().min(1).max(160),tombstone:Pr.optional(),expiresAt:l.z.string().datetime().optional()}).strict(),$r=l.z.object({streamId:l.z.string().trim().min(1).max(240),instanceId:l.z.string().trim().min(1).max(160),sinceRevision:l.z.number().int().min(0),latestRevision:l.z.number().int().min(0),earliestRetainedRevision:l.z.number().int().min(0),syncRequired:l.z.boolean().default(!1),events:l.z.array(l.z.discriminatedUnion("type",[l.z.object({type:l.z.literal(zr),payload:Rr}).strict(),l.z.object({type:l.z.literal(Nr),payload:jr}).strict(),l.z.object({type:l.z.literal(xr),payload:Hr}).strict()])).default([])}).strict();function Lr(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":kr.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=Kr(e.workspace),s=Kr(e.tty),n=Kr(e.launch),r=Kr(e.ai),i=Kr(r.claude),o=Vr(t.cwd)||Vr(s.cwd)||Vr(i.cwd)||Vr(n.cwd);return o?{cwd:o}:void 0}(e),{workspace:r,...i}=e;return Pr.parse({...i,status:t,bindings:Br([...(o=e.bindings,Array.isArray(o)?o.flatMap(e=>{const t=Dr.safeParse(e);return t.success?[t.data]:[]}):[]),...s?[{type:"app-session",id:s}]:[],...qr(e)]),...n?{workspace:n}:{}});var o}(e));return Cr.parse({runningCount:s.filter(e=>"running"===e.status).length,problemCount:s.filter(e=>"failed"===e.status).length,sessions:s,updatedAt:t})}function Ur(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 qr(e){const t=Kr(e.ai),s=Kr(t.claude),n=Kr(t.appServer),r=[],i=Vr(s.short);i&&r.push({type:"adapter-key",adapter:"claude",agent:"claude",id:`short:${i}`,key:`short:${i}`});const o=Vr(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=Vr(t.activeThreadId);for(const e of[...new Set([d,...a].filter(Boolean))])r.push({type:"provider-session",agent:"codex",id:e});const c=Vr(n.socketPath);return c&&r.push({type:"adapter-key",adapter:"codex-app-server",agent:"codex",id:`socket:${c}`,key:`socket:${c}`}),r}function Br(e){const t=new Map;for(const s of e)t.set(Ur(s),s);return[...t.values()]}function Kr(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}function Vr(e){return"string"==typeof e&&e.trim()?e.trim():""}function Gr(e){return e.readyState===(e.OPEN??1)}function Wr(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 Xr(e,t){e.send(t.data,{binary:t.isBinary})}function Jr(e,t){if(Gr(e))for(const s of t.splice(0))Xr(e,s)}const Yr=require("ws");function Qr(e){return{method:e.method,headers:e.headers,body:e.streamRawRequest?e.rawRequest:e.requestBody,...e.streamRawRequest?{duplex:"half"}:{}}}function Zr(e){return o.Readable.fromWeb(e)}class ei{refresh;publish;requestedRevision=0;completedRevision=0;latestReason="discovery-scan";inFlight;constructor(e,t){this.refresh=e,this.publish=t}request(e="discovery-scan"){return this.requestedRevision+=1,this.latestReason=e,this.inFlight||(this.inFlight=this.drain().finally(()=>{this.inFlight=void 0})),this.inFlight}async drain(){for(;this.completedRevision<this.requestedRevision;){const e=this.requestedRevision,t=this.latestReason;await this.refresh(),this.publish(t),this.completedRevision=e}}}const ti=l.z.object({id:l.z.string().trim().min(1).max(120),label:l.z.string().trim().min(1).max(120),projectRoot:l.z.string().trim().min(1).max(500),items:l.z.array(l.z.object({id:l.z.string().trim().min(1).max(120),type:l.z.enum(["file","dir"]),projectPath:l.z.string().trim().min(1).max(500),containerPath:l.z.string().trim().min(1).max(500)}).strip()).min(1).max(50)}).strip(),si=l.z.object({preset:ti.optional()}).strip().default({}),ni=l.z.object({appId:l.z.string().min(1).max(80).regex(/^[a-z0-9][a-z0-9_.-]*$/).optional(),title:l.z.string().trim().min(1).max(120).optional(),args:l.z.array(l.z.string().max(4096)).max(64).optional(),cwd:l.z.string().trim().min(1).max(512).optional(),env:l.z.record(l.z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),l.z.string().max(4096)).optional(),display:l.z.object({width:l.z.number().int().min(320).max(7680).optional(),height:l.z.number().int().min(240).max(4320).optional(),depth:l.z.union([l.z.literal(16),l.z.literal(24),l.z.literal(32)]).optional()}).optional(),displayTarget:l.z.object({mode:l.z.enum(["isolated","shared"]),id:l.z.string().trim().min(1).max(80).regex(/^[a-z0-9][a-z0-9._-]*$/).optional(),autoCreate:l.z.boolean().optional()}).optional()}).strict(),ri=l.z.object({OPENAI_API_KEY:l.z.string().max(4096).optional(),OPENAI_BASE_URL:l.z.string().max(4096).optional(),TASK_HANDOFF_CODEX_BASE_URL:l.z.string().max(4096).optional(),TASK_HANDOFF_CODEX_MODEL:l.z.string().max(4096).optional(),ANTHROPIC_API_KEY:l.z.string().max(4096).optional(),ANTHROPIC_BASE_URL:l.z.string().max(4096).optional(),TASK_HANDOFF_CLAUDE_MODEL:l.z.string().max(4096).optional()}).strict(),ii=Object.keys(ri.shape),oi=l.z.object({width:l.z.number().int().min(320).max(7680).optional(),height:l.z.number().int().min(240).max(4320).optional(),depth:l.z.number().int().min(8).max(32).optional()}).strip(),ai=l.z.object({title:l.z.string().trim().min(1).max(120)}).strict(),di=l.z.object({name:l.z.string().trim().min(1).max(160),description:l.z.string().trim().max(1e3).optional(),source:F,action:M,policy:R.partial().optional(),deployment:l.z.object({deploymentId:l.z.string().trim().min(1).max(240).optional(),origin:l.z.enum(["control-plane","controlled-instance"]).optional(),enabled:l.z.boolean().optional(),target:H,localName:l.z.string().trim().min(1).max(160).optional()}).strict().optional()}).strict(),ci=l.z.object({name:l.z.string().trim().min(1).max(160).optional(),description:l.z.string().trim().max(1e3).nullable().optional()}).strict(),pi=l.z.object({promptOverride:l.z.string().trim().min(1).max(2e4).optional(),eventSummary:l.z.string().trim().max(1e3).optional(),deploymentId:l.z.string().trim().min(1).max(240).optional()}).strict().default({});function ui(e){return e instanceof l.z.ZodError?e.issues.map(e=>`${e.path.join(".")||"body"}: ${e.message}`).join("; "):e instanceof Error?e.message:String(e)}function li(e,t){if(t instanceof l.z.ZodError)return e.code(400).send({error:xt.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:xt.parse({code:n,message:t instanceof Error?t.message:String(t)})})}function mi(e,t=!1){const s=process.env[e];return void 0===s||""===s?t:["1","true","yes","on"].includes(s.toLowerCase())}function hi(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 gi(e={}){const o=(new Date).toISOString(),m=ae(),h={...process.env};!function(e,t){if(mi("TASK_HANDOFF_DIAGNOSTIC_LOGS"))try{const n=s.join(e,"controlled-instance.log");w(n,{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,logPath:n,process:{pid:process.pid,ppid:process.ppid,cwd:process.cwd(),argv:process.argv,parent:_(process.ppid),env:b()}})}catch{}}(m.logDir,m.dataDir),xn(h);const g=function(e){if("off"===process.env.TASK_HANDOFF_WEB_AUTH)return{enabled:!1};const r=process.env.TASK_HANDOFF_WEB_TOKEN?.trim();if(r)return{enabled:!0,source:"env",token:r};const i=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(i)return{enabled:!0,source:"file",token:i,tokenFile:e.webTokenPath};if("required"===process.env.TASK_HANDOFF_WEB_AUTH){const r=n.randomBytes(24).toString("base64url");return function(e,n){t.mkdirSync(s.dirname(e),{recursive:!0}),t.writeFileSync(e,`${n}\n`,{mode:384})}(e.webTokenPath,r),{enabled:!0,source:"generated",token:r,tokenFile:e.webTokenPath}}return{enabled:!1,tokenFile:e.webTokenPath}}(m),f=new In,y=e.appRuntime||new Ue(m);var v;y.replaceManagedEnvironment((v=h,ri.parse(Object.fromEntries(ii.flatMap(e=>"string"==typeof v[e]?[[e,v[e]]]:[])))));const S=e.aiSessionRegistry||Es(),A=new Ge(S),I=new Q(m),z=new T(I,A),N=new O(I,z,m,(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}}(),()=>hr(y,m,S,I)),E=p({logger:e.logger??!0,bodyLimit:67108864});await E.register(c),function(e,t){e.addHook("preHandler",async(e,s)=>{if(t.enabled&&"/api/health"!==e.url&&"/api/auth/status"!==e.url&&"/api/internal/model-environment"!==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."}})})}(E,g),E.addHook("onReady",async()=>{x.enabled()&&await x.start()}),E.addHook("onClose",async()=>{x.stop(),N.stop()});let k="";const D=process.env.TASK_HANDOFF_INSTANCE_ID||"standalone",P=`ais_${D}_${n.randomUUID()}`,C=`aps_${D}_${n.randomUUID()}`;let F=0,M={runningCount:0,waitingCount:0,staleCount:0,sessions:[],updatedAt:o};const R=[],j=new Set,H=new Map;let $,L="",U=0;const q={aiDiscoveryUnchanged:0,aiDiscoveryCorrections:0,appUnchanged:0},B=[];let K=Lr([]);const V=new Ds,G=new fn(S),W=new Gs(S);A.register(G),A.register(W),V.register(new Ps),V.register(W),V.register(new Cs),V.register(G);const X=()=>{const e=y.sharedCodexAppServerInfo();return e?[...y.listSessions(),{id:"__shared_codex_app_server__",appId:"codex",title:"Codex app-server",status:"running",createdAt:o,ai:{appServer:e}}]:y.listSessions()},J=new ei(async()=>{const e=X();S.reconcileAppSessionBindings(e),await V.refresh({registry:S,appSessions:e})},e=>ee(e)),Y=(e="discovery-scan")=>J.request(e),Z=()=>{const e=Date.now()-36e5;for(;R.length&&R[0].createdAtMs<e;)R.shift()},ee=(e="provider-event")=>{const t=S.boundSnapshot(X()),s=JSON.stringify(t.sessions);if(s!==k){k=s,M=t,F+=1;const n=((e,t)=>({meta:{streamId:P,instanceId:D,nodeId:process.env.TASK_HANDOFF_NODE_ID,revision:F,previousRevision:F>0?F-1:void 0,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=>{R.push({type:ht,payload:e,createdAtMs:Date.now()}),Z()})(n),f.publish(ht,n),E.log.info({traceId:n.meta.traceId,instanceId:n.meta.instanceId,streamId:n.meta.streamId,revision:n.meta.revision,reason:e,sessionCount:t.sessions.length,runningCount:t.runningCount,waitingCount:t.waitingCount},"ai-session.snapshot.published"),N.handleAiSessions(t),"discovery-scan"===e&&(q.aiDiscoveryCorrections+=1,E.log.info({instanceId:D,streamId:P,revision:F,correctionCount:q.aiDiscoveryCorrections},"ai-session.discovery.corrected"))}else"discovery-scan"===e&&(q.aiDiscoveryUnchanged+=1,E.log.info({instanceId:D,streamId:P,revision:F,unchangedCount:q.aiDiscoveryUnchanged},"ai-session.discovery.unchanged"))},te=()=>{const e=Date.now()-Er;for(;B.length&&B[0].createdAtMs<e;)B.shift()},se=e=>({streamId:C,instanceId:D,nodeId:process.env.TASK_HANDOFF_NODE_ID,revision:U,previousRevision:U>0?U-1:void 0,traceId:`aps_evt_${Date.now().toString(36)}_${Math.random().toString(16).slice(2,10)}`,generatedAt:(new Date).toISOString(),reason:e}),ne=(e,t)=>({meta:se(t),session:e}),re=(e,t,s)=>({meta:se(s),sessionId:e,tombstone:t,expiresAt:new Date(Date.now()+Er).toISOString()}),ie=(e,t,s)=>{(e=>{B.push({...e,createdAtMs:Date.now()}),te()})(e),f.publish(e.type,e.payload),E.log.info({traceId:e.payload.meta.traceId,instanceId:e.payload.meta.instanceId,streamId:e.payload.meta.streamId,revision:e.payload.meta.revision,reason:s,eventType:e.type,sessionCount:t.sessions.length,runningCount:t.runningCount,problemCount:t.problemCount},"app-session.event.published")},oe=(e,t)=>{te();const s=U,n=B[0]?.payload.meta.revision??s+1;if(e!==C||t>s)return $r.parse({streamId:C,instanceId:D,sinceRevision:t,latestRevision:s,earliestRetainedRevision:n,syncRequired:!0,events:[]});if(t===s)return $r.parse({streamId:C,instanceId:D,sinceRevision:t,latestRevision:s,earliestRetainedRevision:n,syncRequired:!1,events:[]});const r=B.filter(e=>e.payload.meta.revision>t),i=r[0]?.payload.meta.revision,o=!r.length||i!==t+1;return $r.parse({streamId:C,instanceId:D,sinceRevision:t,latestRevision:s,earliestRetainedRevision:n,syncRequired:o,events:o?[]:r.map(e=>({type:e.type,payload:e.payload}))})},de=(e,t)=>{Z();const s=F,n=R[0]?.payload.meta.revision??s+1;if(e!==P||t>s)return qt.parse({streamId:P,instanceId:D,sinceRevision:t,latestRevision:s,earliestRetainedRevision:n,syncRequired:!0,events:[]});if(t===s)return qt.parse({streamId:P,instanceId:D,sinceRevision:t,latestRevision:s,earliestRetainedRevision:n,syncRequired:!1,events:[]});const r=R.filter(e=>e.payload.meta.revision>t),i=r[0]?.payload.meta.revision,o=!r.length||i!==t+1;return qt.parse({streamId:P,instanceId:D,sinceRevision:t,latestRevision:s,earliestRetainedRevision:n,syncRequired:o,events:o?[]:r.map(e=>({type:e.type,payload:e.payload}))})},ce=async e=>{if(j.has(e))return;const t=S.get(e);if(t&&"idle"===t.status&&S.nextQueuedMessage(e)){j.add(e);try{await A.sendNextQueuedMessage(e)}catch(t){E.log.warn({err:t,sessionId:e},"failed to drain AI session message queue")}finally{j.delete(e),ee("control-action")}}};let pe;const ue=S.onChange(()=>{pe||(pe=setTimeout(()=>{pe=void 0,ee()},Number(process.env.TASK_HANDOFF_AI_SESSION_PUBLISH_DEBOUNCE_MS)||50));for(const e of S.list()){const t=H.get(e.id);H.set(e.id,e.status),t&&"idle"!==t&&"idle"===e.status&&e.queue.pendingCount>0&&ce(e.id)}});E.addHook("onReady",async()=>{if(N.start(),mi("TASK_HANDOFF_CODEX_APP_SERVER",!1))try{y.ensureSharedCodexAppServer()}catch(e){E.log.warn({err:e},"failed to start shared Codex app-server")}}),E.addHook("onReady",async()=>{await Y("startup"),$=setInterval(()=>{Y()},Number(process.env.TASK_HANDOFF_AI_SESSION_SCAN_INTERVAL_MS)||3e4)}),E.addHook("onClose",async()=>{ue(),pe&&(clearTimeout(pe),pe=void 0),$&&(clearInterval($),$=void 0),G.stop(),W.stop()});const le=(e,t)=>{(e=>{const t=Lr(y.listSessions()),s=JSON.stringify(t.sessions);if(s===L)return q.appUnchanged+=1,void E.log.info({instanceId:D,streamId:C,revision:U,reason:e,sessionCount:t.sessions.length,unchangedCount:q.appUnchanged},"app-session.snapshot.skipped-unchanged");L=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}(K,t);if(0===U||1!==n.length){U+=1;const s=((e,t)=>({meta:{streamId:C,instanceId:D,nodeId:process.env.TASK_HANDOFF_NODE_ID,revision:U,previousRevision:U>0?U-1:void 0,traceId:`aps_evt_${Date.now().toString(36)}_${Math.random().toString(16).slice(2,10)}`,generatedAt:(new Date).toISOString(),reason:t},snapshot:e}))(t,e);ie({type:zr,payload:s},t,e)}else{U+=1;const s=n[0],r="removed"===s.type?{type:xr,payload:re(s.sessionId,s.tombstone,e)}:{type:Nr,payload:ne(s.session,e)};ie(r,t,e)}K=t})(e),Y("app-session-recovered"===e?"discovery-scan":e).catch(s=>{E.log.warn({err:s,reason:e,sessionId:t.id},"failed to refresh AI sessions after app session event")})};y.on("created",e=>le("app-session-created",e)),y.on("updated",e=>le("app-session-updated",e)),y.on("deleted",e=>le("app-session-deleted",e)),E.addHook("onClose",async()=>{y.stopAll()});const me=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}}();me?await E.register(d,{root:me,prefix:"/api/novnc/",decorateReply:!1}):E.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 E.register(d,{root:he,prefix:"/"}),E.get("/api/health",async()=>({data:{ok:!0,version:ar(),startedAt:o}})),E.get("/api/auth/status",async()=>({data:{enabled:g.enabled,source:g.source,tokenFile:g.tokenFile}})),E.get("/api/events",{websocket:!0},e=>{f.connect(e),f.send(e,"streams.hello",{protocolVersion:1,streams:[{topic:"ai.sessions",instanceId:D,streamId:P,latestRevision:F,earliestRetainedRevision:R[0]?.payload.meta.revision??F+1},{topic:"app.sessions",instanceId:D,streamId:C,latestRevision:U,earliestRetainedRevision:B[0]?.payload.meta.revision??U+1}]})}),E.get("/api/status",async()=>({data:{version:ar(),startedAt:o,runningAppCount:y.runningSessionCount(),storage:m}})),E.get("/api/instance/status",async()=>{const e=await hr(y,m,S,I);return{data:{id:process.env.TASK_HANDOFF_INSTANCE_ID,name:process.env.TASK_HANDOFF_INSTANCE_NAME||i.hostname(),...e,startedAt:o}}}),E.get("/api/instance/capabilities",async()=>({data:lr(y)})),E.get("/api/workspace/status",async()=>({data:ur(m)})),E.get("/api/ai-sessions",async(e,t)=>{const s=void 0===e.query.sinceRevision?void 0:Number(e.query.sinceRevision);return Number.isInteger(s)&&s>=0?e.query.streamId?{data:de(e.query.streamId,s)}:t.code(400).send({error:{code:"AI_SESSION_DELTA_INVALID",message:"streamId is required with sinceRevision."}}):{data:{streamId:P,revision:F,lastEventAt:R.at(-1)?.payload.meta.generatedAt||o,snapshot:M}}}),E.get("/api/ai-sessions/state",async()=>({data:{streamId:P,revision:F,lastEventAt:R.at(-1)?.payload.meta.generatedAt||o,snapshot:M}})),E.get("/api/triggers",async()=>({data:I.list()})),E.get("/api/triggers/:configHash",async(e,t)=>{const s=I.get(e.params.configHash);return s?{data:s}:t.code(404).send({error:{code:"TRIGGER_NOT_FOUND",message:"Trigger not found."}})}),E.post("/api/triggers",async(e,t)=>{try{const t=di.parse(e.body||{}),s=I.create(t);return N.restart(),f.publish("trigger.created",s),f.publish("trigger.updated",mr(I)),{data:s}}catch(e){return t.code(400).send({error:{code:"TRIGGER_INVALID",message:ui(e)}})}}),E.patch("/api/triggers/:configHash",async(e,t)=>{try{const s=ci.parse(e.body||{}),n=I.patch(e.params.configHash,s);return n?(N.restart(),f.publish("trigger.updated",I.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:ui(e)}})}}),E.delete("/api/triggers/:configHash",async(e,t)=>{const s=I.delete(e.params.configHash);return s?(N.restart(),f.publish("trigger.deleted",{configHash:e.params.configHash}),f.publish("trigger.updated",mr(I)),{data:{deleted:s}}):t.code(404).send({error:{code:"TRIGGER_NOT_FOUND",message:"Trigger not found."}})}),E.delete("/api/triggers/:configHash/deployments/:deploymentId",async(e,t)=>{const s=I.deleteDeployment(e.params.configHash,e.params.deploymentId);return s?(N.restart(),f.publish("trigger.deployment.deleted",{configHash:e.params.configHash,deploymentId:e.params.deploymentId}),f.publish("trigger.updated",mr(I)),{data:{deleted:s}}):t.code(404).send({error:{code:"TRIGGER_DEPLOYMENT_NOT_FOUND",message:"Trigger deployment not found."}})}),E.post("/api/triggers/:configHash/enable",async(e,t)=>{const s=I.setEnabled(e.params.configHash,!0);return s?(N.restart(),f.publish("trigger.enabled",s),f.publish("trigger.updated",mr(I)),{data:s}):t.code(404).send({error:{code:"TRIGGER_NOT_FOUND",message:"Trigger not found."}})}),E.post("/api/triggers/:configHash/disable",async(e,t)=>{const s=I.setEnabled(e.params.configHash,!1);return s?(N.restart(),f.publish("trigger.disabled",s),f.publish("trigger.updated",mr(I)),{data:s}):t.code(404).send({error:{code:"TRIGGER_NOT_FOUND",message:"Trigger not found."}})}),E.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=pi.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})}(I,z,e.params.configHash,e.body||{});return f.publish("trigger.run.completed",t),f.publish("trigger.updated",mr(I)),{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:ui(s)}),t.code("TRIGGER_NOT_FOUND"===n?404:400).send({error:{code:n,message:ui(s)}})}}),E.get("/api/triggers/runs",async()=>({data:I.list().recentRuns})),E.get("/api/ai-sessions/:id",async(e,t)=>{const s=S.get(e.params.id);return s?{data:s}:t.code(404).send({error:{code:"AI_SESSION_NOT_FOUND",message:"AI session not found."}})}),E.get("/api/ai-sessions/:id/turns",async(e,t)=>{const s=S.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}}}),E.get("/api/ai-sessions/:id/transcript",async(e,t)=>{const s=S.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:hi(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)}})}}),E.post("/api/ai-sessions/:id/messages",async(e,t)=>{try{const t=Ot.parse(e.body||{}),s=Ft.parse(await A.sendMessage(e.params.id,t));return ee("control-action"),{data:s}}catch(e){return li(t,e)}}),E.get("/api/ai-sessions/:id/queue",async(e,t)=>{const s=S.get(e.params.id);return s?{data:s.queue}:t.code(404).send({error:{code:"AI_SESSION_NOT_FOUND",message:"AI session not found."}})}),E.post("/api/ai-sessions/:id/queue/:queueId/steer",async(e,t)=>{try{const t=Ft.parse(await A.steerQueuedMessage(e.params.id,e.params.queueId));return ee("control-action"),{data:t}}catch(e){return li(t,e)}}),E.post("/api/ai-sessions/:id/queue/:queueId/retry",async(e,t)=>{try{const t=A.retryQueuedMessage(e.params.id,e.params.queueId);return ee("control-action"),{data:t}}catch(e){return li(t,e)}}),E.delete("/api/ai-sessions/:id/queue/:queueId",async(e,t)=>{try{const t=A.removeQueuedMessage(e.params.id,e.params.queueId);return ee("control-action"),{data:t}}catch(e){return li(t,e)}}),E.patch("/api/ai-sessions/:id/queue/reorder",async(e,t)=>{try{const t=Nt.parse(e.body||{}),s=A.reorderQueuedMessages(e.params.id,t.queueIds);return ee("control-action"),{data:s}}catch(e){return li(t,e)}}),E.post("/api/ai-sessions/:id/interrupt",async(e,t)=>{try{const t=Ft.parse(await A.interrupt(e.params.id));return ee("control-action"),{data:t}}catch(e){return li(t,e)}}),E.post("/api/ai-sessions/:id/approval",async(e,t)=>{try{const t=zt.parse(e.body||{}),s=Ft.parse(await A.resolveApproval(e.params.id,t.decision));return ee("control-action"),{data:s}}catch(e){return li(t,e)}}),E.get("/api/diagnostics",async()=>({data:{...cr(m,me),sessionStreams:{ai:{streamId:P,revision:F,retainedEventCount:R.length,discoveryUnchanged:q.aiDiscoveryUnchanged,discoveryCorrections:q.aiDiscoveryCorrections},app:{streamId:C,revision:U,retainedEventCount:B.length,unchangedRefreshes:q.appUnchanged}}}})),E.get("/api/apps/catalog",async()=>({data:y.catalog()})),E.put("/api/internal/model-environment",async(e,t)=>{const s=process.env.TASK_HANDOFF_REGISTRATION_TOKEN?.trim(),n=e.headers.authorization||"";if(!s||n!==`Bearer ${s}`)return t.code(403).send({error:{code:"MANAGED_MODEL_ENVIRONMENT_FORBIDDEN",message:"Instance registration token is required."}});const r=ri.parse(e.body||{});for(const e of ii)delete h[e];Object.assign(h,r),y.replaceManagedEnvironment(r);const i=xn(h);return{data:{applied:!0,codexAuthConfigured:Boolean(r.OPENAI_API_KEY),configUpdated:i.applied}}}),E.get("/api/config-sync/presets",async()=>({data:Tn()})),E.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=si.parse(e.body||{}),n=zn(s,e.params.preset,t.preset);return"import"===s&&"codex"===e.params.preset&&xn(h),{data:n}}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)}})}}),E.get("/api/apps/catalog/custom",async(e,t)=>{const s=y.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}}),E.patch("/api/apps/catalog/custom",async(e,t)=>{try{return{data:y.saveCustomCatalog(e.body?.items||[])}}catch(e){return t.code(400).send({error:{code:"APP_CATALOG_INVALID",message:e instanceof Error?e.message:String(e)}})}}),E.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."}}):e.query.streamId?{data:oe(e.query.streamId,s)}:t.code(400).send({error:{code:"APP_SESSION_DELTA_INVALID",message:"streamId is required with sinceRevision."}})}return{data:{streamId:C,revision:U,lastEventAt:B.at(-1)?.payload.meta.generatedAt||o,snapshot:Lr(y.listSessions())}}}),E.get("/api/apps/sessions/state",async()=>({data:{streamId:C,revision:U,lastEventAt:B.at(-1)?.payload.meta.generatedAt||o,snapshot:Lr(y.listSessions())}})),E.post("/api/apps/sessions",async(e,t)=>{try{const t=function(e={}){const t=ni.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:y.start(t.appId,t.options)}}catch(e){if(e instanceof l.z.ZodError)return t.code(400).send({error:{code:"APP_LAUNCH_INVALID",message:ui(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)}})}}),E.get("/api/apps/sessions/:id",async(e,t)=>{const s=y.getSession(e.params.id);return s?{data:s}:t.code(404).send({error:{code:"APP_SESSION_NOT_FOUND",message:"App session not found."}})}),E.patch("/api/apps/sessions/:id",async(e,t)=>{try{const{title:t}=ai.parse(e.body||{});return{data:y.rename(e.params.id,t)}}catch(e){if(e instanceof l.z.ZodError)return t.code(400).send({error:{code:"APP_SESSION_UPDATE_INVALID",message:ui(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)}})}}),E.post("/api/apps/sessions/:id/stop",async(e,t)=>{try{return{data:y.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)}})}}),E.post("/api/apps/sessions/:id/restart",async(e,t)=>{try{return{data:y.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)}})}}),E.post("/api/apps/sessions/:id/display",async(e,t)=>{try{return{data:y.resizeDisplay(e.params.id,oi.parse(e.body||{}))}}catch(e){const s=e&&"object"==typeof e&&"code"in e?String(e.code):"APP_DISPLAY_RESIZE_FAILED";return e instanceof l.z.ZodError?t.code(400).send({error:{code:"APP_DISPLAY_INVALID",message:ui(e)}}):t.code("APP_DISPLAY_NOT_FOUND"===s?404:400).send({error:{code:s,message:e instanceof Error?e.message:String(e)}})}}),E.delete("/api/apps/sessions/:id",async(e,t)=>{try{return{data:await y.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)}})}}),E.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:y.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)}})}}),E.get("/api/apps/sessions/:id/screenshot",async(e,t)=>{try{const s=y.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)}})}}),E.get("/api/apps/sessions/:id/snapshot",async(e,t)=>{try{const s=y.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)}})}}),E.get("/api/apps/sessions/:id/automation",async(e,t)=>{try{return{data:await y.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)}})}}),E.get("/api/apps/sessions/:id/tty",{websocket:!0},(e,t)=>{y.attachTty(t.params.id,e)}),E.get("/api/apps/sessions/:id/vnc",{websocket:!0},(e,t)=>{const s=y.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=r.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 ge=async(e,t)=>{const s=y.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"===y.getSession(e.params.id)?.vnc?.backend,r=n?{authorization:Sr()}:{};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,d=Date.now(),c=`http://${s.host}:${s.port}`,p=new URL(vr(e.params.id,e.raw.url),`${c}/`).toString();for(;;)try{const d=await u.proxyFetch(c,p,Qr({method:e.method,headers:Ar(e.headers,s.host,s.port,r),requestBody:i,rawRequest:e.raw,streamRawRequest:void 0===i&&!o})),l=Tr(d.headers);if("HEAD"!==e.method&&n&&_r(l)){const e=Buffer.from(wr(Buffer.from(await d.arrayBuffer()),l),"utf8"),s={...l,"content-length":String(e.byteLength)};delete s.etag,t.raw.writeHead(d.status||502,d.statusText,s),t.raw.end(e);break}if(t.raw.writeHead(d.status||502,d.statusText,Or(d.headers)),!d.body||"HEAD"===e.method){t.raw.end();break}await a.pipeline(Zr(d.body),t.raw);break}catch(e){if(o&&yr(e)&&Date.now()-d<8e3){await fr(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};E.route({method:"GET",url:"/api/apps/sessions/:id/web/*",wsHandler:(e,t)=>{const s=y.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"===y.getSession(t.params.id)?.vnc?.backend?{authorization:Sr(),origin:n,"sec-websocket-origin":t.headers.origin||n}:{origin:n},i=Date.now(),o=`ws://${s.host}:${s.port}${vr(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"===y.getSession(t.params.id)?.vnc?.backend?["binary"]:void 0),d=()=>{if(e.readyState!==e.OPEN)return;const n=new Yr(o,a,{headers:Ir(t.headers,s.host,s.port,r)});!function(e,t,s={}){const n=s.pendingFrameLimit??256;let r=!1,i=Gr(t);const o=[],a=[];let d;const c=()=>{d&&(clearTimeout(d),d=void 0)},p=(s,r)=>{if(s.length>=n)return Wr(e,1011,"WebSocket bridge pending frame limit exceeded."),void Wr(t,1011,"WebSocket bridge pending frame limit exceeded.");s.push(r)};s.upstreamOpenTimeoutMs&&!i&&(d=setTimeout(()=>{i||r||(Wr(e,1011,"Upstream websocket did not open."),Wr(t))},s.upstreamOpenTimeoutMs)),e.on("open",()=>Jr(e,a)),t.on("open",()=>{c(),i=!0,s.onUpstreamOpen?.(),Jr(t,o)}),e.on("message",(e,s=!1)=>{const n={data:e,isBinary:Boolean(s)};Gr(t)?Xr(t,n):p(o,n)}),t.on("message",(t,s=!1)=>{const n={data:t,isBinary:Boolean(s)};Gr(e)?Xr(e,n):p(a,n)}),t.on("close",(t,n)=>{c(),s.onUpstreamClose?.(t,n),(i||r||!s.onUpstreamCloseBeforeOpen?.())&&Wr(e,t,n)}),t.on("error",t=>{s.onUpstreamError?.(t),(i||r||!s.onUpstreamErrorBeforeOpen?.(t))&&Wr(e)}),e.on("close",(e,n)=>{c(),r=!0,s.onClientClose?.(e,n),Wr(t,e,n)}),e.on("error",e=>{c(),r=!0,s.onClientError?.(e),Wr(t,1011,"WebSocket bridge client failed.")})}(e,n,{onUpstreamCloseBeforeOpen:()=>Date.now()-i<8e3&&(fr(200).then(d),!0),onUpstreamErrorBeforeOpen:e=>yr(e)})};d()},handler:ge});for(const e of["DELETE","OPTIONS","PATCH","POST","PUT"])E.route({method:e,url:"/api/apps/sessions/:id/web/*",handler:ge});return E.get("/api/apps/sessions/:id/novnc/vnc.html",async(e,t)=>{const s=y.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()}`)}),E.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.")}),E}function fi(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",fi,Number(process.env.TASK_HANDOFF_WEB_PORT)||8080).option("--static-dir <path>","Web UI static directory",process.env.TASK_HANDOFF_WEB_STATIC_DIR||s.resolve(__dirname,"..","ui")).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 gi(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,staticDir:e.staticDir})}),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:crypto"),i=require("node:net"),r=require("node:os"),o=require("node:stream"),a=require("node:stream/promises"),c=require("@fastify/static"),d=require("@fastify/websocket"),p=require("fastify"),u=require("httpxy"),l=require("zod"),m=require("node:child_process"),h=require("chokidar"),g=require("cron-parser"),f=require("picomatch"),y=require("write-file-atomic"),v=require("node:events"),S=require("node-pty"),w=require("ws"),I=require("node:zlib"),A=require("tar"),b=require("@iarna/toml");const _=/(TOKEN|KEY|SECRET|AUTH|PASSWORD|COOKIE)/i,T=/^(TASK_HANDOFF|CODEX|CLAUDE|PWD$|OLDPWD$|SHELL$|TERM$)/;function O(e,t){if(void 0!==t)return _.test(e)?"[redacted]":t}function x(e=process.env){return Object.fromEntries(Object.entries(e).filter(([e])=>T.test(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,O(e,t)]))}function E(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 k(e,n){t.mkdirSync(s.dirname(e),{recursive:!0}),t.appendFileSync(e,`${JSON.stringify({time:(new Date).toISOString(),...n})}\n`,{mode:384})}class z{store;aiSessionController;constructor(e,t){this.store=e,this.aiSessionController=t}async execute(e){const t=this.store.startRun(e.config,e.deployment,e.eventType,e.eventSummary),s=e.promptOverride||(n=e.config.action.promptTemplate,i={trigger:e.config,event:{type:e.eventType,summary:e.eventSummary||""}},n.replaceAll("{{trigger.configHash}}",i.trigger.configHash).replaceAll("{{trigger.name}}",i.trigger.name).replaceAll("{{event.type}}",i.event.type).replaceAll("{{event.summary}}",i.event.summary));var n,i;try{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}}catch(e){const s=this.store.completeRun(t,e);throw Object.assign(e instanceof Error?e:new Error(String(e)),{run:s})}}}class N{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())e.watcher.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 i=e.status!==n.status,r=e.phase!==n.phase;if(!i&&!r)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=P(t);if("intervalMs"in s)return void this.timers.set(n,setInterval(()=>{this.execute(e,t,"schedule",`Interval ${s.intervalMs}ms`)},s.intervalMs));const i=()=>{const r=function(e,t=new Date){if("intervalMs"in e)return new Date(t.getTime()+e.intervalMs);const[s,n]=e.timeOfDay.split(":").map(Number),i="weekly"===e.scheduleKind?e.weekdays.join(","):"*";return g.CronExpressionParser.parse(`0 ${n} ${s} * * ${i}`,{currentDate:t,strict:!0,tz:e.timezone}).next().toDate()}(s),o=Math.max(1e3,r.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)),i()},o);this.timers.set(n,a)};i()}startFileWatch(e,t){if("file-change"!==e.source.type)return;const n=e.source,i=P(t),r=s.resolve(process.env.TASK_HANDOFF_WORKSPACE||process.env.WORKSPACE||"/workspace"),o=n.roots.map(e=>s.resolve(e)).filter(e=>C(r,e));if(!o.length)return;const a=function(e,t=[]){const s=f(e,{dot:!0}),n=t.length?f(t,{dot:!0}):()=>!1;return e=>!R(e)&&!n(e)&&s(e)}(n.globs,n.ignore||[]),c=h.watch(o,{atomic:!0,awaitWriteFinish:{stabilityThreshold:Math.min(n.debounceMs,500),pollInterval:50},followSymlinks:!1,ignoreInitial:!0,ignored:(e,t)=>{if(!C(r,s.resolve(e)))return!0;const n=D(r,e);return Boolean(n&&R(t?.isDirectory()?`${n}/`:n))}}),d={watcher:c,changed:new Set};c.on("all",(s,i)=>{if("add"!==s&&"change"!==s&&"unlink"!==s)return;const o=D(r,i);o&&a(o)&&(d.changed.add(o),d.debounce&&clearTimeout(d.debounce),d.debounce=setTimeout(()=>{const s=[...d.changed].sort();d.changed.clear(),this.execute(e,t,"file-change",`Changed files:\n${s.join("\n")}`)},n.debounceMs))}),c.on("error",s=>{this.publish?.("trigger.watch.failed",{configHash:e.configHash,deploymentId:t.deploymentId,error:s instanceof Error?s.message:String(s)})}),this.watches.set(i,d)}aiSessionMatches(e,t){return!("ai-session"!==e.source.type||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 i=P(t),r=Date.now(),o=e.policy.cooldownMs||0,a=this.lastRunAt.get(i)||0;if(o&&r-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(i))"queue"===e.policy.whenBusy?this.queued.set(i,{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(i),this.lastRunAt.set(i,r),this.publish?.("trigger.run.started",{configHash:e.configHash,deploymentId:t.deploymentId,eventType:s});try{const i=await this.executor.execute({config:e,deployment:t,eventType:s,eventSummary:n});this.publish?.("trigger.run.completed",i),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(i);const e=this.queued.get(i);e&&(this.queued.delete(i),setTimeout(()=>{this.execute(e.config,e.deployment,e.eventType,e.eventSummary)},0))}}}}function P(e){return e.deploymentId||e.configHash}function R(e){return/(^|\/)(\.git|node_modules|dist|build)\//.test(e)||/\.(log|tmp|swp)$/.test(e)}function C(e,t){const n=s.relative(e,t);return""===n||!n.startsWith(`..${s.sep}`)&&".."!==n&&!s.isAbsolute(n)}function D(e,t){const n=s.resolve(t);return C(e,n)?s.relative(e,n).split(s.sep).join("/"):""}const M=l.z.union([l.z.object({type:l.z.literal("schedule"),scheduleKind:l.z.literal("interval").default("interval"),intervalMs:l.z.number().int().min(1e3)}).strict(),l.z.object({type:l.z.literal("schedule"),scheduleKind:l.z.literal("daily"),timeOfDay:l.z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/),timezone:l.z.string().trim().min(1).max(120)}).strict(),l.z.object({type:l.z.literal("schedule"),scheduleKind:l.z.literal("weekly"),weekdays:l.z.array(l.z.number().int().min(0).max(6)).min(1).max(7),timeOfDay:l.z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/),timezone:l.z.string().trim().min(1).max(120)}).strict()]),F=l.z.union([M,l.z.object({type:l.z.literal("file-change"),roots:l.z.array(l.z.string().trim().min(1).max(4096)).min(1).max(50),globs:l.z.array(l.z.string().trim().min(1).max(500)).min(1).max(100),ignore:l.z.array(l.z.string().trim().min(1).max(500)).max(100).optional(),debounceMs:l.z.number().int().min(100).max(6e4).default(1500)}).strict(),l.z.object({type:l.z.literal("ai-session"),agent:l.z.string().trim().min(1).max(80).optional(),statuses:l.z.array(l.z.enum(["running","waiting","idle","failed"])).max(20).optional(),phases:l.z.array(l.z.enum(["thinking","tool","editing","approval","responding","unknown"])).max(20).optional()}).strict()]),j=l.z.object({promptTemplate:l.z.string().trim().min(1).max(2e4)}).strict(),L=l.z.object({cooldownMs:l.z.number().int().min(0).max(864e5).optional(),maxConcurrentRuns:l.z.number().int().min(1).max(20).default(1),whenBusy:l.z.enum(["skip","queue"]).default("skip")}).strict(),$=l.z.object({configHash:l.z.string().trim().min(8).max(80),name:l.z.string().trim().min(1).max(160),description:l.z.string().trim().max(1e3).optional(),source:F,action:j,policy:L.default({maxConcurrentRuns:1,whenBusy:"skip"}),createdAt:l.z.string().datetime(),updatedAt:l.z.string().datetime()}).strict(),H=l.z.object({type:l.z.literal("ai-session"),aiSessionId:l.z.string().trim().min(1).max(160)}).strict(),U=l.z.object({configHash:l.z.string().trim().min(8).max(80),deploymentId:l.z.string().trim().min(1).max(240).optional(),instanceId:l.z.string().trim().min(1).max(160),origin:l.z.enum(["control-plane","controlled-instance"]).default("controlled-instance"),enabled:l.z.boolean().default(!0),target:H,localName:l.z.string().trim().min(1).max(160).optional(),createdAt:l.z.string().datetime(),updatedAt:l.z.string().datetime()}).strict(),q=l.z.object({configHash:l.z.string().trim().min(8).max(80),deploymentId:l.z.string().trim().min(1).max(240).optional(),instanceId:l.z.string().trim().min(1).max(160),status:l.z.enum(["idle","running","disabled","error"]).default("idle"),lastTriggeredAt:l.z.string().datetime().optional(),lastCompletedAt:l.z.string().datetime().optional(),lastSkippedAt:l.z.string().datetime().optional(),lastError:l.z.string().trim().max(4e3).optional(),runCount:l.z.number().int().min(0).default(0),skippedCount:l.z.number().int().min(0).default(0)}).strict(),B=l.z.object({id:l.z.string().trim().min(1).max(160),configHash:l.z.string().trim().min(8).max(80),deploymentId:l.z.string().trim().min(1).max(240).optional(),instanceId:l.z.string().trim().min(1).max(160),eventType:l.z.enum(["manual","schedule","file-change","ai-session"]),status:l.z.enum(["started","completed","failed","skipped"]),target:H,promptPreview:l.z.string().trim().max(500),eventSummary:l.z.string().trim().max(1e3).optional(),error:l.z.string().trim().max(4e3).optional(),startedAt:l.z.string().datetime(),completedAt:l.z.string().datetime().optional()}).strict(),K=l.z.object({schemaVersion:l.z.literal(1).default(1),configs:l.z.array($).default([]),deployments:l.z.array(U).default([]),runtime:l.z.array(q).default([]),recentRuns:l.z.array(B).default([])}).strict();function V(e){return Array.isArray(e)?e.map(V):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,V(t)])):e}function G(e,n,i={}){t.mkdirSync(s.dirname(e),{recursive:!0,mode:i.directoryMode??448}),y.sync(e,n,{encoding:"string"==typeof n?"utf8":void 0,fsync:!0,mode:i.fileMode??384})}function W(e,t,s={}){G(e,`${JSON.stringify(t,null,2)}\n`,s)}const Y=l.z.record(l.z.string(),l.z.unknown());class J{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(this.options.sanitize?this.options.sanitize(e):e)}catch(e){if(e&&"object"==typeof e&&"code"in e&&"ENOENT"===e.code)return this.options.defaultValue();throw e}}save(e){W(this.filePath,this.options.schema.parse(e))}patch(e){const t=this.load(),s=X(Y.parse(t),e),n=this.options.schema.parse(s);return this.save(n),n}}function X(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]=X(t&&"object"==typeof t&&!Array.isArray(t)?Y.parse(t):{},Y.parse(n))}else void 0===n?delete s[e]:s[e]=n;return s}function Q(){return(new Date).toISOString()}function Z(e){return e.deploymentId||e.configHash}function ee(e){return q.parse({configHash:e.configHash,deploymentId:e.deploymentId,instanceId:e.instanceId,status:e.enabled?"idle":"disabled",runCount:0,skippedCount:0})}function te(e){return e.trim().slice(0,500)}class se{indexStore;constructor(e){const t=new Set;this.indexStore=new J(s.join(e.triggersDir,"index.json"),{schema:K,defaultValue:()=>({schemaVersion:1,configs:[],deployments:[],runtime:[],recentRuns:[]}),sanitize:e=>function(e,t){const s=ie(e);if(!s)return t?.({kind:"index",id:"index",reason:"invalid index replaced with an empty index"}),K.parse({});const n=re(s.configs).flatMap((e,s)=>{const n=ie(e),i=oe(n?.configHash)||`config[${s}]`;if(!n)return t?.({kind:"config",id:i,reason:"invalid config removed"}),[];const r=function(e){const t=ae(e,["configHash","name","description","createdAt","updatedAt"]),s=ie(e.source);s&&("schedule"===s.type?t.source=ae(s,["type","scheduleKind","intervalMs","timeOfDay","timezone","weekdays"]):"file-change"===s.type?t.source=ae(s,["type","roots","globs","ignore","debounceMs"]):"ai-session"===s.type?t.source=ae(s,["type","agent","statuses","phases"]):t.source=s);const n=ie(e.action);t.action=n?ae(n,["promptTemplate"]):n;const i=ie(e.policy);return t.policy=i?ae(i,["cooldownMs","maxConcurrentRuns","whenBusy"]):i,t}(n);return ne($,r,n,"config",i,t)}),i=re(s.deployments).flatMap((e,s)=>{const n=ie(e),i=oe(n?.deploymentId)||oe(n?.configHash)||`deployment[${s}]`,r=ie(n?.target);if("conversation"===r?.type)return t?.({kind:"deployment",id:i,reason:"conversation target removed"}),[];if(!n)return t?.({kind:"deployment",id:i,reason:"invalid deployment removed"}),[];const o=ae(n,["configHash","deploymentId","instanceId","origin","enabled","localName","createdAt","updatedAt"]);return o.target=r?ae(r,["type","aiSessionId"]):r,ne(U,o,n,"deployment",i,t)}),r=new Set(i.map(e=>Z(e))),o=re(s.runtime).flatMap((e,s)=>{const n=ie(e),i=oe(n?.deploymentId)||oe(n?.configHash)||`runtime[${s}]`;return n&&r.has(i)?ne(q,ae(n,["configHash","deploymentId","instanceId","status","lastTriggeredAt","lastCompletedAt","lastSkippedAt","lastError","runCount","skippedCount"]),n,"runtime",i,t):(t?.({kind:"runtime",id:i,reason:"orphaned or conversation runtime removed"}),[])}),a=re(s.recentRuns).flatMap((e,s)=>{const n=ie(e),i=oe(n?.id)||`recentRun[${s}]`,r=ie(n?.target);if("conversation"===r?.type)return t?.({kind:"recent-run",id:i,reason:"conversation target run removed"}),[];if(!n)return t?.({kind:"recent-run",id:i,reason:"invalid run removed"}),[];const o=ae(n,["id","configHash","deploymentId","instanceId","eventType","status","promptPreview","eventSummary","error","startedAt","completedAt"]);return o.target=r?ae(r,["type","aiSessionId"]):r,ne(B,o,n,"recent-run",i,t)}),c=ae(s,["schemaVersion","configs","deployments","runtime","recentRuns"]);return Object.keys(s).some(e=>!(e in c))&&t?.({kind:"index",id:"index",reason:"unknown index fields ignored"}),K.parse({schemaVersion:1,configs:n,deployments:i,runtime:o,recentRuns:a})}(e,e=>{const s=`${e.kind}:${e.id}:${e.reason}`;t.has(s)||(t.add(s),console.warn(JSON.stringify({message:"historical trigger entry was sanitized",...e})))})})}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=Q(),s={maxConcurrentRuns:e.policy?.maxConcurrentRuns??1,whenBusy:e.policy?.whenBusy??"skip",cooldownMs:e.policy?.cooldownMs},i=function(e){const t=V({source:e.source,action:e.action,policy:L.parse(e.policy||{})});return`trg_${n.createHash("sha256").update(JSON.stringify(t)).digest("hex").slice(0,24)}`}({source:e.source,action:e.action,policy:s}),r=$.parse({configHash:i,name:e.name,description:e.description,source:e.source,action:e.action,policy:s,createdAt:t,updatedAt:t}),o=function(e,t){const s=Q();return U.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,localName:t.localName,createdAt:s,updatedAt:s})}(i,e.deployment),a=this.list(),c=a.configs.some(e=>e.configHash===i)?a.configs:[...a.configs,r],d=Z(o),p=[...a.deployments.filter(e=>Z(e)!==d),o],u=[...a.runtime.filter(e=>Z(e)!==d),ee(o)];return this.save({...a,configs:c,deployments:p,runtime:u}),{config:r,deployment:o,runtime:ee(o)}}patch(e,t){const s=this.list(),n=s.configs.find(t=>t.configHash===e);if(!n)return;const i=$.parse({...n,name:t.name??n.name,description:null===t.description?void 0:t.description??n.description,updatedAt:Q()});return this.save({...s,configs:s.configs.map(t=>t.configHash===e?i:t)}),i}setEnabled(e,t){const s=this.list(),n=Q();let i=!1;const r=s.deployments.map(s=>s.configHash!==e?s:(i=!0,U.parse({...s,enabled:t,updatedAt:n})));if(!i)return;const o=s.runtime.map(s=>s.configHash===e?q.parse({...s,status:t?"idle":"disabled"}):s);return this.save({...s,deployments:r,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&&Z(s)===t))return!1;const n=s.deployments.filter(s=>!(s.configHash===e&&Z(s)===t)),i=n.some(t=>t.configHash===e);return this.save({...s,configs:i?s.configs:s.configs.filter(t=>t.configHash!==e),deployments:n,runtime:s.runtime.filter(s=>!(s.configHash===e&&Z(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=>Z(e))),i=t.deployments.filter(e=>!n.has(Z(e))),r=new Set(i.map(e=>e.configHash));return this.save({...t,configs:t.configs.filter(e=>r.has(e.configHash)),deployments:i,runtime:t.runtime.filter(e=>!n.has(Z(e)))}),s}startRun(e,t,s,n){const i=Q(),r=B.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:te(e.action.promptTemplate),eventSummary:n,startedAt:i}),o=this.list(),a=this.upsertRuntime(o,t,{status:"running",lastTriggeredAt:i});return this.save({...o,runtime:a,recentRuns:[r,...o.recentRuns].slice(0,100)}),r}completeRun(e,t){const s=Q(),n=Boolean(t),i=this.list(),r=i.recentRuns.map(i=>i.id===e.id?B.parse({...i,status:n?"failed":"completed",error:t instanceof Error?t.message:t?String(t):void 0,completedAt:s}):i),o=i.deployments.find(t=>t.configHash===e.configHash&&Z(t)===(e.deploymentId||e.configHash)),a=o?this.upsertRuntime(i,o,{status:n?"error":o.enabled?"idle":"disabled",lastCompletedAt:s,lastError:n?t instanceof Error?t.message:String(t):void 0,runCount:(i.runtime.find(t=>t.configHash===e.configHash&&Z(t)===Z(o))?.runCount||0)+1}):i.runtime;return this.save({...i,runtime:a,recentRuns:r}),r.find(t=>t.id===e.id)}skipRun(e,t,s,n){const i=Q(),r=B.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:te(e.action.promptTemplate),eventSummary:n,startedAt:i,completedAt:i}),o=this.list(),a=this.upsertRuntime(o,t,{status:t.enabled?"idle":"disabled",lastSkippedAt:i,skippedCount:(o.runtime.find(e=>Z(e)===Z(t))?.skippedCount||0)+1});return this.save({...o,runtime:a,recentRuns:[r,...o.recentRuns].slice(0,100)}),r}primaryDeployment(e){return this.list().deployments.find(t=>t.configHash===e)}upsertRuntime(e,t,s){const n=Z(t),i=e.runtime.find(e=>Z(e)===n)||ee(t),r=q.parse({...i,...s});return[...e.runtime.filter(e=>Z(e)!==n),r]}save(e){this.indexStore.save(K.parse(e))}}function ne(e,t,s,n,i,r){const o=e.safeParse(t);return o.success?(JSON.stringify(t)!==JSON.stringify(s)&&r?.({kind:n,id:i,reason:"unknown or legacy fields ignored"}),[o.data]):(r?.({kind:n,id:i,reason:"entry failed current schema and was removed"}),[])}function ie(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:void 0}function re(e){return Array.isArray(e)?e:[]}function oe(e){return"string"==typeof e?e:""}function ae(e,t){return Object.fromEntries(t.filter(t=>Object.prototype.hasOwnProperty.call(e,t)).map(t=>[t,e[t]]))}const ce=process.env.TASK_HANDOFF_CONFIG||s.join(process.env.XDG_CONFIG_HOME||s.join(r.homedir(),".config"),"task-handoff","config.json");function de(e,t){const n=process.env[e];return n&&n.trim()?s.resolve(n.trim()):t}function pe(){const e=s.join(process.env.XDG_DATA_HOME||s.join(r.homedir(),".local","share"),"task-handoff"),t=de("TASK_HANDOFF_CONFIG",ce),n=de("TASK_HANDOFF_DATA_DIR",s.dirname(t)||e);return{configPath:t,dataDir:n,appCatalogDir:de("TASK_HANDOFF_APP_CATALOG_DIR",s.join(n,"app-catalog")),appSessionsDir:de("TASK_HANDOFF_APP_SESSION_DIR",s.join(n,"app-sessions")),triggersDir:de("TASK_HANDOFF_TRIGGERS_DIR",s.join(n,"triggers")),runtimeDir:de("TASK_HANDOFF_RUNTIME_DIR",s.join(n,"runtime")),eventsDir:de("TASK_HANDOFF_EVENTS_DIR",s.join(n,"events")),artifactDir:de("TASK_HANDOFF_ARTIFACT_DIR",s.join(n,"artifacts")),logDir:de("TASK_HANDOFF_LOG_DIR",s.join(n,"logs")),webTokenPath:de("TASK_HANDOFF_WEB_TOKEN_FILE",s.join(n,"web-token"))}}const ue=new Set(["linux","darwin","win32","freebsd","openbsd","aix","sunos"]),le=new Set(["x64","arm64","arm","ia32","ppc64","s390x","riscv64"]),me={user:0,"passwordless-sudo":1,root:2};function he(e,n,i){const r="win32"===n?(i.PATHEXT||".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean):[""];for(const i of r){const r="win32"!==n||s.extname(e)?e:`${e}${i}`;try{if(t.accessSync(r,t.constants.X_OK),t.statSync(r).isFile())return r}catch{}}}function ge(e,t={}){const n=t.env||process.env,i=t.cwd||process.cwd(),r=t.platform||process.platform;if(s.isAbsolute(e))return he(e,r,n);if(e.includes("/")||e.includes("\\"))return he(s.resolve(i,e),r,n);for(const t of(n.PATH||"").split(s.delimiter).filter(Boolean)){const i=he(s.join(t,e),r,n);if(i)return i}}function fe(e){return ue.has(e)?e:"unknown"}function ye(e){return le.has(e)?e:"unknown"}function ve(e,t,s){const n=ge(e,s)||e;return"win32"===s.platform&&/\.(?:cmd|bat)$/i.test(n)?{executable:s.env.ComSpec||"cmd.exe",args:["/d","/s","/c","call",n,...t]}:{executable:n,args:t}}function Se(e,t){const s=e.distribution.recipes.filter(e=>e.platforms.includes(t.platform)).filter(e=>!e.arches?.length||e.arches.includes(t.arch));if(!s.length)return{reason:{code:"UNSUPPORTED_PLATFORM",message:`No built-in recipe supports ${t.platform}/${t.arch}.`}};const n=s.filter(e=>!function(e){return"system-package"===e.type||"node-package"===e.type}(e)||t.installers.includes(e.installer));if(!n.length)return{reason:{code:"INSTALLER_UNAVAILABLE",message:"The required package installer is unavailable on this computer."}};const i=n.filter(e=>function(e,t="user"){return me[e]>=me[t]}(t.privilege,e.privilege));if(!i.length)return{reason:{code:"INSUFFICIENT_PRIVILEGE",message:"The controlled instance does not have the privilege required by this recipe."}};const r=i.filter(e=>"node-package"!==e.type||"user"!==e.privilege||"root"===t.privilege||!0===t.installerAccess?.npmGlobalWritable);return r.length?{recipe:r[0]}:{reason:{code:"INSTALLER_NOT_WRITABLE",message:"The npm global installation directory is not writable by this controlled-instance user."}}}function we(e){let n=e;for(;!t.existsSync(n)&&s.dirname(n)!==n;)n=s.dirname(n);return n}function Ie(e){try{return t.accessSync(we(e),t.constants.W_OK),!0}catch{return!1}}function Ae(e){return t.promises.access(we(e),t.constants.W_OK).then(()=>!0,()=>!1)}function be(e,t,s={}){const n=s.env||process.env,i=s.platform||process.platform,r="win32"===i&&ge(e,{env:n,platform:i})||e,o="win32"===i&&/\.(?:cmd|bat)$/i.test(r)?{executable:n.ComSpec||"cmd.exe",args:["/d","/s","/c","call",r,...t]}:{executable:r,args:t};return new Promise(e=>{m.execFile(o.executable,o.args,{env:n,encoding:"utf8",timeout:2e3,maxBuffer:1048576},(t,s,n)=>{e({exitCode:t?"number"==typeof t.code?t.code:null:0,stdout:String(s||""),stderr:String(n||"")})})})}function _e(e,t){const n=s.relative(t,e);return""===n||!n.startsWith("..")&&!s.isAbsolute(n)}async function Te(e,t){try{return await t(e)}catch{return s.resolve(e)}}async function Oe(e,t,n,i){const r="passwordless-sudo"===n.privilege&&"user"!==e.privilege?{executable:"sudo",args:["-n",e.installer,"root","--global"]}:{executable:e.installer,args:["root","--global"]},o=await i.runCommand(r.executable,r.args),a=0===o.exitCode?o.stdout.trim():"";if(!a||!s.isAbsolute(a))return!1;const c=await Promise.all(t.executablePaths.map(e=>Te(e,i.realpath)));for(const r of e.packages){const e=s.join(a,...r.split("/"));try{const o=JSON.parse(await i.readFile(s.join(e,"package.json"))),d=r.split("/").at(-1)||r,p="string"==typeof o.bin?{[d]:o.bin}:o.bin||{},u=Object.values(p).map(t=>s.resolve(e,t)).filter(t=>_e(t,e)),l=await Promise.all(u.map(e=>Te(e,i.realpath)));if(c.some(e=>l.includes(e)))return!0;if("win32"===n.platform){const e=s.dirname(a),n=Object.keys(p);if(t.executablePaths.some(t=>s.dirname(t)===e&&n.includes(s.basename(t).replace(/\.(?:cmd|ps1)$/i,""))))return!0}}catch{}}return!1}async function xe(e,t,s){const n=new Set;for(const e of t.executablePaths)n.add(e),n.add(await Te(e,s.realpath));if("apt"===e.installer){for(const t of n){const n=await s.runCommand("dpkg-query",["--search",t]);if(0===n.exitCode&&n.stdout.split(/\r?\n/).some(t=>e.packages.includes(t.split(":",1)[0].replace(/:[^:]+$/,""))))return!0}return!1}if("dnf"===e.installer){for(const t of n){const n=await s.runCommand("rpm",["-qf",t,"--qf","%{NAME}"]);if(0===n.exitCode&&e.packages.includes(n.stdout.trim()))return!0}return!1}for(const t of e.packages){const e=await s.runCommand("brew",["--prefix",t]);if(0!==e.exitCode)continue;const i=await Te(e.stdout.trim(),s.realpath);if([...n].some(e=>_e(e,i)))return!0}return!1}function Ee(e,t,s,n){const i=Se(e,s),r=n||("not-installed"===t.state?"none":"bundled"===i.recipe?.type?"bundled":i.recipe?"recipe":"external"),o="not-installed"!==t.state||i.recipe?t.state:"unsupported",a="bundled"===i.recipe?.type,c="not-installed"===o&&Boolean(i.recipe)&&!a,d=("installed"===o||"broken"===o)&&Boolean(i.recipe)&&!a&&"recipe"===r,p=c?void 0:a?{code:"BUNDLED",message:"This app is supplied with the controlled computer."}:"installed"===o||"broken"===o?{code:"ALREADY_INSTALLED",message:"This app is already present."}:i.reason,u=d?void 0:a?{code:"BUNDLED",message:"Bundled apps cannot be removed by app management."}:"external"===r?{code:"EXTERNALLY_MANAGED",message:"This app was installed outside App management and must be removed with its original installer."}:"not-installed"===o||"unsupported"===o?{code:"NOT_INSTALLED",message:"This app is not installed."}:i.reason;return{id:e.launcher.id,name:e.launcher.name,kind:e.launcher.kind,description:e.launcher.description,state:o,managementSource:r,version:t.version,canInstall:c,canUninstall:d,installReason:p,uninstallReason:u}}const ke=["linux","darwin","win32","freebsd","openbsd","aix","sunos"];function ze(){return{recipes:[{type:"bundled",platforms:[...ke]}]}}function Ne(e,t,s=!1){const n=e[t];return void 0===n||""===n?s:["1","true","yes","on"].includes(n.toLowerCase())}function Pe(e,...t){for(const s of t){const t=e[s]?.trim();if(t)return["--model",t]}return[]}const Re={id:"cc-switch",optional:!0,enabled:({env:e})=>Ne(e,"TASK_HANDOFF_ENABLE_CC_SWITCH"),definition:({env:e})=>({launcher:{id:"cc-switch",name:"CC Switch",kind:"gui",description:"CC Switch desktop app in an isolated virtual desktop.",command:e.TASK_HANDOFF_CC_SWITCH_COMMAND||"cc-switch",display:{width:1440,height:900,depth:24}},detection:[{type:"launcher-executable",versionArgs:["--version"]}],distribution:ze()})};function Ce(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 De(e){return e.toFixed(2).replace(/\.?0+$/,"")}function Me(){return process.env.TASK_HANDOFF_GUI_APP_HOME||process.env.HOME||r.homedir()}function Fe(e){return t.existsSync(s.join(e,"manifest.json"))}function je(e){const n=["1","true","yes","on"].includes(String(process.env.TASK_HANDOFF_CHROMIUM_NO_SANDBOX||"").toLowerCase())?["--no-sandbox"]:[],i=function(e){const t=process.env.TASK_HANDOFF_CHROMIUM_USER_DATA_DIR?.trim();return t||s.join(e,"profile")}(e.sessionDir),r=function(){const e=process.env.TASK_HANDOFF_CHROMIUM_EXTENSION_DIRS;if(e)return e.split(/[,;]/).map(e=>e.trim()).filter(e=>Fe(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=>Fe(e)).sort():[]}();return[...n,"--disable-dev-shm-usage","--no-first-run",...r.length?[`--load-extension=${r.join(",")}`]:[],"--remote-debugging-address=127.0.0.1",...i?[`--user-data-dir=${i}`]:[],...e.app.automation?.portArg?[e.app.automation.portArg.replaceAll("{port}",String(e.automationPort))]:[`--remote-debugging-port=${e.automationPort}`],...e.defaultArgs]}const Le={id:"chromium",createRuntime:()=>({prepareGuiArgs:je}),definition:({env:e})=>({launcher:{id:"chromium",name:"Browser",kind:"gui",description:"Chromium browser with VNC and CDP endpoints.",command:e.TASK_HANDOFF_CHROMIUM_COMMAND||"chromium",args:["about:blank"],display:{width:1440,height:900,depth:24},automation:{type:"cdp",portArg:"--remote-debugging-port={port}"}},detection:[{type:"launcher-executable",versionArgs:["--version"]}],distribution:{recipes:[{type:"system-package",platforms:["linux"],installer:"apt",packages:["chromium","chromium-sandbox"],privilege:"passwordless-sudo"}]}})},$e=/^[a-f0-9]{8}$/;function He(e=process.env){return e.CLAUDE_CONTROL_SOCK||s.join(function(e=process.env){const t=process.getuid?.()??0,i=e.TERMUX_VERSION&&e.PREFIX?s.join(e.PREFIX,"tmp"):"/tmp",o=(e.CLAUDE_CONFIG_DIR??s.join(r.homedir(),".claude")).normalize("NFC"),a=n.createHash("sha256").update(s.resolve(o)).digest("hex").slice(0,8);return s.join(i,`cc-daemon-${t}`,a)}(e),"control.sock")}function Ue(e,t={}){const s=t.sockPath||He(),n=t.timeoutMs??5e3;return new Promise(t=>{let r;try{r=i.connect(s)}catch(e){return void t({ok:!1,code:"ENOCONN",error:String(e)})}let o=!1,a="";const c=e=>{o||(o=!0,r.destroy(),t(e))};r.setTimeout(n,()=>c({ok:!1,code:"ETIMEOUT",error:"control socket timeout"})),r.on("error",e=>c({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{c(JSON.parse(s))}catch(e){c({ok:!1,code:"EBADJSON",error:String(e),raw:s})}}),r.once("close",()=>{o||c({ok:!1,code:"ENOCONN",error:"connection dropped mid-request"})})})}function qe(e,t,s){return Ve(e),Ue({op:"reply",short:e,text:t},s)}function Be(e,t="SIGTERM",s){return Ve(e),Ue({op:"kill",short:e,signal:t},s)}function Ke(e,{tail:t,onMessage:s,options:n={}}={}){Ve(e);const r=i.connect(n.sockPath||He());let o="";return r.on("connect",()=>{r.write(`${JSON.stringify({proto:1,op:"subscribe",short:e,tail:t})}\n`)}),r.on("data",e=>{o+=e.toString("utf8");let t=o.indexOf("\n");for(;t>=0;){const e=o.slice(0,t);if(o=o.slice(t+1),e.trim())try{s?.(JSON.parse(e))}catch{s?.({raw:e})}t=o.indexOf("\n")}}),r.on("error",()=>{}),()=>r.destroy()}function Ve(e){if(!$e.test(e))throw new Error(`Claude worker short id must be 8 hex chars: ${e}`)}function Ge(){return Number(process.env.TASK_HANDOFF_CLAUDE_BG_TIMEOUT_MS)||15e3}function We(e){if(["1","true","yes","on"].includes(String(process.env.TASK_HANDOFF_CLAUDE_BG_DISABLED||"").toLowerCase()))return{};const t=["--bg",...e.args],s=m.spawnSync(e.command,t,{cwd:e.cwd,env:e.env,encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:Ge()}),n=`${s.stdout||""}\n${s.stderr||""}`;if(s.error)throw Object.assign(new Error(`Claude background launch failed: ${s.error.message}`),{code:"APP_LAUNCH_FAILED"});if(0!==s.status)throw Object.assign(new Error(`Claude background launch exited with code ${s.status}: ${n.trim()}`),{code:"APP_LAUNCH_FAILED"});const i=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]}(n);if(!i)throw Object.assign(new Error("Claude background launch did not report a worker id."),{code:"APP_LAUNCH_FAILED"});const r=He(e.env);return{args:["attach",i],env:{...e.env,TASK_HANDOFF_APP_SESSION_ID:e.sessionId,TASK_HANDOFF_CLAUDE_SHORT:i,TASK_HANDOFF_CLAUDE_CONTROL_SOCK:r},ttyMode:"claude-attach",ai:{agent:"claude",claude:{short:i,controlSock:r,cwd:e.cwd}},lifecycle:{spawnFailed:()=>function(e,t,s,n){try{m.spawnSync(e,["stop",t],{cwd:s,env:n,encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:Ge()})}catch{}}(e.command,i,e.cwd,e.env),stop:()=>{Be(i,"SIGTERM",{sockPath:r,timeoutMs:Number(process.env.TASK_HANDOFF_CLAUDE_CONTROL_TIMEOUT_MS)||5e3})}}}}const Ye={id:"claude",capabilities:{supportsCwdSelection:!0,supportsAiSessionResume:!0},aiSessionResumeArgs:e=>["--resume",e],createRuntime:()=>({prepareTtyLaunch:We}),definition:({env:e})=>{const t=Ne(e,"TASK_HANDOFF_CLAUDE_DANGEROUSLY_SKIP_PERMISSIONS")||Ne(e,"TASK_HANDOFF_CLAUDE_SKIP_PERMISSIONS");return{launcher:{id:"claude",name:"Claude",kind:"tty",description:"Claude Code CLI in the task workspace.",command:e.TASK_HANDOFF_CLAUDE_COMMAND||"claude",args:[...t?["--dangerously-skip-permissions"]:[],...Pe(e,"TASK_HANDOFF_CLAUDE_MODEL","CLAUDE_MODEL")]},detection:[{type:"launcher-executable",versionArgs:["--version"]}],distribution:{recipes:[{type:"node-package",platforms:["linux","darwin","win32"],arches:["x64","arm64"],installer:"npm",packages:["@anthropic-ai/claude-code"],privilege:"user"},{type:"node-package",platforms:["linux","darwin","win32"],arches:["x64","arm64"],installer:"npm",packages:["@anthropic-ai/claude-code"],privilege:"passwordless-sudo"}]}}}};class Je{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 w.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 w("ws://localhost/rpc",{createConnection:()=>i.createConnection(this.socketPath),perMessageDeflate:!1}),s=new Map,n=[];e.on("message",(e,i)=>{i||this.observeClientMessage(e.toString(),s),t.readyState===w.OPEN?t.send(e,{binary:i}):t.readyState===w.CONNECTING&&n.push({data:e,isBinary:i})}),t.on("open",()=>{for(;t.readyState===w.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===w.OPEN&&e.send(t,{binary:n})});const r=()=>{e.readyState!==w.OPEN&&e.readyState!==w.CONNECTING||e.close(),t.readyState!==w.OPEN&&t.readyState!==w.CONNECTING||t.close()};e.on("close",r),e.on("error",r),t.on("close",r),t.on("error",r)}observeClientMessage(e,t){const s=Xe(e);if(!s)return;const n=Qe(s.id),i="string"==typeof s.method?s.method:"",r=s.params&&"object"==typeof s.params?s.params:{};if(n&&("thread/start"===i||"thread/resume"===i||"thread/fork"===i))return t.set(n,{method:i,threadId:"string"==typeof r.threadId?r.threadId:void 0}),void("string"==typeof r.threadId&&this.onThreadBound(r.threadId));"string"!=typeof r.threadId||"turn/start"!==i&&"turn/steer"!==i&&"turn/interrupt"!==i&&"thread/unsubscribe"!==i||this.onThreadBound(r.threadId)}observeServerMessage(e,t){const s=Xe(e);if(!s)return;const n=Qe(s.id);if(!n)return;const i=t.get(n);if(!i)return;if(t.delete(n),s.error)return;const r=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)||i.threadId;r&&this.onThreadBound(r)}}function Xe(e){try{const t=JSON.parse(e);return t&&"object"==typeof t&&!Array.isArray(t)?t:void 0}catch{return}}function Qe(e){return"string"==typeof e&&e?e:"number"==typeof e&&Number.isFinite(e)?String(e):void 0}class Ze{host;shared;sessionAi=new Map;constructor(e){this.host=e}sharedResource={ensure:({app:e,cwd:t,env:s})=>{const n=e.command||process.env.TASK_HANDOFF_CODEX_COMMAND||"codex";if(!this.host.hasCommand(n))throw Object.assign(new Error(`Missing required command: ${n}`),{code:"APP_DEPENDENCY_MISSING"});return this.sharedResourceInfo(this.acquire(n,t,s,"__shared_codex_app_server__"))},acquire:(e,t,s,n)=>this.sharedResourceInfo(this.acquire(e,t,s,n)),release:e=>this.release(e),info:()=>{const e=this.appServerInfo();return e?this.sharedResourceInfo(e):void 0},projectSessionAi:()=>{const e=this.appServerInfo();return e?{agent:"codex",appServer:e}:void 0}};prepareTtyLaunch(e){if(["1","true","yes","on"].includes(String(process.env.TASK_HANDOFF_CODEX_APP_SERVER_DISABLED||"").toLowerCase()))return{};const t=this.acquire(e.command,e.cwd,e.env,e.sessionId),s=this.host.allocatePort("web"),n=new Je(t.socketPath,t=>this.bindThread(e.sessionId,t));n.start(s);const i=n.endpoint||t.endpoint,r={agent:"codex",appServer:{transport:"unix",endpoint:t.endpoint,socketPath:t.socketPath,proxyEndpoint:i,proxyPort:s,pid:t.child.pid,command:t.command,args:t.args,logPath:t.logPath,status:"running"}};this.sessionAi.set(e.sessionId,r);let o=!1;const a=()=>{o||(o=!0,n.stop(),this.release(e.sessionId),this.sessionAi.delete(e.sessionId))};return{args:[...e.catalogArgs,"--remote",i,"--cd",e.cwd,...e.launchArgs,...e.resumeArgs],env:{...e.env,TASK_HANDOFF_APP_SESSION_ID:e.sessionId,TASK_HANDOFF_CODEX_APP_SERVER_SOCKET:t.socketPath,TASK_HANDOFF_CODEX_APP_SERVER_URL:t.endpoint,TASK_HANDOFF_CODEX_APP_SERVER_PROXY_URL:i},ai:r,lifecycle:{processExited:a,spawnFailed:a,stop:a}}}managedEnvironmentChanged(){this.stopAll()}stopAll(){const e=this.shared;e&&(this.shared=void 0,e.child.killed||null!==e.child.exitCode||e.child.kill("SIGTERM"),t.rmSync(e.socketPath,{force:!0}))}acquire(e,i,o,a){const c=this.shared;if(c&&null===c.child.exitCode&&!c.child.killed&&t.existsSync(c.socketPath))return c.appSessionIds.add(a),c;if(c&&!c.child.killed&&c.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.host.paths.runtimeDir,"codex-app-server"),p=s.join(this.host.paths.logDir,"app-sessions","codex-app-server"),u=function(e){const i=process.env.TASK_HANDOFF_CODEX_APP_SERVER_SOCKET_DIR?.trim(),o=i?t.realpathSync(i):"darwin"===process.platform?"/private/tmp":t.realpathSync(r.tmpdir()),a=n.createHash("sha256").update(e).digest("hex").slice(0,16);return s.join(o,`task-handoff-codex-${a}`,"app-server.sock")}(d),l=`unix://${u}`,m=process.env.TASK_HANDOFF_CODEX_APP_SERVER_COMMAND||e,h=["app-server","--listen",l];t.mkdirSync(d,{recursive:!0}),t.mkdirSync(p,{recursive:!0}),t.mkdirSync(s.dirname(u),{recursive:!0,mode:448}),t.rmSync(u,{force:!0});const g=this.host.spawnLogged(m,h,o,p,"codex-app-server.log",i),f={status:"running",command:m,args:h,socketPath:u,endpoint:l,logPath:s.join(p,"codex-app-server.log"),child:g,appSessionIds:new Set([a])};let y;this.shared=f,g.once("error",e=>{y=e}),g.on("exit",(e,t)=>{if(this.shared?.child!==g)return;const s=0===e?"exited":"failed";for(const n of f.appSessionIds)this.updateMetadata(n,s,e,t);this.shared=void 0});try{this.host.waitForUnixSocket(u,5e3,()=>y)}catch(e){throw g.killed||g.kill("SIGTERM"),this.shared=void 0,Object.assign(e instanceof Error?e:new Error(String(e)),{code:"CODEX_APP_SERVER_START_FAILED"})}return f}release(e){const s=this.shared;s&&(s.appSessionIds.delete(e),s.appSessionIds.size>0||(this.shared=void 0,s.child.killed||null!==s.child.exitCode||s.child.kill("SIGTERM"),t.rmSync(s.socketPath,{force:!0})))}appServerInfo(){const e=this.shared;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"}}updateMetadata(e,t,s,n){const i=this.sessionAi.get(e);if(!i?.appServer)return;const r={...i,appServer:{...i.appServer,status:t,exitCode:s,signal:n}};this.sessionAi.set(e,r),this.host.patchSession(e,{ai:r})}bindThread(e,t){const s=this.sessionAi.get(e);if(!s)return;const n=Array.isArray(s.threadIds)?s.threadIds:[],i={...s,activeThreadId:t,threadIds:n.includes(t)?n:[...n,t]};this.sessionAi.set(e,i),this.host.patchSession(e,{ai:i})}sharedResourceInfo(e){if(!e)throw new Error("Codex app-server is not running.");return{kind:"codex-app-server",status:"running",details:{transport:"unix",endpoint:e.endpoint,socketPath:e.socketPath,pid:"child"in e?e.child.pid:e.pid,command:e.command,args:e.args,logPath:e.logPath}}}}const et={id:"codex",capabilities:{supportsCwdSelection:!0,supportsAiSessionResume:!0},aiSessionResumeArgs:e=>["resume",e],createRuntime:function(e){return new Ze(e)},definition:({env:e})=>({launcher:{id:"codex",name:"Codex",kind:"tty",description:"OpenAI Codex CLI in the task workspace.",command:e.TASK_HANDOFF_CODEX_COMMAND||"codex",args:["-c","check_for_update_on_startup=false",...Pe(e,"TASK_HANDOFF_CODEX_MODEL","CODEX_MODEL")]},detection:[{type:"launcher-executable",versionArgs:["--version"]}],distribution:{recipes:[{type:"node-package",platforms:["linux","darwin","win32"],arches:["x64","arm64"],installer:"npm",packages:["@openai/codex"],privilege:"user"},{type:"node-package",platforms:["linux","darwin","win32"],arches:["x64","arm64"],installer:"npm",packages:["@openai/codex"],privilege:"passwordless-sudo"}]}})},tt={id:"terminal-gui",matchesRuntime:e=>"gui"===e.kind&&"xterm"===s.basename(e.command||""),createRuntime:()=>({prepareGuiArgs:({defaultArgs:e})=>["-fa",process.env.TASK_HANDOFF_XTERM_FONT_FAMILY||"Monospace","-fs",process.env.TASK_HANDOFF_XTERM_FONT_SIZE||"11",...e]}),definition:({env:e})=>({launcher:{id:"terminal-gui",name:"GUI Terminal",kind:"gui",description:"xterm terminal in an isolated virtual desktop with VNC access.",command:e.TASK_HANDOFF_XTERM_COMMAND||"xterm",args:["-geometry","120x32"],display:{width:1024,height:768,depth:24}},detection:[{type:"launcher-executable",versionArgs:["--version"]}],distribution:{recipes:[{type:"system-package",platforms:["linux"],installer:"apt",packages:["xterm"],privilege:"passwordless-sudo"}]}})},st={id:"terminal-tty",capabilities:{supportsCwdSelection:!0},definition:({env:e})=>({launcher:{id:"terminal-tty",name:"Terminal",kind:"tty",description:"Interactive shell in the task workspace.",command:e.SHELL||"/bin/bash"},detection:[{type:"launcher-executable",versionArgs:["--version"]}],distribution:ze()})},nt={"workbench.colorTheme":"Default Dark Modern","workbench.preferredDarkColorTheme":"Default Dark Modern"},it={id:"vscode-web",createRuntime:()=>({prepareWebSession({sessionDir:e}){const n=s.join(e,"user-data","User"),i=s.join(n,"settings.json");let r={};if(t.mkdirSync(n,{recursive:!0}),t.existsSync(i))try{const e=JSON.parse(t.readFileSync(i,"utf8"));e&&"object"==typeof e&&!Array.isArray(e)&&(r=e)}catch{r={}}y.sync(i,`${JSON.stringify({...nt,...r},null,2)}\n`,{mode:384})}}),definition:({env:e})=>({launcher:{id:"vscode-web",name:"VS Code",kind:"web",description:"VS Code Web in the task workspace.",command:e.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:"/"}},detection:[{type:"launcher-executable",versionArgs:["--version"]}],distribution:ze()})};const rt=new class{providers;providersById;constructor(e){this.providers=e;const t=new Map;for(const s of e){if(t.has(s.id))throw new Error(`Duplicate managed app provider id: ${s.id}`);t.set(s.id,s)}this.providersById=t}provider(e){return this.providersById.get(e)}runtimeProvider(e){const t=this.provider(e.id);if(t)return t;const s=this.providers.filter(t=>t.matchesRuntime?.(e));if(s.length>1)throw new Error(`Multiple managed app providers match runtime for ${e.id}: ${s.map(({id:e})=>e).join(", ")}`);return s[0]}definitions(e={}){const t={env:e.env||process.env};return this.providers.filter(s=>!s.optional||e.includeOptional||s.enabled?.(t)).map(e=>{const s=e.definition(t);if(s.launcher.id!==e.id)throw new Error(`Managed app provider ${e.id} returned launcher id ${s.launcher.id}`);return s})}}([st,et,Ye,tt,Le,it,Re]);function ot(e={}){return rt.definitions(e)}!function(e={}){ot(e).map(e=>e.launcher)}({includeOptional:!0});const at=l.z.string().trim().min(1).max(512).refine(e=>!/\s/.test(e)&&!/[;&|<>`$]/.test(e),"Command must be a single executable path or name."),ct=l.z.object({id:l.z.string().trim().min(1).max(80).regex(/^[a-z0-9][a-z0-9._-]*$/),name:l.z.string().trim().min(1).max(120),kind:l.z.enum(["tty","gui","web"]),description:l.z.string().max(500).optional(),command:at,args:l.z.array(l.z.string().max(1024)).max(64).default([]).optional(),cwd:l.z.string().max(512).optional(),env:l.z.record(l.z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),l.z.string().max(4096)).optional(),display:l.z.object({width:l.z.number().int().min(320).max(7680).optional(),height:l.z.number().int().min(240).max(4320).optional(),depth:l.z.union([l.z.literal(16),l.z.literal(24),l.z.literal(32)]).optional()}).strict().optional(),defaultDisplayTarget:l.z.object({mode:l.z.enum(["isolated","shared"]),id:l.z.string().trim().min(1).max(80).regex(/^[a-z0-9][a-z0-9._-]*$/).optional(),autoCreate:l.z.boolean().optional()}).strict().optional(),automation:l.z.object({type:l.z.literal("cdp"),portArg:l.z.string().optional(),endpointPath:l.z.string().optional()}).strict().optional(),web:l.z.object({portArg:l.z.string().optional(),readyPath:l.z.string().optional()}).strict().optional()}).strict(),dt=l.z.object({schemaVersion:l.z.literal(1).default(1),items:l.z.array(ct).default([])}).strict();function pt(e){try{return t.accessSync(e,t.constants.X_OK),t.statSync(e).isFile()}catch{return!1}}function ut(e,t=process.env,n=process.cwd()){const i="win32"===process.platform?(t.PATHEXT||".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean):[""],r=e=>{for(const t of i){const n="win32"!==process.platform||s.extname(e)?e:`${e}${t}`;if(pt(n))return n}};if(s.isAbsolute(e))return r(e);if(e.includes("/")||e.includes("\\"))return r(s.resolve(n,e));for(const n of(t.PATH||"").split(s.delimiter).filter(Boolean)){const t=r(s.join(n,e));if(t)return t}}function lt(e){const t=e.command?.trim();return Boolean(t&&ut(t,{...process.env,...e.env},e.cwd))}class mt{registry;customStore;customCatalogSchema;inventoryCache;constructor(e,t=rt){this.registry=t,this.customCatalogSchema=function(e){return dt.superRefine((t,s)=>{const n=new Set(e.definitions({includeOptional:!0}).map(({launcher:e})=>e.id)),i=new Set;for(const[e,r]of t.items.entries())n.has(r.id)&&s.addIssue({code:l.z.ZodIssueCode.custom,path:["items",e,"id"],message:"Custom apps cannot override built-in app ids."}),i.has(r.id)&&s.addIssue({code:l.z.ZodIssueCode.custom,path:["items",e,"id"],message:"Custom app ids must be unique."}),i.add(r.id)})}(t),this.customStore=new J(s.join(e.appCatalogDir,"custom.json"),{schema:this.customCatalogSchema,defaultValue:()=>({schemaVersion:1,items:[]}),sanitize:ht})}list(){const e=new Map;for(const{launcher:t}of this.registry.definitions())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(lt)}inventory(e=(new Date).toISOString()){const t=this.registry.definitions().map(({launcher:e})=>({app:e,source:"builtin"})),s=this.safeCustom(),n=new Map;for(const e of t)n.set(e.app.id,e);for(const e of s.data?.items||[])n.set(e.id,{app:e,source:"custom"});const i=[...n.values()].map(({app:e,source:t})=>({app:e,source:t,executable:e.command?.trim()?ut(e.command.trim(),{...process.env,...e.env},e.cwd):void 0})),r=JSON.stringify(i.map(({app:e,source:t,executable:s})=>({id:e.id,name:e.name,kind:e.kind,source:t,executable:s,automation:e.automation?.type,cwd:e.cwd})));return this.inventoryCache&&this.inventoryCache.fingerprint===r||(this.inventoryCache={fingerprint:r,items:i.map(({app:e,source:t,executable:s})=>({id:e.id,name:e.name,kind:e.kind,source:t,availability:s?"available":"missing-dependency",capabilities:{automation:e.automation?.type,supportsCwdSelection:"builtin"===t&&!0===this.registry.provider(e.id)?.capabilities?.supportsCwdSelection},diagnosticCode:s?void 0:"APP_EXECUTABLE_NOT_FOUND"}))}),{items:this.inventoryCache.items,observedAt:e,issues:s.error?[{code:"APP_CATALOG_INVALID",message:"Custom app catalog could not be read completely; valid catalog entries remain available."}]:[]}}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:function(e,s){try{const n=JSON.parse(t.readFileSync(e,"utf8")),i=n&&"object"==typeof n&&!Array.isArray(n)?n:{};if(!Array.isArray(i.items))return;const r=new Set(s.definitions({includeOptional:!0}).map(({launcher:e})=>e.id)),o=new Set,a=[];for(const e of i.items){const t=ct.safeParse(gt(e));!t.success||r.has(t.data.id)||o.has(t.data.id)||(o.add(t.data.id),a.push(t.data))}return{schemaVersion:1,items:a}}catch{return}}(this.customStore.path(),this.registry),error:{code:"APP_CATALOG_INVALID",message:"Custom app catalog is invalid."}}}}saveCustom(e){return this.customStore.save(this.customCatalogSchema.parse(e)),this.inventoryCache=void 0,this.customStore.load()}customPath(){return this.customStore.path()}}function ht(e){if(!e||"object"!=typeof e||Array.isArray(e))return e;const t=e;return{schemaVersion:t.schemaVersion,items:Array.isArray(t.items)?t.items.map(gt):t.items}}function gt(e){if(!e||"object"!=typeof e||Array.isArray(e))return e;const t=e;return{...ft(t,["id","name","kind","description","command","args","cwd","env"]),display:ft(t.display,["width","height","depth"]),defaultDisplayTarget:ft(t.defaultDisplayTarget,["mode","id","autoCreate"]),automation:ft(t.automation,["type","portArg","endpointPath"]),web:ft(t.web,["portArg","readyPath"])}}function ft(e,t){if(!e||"object"!=typeof e||Array.isArray(e))return;const s=e;return Object.fromEntries(t.filter(e=>Object.prototype.hasOwnProperty.call(s,e)).map(e=>[e,s[e]]))}function yt(){return`app_${Date.now().toString(36)}_${Math.random().toString(16).slice(2)}`}function vt(){return(new Date).toISOString()}const St=new Set(["stopped","exited","failed"]);class wt extends v.EventEmitter{paths;registry;sessions=new Map;persistedSessions=new Map;nextDisplay=101;nextVncPort=6101;nextWebsockifyPort=7101;nextWebPort=8101;nextCdpPort=9201;sharedDisplays=new Map;appRuntimeExtensions=new Map;catalogRepository;persistSessionMetadata;managedEnvironment={};constructor(e,t=rt){super(),this.paths=e,this.registry=t,this.catalogRepository=new mt(e,t);const s={paths:e,allocatePort:e=>this.allocatePort(e),hasCommand:(e,t,s)=>this.hasCommand(e,t,s),spawnLogged:(e,t,s,n,i,r)=>this.spawnLogged(e,t,s,n,i,r),waitForUnixSocket:(e,t,s)=>this.waitForUnixSocket(e,t,s),patchSession:(e,t)=>this.patchSessionMetadata(e,t)};for(const e of t.providers)e.createRuntime&&this.appRuntimeExtensions.set(e.id,e.createRuntime(s));this.persistSessionMetadata=function(e,t=!1){const s=process.env[e];return void 0===s||""===s?t:["1","true","yes","on"].includes(s.toLowerCase())}("TASK_HANDOFF_APP_SESSION_PERSIST"),this.persistSessionMetadata&&(this.loadPersistedSessions(),this.cleanupExpiredSessions())}catalog(){return this.catalogRepository.available()}appInventory(e){return this.catalogRepository.inventory(e)}customCatalog(){const e=this.catalogRepository.safeCustom();return e.data?{data:{path:this.catalogRepository.customPath(),...e.data},error:e.error}:{data:void 0,error:e.error}}saveCustomCatalog(e){return{path:this.catalogRepository.customPath(),...this.catalogRepository.saveCustom({schemaVersion:1,items:e})}}replaceManagedEnvironment(e){const t=JSON.stringify(this.managedEnvironment)!==JSON.stringify(e);if(this.managedEnvironment={...e},t)for(const e of this.appRuntimeExtensions.values())e.managedEnvironmentChanged?.()}listSessions(){return Array.from(this.persistedSessions.values()).sort((e,t)=>t.createdAt.localeCompare(e.createdAt))}sharedResourceInfo(e){return this.sharedAppResource(e)?.info()}sharedResourceSessionAi(e){return this.sharedAppResource(e)?.projectSessionAi?.()}ensureSharedResource(e){const t=this.sharedAppResource(e);if(!t)throw Object.assign(new Error(`${e} does not provide a shared resource.`),{code:"APP_SHARED_RESOURCE_UNAVAILABLE"});const s=this.catalogRepository.find(e);if(!s)throw Object.assign(new Error("Shared backend app is unavailable."),{code:"APP_NOT_FOUND"});const n=s.cwd||process.env.TASK_HANDOFF_WORKSPACE||process.cwd(),i={...process.env,...s.env,...this.managedEnvironment,TERM:"xterm-256color"};return t.ensure({app:s,cwd:n,env:i})}acquireSharedResource(e,t,s,n,i){const r=this.sharedAppResource(e);if(!r)throw Object.assign(new Error(`${e} does not provide a shared resource.`),{code:"APP_SHARED_RESOURCE_UNAVAILABLE"});return r.acquire(t,s,n,i)}releaseSharedResource(e,t){this.sharedAppResource(e)?.release(t)}sharedAppResource(e){return this.appRuntimeExtensions.get(e)?.sharedResource}appRuntimeExtension(e){const t=this.registry.runtimeProvider(e);return t?this.appRuntimeExtensions.get(t.id):void 0}patchSessionMetadata(e,t){const s=this.sessions.get(e);s&&(s.metadata.ai=t.ai,s.metadata.updatedAt=vt(),this.persist(s.metadata),this.emit("updated",s.metadata))}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 i=this.getSession(e);if(!i)throw Object.assign(new Error("App session not found."),{code:"APP_SESSION_NOT_FOUND"});const r=s.resolve(i.paths.logDir),o=(t.existsSync(r)?t.readdirSync(r,{withFileTypes:!0}):[]).filter(e=>e.isFile()&&e.name.endsWith(".log")).sort((e,t)=>e.name.localeCompare(t.name)).map(e=>{const i=s.resolve(r,e.name);if(!i.startsWith(`${r}${s.sep}`))throw Object.assign(new Error("Invalid log path."),{code:"APP_LOG_PATH_INVALID"});const o=t.statSync(i),a=Math.max(0,o.size-n),c=t.openSync(i,"r");try{const s=Buffer.alloc(o.size-a);return t.readSync(c,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(c)}});return{sessionId:e,logDir:r,maxBytes:n,files:o}}start(e="terminal-tty",n={}){const i=this.catalogRepository.find(e);if(!i)throw Object.assign(new Error("App not found."),{code:"APP_NOT_FOUND"});if(!this.hasCommand(i.command||i.id,{...process.env,...i.env},n.cwd||i.cwd))throw Object.assign(new Error(`Missing required command: ${i.command||i.id}`),{code:"APP_DEPENDENCY_MISSING"});if("gui"===i.kind)return this.startGuiApp(i,n);if("web"===i.kind)return this.startWebApp(i,n);if("tty"!==i.kind)throw Object.assign(new Error("App kind is not implemented yet."),{code:"APP_NOT_IMPLEMENTED"});const r=yt(),o=i.command||process.env.SHELL||"/bin/bash",a=this.normalizeLaunchOptions(n),c=this.resolveLaunchCwd(a.cwd,i.cwd);a.cwd=c;const d=this.aiSessionResumeArgs(i.id,a);let p=[...i.args||[],...a.args||[],...d],u={...process.env,...i.env,...a.env,...this.managedEnvironment,TERM:"xterm-256color"};const l=s.join(this.paths.appSessionsDir,r),m=s.join(this.paths.logDir,"app-sessions",r);t.mkdirSync(l,{recursive:!0}),t.mkdirSync(m,{recursive:!0});const h=this.appRuntimeExtension(i)?.prepareTtyLaunch?.({app:i,sessionId:r,sessionDir:l,logDir:m,command:o,cwd:c,env:u,args:p,catalogArgs:i.args||[],launchArgs:a.args||[],resumeArgs:d});p=h?.args||p,u=h?.env||u;const g={id:r,appId:e,title:a.title||i.name,kind:"tty",status:"running",createdAt:vt(),updatedAt:vt(),workspace:{cwd:c},launch:a,tty:{webPath:`/api/apps/sessions/${r}/tty`,shell:o,cwd:c,mode:h?.ttyMode||"pty"},process:{command:o},ai:h?.ai,paths:{sessionDir:l,logDir:m}},f=t.createWriteStream(s.join(m,"tty.log"),{flags:"a"}),y={metadata:g,processes:[],appLifecycle:h,ttyDimensions:{cols:120,rows:32},ttyLogStream:f,outputBacklog:"",clients:new Set};f.on("error",()=>{y.ttyLogClosed=!0}),f.on("close",()=>{y.ttyLogClosed=!0});const v=(e,t)=>{y.stopping||(g.status="exited",g.updatedAt=vt(),g.process={...g.process,exitCode:e,signal:void 0===t?void 0:String(t)},this.persist(g),this.emit("updated",g)),y.appLifecycle?.lifecycle?.processExited?.(),this.broadcast(y,{type:"exit",code:e,signal:t}),this.closeTtyLog(y)};let S;try{S=this.spawnTerminalPty(o,p,c,u)}catch(e){throw this.closeTtyLog(y),h?.lifecycle?.spawnFailed?.(),e}return g.process={...g.process,pid:S.pid},y.pty=S,S.onData(e=>{this.writeTtyLog(y,e),y.outputBacklog=`${y.outputBacklog}${e}`.slice(-65536),this.broadcast(y,{type:"output",data:e})}),S.onExit(({exitCode:e,signal:t})=>v(e,t)),this.sessions.set(r,y),this.persist(g),this.emit("created",g),g}startWebApp(e,n){const i=e.command||e.id;if(!this.hasCommand(i))throw Object.assign(new Error(`Missing required command: ${i}`),{code:"APP_DEPENDENCY_MISSING"});const r=yt(),o=s.join(this.paths.appSessionsDir,r),a=s.join(this.paths.logDir,"app-sessions",r);t.mkdirSync(o,{recursive:!0}),t.mkdirSync(a,{recursive:!0});const c=this.normalizeLaunchOptions(n),d=this.resolveLaunchCwd(c.cwd,e.cwd);c.cwd=d;const p=this.allocatePort("web"),u={...process.env,...e.env,...c.env,...this.managedEnvironment},l=this.webArgs(e,o,d,p,c.args||[]);this.prepareWebAppSession(e,o,d,p,c);const m=this.spawnLogged(i,l,u,a,`${e.id}.log`,d),h={id:r,appId:e.id,title:c.title||e.name,kind:"web",status:"running",createdAt:vt(),updatedAt:vt(),workspace:{cwd:d},launch:c,web:{host:"127.0.0.1",port:p,webPath:`/api/apps/sessions/${r}/web/`,readyPath:e.web?.readyPath},process:{pid:m.pid,command:i},paths:{sessionDir:o,logDir:a}},g={metadata:h,processes:[m],outputBacklog:"",clients:new Set};return this.sessions.set(r,g),this.persist(h),this.watchLoggedProcess(g,m,e.id,!1),this.emit("created",h),h}startGuiApp(e,n){const i=e.command||e.id,r="kasmvnc"===process.env.TASK_HANDOFF_VNC_BACKEND?"kasmvnc":"novnc",o="kasmvnc"===r?["vncserver","vncpasswd","openssl","xrdb","xrandr","openbox",i]:["Xvfb","openbox","x11vnc","websockify",i];for(const e of o)if(!this.hasCommand(e))throw Object.assign(new Error(`Missing required command: ${e}`),{code:"APP_DEPENDENCY_MISSING"});const a=yt(),c=s.join(this.paths.appSessionsDir,a),d=s.join(this.paths.logDir,"app-sessions",a);t.mkdirSync(c,{recursive:!0}),t.mkdirSync(d,{recursive:!0});const p=this.normalizeLaunchOptions(n),u=p.displayTarget||this.normalizeDisplayTarget(e.defaultDisplayTarget)||{mode:"isolated"};p.displayTarget=u;const l=this.resolveLaunchCwd(p.cwd,e.cwd);p.cwd=l;const m=this.allocatePort("cdp"),h=this.guiArgs(e,c,m,p.args||[]);if("shared"===u.mode){const t=this.ensureSharedDisplay(e,p,r,l),s=this.appEnvForDisplay(e,p,t),n=this.spawnLogged(i,h,s,d,`${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:vt(),updatedAt:vt(),workspace:{cwd:l},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:i},paths:{sessionDir:c,logDir:d}},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"===r?this.allocatePort("web"):this.allocatePort("vnc"),y="novnc"===r?this.allocatePort("websockify"):void 0,v=p.display?.width||e.display?.width||1440,S=p.display?.height||e.display?.height||900,w=p.display?.depth||e.display?.depth||24,I={...process.env,...e.env,...p.env,...this.managedEnvironment,DISPLAY:g},A=Ce(I),b=s.join(c,"home"),_="kasmvnc"===r?s.join(b,".Xauthority"):void 0,T="kasmvnc"===r?this.startKasmVncDisplay(g,v,S,w,f,I,c,d,A):this.startNoVncDisplay(g,v,S,w,f,y,I,d,l),O="kasmvnc"===r?this.guiScaleEnv({...I,HOME:Me(),XAUTHORITY:_},A):I;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"===r&&this.applyGuiScale(O,c,A);const x=this.spawnLogged("openbox",[],O,d,"openbox.log"),E=this.startCompositor(O,d,l),k=this.spawnLogged(i,h,O,d,`${e.id}.log`,l),z=e.automation?{type:e.automation.type,port:m,endpoint:`http://127.0.0.1:${m}${e.automation.endpointPath||""}`}:void 0,N={id:a,appId:e.id,title:p.title||e.name,kind:"gui",status:"running",createdAt:vt(),updatedAt:vt(),workspace:{cwd:l},launch:p,display:{display:g,mode:"isolated",width:v,height:S,depth:w,xPid:T[0]?.pid,wmPid:x.pid,compositorPid:E?.pid,xauthority:_},vnc:{backend:r,host:"127.0.0.1",port:f,websockifyPort:y,webPath:"kasmvnc"===r?`/api/apps/sessions/${a}/web/`:`/api/apps/sessions/${a}/vnc`,noVncPath:"kasmvnc"===r?`/api/apps/sessions/${a}/web/`:`/api/apps/sessions/${a}/novnc/vnc.html`},web:"kasmvnc"===r?{host:"127.0.0.1",port:f,webPath:`/api/apps/sessions/${a}/web/`}:void 0,automation:z,process:{pid:k.pid,command:i},paths:{sessionDir:c,logDir:d}},P={metadata:N,processes:[k,...T,x,...E?[E]:[]],outputBacklog:"",clients:new Set};this.sessions.set(a,P),this.persist(N);for(const e of T)this.watchLoggedProcess(P,e,"kasmvnc"===r?"kasmvnc":"display",!0);return this.watchLoggedProcess(P,x,"openbox",!0),this.watchLoggedProcess(P,k,e.id,!1),this.emit("created",N),N}ensureSharedDisplay(e,n,i,r){const o="shared"===n.displayTarget?.mode?n.displayTarget:void 0,a=o?.id||"main",c=this.sharedDisplays.get(a);if(c)return c;if(!1===o?.autoCreate)throw Object.assign(new Error(`Shared display session not found: ${a}`),{code:"APP_DISPLAY_SESSION_NOT_FOUND"});const d=a.replace(/[^a-z0-9._-]/gi,"_"),p=s.join(this.paths.appSessionsDir,`display_${d}`),u=s.join(this.paths.logDir,"app-sessions",`display_${d}`);t.mkdirSync(p,{recursive:!0}),t.mkdirSync(u,{recursive:!0});const l=`:${this.allocateDisplay()}`,m="kasmvnc"===i?this.allocatePort("web"):this.allocatePort("vnc"),h="novnc"===i?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,...this.managedEnvironment,DISPLAY:l},S=Ce(v),w=s.join(p,"home"),I="kasmvnc"===i?s.join(w,".Xauthority"):void 0,A="kasmvnc"===i?this.startKasmVncDisplay(l,g,f,y,m,v,p,u,S):this.startNoVncDisplay(l,g,f,y,m,h,v,u,r),b="kasmvnc"===i?this.guiScaleEnv({...v,HOME:Me(),XAUTHORITY:I},S):v;try{this.waitForXDisplay(l)}catch(e){for(const e of A)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(b,p,S);const _=this.spawnLogged("openbox",[],b,u,"openbox.log"),T=this.startCompositor(b,u,r),O={id:a,display:l,width:g,height:f,depth:y,backend:i,vncPort:m,websockifyPort:h,xPid:A[0]?.pid,wmPid:_.pid,compositorPid:T?.pid,xauthority:I,sessionDir:p,logDir:u,processes:[...A,_,...T?[T]:[]],appSessionIds:new Set};this.sharedDisplays.set(a,O);for(const e of[...A,_])this.watchSharedDisplayProcess(O,e);return O}appEnvForDisplay(e,t,s){const n={...process.env,...e.env,...t.env,...this.managedEnvironment,DISPLAY:s.display},i=Ce(n);return"kasmvnc"===s.backend?this.guiScaleEnv({...n,HOME:Me(),XAUTHORITY:s.xauthority},i):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")}}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 i=this.sessions.get(n);i&&this.markFailed(i,"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,i,r,o,a,c){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(i)],o,a,"x11vnc.log"),this.spawnLogged("websockify",[String(r),`127.0.0.1:${i}`],o,a,"websockify.log",c)]}waitForXDisplay(e,n=5e3){const i=e.replace(/^:/,"").split(".")[0],r=s.join("/tmp/.X11-unix",`X${i}`),o=Date.now();for(;Date.now()-o<n;){if(t.existsSync(r))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,i,r,o,a,c,d){this.prepareKasmVncHome(a,t,n,i,r,d);const p={...o,HOME:s.join(a,"home")},u=this.writeKasmVncLauncher(a,e,t,n,i);return[this.spawnLogged("bash",[u],p,c,"kasmvnc.log")]}guiScaleEnv(e,t){return{...e,TASK_HANDOFF_GUI_SCALE:De(t),XCURSOR_SIZE:"24"}}applyGuiScale(e,n,i){if(i<=1)return;const r=s.join(n,"home",".Xresources");if(t.existsSync(r))try{m.execFileSync("xrdb",["-merge",r],{env:e,stdio:"ignore"})}catch{}}writeKasmVncLauncher(e,n,i,r,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(`${i}x${r}`)}`,`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,i,r,o,a){const c=s.join(e,"home"),d=s.join(c,".vnc"),p=s.join(c,".config","gtk-3.0"),u=s.join(c,".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(d,"self.pem");t.mkdirSync(d,{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(c,".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(c,".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(d,"kasmvnc.yaml"),["desktop:"," resolution:",` width: ${n}`,` height: ${i}`," allow_resize: true",` pixel_depth: ${r}`,"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:c},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=vt(),t.stopping=!0,this.persist(t.metadata),t.pty?.kill(),this.closeTtyLog(t);for(const e of t.clients)e.send(JSON.stringify({type:"exit",code:null,signal:"SIGHUP"})),e.close?.();t.clients.clear();for(const e of t.processes)e.killed||e.kill("SIGTERM");return t.appLifecycle?.lifecycle?.stop?.(),"shared"===t.metadata.display?.mode&&t.metadata.display.displaySessionId&&this.releaseSharedDisplaySession(t.metadata.display.displaySessionId,e),t.metadata.status="stopped",t.metadata.updatedAt=vt(),this.persist(t.metadata),this.sessions.delete(e),this.emit("updated",t.metadata),t.metadata}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,i={...t.launch,title:n};return this.sessions.has(e)&&this.stop(e),this.start(s,i)}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=vt(),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 i=await Promise.all(n);let r=t.filter((e,t)=>!i[t]);if(r.length>0){const e=r.map(e=>this.waitForProcessClose(e,1e3));for(const e of r)null===e.exitCode&&null===e.signalCode&&e.kill("SIGKILL");const t=await Promise.all(e);r=r.filter((e,s)=>!t[s])}if(r.length>0)throw Object.assign(new Error(`App session processes did not exit: ${r.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)||!St.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 i=this.normalizeDisplayOptions(t),r=i.width||n.display.width,o=i.height||n.display.height,a=i.depth||n.display.depth,c=this.displayCommandEnv(n);try{this.resizeDisplayWithXrandr(c,r,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:r,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=vt(),this.persist(e.metadata),e.appLifecycle?.lifecycle?.stop?.(),e.pty?.kill(),this.closeTtyLog(e);for(const t of e.processes)t.kill("SIGTERM")}for(const e of Array.from(this.sharedDisplays.keys()))this.stopSharedDisplay(e);for(const e of this.appRuntimeExtensions.values())e.stopAll?.();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,i=e.rows;s.ttyDimensions={cols:n,rows:i},s.pty?.resize(n,i);for(const e of s.clients)e!==t&&e.send(JSON.stringify({type:"resize",cols:n,rows:i}))}}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}),y.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=this.sanitizePersistedSession(JSON.parse(t.readFileSync(n,"utf8")),e.name);if(!s)continue;const i=this.recoverPersistedSession(s);this.persistedSessions.set(i.id,i),i!==s&&this.persist(i)}catch{continue}}}recoverPersistedSession(e){return"running"!==e.status&&"stopping"!==e.status?e:{...e,status:"exited",updatedAt:vt(),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}}}sanitizePersistedSession(e,t){if(!e||"object"!=typeof e||Array.isArray(e))return;const n=e,i=n.paths&&"object"==typeof n.paths&&!Array.isArray(n.paths)?n.paths:void 0;if(n.id!==t||"string"!=typeof n.appId||"string"!=typeof n.title||!["tty","gui","web"].includes(String(n.kind))||!["created","running","stopping","stopped","exited","failed"].includes(String(n.status))||"string"!=typeof n.createdAt||"string"!=typeof n.updatedAt||"string"!=typeof i?.sessionDir||"string"!=typeof i?.logDir)return;const r=e=>e&&"object"==typeof e&&!Array.isArray(e)?e:{},o=r(n.workspace),a=r(n.tty),c=r(n.launch),d=r(n.ai),p=r(d.claude),u=this.catalogRepository.find(n.appId),l=[o.cwd,a.cwd,p.cwd,c.cwd,u?.cwd,process.env.TASK_HANDOFF_WORKSPACE,process.cwd()].find(e=>"string"==typeof e&&e.trim().length>0);return l?{...n,workspace:{cwd:s.resolve(l)}}:void 0}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)),i=this.nextNumber(n,t.start,t.end);return"vnc"===e?this.nextVncPort=i:"websockify"===e?this.nextWebsockifyPort=i:"web"===e?this.nextWebPort=i:this.nextCdpPort=i,n}findAvailableNumber(e,t,s,n){const i=s-t+1;for(let s=0;s<i;s+=1){const r=t+(Math.max(e,t)-t+s)%i;if(n(r))return r}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",env:{...process.env,ELECTRON_RUN_AS_NODE:"1"}}).status}waitForUnixSocket(e,s,n){const i=Date.now();for(;Date.now()-i<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=vt(),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 i=t=>{n||(n=!0,clearTimeout(a),e.off("close",r),e.off("error",o),s(t))},r=()=>i(!0),o=()=>i(!0),a=setTimeout(()=>i(!1),t);e.once("close",r),e.once("error",o)})}watchLoggedProcess(e,t,s,n,i){t.on("error",t=>{this.markFailed(e,"APP_PROCESS_ERROR",`${s} failed: ${t.message}`)}),t.on("exit",(t,r)=>{if(e.stopping)i?.();else{if(n&&0!==t)return this.markFailed(e,"APP_PROCESS_EXITED",`${s} exited unexpectedly with code ${t??"null"} signal ${r??"null"}.`),void i?.();n||(e.metadata.status=0===t?"exited":"failed",e.metadata.updatedAt=vt(),e.metadata.process={...e.metadata.process,exitCode:t,signal:r},0!==t&&(e.metadata.error={code:"APP_PROCESS_EXITED",message:`${s} exited with code ${t??"null"} signal ${r??"null"}.`}),this.persist(e.metadata),this.emit("updated",e.metadata)),i?.()}})}guiArgs(e,t,s,n){const i=[...e.args||[],...n].map(e=>e.replaceAll("{sessionDir}",t).replaceAll("{cdpPort}",String(s))),r=this.appRuntimeExtension(e)?.prepareGuiArgs?.({app:e,sessionDir:t,automationPort:s,launchArgs:n,defaultArgs:i});return r||(e.automation?.portArg&&i.unshift(e.automation.portArg.replaceAll("{port}",String(s))),i)}webArgs(e,t,s,n,i){const r=e=>e.replaceAll("{sessionDir}",t).replaceAll("{cwd}",s).replaceAll("{port}",String(n)),o=[...e.args||[],...i].map(r);return e.web?.portArg&&o.unshift(r(e.web.portArg)),o}prepareWebAppSession(e,t,s=process.cwd(),n=0,i={}){this.appRuntimeExtension(e)?.prepareWebSession?.({app:e,sessionDir:t,cwd:s,port:n,launch:i})}async fetchCdpVersion(e){const t=new URL(e);t.pathname=s.posix.join(t.pathname,"json","version");const n=new AbortController,i=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(i)}}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);if(n&&(t.displayTarget=n),e.aiSessionResume){const s=e.aiSessionResume.aiSessionId?.trim(),n=e.aiSessionResume.providerSessionId?.trim();if(!s||!n)throw Object.assign(new Error("AI session resume requires both AI and provider session ids."),{code:"APP_RESUME_INVALID"});t.aiSessionResume={aiSessionId:s,providerSessionId:n}}return t}resolveLaunchCwd(e,t){return s.resolve(e||t||process.env.TASK_HANDOFF_WORKSPACE||process.cwd())}aiSessionResumeArgs(e,t){if(!t.aiSessionResume)return[];const s=this.registry.provider(e);if(!s?.capabilities?.supportsAiSessionResume||!s.aiSessionResumeArgs)throw Object.assign(new Error(`${e} does not support AI session resume.`),{code:"APP_RESUME_UNSUPPORTED"});return s.aiSessionResumeArgs(t.aiSessionResume.providerSessionId)}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),i={};return Number.isInteger(t)&&t>=320&&t<=7680&&(i.width=t),Number.isInteger(s)&&s>=240&&s<=4320&&(i.height=s),Number.isInteger(n)&&n>=8&&n<=32&&(i.depth=n),i}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}`,i=this.connectedDisplayOutput(e),r=i?[["--output",i,"--mode",n],["--fb",n]]:[["--fb",n]];let o;for(const t of r)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(ut(e,t,s))}spawnTerminalPty(e,n,i,r){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"),i=t.statSync(n);73&i.mode||t.chmodSync(n,493|i.mode)}catch{}}(),S.spawn(e,n,{name:"xterm-256color",cols:120,rows:32,cwd:i,env:r})}catch(e){throw Object.assign(new Error(`PTY unavailable: ${e instanceof Error?e.message:String(e)}`),{code:"PTY_UNAVAILABLE"})}}spawnLogged(e,n,i,r,o,a){const c=t.createWriteStream(s.join(r,o),{flags:"a"}),d=m.spawn(e,n,{cwd:a,env:i,stdio:["ignore","pipe","pipe"]});return d.stdout.pipe(c),d.stderr.pipe(c),d}}const It={"image/bmp":".bmp","image/gif":".gif","image/jpeg":".jpg","image/png":".png","image/webp":".webp"};function At(e=[]){if(!e.length)return[];const n=function(){const e=process.env.TASK_HANDOFF_AI_SESSION_ATTACHMENT_DIR?.trim();return e?s.resolve(e):s.join(r.tmpdir(),"task-handoff-ai-session-attachments")}();return t.mkdirSync(n,{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 i of t.readdirSync(e,{withFileTypes:!0})){if(!i.isFile())continue;const r=s.join(e,i.name);try{t.statSync(r).mtimeMs<n&&t.unlinkSync(r)}catch{}}}catch{}}(n),e.map(e=>{const i=It[e.mime.toLowerCase()]||s.extname(e.name)||".img",r=`${e.id}-${(o=e.name,s.basename(o).replace(/[^\w.\- ()\u4e00-\u9fff]/g,"_").slice(0,160)||"image").replace(/\.[^.]+$/,"")}${i}`;var o;const a=s.join(n,r);return t.writeFileSync(a,Buffer.from(e.data,"base64")),{...e,path:a}})}async function bt(e,t=[],s){const n=At(t);if(!n.length)return s(e);const i=n.map((e,t)=>`图片${n.length>1?t+1:""}路径:${e.path}`);return s([e.trim(),i.join("\n")].filter(Boolean).join("\n\n"))}class _t{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)}clear(){this.approvals.clear()}}class Tt{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 xt("AI_SESSION_MESSAGE_EMPTY","Message is required.");if(t.references?.length&&"codex"!==s.agent)throw xt("AI_SESSION_REFERENCES_UNSUPPORTED",`${s.agent} sessions do not support Codex references.`,400);const i=t.mode||"auto";if("queue"===i||"auto"===i&&Ot(s)){const e=this.registry.enqueueMessage(s.id,n,t.attachments||[],t.references||[]);if(!e)throw xt("AI_SESSION_NOT_FOUND","AI session not found.",404);return{session:e.session,provider:s.agent,action:"queue",queueId:e.item.id}}if("steer"===i)return this.steerMessage(s.id,{message:n,attachments:t.attachments||[],references:t.references||[]});if(Ot(s))throw xt("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||[],references:t.references||[]})}async startMessage(e,t){const s=this.requireSession(e);if(Ot(s))throw xt("AI_SESSION_BUSY","AI session is busy. Queue the message or steer it into the running turn.",409);const n=this.requireProvider(s),i=n.startMessage||n.sendMessage;if(!i)throw xt("AI_SESSION_SEND_UNSUPPORTED",`${s.agent} sessions do not support starting turns.`,400);return i.call(n,s,t)}async steerMessage(e,t){const s=this.requireSession(e);if(!Ot(s))throw xt("AI_SESSION_NOT_ACTIVE","AI session is not active.",409);const n=this.requireProvider(s),i=n.steerMessage||n.sendMessage;if(!i)throw xt("AI_SESSION_STEER_UNSUPPORTED",`${s.agent} sessions do not support turn steering.`,400);const r="string"==typeof t?{message:t}:t;return i.call(n,s,r)}async sendNextQueuedMessage(e){const t=this.requireSession(e);if(Ot(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),references:s.references}),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 xt("AI_SESSION_QUEUE_ITEM_NOT_FOUND","Queued message not found.",404);const i=await this.steerMessage(s.id,{message:n.message,attachments:this.registry.queuedMessageAttachments(n.id),references:n.references}),r=this.registry.removeQueuedMessage(s.id,n.id);return{...i,session:r||i.session,action:"steer",queueId:n.id}}retryQueuedMessage(e,t){const s=this.registry.retryQueuedMessage(e,t);if(!s)throw xt("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 xt("AI_SESSION_NOT_FOUND","AI session not found.",404);return s}reorderQueuedMessages(e,t){const s=this.registry.reorderQueuedMessages(e,t);if(!s)throw xt("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 xt("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 xt("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 xt("AI_SESSION_NOT_FOUND","AI session not found.",404);return t}requireProvider(e){const t=this.providers.get(e.agent);if(!t)throw xt("AI_SESSION_CONTROL_UNSUPPORTED",`${e.agent} sessions do not support direct control yet.`,400);return t}}function Ot(e){return"running"===e.status||"waiting"===e.status}function xt(e,t,s=400){const n=new Error(t);return n.code=e,n.statusCode=s,n}function Et(e,t=500){const s=String(e??"").replace(/\s+/g," ").trim();return s.length>t?`${s.slice(0,t-3)}...`:s}function kt(e){return String(e??"").trim()}const zt={control:90,realtime:80,"adapter-snapshot":60,"transcript-tail":50,"app-session":40,"process-scan":30,"transcript-scan":20};function Nt(e,t){return Math.max(0,Math.min(100,Number.isInteger(t)?Number(t):e?zt[e]:0))}function Pt(e){const t={};return e.source&&(t.source=e.source,t.sourcePriority=Nt(e.source,e.sourcePriority)),e.providerTurnId&&(t.providerTurnId=Et(e.providerTurnId,240)),Number.isInteger(e.snapshotVersion)&&(t.snapshotVersion=Number(e.snapshotVersion)),e.observedAt&&(t.observedAt=e.observedAt),t}function Rt(e){if(!Array.isArray(e))return;const t=new Map;for(const s of e){if(!s||"object"!=typeof s||Array.isArray(s))continue;const e=s;if("string"!=typeof e.id||!e.id.trim()||"running"!==e.status&&"completed"!==e.status)continue;const n=Et(e.id,240),i=t.get(n),r="completed"===i?.status||"completed"===e.status?"completed":"running",o=Ct(e.startedAt)||i?.startedAt,a=Ct(e.completedAt)||i?.completedAt;t.set(n,{id:n,status:r,...o?{startedAt:o}:{},...a?{completedAt:a}:{}})}const s=[...t.values()].slice(-20);return s.length?s:void 0}function Ct(e){if("string"!=typeof e||!e.trim())return;const t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():void 0}function Dt(e){const t=Et(e,120),s=t.replace(/[^a-zA-Z0-9_.:-]+/g,"_").replace(/^_+|_+$/g,""),i=n.createHash("sha1").update(t).digest("hex").slice(0,10);return s?`${s}_${i}`:i}function Mt(e,t){return`turn_${Dt(e)}_${Dt(t)}`}function Ft(e,t,s=1){return Mt(e,t||`${e}:${s}`)}function jt(e,t){return`turn_legacy_${t}_${Dt(e.userPrompt||e.updatedAt||e.lastMessage||e.summary)}`}function Lt(e,t={}){const s=[];for(const[n,i]of(e||[]).entries()){const e=i&&"object"==typeof i?i:void 0;if(!e)continue;const r={id:e.id?Et(e.id,240):jt(e,n),providerTurnId:e.providerTurnId?Et(e.providerTurnId,240):t.providerTurnId,source:e.source||t.source,userPrompt:e.userPrompt?kt(e.userPrompt):void 0,status:e.status||"completed",phase:e.phase,summary:e.summary?Et(e.summary,1e3):void 0,lastMessage:e.lastMessage?kt(e.lastMessage):void 0,lastMessageItemId:e.lastMessageItemId?Et(e.lastMessageItemId,240):void 0,contextCompactions:Rt(e.contextCompactions),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};(r.userPrompt||r.summary||r.lastMessage||r.contextCompactions?.length)&&s.push(r)}return s.slice(-50)}function $t(e,t){if(!e)return!0;if(function(e,t){const s=new Map((e?.contextCompactions||[]).map(e=>[e.id,e.status]));return(t.contextCompactions||[]).some(e=>!s.has(e.id)||"running"===s.get(e.id)&&"completed"===e.status)}(e,t))return!0;const s=Nt(e.source,e.sourcePriority),n=Nt(t.source,t.sourcePriority);if(n!==s)return n>s||Boolean(t.lastMessage||t.summary)&&!e.lastMessage&&!e.summary;const i=Number(e.snapshotVersion)||0,r=Number(t.snapshotVersion)||0;return r!==i?r>i:(t.revision||0)>=(e.revision||0)||Date.parse(t.observedAt||t.updatedAt||"")>=Date.parse(e.observedAt||e.updatedAt||"")}function Ht(e,t){const s=function(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e))}(t);var n;if(s.contextCompactions=(n=e?.contextCompactions,Rt([...n||[],...t.contextCompactions||[]])),!e)return s;const i=e.userPrompt===(t.userPrompt??e.userPrompt)&&e.summary===(t.summary??e.summary)&&e.lastMessage===(t.lastMessage??e.lastMessage)&&e.lastMessageItemId===(t.lastMessageItemId??e.lastMessageItemId)&&JSON.stringify(e.contextCompactions||[])===JSON.stringify(s.contextCompactions||[]),r=e.status===(t.status??e.status)&&e.phase===(t.phase??e.phase);return i&&r&&(delete s.observedAt,delete s.updatedAt,delete s.completedAt),s}function Ut(e){return Boolean(e?.lastMessage||e?.summary)}function qt(e){if(!e.activeTurnId||"running"!==e.status)return!1;const t=Lt(e.turns).find(t=>t.id===e.activeTurnId);return Boolean(!t||!Ut(t))}function Bt(e,t,s){return s?e.activeTurnId:"idle"!==t.status&&"failed"!==t.status?t.activeTurnId?Et(t.activeTurnId,240):e.activeTurnId:void 0}function Kt(e,t,s,i={}){const r=function(e,t,s={}){const n=Lt(e),i=Lt(t,s);function r(e,t){const s=i.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 r=i.slice(t+1).find(e=>n.some(t=>t.id===e.id));if(r){const t=n.findIndex(e=>e.id===r.id);return void n.splice(t,0,e)}n.push(e)}for(const[e,t]of i.entries()){let s=!1;for(const[e,i]of n.entries())if(i.id!==t.id&&i.userPrompt&&i.userPrompt===t.userPrompt&&!i.lastMessage&&!i.summary&&(t.lastMessage||t.summary)){const r={...i,...Ht(i,t),id:i.id,providerTurnId:t.providerTurnId||t.id,revision:Math.max(i.revision||0,t.revision||0)};$t(i,r)&&(n[e]=r),s=!0;break}if(s)continue;const i=n.findIndex(e=>e.id===t.id),o=i>=0?n[i]:void 0;if($t(o,t)){const s={...o,...Ht(o,t),revision:Math.max(o?.revision||0,t.revision||0)};i>=0?n[i]=s:r(s,e)}}return n.slice(-50)}(e,t.turns,i),o=t.activeTurnId?Et(t.activeTurnId,240):"",a=kt((o?t.turns?.find(e=>e.id===o)?.userPrompt:void 0)||t.userPrompt);if(a){const e=r.at(-1),n=(o?r.find(e=>e.id===o):void 0)||[...r].reverse().find(e=>e.userPrompt===a&&!e.lastMessage&&!e.summary),c=Boolean(t.turns?.some(e=>e.userPrompt&&kt(e.userPrompt)===a));n?(o&&n.id!==o&&(n.id=o),n.userPrompt=a,n.updatedAt=s,n.status="waiting"===t.status?"waiting":"running",n.phase=t.phase||n.phase||"thinking",Object.assign(n,i),n.revision+=1):!e||e.lastMessage||e.summary||e.userPrompt!==a?c||r.push({id:o||Mt(a,s),...i,userPrompt:a,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,i),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,...i,status:"waiting"===t.status?"waiting":"failed"===t.status?"failed":"running",phase:t.phase||"unknown",revision:0,startedAt:s,updatedAt:s},r.push(e));const a={summary:t.summary?Et(t.summary,1e3):e?.summary,lastMessage:t.lastMessage?kt(t.lastMessage):e?.lastMessage,lastMessageItemId:t.lastMessageItemId?Et(t.lastMessageItemId,240):e?.lastMessageItemId,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,...i};if(e){const t=e.summary===a.summary&&e.lastMessage===a.lastMessage&&e.lastMessageItemId===a.lastMessageItemId,s=e.status===a.status&&e.phase===a.phase,n=t&&s;Object.assign(e,{...a,observedAt:n?e.observedAt:a.observedAt,updatedAt:n||t?e.updatedAt:a.updatedAt,completedAt:n?e.completedAt:a.completedAt}),t&&s||(e.revision+=1)}else r.push({id:`turn_${n.randomUUID().replace(/-/g,"").slice(0,20)}`,...a,status:a.status||"running",revision:0,startedAt:s})}else if((t.status||t.phase)&&o){const e=r.find(e=>e.id===o);if(e){const n="idle"===t.status?"completed":"waiting"===t.status?"waiting":"failed"===t.status?"failed":e.status,r=t.phase||e.phase,o="idle"===t.status||"failed"===t.status?s:e.completedAt,a=e.status!==n||e.phase!==r||e.completedAt!==o;Object.assign(e,{status:n,phase:r,completedAt:o,updatedAt:a?s:e.updatedAt,...i}),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 Lt(r)}function Vt(e,t){const s=e.replace(/\s+/g," ").trim();return s.length>t?`${s.slice(0,t-3)}...`:s}function Gt(e,t){const s=Vt(e,80),n=Vt(t,240);if(s&&n)return{agent:s,providerSessionId:n,key:`${s}\0${n}`}}class Wt{sessionIdsByProvider=new Map;providerKeysBySessionId=new Map;candidates(e,t){const s=Gt(e,t);return s?[...this.sessionIdsByProvider.get(s.key)||[]]:[]}replace(e){this.remove(e.id);const t=e.providerSessionId;if(!t)return;const s=Gt(e.agent,t);if(!s)return;const n=this.sessionIdsByProvider.get(s.key)||new Set;n.add(e.id),this.sessionIdsByProvider.set(s.key,n),this.providerKeysBySessionId.set(e.id,new Set([s.key]))}remove(e){const t=this.providerKeysBySessionId.get(e);if(t){for(const s of t){const t=this.sessionIdsByProvider.get(s);t?.delete(e),t?.size||this.sessionIdsByProvider.delete(s)}this.providerKeysBySessionId.delete(e)}}rebuild(e){this.clear();for(const t of e)this.replace(t)}clear(){this.sessionIdsByProvider.clear(),this.providerKeysBySessionId.clear()}}const Yt=41943040,Jt="ai-session.snapshot",Xt=l.z.string().trim().min(1).max(80),Qt=l.z.enum(["running","waiting","idle","failed"]),Zt=l.z.enum(["thinking","tool","editing","approval","responding","unknown"]),es=l.z.object({id:l.z.string().trim().min(1).max(240).optional(),kind:l.z.string().trim().min(1).max(80).optional(),name:l.z.string().trim().min(1).max(120),inputPreview:l.z.string().trim().max(500).optional(),startedAt:l.z.string().datetime().optional()}).strict(),ts=l.z.enum(["pending-init","running","interrupted","completed","errored","shutdown","not-found"]),ss=l.z.enum(["started","interacted","interrupted"]),ns=l.z.object({threadId:l.z.string().trim().min(1).max(240),path:l.z.string().trim().max(4096).optional(),status:ts,activity:ss.optional(),message:l.z.string().trim().max(1e3).optional(),updatedAt:l.z.string().datetime()}).strict(),is=l.z.object({toolCalls:l.z.number().int().min(0).default(0),edits:l.z.number().int().min(0).default(0),approvals:l.z.number().int().min(0).default(0)}).strict().default({toolCalls:0,edits:0,approvals:0}),rs=l.z.object({send:l.z.boolean().optional(),interrupt:l.z.boolean().optional(),approval:l.z.boolean().optional()}).strict(),os=l.z.object({id:l.z.string().trim().min(1).max(120),kind:l.z.enum(["image"]),name:l.z.string().trim().min(1).max(240),mime:l.z.string().trim().min(1).max(120),size:l.z.number().int().min(0).max(20971520),data:l.z.string().min(1).max(31457280)}).strict(),as=os.omit({data:!0}),cs=l.z.object({id:l.z.string().trim().min(1).max(120),kind:l.z.enum(["image"]).optional()}).strict(),ds=l.z.enum(["auto","queue","steer","immediate"]),ps=l.z.enum(["review","rename","goal","compact"]),us=l.z.object({command:ps,argument:l.z.string().trim().max(4e3).optional()}).strict().superRefine((e,t)=>{"rename"!==e.command||e.argument||t.addIssue({code:"custom",path:["argument"],message:"Rename requires a thread name."}),"review"!==e.command&&"compact"!==e.command||!e.argument||t.addIssue({code:"custom",path:["argument"],message:`${e.command} does not accept an argument.`})}),ls=l.z.object({command:ps,value:l.z.string().max(4e3).optional(),turnId:l.z.string().trim().min(1).max(240).optional()}).strict();l.z.enum(["skill","app","plugin"]);const ms=l.z.object({name:l.z.string().trim().min(1).max(240),path:l.z.string().trim().min(1).max(4096)}),hs=l.z.discriminatedUnion("kind",[ms.extend({kind:l.z.literal("skill"),path:l.z.string().trim().min(1).max(4096).refine(e=>e.startsWith("/"),"Skill paths must be absolute.")}).strict(),ms.extend({kind:l.z.literal("app"),path:l.z.string().trim().min(7).max(4096).regex(/^app:\/\/[^\s/]+$/,"App paths must use app://<id>.")}).strict(),ms.extend({kind:l.z.literal("plugin"),path:l.z.string().trim().min(10).max(4096).regex(/^plugin:\/\/[^\s/]+$/,"Plugin paths must use plugin://<id>.")}).strict()]),gs=l.z.array(hs).max(20).default([]),fs=l.z.enum(["plugin","skill","file","directory","app"]),ys=l.z.object({kind:fs,name:l.z.string().trim().min(1).max(240),description:l.z.string().trim().max(1e3).optional(),path:l.z.string().trim().min(1).max(4096),icon:l.z.string().trim().max(4096).optional()}).strict().superRefine((e,t)=>{"skill"!==e.kind||e.path.startsWith("/")||t.addIssue({code:"custom",path:["path"],message:"Skill paths must be absolute."}),"app"!==e.kind||/^app:\/\/[^\s/]+$/.test(e.path)||t.addIssue({code:"custom",path:["path"],message:"App paths must use app://<id>."}),"plugin"!==e.kind||/^plugin:\/\/[^\s/]+$/.test(e.path)||t.addIssue({code:"custom",path:["path"],message:"Plugin paths must use plugin://<id>."}),"file"!==e.kind&&"directory"!==e.kind||!e.path.startsWith("/")&&!e.path.split(/[\\/]+/).includes("..")||t.addIssue({code:"custom",path:["path"],message:"File and directory paths must be relative to the session cwd."})}),vs=l.z.object({category:l.z.enum(["skills","plugins","apps","files"]),code:l.z.string().trim().min(1).max(160),message:l.z.string().trim().min(1).max(2e3)}).strict(),Ss=l.z.object({sessionId:l.z.string().trim().min(1).max(120),providerSessionId:l.z.string().trim().min(1).max(240),cwd:l.z.string().trim().min(1).max(4096),candidates:l.z.array(ys).max(1e3).default([]),diagnostics:l.z.array(vs).max(20).default([])}).strict(),ws=l.z.object({query:l.z.string().trim().max(240).default("")}).strict(),Is=l.z.object({sessionId:l.z.string().trim().min(1).max(120),cwd:l.z.string().trim().min(1).max(4096),query:l.z.string().trim().max(240),requestId:l.z.string().trim().min(1).max(160),candidates:l.z.array(ys.refine(e=>"file"===e.kind||"directory"===e.kind,"File search only returns files and directories.")).max(200).default([]),complete:l.z.boolean().default(!1)}).strict(),As=l.z.object({message:l.z.string().trim().min(1).max(2e4),mode:ds.optional()}),bs=As.extend({attachments:l.z.array(os).max(6).default([]),references:gs}).strict().superRefine((e,t)=>{e.attachments.reduce((e,t)=>e+t.size,0)>Yt&&t.addIssue({code:l.z.ZodIssueCode.custom,path:["attachments"],message:"Images must be 41943040 bytes or less in total."})});As.extend({attachments:l.z.array(cs).max(6).default([]),references:gs}).strict();const _s=l.z.object({decision:l.z.enum(["allow","deny","skip"])}).strict(),Ts=l.z.object({queueIds:l.z.array(l.z.string().trim().min(1).max(120)).max(100)}).strict(),Os=l.z.object({code:l.z.string().trim().min(1).max(160),message:l.z.string(),instanceId:l.z.string().trim().min(1).max(160).optional(),nodeId:l.z.string().trim().min(1).max(160).optional(),route:l.z.string().trim().min(1).max(4096).optional()}).strict(),xs=l.z.object({id:l.z.string().trim().min(1).max(120),message:l.z.string().trim().min(1).max(2e4),attachments:l.z.array(as).max(6).default([]),references:gs,status:l.z.enum(["queued","sending","failed"]).default("queued"),createdAt:l.z.string().datetime(),updatedAt:l.z.string().datetime(),error:l.z.string().trim().max(4e3).optional()}).strict(),Es=l.z.object({pendingCount:l.z.number().int().min(0).default(0),items:l.z.array(xs).max(100).default([])}).strict().default({pendingCount:0,items:[]}),ks=l.z.enum(["control","realtime","adapter-snapshot","transcript-tail","transcript-scan","process-scan","app-session"]),zs=l.z.object({id:l.z.string().trim().min(1).max(240),status:l.z.enum(["running","completed"]),startedAt:l.z.string().datetime().optional(),completedAt:l.z.string().datetime().optional()}).strict(),Ns=l.z.object({id:l.z.string().trim().min(1).max(240),providerTurnId:l.z.string().trim().max(240).optional(),source:ks.optional(),userPrompt:l.z.string().trim().optional(),status:l.z.enum(["queued","running","waiting","completed","failed"]).default("running"),phase:Zt.optional(),summary:l.z.string().trim().max(1e3).optional(),lastMessage:l.z.string().trim().optional(),lastMessageItemId:l.z.string().trim().max(240).optional(),contextCompactions:l.z.array(zs).max(20).optional(),revision:l.z.number().int().min(0).default(0),sourcePriority:l.z.number().int().min(0).max(100).optional(),snapshotVersion:l.z.number().int().min(0).optional(),observedAt:l.z.string().datetime().optional(),startedAt:l.z.string().datetime().optional(),updatedAt:l.z.string().datetime().optional(),completedAt:l.z.string().datetime().optional()}).strict(),Ps=Ns.pick({id:!0,providerTurnId:!0,userPrompt:!0,status:!0,phase:!0,summary:!0,lastMessage:!0,contextCompactions:!0,startedAt:!0,updatedAt:!0,completedAt:!0}).strict(),Rs=l.z.object({id:l.z.string().trim().min(1).max(120),agent:Xt,appSessionId:l.z.string().trim().max(120).optional(),appId:l.z.string().trim().max(120).optional(),providerSessionId:l.z.string().trim().max(240).optional(),providerMeta:l.z.record(l.z.string(),l.z.unknown()).optional(),appBindingKeys:l.z.array(l.z.string().trim().min(1).max(240)).max(20).optional(),actions:rs.optional(),activeTurnId:l.z.string().trim().max(240).optional(),title:l.z.string().trim().max(240).optional(),cwd:l.z.string().trim().max(4096).optional(),userPrompt:l.z.string().trim().optional(),turns:l.z.array(Ns).max(50).optional(),status:Qt.default("running"),phase:Zt.default("unknown"),summary:l.z.string().trim().max(1e3).optional(),lastMessage:l.z.string().trim().optional(),lastMessageItemId:l.z.string().trim().max(240).optional(),currentTool:es.optional(),toolCallsSinceLastMessage:l.z.number().int().min(0).default(0),subAgents:l.z.array(ns).max(50).default([]),transcriptPath:l.z.string().trim().max(4096).optional(),transcriptSize:l.z.number().int().min(0).optional(),startedAt:l.z.string().datetime(),updatedAt:l.z.string().datetime(),completedAt:l.z.string().datetime().optional(),error:l.z.string().trim().max(4e3).optional(),counters:is,queue:Es}).strict(),Cs=l.z.object({session:Rs,provider:l.z.string().trim().min(1).max(80),action:l.z.enum(["send","queue","steer","interrupt","approval"]),decision:l.z.enum(["allow","deny","skip"]).optional(),turnId:l.z.string().trim().min(1).max(240).optional(),providerTurnId:l.z.string().trim().min(1).max(240).optional(),queueId:l.z.string().trim().min(1).max(120).optional()}).strict(),Ds=l.z.object({id:l.z.string().trim().min(1).max(120),agent:l.z.enum(["codex","claude"]),providerSessionId:l.z.string().trim().min(1).max(240),title:l.z.string().trim().max(240).optional(),userPrompt:l.z.string().trim().optional(),lastMessage:l.z.string().trim().optional(),cwd:l.z.string().trim().min(1).max(4096),lastActiveAt:l.z.string().datetime(),archivedAt:l.z.string().datetime()}).strict(),Ms=l.z.object({schemaVersion:l.z.literal(1).default(1),items:l.z.array(Ds).max(50).default([])}).strict(),Fs=l.z.object({items:l.z.array(Ds).max(50).default([])}).strict(),js=l.z.object({item:Ds,turns:l.z.array(Ps).max(50).default([])}).strict(),Ls=l.z.object({disposition:l.z.enum(["resumed","already-open"]),aiSessionId:l.z.string().trim().min(1).max(120),providerSessionId:l.z.string().trim().min(1).max(240),appSessionId:l.z.string().trim().min(1).max(120)}).strict(),$s=Rs.pick({id:!0,agent:!0,appSessionId:!0,appId:!0,providerSessionId:!0,providerMeta:!0,appBindingKeys:!0,actions:!0,activeTurnId:!0,title:!0,cwd:!0,userPrompt:!0,turns:!0,status:!0,phase:!0,summary:!0,lastMessage:!0,lastMessageItemId:!0,currentTool:!0,toolCallsSinceLastMessage:!0,subAgents:!0,queue:!0,startedAt:!0,updatedAt:!0,error:!0}),Hs=l.z.object({runningCount:l.z.number().int().min(0).default(0),waitingCount:l.z.number().int().min(0).default(0),staleCount:l.z.number().int().min(0).default(0),sessions:l.z.array($s).default([]),updatedAt:l.z.string().datetime()}).strict();l.z.object({streamId:l.z.string().trim().min(1).max(240),revision:l.z.number().int().min(0),lastEventAt:l.z.string().datetime(),snapshot:Hs}).strict(),Hs.pick({runningCount:!0,waitingCount:!0,staleCount:!0,updatedAt:!0}).extend({idleCount:l.z.number().int().min(0).default(0),problemCount:l.z.number().int().min(0).default(0),revision:l.z.number().int().min(0).optional()});const Us=l.z.enum(["provider-event","app-session-created","app-session-updated","app-session-deleted","discovery-scan","control-action","heartbeat-sync","startup"]),qs=l.z.object({streamId:l.z.string().trim().min(1).max(240),instanceId:l.z.string().trim().min(1).max(160),nodeId:l.z.string().trim().min(1).max(160).optional(),revision:l.z.number().int().min(0),previousRevision:l.z.number().int().min(0).optional(),traceId:l.z.string().trim().min(1).max(160),generatedAt:l.z.string().datetime(),reason:Us}).strict(),Bs=l.z.object({meta:qs,snapshot:Hs}).strict(),Ks=l.z.object({meta:qs,upserted:l.z.array($s).default([]),removed:l.z.array(l.z.string().trim().min(1).max(120)).default([])}).strict(),Vs=l.z.object({meta:qs,sessionIds:l.z.array(l.z.string().trim().min(1).max(120)).default([]),expiresAt:l.z.string().datetime()}).strict(),Gs=l.z.object({instanceId:l.z.string().trim().min(1).max(160),nodeId:l.z.string().trim().min(1).max(160).optional(),sessionId:l.z.string().trim().min(1).max(120),providerSessionId:l.z.string().trim().min(1).max(240),turnId:l.z.string().trim().min(1).max(240),itemId:l.z.string().trim().min(1).max(240),delta:l.z.string().min(1),generatedAt:l.z.string().datetime()}).strict(),Ws=l.z.object({streamId:l.z.string().trim().min(1).max(240),instanceId:l.z.string().trim().min(1).max(160),sinceRevision:l.z.number().int().min(0),latestRevision:l.z.number().int().min(0),earliestRetainedRevision:l.z.number().int().min(0),syncRequired:l.z.boolean().default(!1),events:l.z.array(l.z.discriminatedUnion("type",[l.z.object({type:l.z.literal(Jt),payload:Bs}).strict(),l.z.object({type:l.z.literal("ai-session.patch"),payload:Ks}).strict(),l.z.object({type:l.z.literal("ai-session.removed"),payload:Vs}).strict()])).default([])}).strict(),Ys=l.z.object({source:ks,sourcePriority:l.z.number().int().min(0).max(100).optional(),observedAt:l.z.string().datetime().optional(),snapshotVersion:l.z.number().int().min(0).optional()}).strict(),Js=Ys.extend({type:l.z.literal("snapshot"),agent:l.z.string().trim().min(1).max(80),appSessionId:l.z.string().trim().max(120).optional(),appId:l.z.string().trim().max(120).optional(),providerSessionId:l.z.string().trim().max(240).optional(),providerMeta:l.z.record(l.z.string(),l.z.unknown()).optional(),appBindingKeys:l.z.array(l.z.string().trim().min(1).max(240)).max(20).optional(),actions:rs.optional(),title:l.z.string().trim().max(240).optional(),cwd:l.z.string().trim().max(4096).optional(),activeTurnId:l.z.string().trim().max(240).optional(),userPrompt:l.z.string().trim().optional(),turns:l.z.array(Ns).max(50).optional(),status:Qt.optional(),phase:Zt.optional(),summary:l.z.string().trim().max(1e3).optional(),lastMessage:l.z.string().trim().optional(),lastMessageItemId:l.z.string().trim().max(240).optional(),currentTool:es.optional(),toolCallsSinceLastMessage:l.z.number().int().min(0).optional(),subAgents:l.z.array(ns).max(50).optional(),transcriptPath:l.z.string().trim().max(4096).optional(),transcriptSize:l.z.number().int().min(0).optional(),replaceActivity:l.z.boolean().optional()}).strict(),Xs=Ys.extend({type:l.z.literal("event"),sessionId:l.z.string().trim().min(1).max(120),kind:l.z.enum(["lifecycle","send-ack","turn-started","user-message","assistant-message","approval-requested","turn-completed","tool-activity","sub-agent-activity","context-compaction"]),activeTurnId:l.z.string().trim().max(240).optional(),providerTurnId:l.z.string().trim().max(240).optional(),userPrompt:l.z.string().trim().optional(),text:l.z.string().optional(),itemId:l.z.string().trim().max(240).optional(),status:Qt.optional(),phase:Zt.optional(),summary:l.z.string().trim().max(1e3).optional(),error:l.z.string().trim().max(4e3).optional(),currentTool:es.nullable().optional(),toolCallsSinceLastMessage:l.z.number().int().min(0).optional(),subAgents:l.z.array(ns).max(50).optional(),contextCompaction:zs.optional(),counters:l.z.object({toolCalls:l.z.number().int().min(0).optional(),edits:l.z.number().int().min(0).optional(),approvals:l.z.number().int().min(0).optional()}).strict().optional()}).strict().superRefine((e,t)=>{if("context-compaction"===e.kind?e.contextCompaction||t.addIssue({code:"custom",path:["contextCompaction"],message:"context-compaction events require contextCompaction"}):void 0!==e.contextCompaction&&t.addIssue({code:"custom",path:["contextCompaction"],message:"contextCompaction is only valid for context-compaction events"}),"sub-agent-activity"===e.kind?e.subAgents||t.addIssue({code:"custom",path:["subAgents"],message:"sub-agent-activity events require subAgents"}):void 0!==e.subAgents&&t.addIssue({code:"custom",path:["subAgents"],message:"subAgents is only valid for sub-agent-activity events"}),"tool-activity"!==e.kind)return void 0!==e.currentTool&&t.addIssue({code:"custom",path:["currentTool"],message:"currentTool is only valid for tool-activity events"}),void(void 0!==e.toolCallsSinceLastMessage&&t.addIssue({code:"custom",path:["toolCallsSinceLastMessage"],message:"toolCallsSinceLastMessage is only valid for tool-activity events"}));"currentTool"in e||t.addIssue({code:"custom",path:["currentTool"],message:"tool-activity events require currentTool"}),void 0===e.toolCallsSinceLastMessage&&t.addIssue({code:"custom",path:["toolCallsSinceLastMessage"],message:"tool-activity events require toolCallsSinceLastMessage"})});l.z.discriminatedUnion("type",[Js,Xs]);const Qs=new Set(["id","agent","appSessionId","appId","providerSessionId","providerMeta","appBindingKeys","actions","activeTurnId","title","cwd","userPrompt","turns","status","phase","summary","lastMessage","lastMessageItemId","currentTool","toolCallsSinceLastMessage","subAgents","transcriptPath","transcriptSize","startedAt","updatedAt","completedAt","error","counters","queue"]),Zs=new Set(["id","kind","name","inputPreview","startedAt"]),en=new Set(["threadId","path","status","activity","message","updatedAt"]),tn=new Set(["id","message","attachments","references","status","createdAt","updatedAt","error"]),sn=new Set(["id","kind","name","mime","size"]);function nn(e,t,s){const n=Object.keys(e).filter(e=>!t.has(e));n.length&&console.warn(`[ai-session] Ignoring unknown ${s} fields: ${n.join(", ")}`)}function rn(e){return{toolCalls:Math.max(0,Number(e?.toolCalls)||0),edits:Math.max(0,Number(e?.edits)||0),approvals:Math.max(0,Number(e?.approvals)||0)}}function on(e){const t=Number(e);return Number.isInteger(t)&&t>=0?t:0}function an(e){if(!Array.isArray(e))return[];const t=new Map;for(const s of e){if(!s||"object"!=typeof s||Array.isArray(s))continue;const e=s;nn(e,en,"subAgent");const n={..."string"==typeof e.threadId?{threadId:e.threadId}:{},..."string"==typeof e.path?{path:e.path}:{},..."string"==typeof e.status?{status:e.status}:{},..."string"==typeof e.activity?{activity:e.activity}:{},..."string"==typeof e.message?{message:e.message}:{},..."string"==typeof e.updatedAt?{updatedAt:e.updatedAt}:{}},i=ns.safeParse(n);if(!i.success)continue;const r=t.get(i.data.threadId);(!r||Date.parse(i.data.updatedAt)>=Date.parse(r.updatedAt))&&t.set(i.data.threadId,i.data)}return[...t.values()].sort((e,t)=>Date.parse(t.updatedAt)-Date.parse(e.updatedAt)||e.threadId.localeCompare(t.threadId)).slice(0,50)}function cn(e){const t=e.map(pn).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 cn(Array.isArray(t.items)?t.items:[])}function pn(e){if(!e||"object"!=typeof e||Array.isArray(e))return;const t=e;if(nn(t,tn,"queue item"),"string"!=typeof t.id||"string"!=typeof t.message||"string"!=typeof t.createdAt||"string"!=typeof t.updatedAt)return;const s={id:Et(t.id,120),message:kt(t.message),attachments:ln(t.attachments),references:un(t.references),status:"sending"===t.status||"failed"===t.status?t.status:"queued",createdAt:t.createdAt,updatedAt:t.updatedAt,..."string"==typeof t.error&&t.error?{error:Et(t.error,4e3)}:{}},n=xs.safeParse(s);return n.success?n.data:void 0}function un(e){return Array.isArray(e)?e.flatMap(e=>{const t=hs.safeParse(e);return t.success?[t.data]:[]}).slice(0,20):[]}function ln(e){return Array.isArray(e)?e.map(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return;const t=e;nn(t,sn,"queue attachment");const s={..."string"==typeof t.id?{id:t.id}:{},..."string"==typeof t.kind?{kind:t.kind}:{},..."string"==typeof t.name?{name:t.name}:{},..."string"==typeof t.mime?{mime:t.mime}:{},..."number"==typeof t.size?{size:t.size}:{}},n=as.safeParse(s);return n.success?n.data:void 0}).filter(e=>Boolean(e)).slice(0,6):[]}function mn(e=[]){return e.slice(0,6).map(e=>as.parse({id:e.id,kind:e.kind,name:e.name,mime:e.mime,size:e.size}))}function hn(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 gn(e){return["thinking","tool","editing","approval","responding","unknown"].includes(String(e))?e:"unknown"}function fn(e){return Array.isArray(e)?Lt(e).map(e=>{const t=Ns.safeParse(e);return t.success?t.data:void 0}).filter(e=>Boolean(e)):[]}function yn(e){if(!e||"object"!=typeof e||Array.isArray(e))return;const t=e;if("string"!=typeof t.id||"string"!=typeof t.agent||"string"!=typeof t.startedAt||"string"!=typeof t.updatedAt)return;nn(t,Qs,"session");const s=function(e){if(!Array.isArray(e))return;const t=[...new Set(e.map(e=>Et(e,240)).filter(Boolean))].slice(0,20);return t.length?t:void 0}(t.appBindingKeys),n=function(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}(t.actions),i=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return;const t=e;if(nn(t,Zs,"currentTool"),"string"!=typeof t.name||!t.name.trim())return;const s={..."string"==typeof t.id&&t.id.trim()?{id:Et(t.id,240)}:{},..."string"==typeof t.kind&&t.kind.trim()?{kind:Et(t.kind,80)}:{},name:Et(t.name,120),..."string"==typeof t.inputPreview&&t.inputPreview.trim()?{inputPreview:Et(t.inputPreview,500)}:{},..."string"==typeof t.startedAt&&es.shape.startedAt.safeParse(t.startedAt).success?{startedAt:t.startedAt}:{}},n=es.safeParse(s);return n.success?n.data:void 0}(t.currentTool),r="string"==typeof t.completedAt&&Rs.shape.completedAt.safeParse(t.completedAt).success?t.completedAt:void 0,o={id:Et(t.id,120),agent:Et(t.agent,80),..."string"==typeof t.appSessionId&&t.appSessionId?{appSessionId:Et(t.appSessionId,120)}:{},..."string"==typeof t.appId&&t.appId?{appId:Et(t.appId,120)}:{},..."string"==typeof t.providerSessionId&&t.providerSessionId?{providerSessionId:Et(t.providerSessionId,240)}:{},...t.providerMeta&&"object"==typeof t.providerMeta&&!Array.isArray(t.providerMeta)?{providerMeta:t.providerMeta}:{},...s?{appBindingKeys:s}:{},...n?{actions:n}:{},..."string"==typeof t.activeTurnId&&t.activeTurnId?{activeTurnId:Et(t.activeTurnId,240)}:{},..."string"==typeof t.title&&t.title?{title:Et(t.title,240)}:{},..."string"==typeof t.cwd&&t.cwd?{cwd:Et(t.cwd,4096)}:{},..."string"==typeof t.userPrompt&&t.userPrompt?{userPrompt:kt(t.userPrompt)}:{},turns:fn(t.turns),status:hn(t.status),phase:gn(t.phase),..."string"==typeof t.summary&&t.summary?{summary:Et(t.summary,1e3)}:{},..."string"==typeof t.lastMessage&&t.lastMessage?{lastMessage:kt(t.lastMessage)}:{},...i?{currentTool:i}:{},toolCallsSinceLastMessage:on(t.toolCallsSinceLastMessage),subAgents:an(t.subAgents),..."string"==typeof t.transcriptPath&&t.transcriptPath?{transcriptPath:Et(t.transcriptPath,4096)}:{},...Number.isInteger(t.transcriptSize)&&Number(t.transcriptSize)>=0?{transcriptSize:Number(t.transcriptSize)}:{},startedAt:t.startedAt,updatedAt:t.updatedAt,...r?{completedAt:r}:{},..."string"==typeof t.error&&t.error?{error:Et(t.error,4e3)}:{},counters:rn(t.counters),queue:dn(t.queue)},a=Rs.safeParse(o);return a.success?a.data:void 0}function vn(e){return[...e].sort((e,t)=>Date.parse(t.updatedAt)-Date.parse(e.updatedAt)||t.id.localeCompare(e.id))[0]}function Sn(e){return Boolean(e&&"."!==e&&".."!==e&&!e.includes("/")&&!e.includes("\\")&&!e.includes("\0"))}function wn(e){if(!Sn(e))throw new Error(`Invalid AI session id: ${JSON.stringify(e)}`)}function In(e){try{return JSON.parse(t.readFileSync(e,"utf8"))}catch{return}}class An{dir;index=new Wt;selectProviderCandidate;constructor(e){this.dir=s.resolve(e.dir),this.selectProviderCandidate=e.selectProviderCandidate||vn}sessionPath(e){return wn(e),s.join(this.dir,`${e}.json`)}get(e){if(!Sn(e))return;const t=yn(In(this.sessionPath(e)));if(t&&t.id===e)return t;this.index.remove(e)}list(){let e;this.ensureDirectory();try{e=t.readdirSync(this.dir).filter(e=>e.endsWith(".json"))}catch{return[]}const n=e.map(e=>({expectedId:e.slice(0,-5),session:yn(In(s.join(this.dir,e)))})).filter(({expectedId:e,session:t})=>t?.id===e).map(({session:e})=>e).filter(e=>Boolean(e)).sort((e,t)=>Date.parse(t.updatedAt)-Date.parse(e.updatedAt));return this.index.rebuild(n),n}save(e){return wn(e.id),this.ensureDirectory(),y.sync(this.sessionPath(e.id),`${JSON.stringify(e,null,2)}\n`,{encoding:"utf8"}),this.index.replace(e),e}update(e,t){const s=this.get(e);if(!s)return;const n=t(s);if(n.id!==e)throw new Error(`AI session update cannot change id from ${JSON.stringify(e)} to ${JSON.stringify(n.id)}`);return this.save(n)}remove(e){const s=this.sessionPath(e);let n=!1;try{t.rmSync(s),n=!0}catch(e){if("ENOENT"!==e.code)throw e}return this.index.remove(e),n}removeMany(e){let t=0;for(const s of new Set(e))t+=Number(this.remove(s));return t}findByProviderSession(e,t){const s=Gt(e,t);if(!s)return;const n=this.index.candidates(s.agent,s.providerSessionId).map(e=>this.get(e)).filter(e=>Boolean(e&&e.agent===s.agent&&e.providerSessionId===s.providerSessionId));if(n.length)return this.selectProviderCandidate(n);const i=this.list().filter(e=>e.agent===s.agent&&e.providerSessionId===s.providerSessionId);return i.length?this.selectProviderCandidate(i):void 0}ensureDirectory(){t.mkdirSync(this.dir,{recursive:!0})}}function bn(){return`aiq_${n.randomUUID().replace(/-/g,"").slice(0,20)}`}class _n{queuedAttachmentPayloads=new Map;now;generateQueueId;constructor(e={}){this.now=e.now||(()=>(new Date).toISOString()),this.generateQueueId=e.generateQueueId||bn}enqueueMessage(e,t,s=[],n=[]){const i=this.now(),r={id:this.generateQueueId(),message:kt(t),attachments:mn(s),references:n,status:"queued",createdAt:i,updatedAt:i},o=this.withQueue(e,[...this.queuedMessages(e).items,r],i);if(o.queue.items.some(e=>e.id===r.id))return s.length&&this.queuedAttachmentPayloads.set(r.id,s.slice(0,6)),{session:o,item:r}}queuedMessages(e){return 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:Et(n,4e3)})}retryQueuedMessage(e,t){return this.patchQueuedMessage(e,t,{status:"queued",error:void 0})}removeQueuedMessage(e,t){const s=this.queuedMessages(e).items.filter(e=>e.id!==t);return this.queuedAttachmentPayloads.delete(t),this.withQueue(e,s,this.now())}reorderQueuedMessages(e,t){const s=this.queuedMessages(e).items,n=new Map(s.map(e=>[e.id,e])),i=t.map(e=>n.get(e)).filter(e=>Boolean(e)),r=new Set(t),o=s.filter(e=>!r.has(e.id));return this.withQueue(e,[...i,...o],this.now())}patchQueuedMessage(e,t,s){const n=this.now();let i=!1;const r=this.queuedMessages(e).items.map(e=>e.id!==t?e:(i=!0,{...e,...s,updatedAt:n}));return i?this.withQueue(e,r,n):void 0}withQueue(e,t,s){return{...e,updatedAt:s,queue:cn(t)}}}function Tn(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 On(e,t){const s=Nn(e),n=Nn(t);return s!==n?s>n?e:t:Date.parse(e.updatedAt)>=Date.parse(t.updatedAt)?e:t}function xn(e){const t=new Map;for(const s of e){const e=Tn(s),n=t.get(e);t.set(e,n?On(n,s):s)}return[...t.values()].sort(Pn)}function En(e){return new Set(e.filter(e=>"string"!=typeof e.status||"running"===e.status).map(e=>"string"==typeof e.id?e.id.trim():"").filter(Boolean))}class kn{orphanedAppSessionAt=new Map;canonicalSessions(e){return xn(e)}visibility(e){const t=e.filter(e=>this.orphanedAppSessionAt.has(e.id)).map(e=>e.id),s=new Set(t);return{visibleSessionIds:xn(e.filter(e=>!s.has(e.id))).map(e=>e.id),hiddenSessionIds:t}}reconcileAppSessionBindings(e){const t=En(e.appSessions||[]),s=[],n=[],i=[];for(const r of e.sessions){if(!r.appSessionId||t.has(r.appSessionId)){this.recordOrphanClear(r.id,i);continue}let o=this.orphanedAppSessionAt.get(r.id);void 0===o&&(o=e.now,this.orphanedAppSessionAt.set(r.id,o),i.push({kind:"marked",sessionId:r.id,orphanedAt:o})),n.push(r.id),e.now-o>=e.orphanRetentionMs&&(s.push(r.id),this.recordOrphanClear(r.id,i))}const r=new Set([...n,...s]);return{visibleSessionIds:xn(e.sessions.filter(e=>!r.has(e.id))).map(e=>e.id),hiddenSessionIds:n,removeSessionIds:s,orphanStateChanges:i}}reconcileAdapterSessions(e){const t=e.appSessionIds||zn,s=e.providerSessionIds||zn,n=e.providerShorts||zn,i=[],r=[];for(const o of e.sessions){if(o.agent!==e.agent)continue;if(!o.appSessionId&&!o.providerSessionId&&!o.providerMeta?.short)continue;const a="string"==typeof o.providerMeta?.short?o.providerMeta.short:"";Boolean(o.appSessionId&&t.has(o.appSessionId)||o.providerSessionId&&s.has(o.providerSessionId)||a&&n.has(a))||i.push(o.id),this.recordOrphanClear(o.id,r)}const o=new Set(i),a=e.sessions.filter(e=>!o.has(e.id));return{...this.visibility(a),removeSessionIds:i,orphanStateChanges:r}}prune(e){const t=xn(e.sessions).map(e=>e.id),s=new Set(t),n=e.sessions.filter(e=>!s.has(e.id)).map(e=>e.id),i=new Set(n),r=e.now-e.retentionMs,o=e.sessions.filter(e=>!i.has(e.id)).filter(e=>["idle","failed"].includes(e.status)&&Date.parse(e.updatedAt)<r).map(e=>e.id);return{canonicalSessionIds:t,duplicateSessionIds:n,expiredSessionIds:o,removeSessionIds:[...n,...o]}}clearOrphan(e){this.orphanedAppSessionAt.delete(e)}forgetSession(e){this.orphanedAppSessionAt.delete(e)}recordOrphanClear(e,t){this.orphanedAppSessionAt.delete(e)&&t.push({kind:"cleared",sessionId:e})}}const zn=new Set;function Nn(e){return Number(Boolean(e.userPrompt))+Number(Boolean(e.summary))+Number(Boolean(e.lastMessage))+(e.turns?.length||0)}function Pn(e,t){return Date.parse(t.updatedAt)-Date.parse(e.updatedAt)}function Rn(e,t,s={}){const n=rn(t.counters),i={toolCalls:e.counters.toolCalls+n.toolCalls,edits:e.counters.edits+n.edits,approvals:e.counters.approvals+n.approvals},r=s.preserveUpdatedAt?e.updatedAt:s.updatedAt??e.updatedAt,o=s.suppressPromptTurn?{...t,userPrompt:void 0}:t,a=s.suppressTurnUpdate?Lt(s.replaceTurns?void 0:e.turns):Kt(s.replaceTurns?void 0:e.turns,o,r,s.meta),c=t.userPrompt?kt(t.userPrompt):"",d=a.at(-1),p=function(e){return[...e||[]].reverse().find(e=>e.userPrompt?.trim())?.userPrompt}(a),u=Boolean(c&&!t.lastMessage&&d?.userPrompt===c&&!d.summary&&!d.lastMessage);return{...e,...t,id:e.id,agent:e.agent,startedAt:e.startedAt,updatedAt:r,status:t.status?hn(t.status):e.status,phase:t.phase?gn(t.phase):e.phase,summary:s.replaceActivity?t.summary?Et(t.summary,1e3):void 0:s.clearResponse?void 0:t.summary?Et(t.summary,1e3):u?void 0:e.summary,lastMessage:s.replaceActivity?t.lastMessage?kt(t.lastMessage):void 0:s.clearResponse?void 0:t.lastMessage?kt(t.lastMessage):u?void 0:e.lastMessage,userPrompt:p||(s.replaceActivity?t.userPrompt?kt(t.userPrompt):void 0:t.userPrompt?kt(t.userPrompt):e.userPrompt),turns:a,error:t.error?Et(t.error,4e3):e.error,counters:i,queue:t.queue?dn(t.queue):e.queue,subAgents:void 0!==t.subAgents?an(t.subAgents):e.subAgents}}function Cn(e,t,s){const n=t.activeTurnId?Et(t.activeTurnId,240):void 0;if("transcript-tail"!==t.source||!n||!e.activeTurnId||n===e.activeTurnId)return n||e.activeTurnId;const i=Lt(e.turns).find(t=>t.id===e.activeTurnId);if(!i||Ut(i))return n;const r=s?kt(s):"";return r&&i.userPrompt&&i.userPrompt!==r?n:e.activeTurnId}function Dn(e){const t=Kn(e);return/^\[(?:request interrupted by user|user interrupted request)\]$/i.test(t)}function Mn(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}function Fn(e){if(e.timestamp)return e;const{timestamp:t,...s}=e;return s}function jn(e){return Array.isArray(e)?e:[]}function Ln(e){return"tool_use"===e.type}function $n(e){return"tool_result"===e.type}function Hn(e){return"text"===e.type}function Un(e){return"text"!==e.type&&"output_text"!==e.type&&"input_text"!==e.type||"string"!=typeof e.text?"":e.text}function qn(e){if("string"==typeof e)return Kn(e);const t=jn(e).map(Un).filter(Boolean).join("\n");return t?Kn(t):""}function Bn(e,t=180){const s=String(e??"").replace(/\s+/g," ").trim();return s.length>t?`${s.slice(0,t-3)}...`:s}function Kn(e){return String(e??"").trim()}function Vn(e){try{const t=Mn(JSON.parse(String(e||"{}")));return Bn(t.cmd||t.command||t.path||t.ref_id||t.pattern||"")}catch{return""}}function Gn(e){if(e&&"object"==typeof e&&!Array.isArray(e)){const t=e;return Bn(t.command||t.cmd||t.file_path||t.filePath||t.path||t.ref_id||t.pattern||t.description||"")}return Vn(e)}function Wn(e){return/\btask-handoff(\.js)?\b/.test(e)}function Yn(e){return["edit","multiedit","write","notebookedit"].includes(e.toLowerCase())}function Jn(e,n,i=s.join(r.homedir(),".claude")){const o=Bn(e,200);if(!o)return;const a=s.join(i,"projects"),c=Bn(n);if(c){const e=s.join(a,function(e){return s.resolve(e).split(s.sep).join("-")}(c),`${o}.jsonl`);if(t.existsSync(e))return e}const d=[a];for(;d.length>0;){const e=d.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())d.push(n);else if(t.isFile()&&t.name.endsWith(".jsonl")&&t.name.includes(o))return n}}}function Xn(e,t){let n;try{n=JSON.parse(e)}catch{return}const i=Mn(n),r=Mn(i.payload),o="string"==typeof Mn(n).timestamp?Mn(n).timestamp:void 0;if("turn_context"===i.type)return;if("event_msg"===i.type)return"agent_message"===r.type?Fn({text:Kn(r.message),kind:"assistant",timestamp:o}):void 0;if("assistant"===i.type){const e=jn(i.message?.content);let s,n;for(const i of e){if(Ln(i)){const e=Bn(i.name||"tool",80),n=Gn(i.input),r=Wn(n),a=Yn(e)?"edit":void 0;if(i.id&&t.calls.set(i.id,{tool:e,command:n,ignored:r,action:a}),r)continue;s??=Fn({key:i.id,text:"edit"===a?`Editing ${n||"files"}`:n?`Running ${e}: ${n}`:`Running ${e}`,kind:"tool",timestamp:o});continue}Hn(i)&&i.text&&(n??=Kn(i.text))}return s||(n?Fn({text:n,kind:"assistant",timestamp:o}):void 0)}if("user"===i.type){const e=qn(i.message?.content);if(e&&!Dn(e))return Fn({text:e,kind:"user",timestamp:o});const s=jn(i.message?.content);for(const e of s){if(!$n(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 Fn({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"!==i.type)return;const a=i.payload;if(a){if("custom_tool_call"===a.type){const e=Bn(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"}),Fn({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=Bn(a.output,120),n=/failed|error/i.test(s);return Fn({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=Bn(a.name||"tool",80),s=Vn(a.arguments),n="write_stdin"===e||Wn(s);if(a.call_id&&t.calls.set(a.call_id,{tool:e,command:s,ignored:n}),n)return;return Fn({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 Fn({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=qn(a.content);if(!e)return;return Fn({text:Kn(e),kind:"user"===a.role?"user":"assistant",timestamp:o})}}}function Qn(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"}function Zn(e){try{return JSON.parse(t.readFileSync(e,"utf8"))}catch{return}}function ei(e,n,i){if(n)return"claude"===e?Jn(n,i):function(e,n=s.join(r.homedir(),".codex")){const i=Bn(e,200);if(!i)return;const o=[s.join(n,"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}}}(n)}class ti{idleAfterMs;staleAfterMs;maxBackfillBytes;now;constructor(e){this.idleAfterMs=e.idleAfterMs,this.staleAfterMs=e.staleAfterMs,this.maxBackfillBytes=e.maxBackfillBytes??524288,this.now=e.now??Date.now}readTail(e,s=t.statSync(e)){const n=Math.max(0,s.size-this.maxBackfillBytes),i=t.openSync(e,"r");try{const e=Buffer.alloc(s.size-n);return t.readSync(i,e,0,e.length,n),e.toString("utf8")}finally{t.closeSync(i)}}backfill(e,s=t.statSync(e)){const n={calls:new Map},i={},r=new Map;for(const t of this.readTail(e,s).split(/\r?\n/)){const e=Xn(t,n);if(!e?.text)continue;const o=e.timestamp||s.mtime.toISOString();if("user"===e.kind){const t=kt(e.text);i.userPrompt=t;const s=e.key||e.timestamp;if(s)n.activeTurnId=Ft(t,s);else{const e=(r.get(t)||0)+1;r.set(t,e),n.activeTurnId=Ft(t,void 0,e)}i.turns=Kt(i.turns,{activeTurnId:n.activeTurnId,userPrompt:t},o);continue}i.summary=Et(e.text,1e3),i.lastMessage=kt(e.text),i.turns=Kt(i.turns,{activeTurnId:n.activeTurnId,summary:i.summary,lastMessage:i.lastMessage},o)}return i}ingestLine(e,t,s,n){const i=Xn(s,n);if(!i?.text)return e.get(t);const r=i.timestamp||new Date(this.now()).toISOString();if("user"===i.kind){const s=kt(i.text),o=i.key||i.timestamp;if(o)n.activeTurnId=Ft(s,o);else{n.promptCounts||=new Map;const e=(n.promptCounts.get(s)||0)+1;n.promptCounts.set(s,e),n.activeTurnId=Ft(s,void 0,e)}return e.applyRealtimeEvent(t,{kind:"user-message",activeTurnId:n.activeTurnId,providerTurnId:n.activeTurnId,userPrompt:s,observedAt:r,source:"transcript-tail"})}if("assistant"===i.kind)return e.applyRealtimeEvent(t,{kind:"assistant-message",activeTurnId:n.activeTurnId,providerTurnId:n.activeTurnId,text:i.text,observedAt:r,source:"transcript-tail"});const o=function(e,t){const s=Et(e,1e3);return"user"===t?{userPrompt:kt(e)}:"assistant"===t?{status:"running",phase:"responding",summary:s}:/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}:{}}(i.text,i.kind);return e.applyRealtimeEvent(t,{kind:"waiting"===o.status?"approval-requested":"assistant-message",activeTurnId:n.activeTurnId,providerTurnId:n.activeTurnId,text:o.summary||i.text,status:o.status,phase:o.phase,counters:o.counters,observedAt:r,source:"transcript-tail"})}createFromTranscript(e,s,n,i={}){const r=t.statSync(n),o=r.mtime.toISOString(),a=this.backfill(n,r),c=e.findTranscriptSession({transcriptPath:n,providerSessionId:i.providerSessionId});if(c){const t=!c.appSessionId,u=Number.isInteger(c.transcriptSize)&&r.size>Number(c.transcriptSize),l=t&&u?new Date(this.now()).toISOString():t&&!u?c.updatedAt:(d=c.updatedAt,p=o,Date.parse(d)>=Date.parse(p)?d:p);return e.applyAdapterSnapshot({source:"transcript-scan",agent:s,transcriptPath:n,transcriptSize:r.size,providerSessionId:i.providerSessionId||c.providerSessionId,cwd:i.cwd||c.cwd,userPrompt:c.userPrompt||a.userPrompt,turns:a.turns?.length?a.turns:c.turns,summary:a.summary||c.summary,lastMessage:a.lastMessage||c.lastMessage,status:t&&u?"running":c.status,phase:t&&u&&"unknown"===c.phase?"responding":c.phase,observedAt:l,replaceActivity:Boolean(a.turns?.length)})||c}var d,p;const u=e.start({agent:s,providerSessionId:i.providerSessionId,cwd:i.cwd,userPrompt:a.userPrompt,turns:a.turns,status:this.lifecycleForMtime(r.mtimeMs),phase:"unknown",summary:a.summary||`${s} transcript detected`},{meta:Pt({source:"transcript-scan",observedAt:o}),timestamp:o,suppressPromptTurn:!a.turns?.length});return e.applyAdapterSnapshot({source:"transcript-scan",agent:u.agent,providerSessionId:u.providerSessionId,cwd:u.cwd,userPrompt:u.userPrompt,turns:u.turns,summary:u.summary,lastMessage:a.lastMessage,transcriptPath:n,transcriptSize:r.size,status:u.status,phase:u.phase,observedAt:o})||u}lifecycleForMtime(e){const t=this.now()-e;return t>this.staleAfterMs||t>this.idleAfterMs?"idle":"running"}}function si(){return(new Date).toISOString()}function ni(e){return{id:e.id,agent:e.agent,appSessionId:e.appSessionId,appId:e.appId,providerSessionId:e.providerSessionId,providerMeta:e.providerMeta,appBindingKeys:e.appBindingKeys,actions:ii(e),activeTurnId:e.activeTurnId,title:e.title,cwd:e.cwd,userPrompt:e.userPrompt,turns:e.turns,status:e.status,phase:e.phase,summary:e.summary,lastMessage:e.lastMessage,lastMessageItemId:e.lastMessageItemId,currentTool:e.currentTool,toolCallsSinceLastMessage:e.toolCallsSinceLastMessage,subAgents:e.subAgents,queue:e.queue,startedAt:e.startedAt,updatedAt:e.updatedAt,error:e.error}}function ii(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)}}class ri{dir;retentionMs;idleAfterMs;staleAfterMs;orphanedAppSessionRetentionMs;reconciliation=new kn;queueService=new _n;transcriptService;store;changes=new v.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(pe().dataDir,"ai-sessions")}(),this.store=new An({dir:this.dir,selectProviderCandidate:e=>e.reduce((e,t)=>On(e,t))}),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),this.transcriptService=new ti({idleAfterMs:this.idleAfterMs,staleAfterMs:this.staleAfterMs})}sessionPath(e){return this.store.sessionPath(e)}onChange(e){return this.changes.on("change",e),()=>{this.changes.off("change",e)}}start(e,t={}){const s=t.timestamp||si(),i=t.meta||Pt({source:"control",observedAt:s}),r={id:`ais_${n.randomUUID().replace(/-/g,"").slice(0,20)}`,agent:Et(e.agent||"unknown",80),appSessionId:e.appSessionId?Et(e.appSessionId,120):void 0,appId:e.appId?Et(e.appId,120):void 0,providerSessionId:e.providerSessionId?Et(e.providerSessionId,240):void 0,providerMeta:void 0,activeTurnId:void 0,title:e.title?Et(e.title,240):void 0,cwd:e.cwd?Et(e.cwd,4096):void 0,userPrompt:e.userPrompt?kt(e.userPrompt):void 0,turns:Kt(void 0,{userPrompt:t.suppressPromptTurn?void 0:e.userPrompt,turns:e.turns},s,i),status:hn(e.status||"idle"),phase:gn(e.phase||"unknown"),summary:e.summary?Et(e.summary,1e3):void 0,toolCallsSinceLastMessage:0,subAgents:[],startedAt:s,updatedAt:s,counters:{toolCalls:0,edits:0,approvals:0},queue:{pendingCount:0,items:[]}};return this.put(r),r}get(e){return this.store.get(e)}restoreHistory(e){const t=this.get(e.id),s={id:e.id,agent:e.agent,appId:e.agent,providerSessionId:e.providerSessionId,title:e.title,cwd:e.cwd,userPrompt:e.userPrompt,turns:t?.turns||[],status:"idle",phase:"unknown",lastMessage:e.lastMessage,toolCallsSinceLastMessage:0,subAgents:[],startedAt:t?.startedAt||e.lastActiveAt,updatedAt:e.lastActiveAt,counters:t?.counters||{toolCalls:0,edits:0,approvals:0},queue:t?.queue||{pendingCount:0,items:[]}};return this.put(s)}discard(e){return this.removeStoredSession(e)}put(e){return this.store.save(e),this.emitChange("write"),e}removeStoredSession(e){const t=this.store.remove(e);return this.reconciliation.forgetSession(e),t&&this.emitChange("delete"),t}getByProviderSessionId(e,t){return this.store.findByProviderSession(Et(e,80),Et(t,240))}findTranscriptSession(e){return this.readSessions().find(t=>t.transcriptPath===e.transcriptPath||Boolean(e.providerSessionId&&t.providerSessionId===e.providerSessionId))}update(e,t,s={}){const n=this.get(e);if(n)return this.put(Rn(n,t,{...s,updatedAt:s.preserveUpdatedAt?n.updatedAt:s.updatedAt||si()}))}enqueueMessage(e,t,s=[],n=[]){const i=this.get(e);if(!i)return;const r=this.queueService.enqueueMessage(i,t,s,n);return r?{...r,session:this.put(r.session)}:void 0}queuedMessages(e){return this.queueService.queuedMessages(this.get(e))}nextQueuedMessage(e){return this.queueService.nextQueuedMessage(this.get(e))}queuedMessageAttachments(e){return this.queueService.queuedMessageAttachments(e)}markQueuedMessageSending(e,t){const s=this.get(e),n=s?this.queueService.markQueuedMessageSending(s,t):void 0;return n?this.put(n):void 0}markQueuedMessageFailed(e,t,s){const n=this.get(e),i=n?this.queueService.markQueuedMessageFailed(n,t,s):void 0;return i?this.put(i):void 0}retryQueuedMessage(e,t){const s=this.get(e),n=s?this.queueService.retryQueuedMessage(s,t):void 0;return n?this.put(n):void 0}removeQueuedMessage(e,t){const s=this.get(e);return s?this.put(this.queueService.removeQueuedMessage(s,t)):void 0}reorderQueuedMessages(e,t){const s=this.get(e);return s?this.put(this.queueService.reorderQueuedMessages(s,t)):void 0}bindProviderSession(e,t){const s=this.get(e),n=s?ei(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||si(),s={...e,observedAt:t,sourcePriority:Nt(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=this.get(e.sessionId);if(!t)return;const s=function(e,t){const s=t.observedAt??e.updatedAt,n=Pt(t);if("send-ack"===t.kind){const i=kt(t.userPrompt);return Rn(e,{activeTurnId:t.activeTurnId||Mt(i,s),status:t.status||"running",phase:t.phase||"thinking",userPrompt:i},{updatedAt:s,meta:n})}if("lifecycle"===t.kind){const i=t.status||e.status;return"idle"!==i&&"failed"!==i||!qt(e)?Rn(e,{activeTurnId:("running"===i||"waiting"===i)&&t.activeTurnId||e.activeTurnId,status:i,phase:t.phase||e.phase,currentTool:"idle"===i||"failed"===i?void 0:e.currentTool},{updatedAt:s,meta:n}):e}if("turn-started"===t.kind)return Rn(e,{activeTurnId:t.activeTurnId||e.activeTurnId,status:t.status||"running",phase:t.phase||"thinking"},{updatedAt:s,meta:n});if("user-message"===t.kind)return Rn(e,{activeTurnId:Cn(e,t,t.userPrompt),status:t.status||"running",phase:t.phase||"thinking",userPrompt:t.userPrompt},{updatedAt:s,meta:n});if("assistant-message"===t.kind){const i="transcript-tail"===t.source;return Rn(e,{activeTurnId:Cn(e,t),status:t.status||(i?"idle":"running"),phase:t.phase||(i?"unknown":"responding"),summary:t.text,lastMessage:t.text,lastMessageItemId:t.itemId,currentTool:void 0,toolCallsSinceLastMessage:0},{updatedAt:s,meta:n})}if("approval-requested"===t.kind)return Rn(e,{activeTurnId:t.activeTurnId||e.activeTurnId,status:t.status||"waiting",phase:t.phase||"approval",summary:t.summary||t.text,actions:{...e.actions,approval:!0},counters:t.counters||{approvals:1}},{updatedAt:s,meta:n});if("tool-activity"===t.kind)return Rn(e,{currentTool:t.currentTool||void 0,toolCallsSinceLastMessage:t.toolCallsSinceLastMessage},{updatedAt:s,meta:n,suppressTurnUpdate:!0});if("sub-agent-activity"===t.kind)return Rn(e,{subAgents:t.subAgents},{updatedAt:s,meta:n,suppressTurnUpdate:!0});if("context-compaction"===t.kind&&t.contextCompaction){const i=t.activeTurnId||e.activeTurnId;if(!i)return e;const r=Lt(e.turns).find(e=>e.id===i),o=r?.contextCompactions?.find(e=>e.id===t.contextCompaction?.id);return"completed"===o?.status||o?.status===t.contextCompaction.status&&o.startedAt===t.contextCompaction.startedAt&&o.completedAt===t.contextCompaction.completedAt?e:Rn(e,{turns:[{...r,id:i,providerTurnId:t.providerTurnId||r?.providerTurnId||i,source:t.source,status:r?.status||"running",phase:r?.phase||"thinking",contextCompactions:[t.contextCompaction],revision:(r?.revision||0)+1,updatedAt:s}]},{updatedAt:s,meta:n,suppressPromptTurn:!0})}if("turn-completed"===t.kind){const i=t.error?Et(t.error,4e3):void 0,r=t.text||t.summary||("failed"===t.status?i:void 0);return Rn(e,{activeTurnId:t.activeTurnId&&t.activeTurnId!==e.activeTurnId?e.activeTurnId:void 0,status:t.status||"idle",phase:t.phase||"unknown",summary:r,lastMessage:r,error:i,currentTool:void 0},{updatedAt:s,meta:n,clearResponse:!r})}}(t,e);return s===t?t:s?this.put(s):void 0}applyAdapterSnapshot(e){return this.apply({type:"snapshot",source:e.source||"control",...e})}reduceSnapshotInput(e){const t=Pt(e);let s=e.providerSessionId?this.getByProviderSessionId(e.agent,e.providerSessionId):void 0;if(s||(s=this.readSessions().find(t=>e.appSessionId&&t.appSessionId===e.appSessionId||e.transcriptPath&&t.transcriptPath===e.transcriptPath)),!s){const s=this.start({agent:e.agent,appSessionId:e.appSessionId,appId:e.appId,providerSessionId:e.providerSessionId,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,activeTurnId:e.activeTurnId,lastMessage:e.lastMessage,lastMessageItemId:e.lastMessageItemId,currentTool:"running"===e.status||"waiting"===e.status?e.currentTool:void 0,toolCallsSinceLastMessage:e.toolCallsSinceLastMessage??0,subAgents:e.subAgents||[],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.reconciliation.clearOrphan(s.id),this.put(function(e,t){const s=Pt(t),n=Lt(t.turns,s),i=function(e,t){if(!qt(e))return!1;const s=Lt(e.turns).find(t=>t.id===e.activeTurnId);return!Lt(t).some(t=>t.id===e.activeTurnId||Boolean(s?.userPrompt&&t.userPrompt===s.userPrompt&&Ut(t)&&!Ut(s)))}(e,n),r=Boolean(e.activeTurnId&&n.some(t=>t.id===e.activeTurnId)),o=e.activeTurnId?n.find(t=>t.id===e.activeTurnId):void 0,a=Boolean(t.replaceActivity&&e.activeTurnId&&r&&!Ut(o)),c=function(e){return"app-session"===e.source||"adapter-snapshot"===e.source&&"codex"===e.agent&&"codex-app-server"===e.appId}(t);return Rn(e,{appSessionId:c?t.appSessionId:t.appSessionId||e.appSessionId,appId:t.appId||e.appId,providerSessionId:t.providerSessionId||e.providerSessionId,providerMeta:t.providerMeta||e.providerMeta,appBindingKeys:c?t.appBindingKeys:t.appBindingKeys||e.appBindingKeys,actions:t.actions||e.actions,activeTurnId:Bt(e,t,i),title:t.title||e.title,cwd:t.cwd||e.cwd,userPrompt:i?e.userPrompt:t.userPrompt||e.userPrompt,turns:i?e.turns:t.turns,lastMessage:i?e.lastMessage:a?void 0:t.lastMessage||e.lastMessage,transcriptPath:t.transcriptPath||e.transcriptPath,transcriptSize:t.transcriptSize??e.transcriptSize,status:i?e.status:t.status||e.status,phase:i?e.phase:t.phase||e.phase,summary:i?e.summary:a?void 0:t.replaceActivity?t.summary:t.summary||e.summary,lastMessageItemId:i?e.lastMessageItemId:a?void 0:t.lastMessageItemId||e.lastMessageItemId,currentTool:"idle"===t.status||"failed"===t.status?void 0:i?e.currentTool:t.replaceActivity?t.currentTool:t.currentTool||e.currentTool,toolCallsSinceLastMessage:i?e.toolCallsSinceLastMessage:t.toolCallsSinceLastMessage??(t.replaceActivity?0:e.toolCallsSinceLastMessage),subAgents:i?e.subAgents:void 0!==t.subAgents?t.subAgents:e.subAgents},{updatedAt:t.observedAt??e.updatedAt,meta:s,replaceActivity:Boolean(t.replaceActivity),suppressPromptTurn:!n.length,suppressTurnUpdate:!n.length,replaceTurns:Boolean(t.replaceActivity&&!i&&0===n.length&&!t.userPrompt&&!t.summary&&!t.lastMessage)})}(s,e))}attachTranscript(e,t){if(!t){const s=this.get(e);t=s?ei(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=function(e,t){const s=Et(e,1e3);return"user"===t?{userPrompt:kt(e)}:"assistant"===t?{status:"running",phase:"responding",summary:s,lastMessage:kt(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:kt(e)}:{}}(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?kt(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"})}list(){const e=this.readSessions(),t=new Map(e.map(e=>[e.id,e]));return this.reconciliation.visibility(e).visibleSessionIds.map(e=>t.get(e)).filter(e=>Boolean(e))}all(){return this.readSessions()}readSessions(){const e=Date.now();return this.store.list().map(t=>this.withDerivedLifecycle(t,e)).sort((e,t)=>Date.parse(t.updatedAt)-Date.parse(e.updatedAt))}reconcileAppSessionBindings(e=[],t=Date.now()){const s=this.reconciliation.reconcileAppSessionBindings({sessions:this.readSessions(),appSessions:e,now:t,orphanRetentionMs:this.orphanedAppSessionRetentionMs});let n=0;for(const e of s.removeSessionIds)n+=Number(this.removeStoredSession(e));return{hidden:s.hiddenSessionIds.length,deleted:n}}reconcileAdapterSessions(e){const t=this.reconciliation.reconcileAdapterSessions({sessions:this.readSessions(),...e});let s=0;for(const e of t.removeSessionIds)s+=Number(this.removeStoredSession(e));return{deleted:s}}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(ni),updatedAt:si()}}prune(){const e=this.reconciliation.prune({sessions:this.readSessions(),now:Date.now(),retentionMs:this.retentionMs});for(const t of e.removeSessionIds)this.removeStoredSession(t)}ingestTranscriptLine(e,t,s){return this.transcriptService.ingestLine(this,e,t,s)}createFromTranscript(e,t,s={}){return this.transcriptService.createFromTranscript(this,e,t,s)}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,lastMessageItemId:e.lastMessageItemId,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||s>this.idleAfterMs&&"running"===e.status?{...e,status:"idle"}:e}}function oi(e={}){return new ri(e)}function ai(e=oi(),n=[],i){return function(e,n=[],i=process.env.CLAUDE_HOME||s.join(r.homedir(),".claude")){const o=function(e){const n=function(e=process.env.CLAUDE_HOME||s.join(r.homedir(),".claude")){return s.join(e,"sessions")}(e);let i=[];try{i=t.readdirSync(n,{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=Zn(s.join(n,e.name)),i=Number(t?.pid||s.basename(e.name,".json"));t?.sessionId&&Number.isInteger(i)&&i>0&&o.set(i,t)}return o}(i);for(const t of n){const s=Et(t.appId,120),n=Et(t.id,120),r=Et(t.status,80).toLowerCase(),a=Number(t.process?.pid);if("claude"!==s||!n||r&&"running"!==r||!Number.isInteger(a)||a<=0)continue;const c=o.get(a),d=Et(c?.sessionId,240);if(!d)continue;const p=Et(c?.cwd||t.tty?.cwd||t.launch?.cwd,4096);e.applyAdapterSnapshot({agent:"claude",appId:s,appSessionId:n,providerSessionId:d,title:Et(t.title,240)||"Claude",cwd:p,transcriptPath:Jn(d,p,i),status:Qn(c?.status)})}return e.snapshot()}(e,n,i)}class ci{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 di{id="claude-app-session-binding";refresh(e){ai(e.registry,e.appSessions)}}class pi{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 i;try{i=t.statSync(n.transcriptPath)}catch{continue}const r=s.get(n.id)||{offset:Math.max(0,i.size-65536),partial:"",calls:new Map,promptCounts:new Map};if(i.size<r.offset&&(r.offset=0,r.partial="",r.calls.clear(),r.promptCounts?.clear(),r.activeTurnId=void 0),i.size===r.offset){s.set(n.id,r);continue}const o=t.readFileSync(n.transcriptPath).subarray(r.offset).toString("utf8");r.offset=i.size,r.partial+=o;const a=r.partial.split(/\r?\n/);r.partial=a.pop()||"";for(const t of a)e.ingestTranscriptLine(n.id,t,r);s.set(n.id,r)}}(e.registry,this.tailState)}}function ui(e){return"codex"===e||"claude"===e}function li(e){const t=(e.turns||[]).slice(-50).map(e=>Ps.parse({id:e.id,providerTurnId:e.providerTurnId,userPrompt:e.userPrompt,status:e.status,phase:e.phase,summary:e.summary,lastMessage:e.lastMessage,contextCompactions:e.contextCompactions,startedAt:e.startedAt,updatedAt:e.updatedAt,completedAt:e.completedAt}));return t.length||!e.userPrompt&&!e.lastMessage?t:[Ps.parse({id:e.activeTurnId||`history:${e.id}`,userPrompt:e.userPrompt,status:"failed"===e.status?"failed":"waiting"===e.status?"waiting":"completed",phase:e.phase,summary:e.summary,lastMessage:e.lastMessage,startedAt:e.startedAt,updatedAt:e.updatedAt,completedAt:e.completedAt||e.updatedAt})]}function mi(e,t=(new Date).toISOString()){if(ui(e.agent)&&e.providerSessionId&&e.cwd&&e.appSessionId)return Ds.parse({id:e.id,agent:e.agent,providerSessionId:e.providerSessionId,title:e.title,userPrompt:e.userPrompt,lastMessage:e.lastMessage,cwd:e.cwd,lastActiveAt:e.updatedAt,archivedAt:t})}class hi{store;constructor(e){this.store=e}reconcile(e,t,s=(new Date).toISOString()){const n=En(t);let i=0,r=0;for(const t of e){if(!ui(t.agent)||!t.providerSessionId||!t.appSessionId)continue;if(n.has(t.appSessionId)){r+=Number(this.store.remove(t.id)),r+=Number(this.store.removeIdentity(t.agent,t.providerSessionId));continue}const e=this.store.get(t.id)||this.store.list().find(e=>e.agent===t.agent&&e.providerSessionId===t.providerSessionId),o=mi(t,e?.archivedAt||s);o&&(this.store.upsert(o,li(t)),i+=Number(!e))}return{archived:i,activated:r,items:this.store.list()}}}const gi=new Set(["schemaVersion","items"]),fi=new Set(["id","agent","providerSessionId","title","userPrompt","lastMessage","cwd","lastActiveAt","archivedAt"]),yi=new Set(["id","providerTurnId","userPrompt","status","phase","summary","lastMessage","contextCompactions","startedAt","updatedAt","completedAt"]);function vi(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:void 0}function Si(e,t){return Object.fromEntries([...t].filter(t=>Object.prototype.hasOwnProperty.call(e,t)).map(t=>[t,e[t]]))}function wi(e){return`${e.agent}:${e.providerSessionId}`}function Ii(e){const t=[...e].sort((e,t)=>Date.parse(t.lastActiveAt)-Date.parse(e.lastActiveAt)||Date.parse(t.archivedAt)-Date.parse(e.archivedAt)||e.id.localeCompare(t.id)),s=new Set,n=new Set,i=[];for(const e of t){const t=wi(e);if(!s.has(e.id)&&!n.has(t)&&(s.add(e.id),n.add(t),i.push(e),50===i.length))break}return i}class Ai{filePath;onWarning;constructor(e,t={}){this.filePath=s.join(e.dataDir,"ai-session-history","index.json"),this.onWarning=t.onWarning}path(){return this.filePath}list(){const e=this.load();return e.rewrite&&this.saveIndex(e.index),e.index.items}get(e){return this.list().find(t=>t.id===e)}detail(e){const s=this.get(e);if(!s)return;let n;try{n=JSON.parse(t.readFileSync(this.detailPath(e),"utf8"))}catch(t){const n=t&&"object"==typeof t&&"code"in t&&"ENOENT"===t.code;return this.onWarning?.({kind:"detail",id:e,reason:(n?"missing":"unreadable")+" detail replaced with empty turns"}),js.parse({item:s,turns:[]})}const i=this.sanitizeDetail(s,n);return i.rewrite&&this.saveDetail(i.detail),i.detail}upsert(e,t){const s=Ds.parse(e),n=this.list();t&&this.saveDetail(js.parse({item:s,turns:[...t].slice(-50)}));const i=Ii([s,...n.filter(e=>e.id!==s.id&&wi(e)!==wi(s))]);return JSON.stringify(i)!==JSON.stringify(n)&&this.saveIndex({schemaVersion:1,items:i}),this.removeDetails(n.filter(e=>!i.some(t=>t.id===e.id)).map(e=>e.id)),s}remove(e){const t=this.list(),s=t.filter(t=>t.id!==e);return s.length!==t.length&&(this.saveIndex({schemaVersion:1,items:s}),this.removeDetails([e]),!0)}removeIdentity(e,t){const s=this.list(),n=`${e}:${t}`,i=s.filter(e=>wi(e)!==n);return i.length!==s.length&&(this.saveIndex({schemaVersion:1,items:i}),this.removeDetails(s.filter(e=>wi(e)===n).map(e=>e.id)),!0)}load(){let e;try{e=JSON.parse(t.readFileSync(this.filePath,"utf8"))}catch(e){return e&&"object"==typeof e&&"code"in e&&"ENOENT"===e.code||this.onWarning?.({kind:"index",id:"index",reason:"unreadable index replaced with an empty index"}),{index:Ms.parse({}),rewrite:!1}}const s=function(e,t){const s=vi(e);if(!s)return t?.({kind:"index",id:"index",reason:"invalid index replaced with an empty index"}),Ms.parse({});const n=Object.keys(s).filter(e=>!gi.has(e));n.length&&t?.({kind:"index",id:"index",reason:`unknown fields ignored: ${n.join(", ")}`});const i=Array.isArray(s.items)?s.items:[];Array.isArray(s.items)||void 0===s.items||t?.({kind:"index",id:"index",reason:"invalid items replaced with an empty list"});const r=i.flatMap((e,s)=>{const n=vi(e),i="string"==typeof n?.id&&n.id.trim()?n.id.trim():`item[${s}]`;if(!n)return t?.({kind:"item",id:i,reason:"invalid item removed"}),[];const r=Si(n,fi),o=Ds.safeParse(r);return o.success?(Object.keys(n).some(e=>!fi.has(e))&&t?.({kind:"item",id:i,reason:"unknown or legacy fields ignored"}),[o.data]):(t?.({kind:"item",id:i,reason:"item failed current schema and was removed"}),[])}),o=Ii(r);return o.length<r.length&&t?.({kind:"index",id:"index",reason:"duplicate or excess items removed"}),Ms.parse({schemaVersion:1,items:o})}(e,this.onWarning);return{index:s,rewrite:JSON.stringify(e)!==JSON.stringify(s)}}saveIndex(e){const n=Ms.parse({schemaVersion:1,items:Ii(e.items)});t.mkdirSync(s.dirname(this.filePath),{recursive:!0}),y.sync(this.filePath,`${JSON.stringify(n,null,2)}\n`,{mode:384})}sanitizeDetail(e,t){const s=vi(t);if(!s||vi(s.item)?.id!==e.id||!Array.isArray(s.turns))return this.onWarning?.({kind:"detail",id:e.id,reason:"invalid detail replaced with empty turns"}),{detail:js.parse({item:e,turns:[]}),rewrite:!0};const n=s.turns.flatMap((t,s)=>{const n=vi(t),i=n?Ps.safeParse(Si(n,yi)):void 0;return i?.success?[i.data]:(this.onWarning?.({kind:"detail",id:e.id,reason:`invalid turn[${s}] removed`}),[])}).slice(-50),i=js.parse({item:e,turns:n});return{detail:i,rewrite:JSON.stringify(t)!==JSON.stringify(i)}}detailPath(e){const t=`${n.createHash("sha256").update(e).digest("hex")}.json`;return s.join(s.dirname(this.filePath),"details",t)}saveDetail(e){const n=this.detailPath(e.item.id);t.mkdirSync(s.dirname(n),{recursive:!0}),y.sync(n,`${JSON.stringify(e,null,2)}\n`,{mode:384})}removeDetails(e){for(const s of e)try{t.unlinkSync(this.detailPath(s))}catch(e){e&&"object"==typeof e&&"code"in e&&"ENOENT"===e.code||this.onWarning?.({kind:"detail",id:s,reason:"detail cleanup failed"})}}}class bi{options;pending=new Map;constructor(e){this.options=e}resume(e){const t=this.options.history.get(e);if(!t)throw _i("AI_SESSION_HISTORY_NOT_FOUND","AI session history entry not found.",404);const s=[`ai:${t.id}`,`provider:${t.agent}:${t.providerSessionId}`],n=s.map(e=>this.pending.get(e)).find(Boolean);if(n)return n;const i=this.perform(t).finally(()=>{for(const e of s)this.pending.get(e)===i&&this.pending.delete(e)});for(const e of s)this.pending.set(e,i);return i}async perform(e){const t=new Set(this.options.appSessions().filter(e=>"string"!=typeof e.status||"running"===e.status).map(e=>e.id)),s=this.options.registry.all().find(t=>t.id===e.id||t.agent===e.agent&&t.providerSessionId===e.providerSessionId);if(s?.appSessionId&&t.has(s.appSessionId))return Ls.parse({disposition:"already-open",aiSessionId:s.id,providerSessionId:e.providerSessionId,appSessionId:s.appSessionId});const n=this.options.registry.get(e.id),i=s?.id===e.id?void 0:s;s&&s.id!==e.id&&this.options.registry.discard(s.id),this.options.registry.restoreHistory(e);try{const t=await this.options.startApp(e);if(!t?.id||"string"==typeof t.status&&"running"!==t.status)throw new Error("Provider resume did not create a running app session.");return Ls.parse({disposition:"resumed",aiSessionId:e.id,providerSessionId:e.providerSessionId,appSessionId:t.id})}catch(t){throw n?this.options.registry.put(n):this.options.registry.discard(e.id),i&&this.options.registry.put(i),_i("AI_SESSION_RESUME_UNAVAILABLE",t instanceof Error?t.message:"Provider session could not be resumed.",409,t)}}}function _i(e,t,s,n){return Object.assign(new Error(t),{code:e,statusCode:s,...void 0===n?{}:{cause:n}})}const Ti=process.env.TASK_HANDOFF_CLAUDE_CONTROL_SOCK_LOG||(process.env.TASK_HANDOFF_LOG_DIR?`${process.env.TASK_HANDOFF_LOG_DIR}/claude-control-sock.log`:void 0)||(Oi=ce,xi="claude-control-sock.log",process.env.CODEX_SANDBOX?s.join(process.cwd(),".task-handoff",xi):s.join(s.dirname(Oi),xi));var Oi,xi;class Ei{registry;client;id="claude-control-sock";agent="claude";subscriptions=new Map;textByShort=new Map;constructor(e,t={list:()=>Ue({op:"list"},{timeoutMs:Number(process.env.TASK_HANDOFF_CLAUDE_CONTROL_TIMEOUT_MS)||5e3}),reply:qe,kill:Be,subscribe:Ke}){this.registry=e,this.client=t}async refresh(e){if(!Mi("TASK_HANDOFF_AI_SESSION_SCAN",!0)||!Mi("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(Li),i=new Map;for(const e of n){const t=Pi(e.ai?.claude?.short,80);t&&i.set(t,e)}for(const e of n){const t=Pi(e.ai?.claude?.short,80);if(!t)continue;const n=s.find(e=>e.short===t);this.upsertJob(n||Fi(e)||{short:t},e)}for(const e of s)e.short&&!i.has(e.short)&&this.upsertJob(e);this.reconcileSubscriptions(new Set([...s.map(e=>Pi(e.short,80)).filter(Boolean),...Array.from(i.keys())])),e.registry.reconcileAdapterSessions({agent:this.agent,appSessionIds:new Set(n.map(e=>Pi(e.id,120)).filter(Boolean)),providerSessionIds:new Set(s.map(e=>Pi(e.sessionId,240)).filter(Boolean)),providerShorts:new Set([...s.map(e=>Pi(e.short,80)).filter(Boolean),...Array.from(i.keys())])})}async sendMessage(e,t){return this.startMessage(e,t)}async startMessage(e,t){const s=this.requireShort(e),n=await bt(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 xt("AI_SESSION_SEND_FAILED",n.error||`Claude reply failed: ${n.code||"unknown"}`);const i=this.registry.applyRealtimeEvent(e.id,{kind:"send-ack",userPrompt:t.message,source:"control"})||e;return{session:i,provider:this.agent,action:"send",turnId:i.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 xt("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 xt("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=Pi(e.short,80);if(!s)return;const n=Pi(e.sessionId||t?.ai?.claude?.providerSessionId,240),i=Pi(e.cwd||t?.ai?.claude?.cwd||t?.tty?.cwd||t?.launch?.cwd,4096),r=this.sessionForShort(s),o=ki(e.state||t?.ai?.claude?.state,{hasWorkSignal:Ni(e),isAppSession:Boolean(t||r?.appSessionId)}),a=Pi(t?.ai?.claude?.controlSock,4096)||He();this.registry.applyAdapterSnapshot({source:"adapter-snapshot",agent:"claude",appId:Pi(t?.appId,120)||(t?"claude":"claude-daemon"),appSessionId:Pi(t?.id,120),providerSessionId:n,appBindingKeys:ji(t,s),actions:zi(o),providerMeta:{short:s,controlSock:a,pid:Number(e.pid||t?.ai?.claude?.pid)||void 0,state:Pi(e.state||t?.ai?.claude?.state,80),tempo:Pi(e.tempo||t?.ai?.claude?.tempo,80),cliVersion:Pi(e.cliVersion||t?.ai?.claude?.cliVersion,80),source:Pi(e.source||t?.ai?.claude?.source,80)},title:Pi(t?.title,240)||"Claude",cwd:i,transcriptPath:Jn(n,i),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=Ri(s.record);n&&this.upsertJob(n);const i=this.textFromSubscribeMessage(e,s);if(i){const t=this.sessionForShort(e);t&&this.registry.applyRealtimeEvent(t.id,{kind:"assistant-message",text:i,source:"realtime"})}const r=this.stateFromSubscribeMessage(s,n);if(r.observedState){const i=this.sessionForShort(e),o=r.lifecycleState?ki(r.lifecycleState,{hasWorkSignal:!1,isAppSession:Boolean(i?.appSessionId)}):void 0;this.logSubscribeMessage(e,t,s,n,r,i,o),i&&this.registry.applyAdapterSnapshot({source:"adapter-snapshot",agent:i.agent,appId:i.appId,appSessionId:i.appSessionId,providerSessionId:i.providerSessionId,appBindingKeys:i.appBindingKeys,actions:zi(o),providerMeta:{...i.providerMeta||{},short:e,controlSock:t,state:r.observedState,stateSource:r.source},status:o?.status,phase:o?.phase,cwd:i.cwd,title:i.title})}else this.logSubscribeMessage(e,t,s,n,r,this.sessionForShort(e))}sessionForShort(e){return this.registry.list().find(t=>"claude"===t.agent&&t.providerMeta?.short===e)}stateFromSubscribeMessage(e,t){const s=Ri(e.patch),n="settled"===Pi(e.type,80)?e.outcome:void 0,i=[{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=>Pi(e.value,80));return{observedState:Pi(i?.value,80),lifecycleState:Pi(n,80),source:i?.source,patch:s}}logSubscribeMessage(e,t,s,n,i,r,o){if(Mi("TASK_HANDOFF_DIAGNOSTIC_LOGS"))try{k(Ti,{event:"claude_control_subscribe",short:e,controlSock:t,messageType:Pi(s.type,80)||void 0,state:i.observedState||void 0,lifecycleState:i.lifecycleState||void 0,stateSource:i.source,recordState:Pi(n?.state,80)||void 0,patchKeys:i.patch?Object.keys(i.patch).sort():void 0,outcome:Pi(s.outcome,80)||void 0,streamLineBytes:"string"==typeof s.line?Buffer.byteLength(s.line):void 0,streamTailCount:Ci(s.streamTail).length||void 0,aiSessionId:r?.id,appSessionId:r?.appSessionId,providerSessionId:r?.providerSessionId,mappedStatus:o?.status,mappedPhase:o?.phase})}catch{}}textFromSubscribeMessage(e,t){const s=[...Ci(t.streamTail).map(e=>String(e||"")),...Ci(t.output).map(e=>String(e||"")),Di(t.data),Di(t.text),Di(t.delta),Di(t.raw)].filter(Boolean);if(0===s.length)return"";const n=(i=s.join("\n"),String(i).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 i;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 xt("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 ki(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 zi(e){return{send:!0,interrupt:"running"===e?.status||"waiting"===e?.status,approval:!1}}function Ni(e){return Boolean(Pi(e.detail,500)||Pi(e.intent,500)||Pi(e.needs,500))}function Pi(e,t=500){const s=String(e??"").replace(/\s+/g," ").trim();return s.length>t?`${s.slice(0,t-3)}...`:s}function Ri(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:void 0}function Ci(e){return Array.isArray(e)?e:[]}function Di(e){return"string"==typeof e?e:""}function Mi(e,t=!1){const s=process.env[e];return void 0===s||""===s?t:!["0","false","no","off"].includes(String(s).toLowerCase())}function Fi(e){const t=e.ai?.claude,s=Pi(t?.short,80);if(s)return{short:s,sessionId:Pi(t?.providerSessionId,240)||void 0,pid:Number(t?.pid)||void 0,cwd:Pi(t?.cwd||e.tty?.cwd||e.launch?.cwd,4096)||void 0,state:Pi(t?.state,80)||void 0,tempo:Pi(t?.tempo,80)||void 0,cliVersion:Pi(t?.cliVersion,80)||void 0,source:Pi(t?.source,80)||void 0}}function ji(e,t){const s=[e?.id?`app:${Pi(e.id,120)}`:"",t?`claude-short:${t}`:""].filter(Boolean);return s.length?s:void 0}function Li(e){const t=Pi(e.status,80).toLowerCase();return!t||"running"===t}function $i(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}function Hi(e,t){const s=e[t];return"string"==typeof s&&s.trim()?s:void 0}function Ui(e){if("subAgentActivity"===e.type){const t=Hi(e,"agentThreadId"),s=["started","interacted","interrupted"].includes(String(e.kind))?e.kind:void 0;return t&&s?[{threadId:t,path:Hi(e,"agentPath"),status:"interrupted"===s?"interrupted":"started"===s?"pending-init":"running",activity:s,observation:"activity"}]:[]}return"collabAgentToolCall"!==e.type?[]:Object.entries($i(e.agentsStates)).flatMap(([e,t])=>{const s=$i(t),n=function(e){switch(e){case"pendingInit":return"pending-init";case"running":return"running";case"interrupted":return"interrupted";case"completed":return"completed";case"errored":return"errored";case"shutdown":return"shutdown";case"notFound":return"not-found";default:return}}(s.status);return e.trim()&&n?[{threadId:e,status:n,message:Hi(s,"message"),observation:"state"}]:[]})}function qi(e,t){const s=function(e){switch(e.type){case"commandExecution":case"fileChange":case"mcpToolCall":case"dynamicToolCall":case"collabAgentToolCall":case"webSearch":case"imageView":case"sleep":case"imageGeneration":return"tool";case"userMessage":case"hookPrompt":case"agentMessage":case"plan":case"reasoning":case"subAgentActivity":case"enteredReviewMode":case"exitedReviewMode":case"contextCompaction":return"non-tool";default:return"unknown"}}(e);if("tool"!==s)return void("unknown"===s&&"string"==typeof e.type&&e.type&&console.warn(`[codex-app-server] ignoring unknown ThreadItem.type: ${e.type}`));const n=Hi(e,"id"),i=Hi(e,"type");if(!n||!i)return;const r=function(e,t){switch(t){case"commandExecution":return{name:"Command",inputPreview:Hi(e,"command")};case"fileChange":{const t=Array.isArray(e.changes)?e.changes.map(e=>Hi($i(e),"path")).filter(e=>Boolean(e)):[];return{name:"File change",inputPreview:[...new Set(t)].join(", ")||void 0}}case"mcpToolCall":{const t=Hi(e,"server"),s=Hi(e,"tool")||"Tool";return{name:t?`${t} · ${s}`:s,inputPreview:Vi(e.arguments)}}case"dynamicToolCall":{const t=Hi(e,"namespace"),s=Hi(e,"tool")||"Tool";return{name:t?`${t} · ${s}`:s,inputPreview:Vi(e.arguments)}}case"collabAgentToolCall":{const t=Hi(e,"tool")||"collabAgentToolCall";return{name:{spawnAgent:"Spawn agent",sendInput:"Send agent input",resumeAgent:"Resume agent",wait:"Wait for agents",closeAgent:"Close agent"}[t]||t,inputPreview:Hi(e,"prompt")}}case"webSearch":return{name:"Web search",inputPreview:Hi(e,"query")};case"imageView":return{name:"View image",inputPreview:Hi(e,"path")};case"sleep":return{name:"Sleep",inputPreview:"number"==typeof e.durationMs?`${e.durationMs} ms`:void 0};case"imageGeneration":return{name:"Image generation",inputPreview:Hi(e,"revisedPrompt")};default:return{name:t}}}(e,i);return{id:n,kind:i,name:r.name,inputPreview:Ki(r.inputPreview),startedAt:Bi(t)}}function Bi(e){if("number"!=typeof e||!Number.isFinite(e))return;const t=new Date(e);return Number.isNaN(t.getTime())?void 0:t.toISOString()}function Ki(e){const t=e?.replace(/\s+/g," ").trim();return t?t.length>500?`${t.slice(0,497)}...`:t:void 0}function Vi(e){try{return void 0===e?void 0:JSON.stringify(e)}catch{return}}function Gi(e){const t=$i(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}function Wi(e){const t=e.turn&&"object"==typeof e.turn?e.turn:void 0;return"string"==typeof t?.id?t.id:void 0}function Yi(e){return e instanceof Error&&/no active turn/i.test(e.message)}function Ji(e){if(e instanceof Error)return e.message.match(/expected active turn id `[^`]+` but found `([^`]+)`/i)?.[1]}class Xi extends v.EventEmitter{child;proxyChild;socket;buffer="";nextId=1;pending=new Map;mode;requestTimeoutMs;constructor(e={}){super();const t=e.command||process.env.TASK_HANDOFF_CODEX_APP_SERVER_COMMAND||process.env.TASK_HANDOFF_CODEX_COMMAND||"codex";this.mode=e.socketPath?{type:"unix",command:t,socketPath:e.socketPath}:{type:"stdio",command:t},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===w.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===w.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,s){return{turnId:Wi(await this.request("turn/start",{threadId:e,input:s||[{type:"text",text:t,text_elements:[]}]}))}}async steerTurn(e,t,s,n){const i=await this.request("turn/steer",{threadId:e,expectedTurnId:t,input:n||[{type:"text",text:s,text_elements:[]}]});return{turnId:"string"==typeof i.turnId?i.turnId:t}}async interruptTurn(e,t){await this.request("turn/interrupt",{threadId:e,turnId:t})}listSkills(e){return this.request("skills/list",{cwds:[e],forceReload:!1})}listPlugins(e){return this.request("plugin/list",{cwds:[e],marketplaceKinds:null})}listApps(e){return this.request("app/list",{cursor:null,limit:1e3,threadId:e,forceRefetch:!1})}async startFuzzyFileSearch(e,t){await this.request("fuzzyFileSearch/sessionStart",{sessionId:e,roots:[t]})}async updateFuzzyFileSearch(e,t){await this.request("fuzzyFileSearch/sessionUpdate",{sessionId:e,query:t})}async stopFuzzyFileSearch(e){await this.request("fuzzyFileSearch/sessionStop",{sessionId:e})}async resumeThread(e){const t=await this.request("thread/resume",{threadId:e});return t.thread&&"object"==typeof t.thread?t.thread:void 0}async startReview(e){return{turnId:Wi(await this.request("review/start",{threadId:e,target:{type:"uncommittedChanges"}}))}}async setThreadName(e,t){await this.request("thread/name/set",{threadId:e,name:t})}setThreadGoal(e,t){return this.request("thread/goal/set",{threadId:e,objective:t})}getThreadGoal(e){return this.request("thread/goal/get",{threadId:e})}async compactThread(e){await this.request("thread/compact/start",{threadId:e})}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=$i(e.params.permissions),n=$i(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===w.OPEN;if(!s&&!n)return Promise.reject(new Error("Codex app-server is not connected."));const i=this.nextId++,r=JSON.stringify({id:i,method:e,params:t});return new Promise((t,s)=>{const o=setTimeout(()=>{this.pending.delete(i),s(new Error(`Codex app-server request timed out: ${e}`))},this.requestTimeoutMs);this.pending.set(i,{resolve:t,reject:s,timer:o}),n?this.socket?.send(r):this.child?.stdin.write(`${r}\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!==w.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!==w.OPEN?this.child?.stdin.writable&&this.child.stdin.write(`${s}\n`):this.socket.send(s)}startUnixSocket(e,t){return new Promise((s,n)=>{const i=m.spawn(e,["app-server","proxy","--sock",t],{stdio:["pipe","pipe","ignore"],env:process.env});this.proxyChild=i;const r=new w("ws://localhost/rpc",{createConnection:()=>function(e){const t=new o.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}(i),perMessageDeflate:!1});this.socket=r;let a=!1;const c=e=>{a||(a=!0,this.socket=void 0,this.proxyChild=void 0,i.killed||i.kill("SIGTERM"),n(e))};i.once("error",c),i.once("exit",(e,t)=>{a?this.proxyChild===i&&(this.proxyChild=void 0,this.emit("disconnect")):c(new Error(`Codex app-server proxy exited before connect: code=${e??"null"} signal=${t??"null"}.`))}),r.once("error",c),r.once("open",()=>{a=!0,i.off("error",c),r.off("error",c),r.on("message",e=>this.handleLine(e.toString())),r.once("close",()=>{this.socket=void 0,this.proxyChild===i&&(this.proxyChild=void 0),i.killed||i.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=>{r.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||""),i=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=Hi(s,"threadId");if(!n)return;const i=Hi(s,"command"),r=Hi(s,"reason");return{id:e,method:t,kind:"command",threadId:n,turnId:Hi(s,"turnId"),itemId:Hi(s,"itemId"),summary:[r,i?`Command: ${i}`:void 0].filter(Boolean).join(" · ")||"Codex is requesting command approval.",params:s}}if("item/fileChange/requestApproval"===t){const n=Hi(s,"threadId");if(!n)return;const i=Hi(s,"grantRoot");return{id:e,method:t,kind:"file-change",threadId:n,turnId:Hi(s,"turnId"),itemId:Hi(s,"itemId"),summary:Hi(s,"reason")||(i?`Approve file changes under ${i}`:"Codex is requesting file change approval."),params:s}}if("item/permissions/requestApproval"===t){const n=Hi(s,"threadId");if(!n)return;return{id:e,method:t,kind:"permissions",threadId:n,turnId:Hi(s,"turnId"),itemId:Hi(s,"itemId"),summary:Hi(s,"reason")||"Codex is requesting additional permissions.",params:s}}}(s,n,i);return void(e&&this.emit("event",{type:"approval-request",request:e}))}this.emit("notification",{method:n,params:i});const r=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("thread/name/updated"===e&&"string"==typeof t.threadId&&"string"==typeof t.threadName)return{type:"thread-name",threadId:t.threadId,name:t.threadName};if("thread/compacted"===e&&"string"==typeof t.threadId&&"string"==typeof t.turnId)return{type:"context-compaction",threadId:t.threadId,turnId:t.turnId,itemId:`context_compaction:${t.turnId}`,status:"completed"};if("turn/started"===e&&"string"==typeof t.threadId){const e=$i(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=$i(t.turn);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:Gi(e.error)}}if(("item/started"===e||"item/completed"===e)&&"string"==typeof t.threadId){const s=$i(t.item);if("contextCompaction"===s.type&&"string"==typeof t.turnId&&"string"==typeof s.id){const s=Bi("item/started"===e?t.startedAtMs:t.completedAtMs);return{type:"context-compaction",threadId:t.threadId,turnId:t.turnId,itemId:`context_compaction:${t.turnId}`,status:"item/started"===e?"running":"completed",observedAt:s}}if("userMessage"===s.type){const e=function(e){return(Array.isArray(e.content)?e.content:[]).map(e=>{const t=$i(e);return"text"===t.type&&"string"==typeof t.text?t.text.trim():""}).filter(Boolean).join("\n").trim()}(s);return e?{type:"user-message",threadId:t.threadId,turnId:"string"==typeof t.turnId?t.turnId:void 0,text:e}:void 0}const n=Bi("item/started"===e?t.startedAtMs:t.completedAtMs),i=Ui(s).map(e=>n?{...e,observedAt:n}:e);if("subAgentActivity"===s.type&&i[0])return{type:"sub-agent-activity",threadId:t.threadId,turnId:"string"==typeof t.turnId?t.turnId:void 0,subAgent:i[0]};const r=qi(s,"item/started"===e&&"number"==typeof t.startedAtMs?t.startedAtMs:void 0);if(r)return{type:"item/started"===e?"tool-item-started":"tool-item-completed",threadId:t.threadId,turnId:"string"==typeof t.turnId?t.turnId:void 0,tool:r,subAgents:i.length?i:void 0}}if("item/agentMessage/delta"===e&&"string"==typeof t.threadId&&"string"==typeof t.turnId&&"string"==typeof t.itemId&&"string"==typeof t.delta)return{type:"agent-message-delta",threadId:t.threadId,turnId:t.turnId,itemId:t.itemId,delta:t.delta};if("item/completed"===e&&"string"==typeof t.threadId){const e=$i(t.item);if("agentMessage"===e.type&&"string"==typeof t.turnId&&"string"==typeof e.id&&"string"==typeof e.text)return{type:"agent-message-completed",threadId:t.threadId,turnId:t.turnId,itemId:e.id,text:e.text}}}(n,i);r&&this.emit("event",r)}}class Qi{options;clientValue;socketPathValue;state="idle";epochValue=0;retryAfter=0;startPromise;listeners;subscribedThreadIds=new Set;subscriptionAttempts=new Map;constructor(e){this.options=e,e.injectedClient&&this.install(e.injectedClient,void 0)}get client(){return this.clientValue}get socketPath(){return this.socketPathValue}get epoch(){return this.epochValue}configure(e){return this.options.injectedClient?(this.clientValue||this.install(this.options.injectedClient,void 0),this.current()):(this.clientValue&&this.socketPathValue===e||(this.disposeCurrent(),this.install(this.options.createClient(e?{socketPath:e}:{}),e)),this.current())}current(){return this.clientValue?{client:this.clientValue,epoch:this.epochValue}:void 0}isCurrent(e){return e.client===this.clientValue&&e.epoch===this.epochValue}connectionFor(e){return e===this.clientValue?this.current():void 0}canRetry(){return Date.now()>=this.retryAfter}async ready(e={}){const t=this.current();if(!t)throw new Error("Codex app-server is not configured.");if("ready"===this.state)return t;if(e.respectRetry&&!this.canRetry())return;if(this.startPromise)return this.startPromise;this.listeners&&this.listeners.client===t.client||this.attachListeners(t.client,t.epoch),this.state="connecting";const s=t.client.start().then(()=>{if(!this.isCurrent(t))throw new Error("Codex app-server connection changed while starting.");return this.state="ready",this.retryAfter=0,t}).catch(s=>{throw this.isCurrent(t)&&(this.state="idle",e.respectRetry&&(this.retryAfter=Date.now()+(this.options.retryDelayMs??3e4))),s}).finally(()=>{this.startPromise===s&&(this.startPromise=void 0)});return this.startPromise=s,s}markUnhealthy(e){this.isCurrent(e)&&(this.advanceGeneration(),e.client.stop())}ensureThreadSubscribed(e,t){const{client:s,epoch:n}=e;if(!this.isCurrent(e)||!s.resumeThread||this.subscribedThreadIds.has(t))return Promise.resolve(void 0);const i=this.subscriptionAttempts.get(t);if(i)return i;const r=s.resumeThread(t).then(e=>(s===this.clientValue&&n===this.epochValue&&this.subscribedThreadIds.add(t),e)).finally(()=>{this.subscriptionAttempts.get(t)===r&&this.subscriptionAttempts.delete(t)});return this.subscriptionAttempts.set(t,r),r}stop(){this.disposeCurrent(),this.retryAfter=0}install(e,t){this.clientValue=e,this.socketPathValue=t,this.state="idle",this.epochValue+=1,this.attachListeners(e,this.epochValue)}attachListeners(e,t){const s=s=>{const n={client:e,epoch:t};this.isCurrent(n)&&this.options.onEvent(s,n)},n=()=>{const s={client:e,epoch:t};this.isCurrent(s)&&(this.advanceGeneration(),this.options.onDisconnect?.(s))};e.on("event",s),e.on("disconnect",n),this.listeners={client:e,event:s,disconnect:n}}advanceGeneration(){const e=this.current();this.state="idle",this.retryAfter=Date.now()+(this.options.retryDelayMs??3e4),this.startPromise=void 0,this.resetSubscriptions(),this.detachListeners(),this.epochValue+=1,e&&this.options.onInvalidate?.(e)}detachListeners(){const e=this.listeners;e&&(e.client.off("event",e.event),e.client.off("disconnect",e.disconnect),this.listeners=void 0)}disposeCurrent(){const e=this.clientValue,t=this.current();this.state="closing",this.epochValue+=1,this.startPromise=void 0,this.detachListeners(),this.resetSubscriptions(),e?.stop(),this.clientValue=void 0,this.socketPathValue=void 0,this.state="idle",t&&this.options.onInvalidate?.(t)}resetSubscriptions(){this.subscribedThreadIds.clear(),this.subscriptionAttempts.clear()}}class Zi{options;pending=new _t;connectionEpoch=0;constructor(e){this.options=e}latestForSession(e){return this.pending.latestForSession(e)}clearSession(e){this.pending.clearSession(e)}resetConnection(){this.connectionEpoch+=1,this.pending.clear()}attachLifecycle(e,t){return"approval"!==t.phase||e&&this.pending.latestForSession(e)?t:{status:"waiting",phase:"thinking"}}register(e){const t=this.options.findSession(e.threadId),s=this.options.currentClient();if(!t||!s?.respondToApproval)return;const n=this.connectionEpoch;this.pending.register({id:`${e.threadId}:${e.id}`,sessionId:t.id,provider:"codex",summary:e.summary,metadata:{kind:e.kind,requestId:e.id,itemId:e.itemId},resolve:async t=>{const i=this.options.currentClient();if(n!==this.connectionEpoch||i!==s||!i.respondToApproval)throw xt("AI_SESSION_APPROVAL_CONNECTION_CHANGED","The Codex connection changed before the approval could be resolved. Wait for the app-server to replay the pending request.",409);await i.respondToApproval(e,t)}}),this.options.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 resolve(e,t){let s=await this.pending.resolveForSession(e.id,t);if(s||(await this.attachPendingRequest(e),s=await this.pending.resolveForSession(e.id,t)),!s)throw xt("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);return{session:this.options.registry.applyRealtimeEvent(e.id,{kind:"lifecycle",status:"skip"===t?"idle":"running",phase:"skip"===t?"unknown":"thinking",source:"control"})||e,provider:"codex",action:"approval",decision:t}}async attachPendingRequest(e){const t=await this.options.readyClient();if(!t.resumeThread||this.pending.latestForSession(e.id))return;if(!e.providerSessionId)throw xt("AI_SESSION_THREAD_NOT_FOUND","AI session is not bound to a Codex thread.");const s=await t.resumeThread(e.providerSessionId);s&&this.options.applyThreadSnapshot(s),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.pending.latestForSession(e.id)))}}function er(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function tr(e){return"string"==typeof e&&e.trim().length>0?e:void 0}function sr(e){return"codex"===e.appId&&"running"===e.status&&void 0!==e.socketPath}class nr{sessions=[];socketPathValue;get socketPath(){return this.socketPathValue}update(e=[]){return this.sessions=e.flatMap(e=>{const t=function(e){if(!er(e))return;const t=er(e.ai)?e.ai:void 0,s=t&&er(t.appServer)?t.appServer:void 0;return{id:tr(e.id),appId:"string"==typeof e.appId?e.appId:void 0,status:"string"==typeof e.status?e.status:void 0,socketPath:tr(s?.socketPath),activeThreadId:"string"==typeof t?.activeThreadId?t.activeThreadId:void 0,threadIds:Array.isArray(t?.threadIds)?t.threadIds.filter(e=>"string"==typeof e):[]}}(e);return t?[t]:[]}),this.socketPathValue=this.sessions.find(sr)?.socketPath,this.socketPathValue}clear(){this.sessions=[],this.socketPathValue=void 0}appSessionIdForThread(e){const t=this.socketPathValue;if(t)for(const s of this.sessions)if(s.id&&sr(s)&&s.socketPath===t&&(s.activeThreadId===e||s.threadIds.includes(e)))return s.id}}class ir{options;constructor(e){this.options=e}async sendMessage(e,t){const s=await this.options.readyClient(),n=await this.validateReferences(e,t.references||[]),i=this.requireThreadId(e),r=await bt(t.message,t.attachments,t=>this.steerOrStartTurnForCompatibility(s,i,e,t,n)),o=this.options.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:o,provider:"codex",action:r.started?"send":"steer",turnId:o.activeTurnId,providerTurnId:r.turnId}}async startMessage(e,t){const s=await this.options.readyClient(),n=await this.validateReferences(e,t.references||[]),i=this.requireThreadId(e),r=await bt(t.message,t.attachments,e=>this.startTurn(s,i,e,n)),o=this.options.registry.applyRealtimeEvent(e.id,{kind:"send-ack",activeTurnId:r.turnId,providerTurnId:r.turnId,userPrompt:t.message,source:"control"})||e;return{session:o,provider:"codex",action:"send",turnId:o.activeTurnId,providerTurnId:r.turnId}}async steerMessage(e,t){const s=await this.options.readyClient(),n=await this.validateReferences(e,t.references||[]),i=this.requireThreadId(e),r=await bt(t.message,t.attachments,t=>this.steerTurn(s,i,e,t,n)),o=this.options.registry.applyRealtimeEvent(e.id,{kind:"user-message",activeTurnId:r.turnId,providerTurnId:r.turnId,userPrompt:t.message,source:"control"})||e;return{session:o,provider:"codex",action:"steer",turnId:o.activeTurnId,providerTurnId:r.turnId}}async interrupt(e){const t=await this.options.readyClient(),s=this.requireThreadId(e),n=e.activeTurnId;if(!n)throw xt("AI_SESSION_NO_ACTIVE_TURN","AI session has no active turn to interrupt.");if(!t.interruptTurn)throw xt("AI_SESSION_INTERRUPT_UNSUPPORTED","Codex app-server client does not support turn interruption.");try{await t.interruptTurn(s,n)}catch(i){const r=Ji(i);if(r)return await t.interruptTurn(s,r),{session:this.options.registry.applyRealtimeEvent(e.id,{kind:"lifecycle",activeTurnId:r,status:"running",phase:"unknown",source:"control"})||e,provider:"codex",action:"interrupt",providerTurnId:r};if(!Yi(i))throw i;return{session:this.options.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:"codex",action:"interrupt",providerTurnId:n}}return{session:this.options.registry.applyRealtimeEvent(e.id,{kind:"lifecycle",status:"running",phase:"unknown",source:"control"})||e,provider:"codex",action:"interrupt",providerTurnId:n}}async steerTurn(e,t,s,n,i=[]){if(!s.activeTurnId)throw xt("AI_SESSION_NO_ACTIVE_TURN","AI session has no active turn to steer.",409);if(!e.steerTurn)throw xt("AI_SESSION_STEER_UNSUPPORTED","Codex app-server client does not support turn steering.");try{return{turnId:(await e.steerTurn(t,s.activeTurnId,n,rr(n,i))).turnId||s.activeTurnId}}catch(s){const r=Ji(s);if(r)return{turnId:(await e.steerTurn(t,r,n,rr(n,i))).turnId||r};throw s}}async steerOrStartTurnForCompatibility(e,t,s,n,i){if(!Boolean(s.activeTurnId&&("running"===s.status||"waiting"===s.status)))return this.startTurn(e,t,n,i);try{return{...await this.steerTurn(e,t,s,n,i),started:!1}}catch(s){if(!Yi(s))throw s;return this.startTurn(e,t,n,i)}}async startTurn(e,t,s,n=[]){if(!e.startTurn)throw xt("AI_SESSION_SEND_UNSUPPORTED","Codex app-server client does not support starting turns.");return{turnId:(await e.startTurn(t,s,rr(s,n))).turnId,started:!0}}validateReferences(e,t){return this.options.validateReferences?this.options.validateReferences(e,t):Promise.resolve(t)}requireThreadId(e){if(!e.providerSessionId)throw xt("AI_SESSION_THREAD_NOT_FOUND","AI session is not bound to a Codex thread.");return e.providerSessionId}}function rr(e,t){return[{type:"text",text:e,text_elements:[]},...t.map(e=>"skill"===e.kind?{type:"skill",name:e.name,path:e.path}:{type:"mention",name:e.name,path:e.path})]}class or{options;constructor(e){this.options=e}async sync(e,t=()=>!0){const s=await e.listLoadedThreadIds();if(!t())return;const n=new Map;if(e.listThreads)try{for(const s of await e.listThreads()){if(!t())return;const e="string"==typeof s.id?s.id:void 0;e&&n.set(e,s)}}catch{}for(const i of s){let s=n.get(i);if(e.readThread)try{s={...s||{},...await e.readThread(i,{includeTurns:!0})}}catch{s||={id:i}}if(!t())return;if(this.options.applyThreadSnapshot(s||{id:i}),e.resumeThread)try{const s=await this.options.ensureThreadSubscribed(e,i);if(!t())return;s&&this.options.applyThreadSnapshot(s)}catch{}}}}class ar{subAgents=new Map;observations=new Map;replace(e){for(const t of e){const e=this.subAgents.get(t.threadId),s=this.observations.get(t.threadId)||{},n=Boolean(e&&mr(e.status,t.status)),i="realtime"===s.activityOrigin,r=e?{...e,status:n?e.status:t.status,message:n?e.message:t.message,path:t.path||e.path,activity:i?e.activity:t.activity||e.activity,updatedAt:e.updatedAt}:t,o=!e||e.path!==r.path||e.status!==r.status||e.activity!==r.activity||e.message!==r.message;this.subAgents.set(t.threadId,o?{...r,updatedAt:hr(e?.updatedAt,t.updatedAt)}:e),this.observations.set(t.threadId,{...s,stateAt:n?s.stateAt:hr(s.stateAt,t.updatedAt),activityAt:t.activity&&!i?hr(s.activityAt,t.updatedAt):s.activityAt,activityOrigin:i?"realtime":t.activity?"snapshot":s.activityOrigin})}return this.prune(),this.snapshot()}apply(e,t){for(const s of e){const e=this.subAgents.get(s.threadId),n=this.observations.get(s.threadId)||{},{observation:i,observedAt:r,...o}=s,a=r||t,c="state"===i&&lr(a,n.stateAt),d="activity"===i&&lr(a,n.activityAt),p="state"===i?{...e||o,status:c&&e?e.status:o.status,message:c&&e?e.message:o.message,updatedAt:e?.updatedAt||a}:{...e||o,status:e&&n.stateAt||d&&e?e.status:o.status,path:!o.path||d&&e?.path?e?.path:o.path,activity:d&&e?e.activity:o.activity||e?.activity,message:e?.message,updatedAt:e?.updatedAt||a},u=!e||e.path!==p.path||e.status!==p.status||e.activity!==p.activity||e.message!==p.message;this.subAgents.set(s.threadId,u?{...p,updatedAt:hr(e?.updatedAt,a)}:e),this.observations.set(s.threadId,"state"===i?{...n,stateAt:c?n.stateAt:a}:{...n,activityAt:d?n.activityAt:a,activityOrigin:d?n.activityOrigin:"realtime"})}return this.prune(),this.snapshot()}clear(){return this.subAgents.clear(),this.observations.clear(),this.snapshot()}snapshot(){return[...this.subAgents.values()].sort((e,t)=>e.threadId.localeCompare(t.threadId))}prune(){if(this.subAgents.size<=50)return;const e=new Set(["pending-init","running","interrupted","errored"]),t=[...this.subAgents.values()].sort((t,s)=>Number(e.has(s.status))-Number(e.has(t.status))||Date.parse(s.updatedAt)-Date.parse(t.updatedAt)||t.threadId.localeCompare(s.threadId)).slice(0,50),s=new Set(t.map(e=>e.threadId));for(const e of this.subAgents.keys())s.has(e)||(this.subAgents.delete(e),this.observations.delete(e))}}class cr{seenToolIds=new Set;activeTools=new Map;contextCompaction;replace(e){this.seenToolIds.clear(),this.activeTools.clear(),this.contextCompaction="context-compaction"===e.currentTool?.kind?e.currentTool:void 0;for(const t of e.seenToolIds)this.seenToolIds.add(t);for(const t of e.activeTools)this.activeTools.set(t.id,t);return this.snapshot()}started(e){return this.contextCompaction=void 0,this.seenToolIds.has(e.id)||(this.seenToolIds.add(e.id),this.activeTools.set(e.id,e)),this.snapshot()}completed(e){return this.seenToolIds.add(e.id),this.activeTools.delete(e.id),this.snapshot()}compacting(e,t,s){return this.contextCompaction={id:`context_compaction:${e}`,kind:"context-compaction",name:"completed"===t?"Context compacted":"Compacting context…",..."running"===t&&s?{startedAt:s}:{}},this.snapshot()}restoreActive(e){return this.seenToolIds.add(e.id),this.activeTools.delete(e.id),this.activeTools.set(e.id,e),this.snapshot()}resetForAgentMessage(){return this.seenToolIds.clear(),this.activeTools.clear(),this.contextCompaction=void 0,this.snapshot()}clearActiveTools(){return this.activeTools.clear(),this.contextCompaction=void 0,this.snapshot()}snapshot(){const e=[...this.activeTools.values()];return{seenToolIds:[...this.seenToolIds],activeTools:e,toolCallsSinceLastMessage:this.seenToolIds.size,currentTool:this.contextCompaction||e.at(-1)}}}function dr(e){const t=new cr;let s,n=!1;const i=Array.isArray(e.turns)?e.turns:[];for(const e of i){const i=gr(e);n="inProgress"===i.status;const r=Array.isArray(i.items)?i.items:[];for(const e of r){const n=gr(e);if("agentMessage"===n.type){t.resetForAgentMessage(),s=void 0;continue}if("contextCompaction"===n.type){t.compacting("string"==typeof i.id?i.id:"unknown","completed"),s=void 0;continue}const r=qi(n);(s={item:n,tool:r},r)&&("active"===ur(n)?t.started(r):t.completed(r))}}return"active"===e.status?.type&&n&&s?.tool&&"unknown"===ur(s.item)&&t.restoreActive(s.tool),t.snapshot()}function pr(e,t){const s=new ar,n=Array.isArray(e.turns)?e.turns:[];for(const e of n){const n=gr(e),i=Array.isArray(n.items)?n.items:[];for(const e of i)s.apply(Ui(gr(e)),t)}return s.snapshot()}function ur(e){switch(e.type){case"commandExecution":case"fileChange":case"mcpToolCall":case"dynamicToolCall":case"collabAgentToolCall":case"imageGeneration":return"inProgress"===e.status?"active":"string"==typeof e.status?"inactive":"unknown";case"webSearch":case"imageView":case"sleep":return"unknown";default:return"inactive"}}function lr(e,t){return Boolean(t&&Date.parse(e)<Date.parse(t))}function mr(e,t){const s={"pending-init":0,running:1,interrupted:2,completed:3,errored:3,shutdown:3,"not-found":3};return s[t]<s[e]}function hr(e,t){return e&&Date.parse(e)>=Date.parse(t)?e:t}function gr(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}function fr(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 yr(e){return(Array.isArray(e.content)?e.content:[]).map(vr).filter(Boolean).join("\n").trim()}function vr(e){const t=$i(e);return"text"===t.type&&"string"==typeof t.text?t.text.trim():""}class Sr{options;toolActivityByThread=new Map;subAgentsByThread=new Map;constructor(e){this.options=e}clearThread(e){this.toolActivityByThread.delete(e),this.subAgentsByThread.delete(e)}resetConnection(){this.toolActivityByThread.clear(),this.subAgentsByThread.clear()}apply(e){if("thread"===e.type||"approval-request"===e.type)return!1;const t=this.options.findSession(e.threadId);if(!t)return!1;if("thread-closed"===e.type)return this.options.clearApprovalSession(t.id),this.applyToolActivity(t.id,this.toolTracker(e.threadId).clearActiveTools()),this.options.registry.applyRealtimeEvent(t.id,{kind:"turn-completed",activeTurnId:t.activeTurnId,status:"idle",phase:"unknown",text:"Codex thread closed.",source:"realtime"}),this.clearThread(e.threadId),!0;if("thread-status"===e.type){const s=fr(e.status);"approval"!==s.phase&&this.options.clearApprovalSession(t.id);const n=this.options.attachApprovalLifecycle(t.id,s);return this.options.registry.applyRealtimeEvent(t.id,{kind:"lifecycle",activeTurnId:t.activeTurnId,status:n.status,phase:n.phase,source:"realtime"}),!0}return"turn-started"===e.type?(this.options.registry.applyRealtimeEvent(t.id,{kind:"turn-started",activeTurnId:e.turnId,providerTurnId:e.turnId,source:"realtime"}),!0):"context-compaction"===e.type?(this.applyToolActivity(t.id,this.toolTracker(e.threadId).compacting(e.turnId,e.status,e.observedAt)),this.options.registry.applyRealtimeEvent(t.id,{kind:"context-compaction",activeTurnId:e.turnId,providerTurnId:e.turnId,contextCompaction:{id:e.itemId,status:e.status,..."running"===e.status&&e.observedAt?{startedAt:e.observedAt}:{},..."completed"===e.status&&e.observedAt?{completedAt:e.observedAt}:{}},observedAt:e.observedAt,source:"realtime"}),!0):"tool-item-started"===e.type?(e.subAgents?.length&&this.applySubAgentUpdates(t.id,e.threadId,e.subAgents),this.applyToolActivity(t.id,this.toolTracker(e.threadId).started(e.tool)),!0):"tool-item-completed"===e.type?(e.subAgents?.length&&this.applySubAgentUpdates(t.id,e.threadId,e.subAgents),this.applyToolActivity(t.id,this.toolTracker(e.threadId).completed(e.tool)),!0):"sub-agent-activity"===e.type?(this.applySubAgentUpdates(t.id,e.threadId,[e.subAgent]),!0):"user-message"===e.type?(this.options.registry.applyRealtimeEvent(t.id,{kind:"user-message",activeTurnId:e.turnId||t.activeTurnId,providerTurnId:e.turnId||t.activeTurnId,userPrompt:e.text,source:"realtime"}),!0):"turn-completed"===e.type?(this.options.clearApprovalSession(t.id),this.applyToolActivity(t.id,this.toolTracker(e.threadId).clearActiveTools()),this.options.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"}),!0):"agent-message-delta"===e.type?(this.options.onMessageDelta?.({sessionId:t.id,providerSessionId:e.threadId,turnId:e.turnId,itemId:e.itemId,delta:e.delta}),!0):"agent-message-completed"===e.type&&(this.applyToolActivity(t.id,this.toolTracker(e.threadId).resetForAgentMessage()),this.options.registry.applyRealtimeEvent(t.id,{kind:"assistant-message",activeTurnId:e.turnId||t.activeTurnId,providerTurnId:e.turnId||t.activeTurnId,itemId:e.itemId,text:e.text,status:t.status,source:"realtime"}),!0)}applyThreadSnapshot(e,t={}){const s="string"==typeof e.id?e.id:void 0;if(!s||!0===e.ephemeral)return;const n=this.options.findSession(s),i=this.options.attachApprovalLifecycle(n?.id,fr(e.status||{})),r=function(e){let t,s,n,i;const r=[],o=Array.isArray(e.turns)?e.turns:[];for(const[e,a]of o.entries()){const o=$i(a),c="string"==typeof o.id&&o.id.trim()?o.id.trim():`turn_${e}`,d="string"==typeof o.status?o.status:"completed",p={id:c,status:"inProgress"===d?"running":"failed"===d?"failed":"completed",revision:0};"inProgress"===d&&(t=c);const u=Array.isArray(o.items)?o.items:[];for(const e of u){const t=$i(e);if("userMessage"===t.type){const e=yr(t);e&&!Dn(e)&&(s=e,p.userPrompt=e)}else"agentMessage"===t.type&&"string"==typeof t.text&&t.text.trim()?(n=t.text.trim(),i="string"==typeof t.id&&t.id.trim()?t.id.trim():void 0,p.lastMessage=n,p.lastMessageItemId=i,p.summary=n.length>1e3?`${n.slice(0,997)}...`:n):"contextCompaction"===t.type&&"string"==typeof t.id&&t.id.trim()&&(p.contextCompactions=[...p.contextCompactions||[],{id:`context_compaction:${c}`,status:"completed"}])}(p.userPrompt||p.lastMessage||p.summary||p.contextCompactions?.length)&&r.push(p)}const a=(new Date).toISOString();return{activeTurnId:t,userPrompt:s,turns:r,summary:n,lastMessage:n,lastMessageItemId:i,toolActivity:dr(e),subAgents:pr(e,a)}}(e),o=Array.isArray(e.turns)?this.replaceThreadActivity(s,r.toolActivity,r.subAgents):this.snapshotThreadActivity(s);return this.options.registry.applyAdapterSnapshot({source:"adapter-snapshot",agent:"codex",appId:t.appSessionId?"codex":"codex-app-server",appSessionId:t.appSessionId,providerSessionId:s,appBindingKeys:t.appSessionId?[`app:${t.appSessionId}`]:void 0,actions:{send:!0,interrupt:"running"===i.status||"waiting"===i.status,approval:"waiting"===i.status&&"approval"===i.phase},title:"string"==typeof e.name?e.name:void 0,cwd:"string"==typeof e.cwd?e.cwd:void 0,activeTurnId:r.activeTurnId,userPrompt:r.userPrompt,turns:r.turns,summary:n&&this.options.latestApprovalSummary(n.id)||r.summary,lastMessage:r.lastMessage,lastMessageItemId:r.lastMessageItemId,currentTool:o.toolActivity.currentTool,toolCallsSinceLastMessage:o.toolActivity.toolCallsSinceLastMessage,subAgents:o.subAgents,status:i.status,phase:i.phase,replaceActivity:!0})}replaceThreadActivity(e,t,s){return{toolActivity:this.toolTracker(e).replace(t),subAgents:this.subAgentTracker(e).replace(s)}}snapshotThreadActivity(e){return{toolActivity:this.toolTracker(e).snapshot(),subAgents:this.subAgentTracker(e).snapshot()}}toolTracker(e){let t=this.toolActivityByThread.get(e);return t||(t=new cr,this.toolActivityByThread.set(e,t)),t}subAgentTracker(e){let t=this.subAgentsByThread.get(e);return t||(t=new ar,this.subAgentsByThread.set(e,t)),t}applyToolActivity(e,t){this.options.registry.applyRealtimeEvent(e,{kind:"tool-activity",currentTool:t.currentTool||null,toolCallsSinceLastMessage:t.toolCallsSinceLastMessage,source:"realtime"})}applySubAgentUpdates(e,t,s){const n=this.subAgentTracker(t).apply(s,(new Date).toISOString());this.options.registry.applyRealtimeEvent(e,{kind:"sub-agent-activity",subAgents:n,source:"realtime"})}}class wr{options;cache=new Map;attachedClient;activeSearches=new Map;notification=e=>this.handleNotification(e);constructor(e){this.options=e}resetConnection(){this.cache.clear();for(const e of this.activeSearches.values())e.stop();this.activeSearches.clear(),this.detachClient()}async catalog(e,t={}){const s=this.requireContext(e),n=await this.client(),i=`${this.options.connectionEpoch()}:${s.cwd}:${s.threadId}`;if(!t.force){const e=this.cache.get(i);if(e)return e}const r=[],o=[],[a,c,d]=await Promise.allSettled([this.requireMethod(n.listSkills,"skills/list").call(n,s.cwd),this.requireMethod(n.listPlugins,"plugin/list").call(n,s.cwd),this.requireMethod(n.listApps,"app/list").call(n,s.threadId)]);this.collect(a,"skills",o,r,Ir),this.collect(c,"plugins",o,r,Ar),this.collect(d,"apps",o,r,br);const p=Ss.parse({sessionId:e.id,providerSessionId:s.threadId,cwd:s.cwd,candidates:_r(o),diagnostics:r});return this.cache.set(i,p),p}async validateReferences(e,t){const s=t.map(e=>hs.parse(e));if(!s.length)return[];const n=await this.catalog(e),i=new Set(n.candidates.filter(e=>"skill"===e.kind||"app"===e.kind||"plugin"===e.kind).map(e=>`${e.kind}:${e.path}`)),r=new Map;for(const e of s){const t=`${e.kind}:${e.path}`;if(!i.has(t))throw xt("AI_SESSION_REFERENCE_UNAVAILABLE",`${e.kind} reference is not available in the current Codex session: ${e.name}`,409);r.has(t)||r.set(t,e)}return[...r.values()]}async searchFiles(e,t){const i=this.requireContext(e),r=await this.client(),o=this.requireMethod(r.startFuzzyFileSearch,"fuzzyFileSearch/sessionStart"),a=this.requireMethod(r.updateFuzzyFileSearch,"fuzzyFileSearch/sessionUpdate"),c=this.requireMethod(r.stopFuzzyFileSearch,"fuzzyFileSearch/sessionStop"),d=e.id;this.activeSearches.get(d)?.stop();const p=`mention_${n.randomUUID().replace(/-/g,"").slice(0,20)}`;let u,l=!1,m=!1,h=[];const g=new Promise(e=>{u=e}),f=e=>{const n=Tr(e.params);var r,o;n.sessionId===p&&("fuzzyFileSearch/sessionUpdated"===e.method&&n.query===t&&Array.isArray(n.files)&&(r=n.files,o=i.cwd,h=r.flatMap(e=>{const t=Tr(e);if("string"!=typeof t.path)return[];const n=s.isAbsolute(t.path)?s.resolve(t.path):s.resolve(o,t.path),i=s.relative(o,n);return!i||".."===i||i.startsWith(`..${s.sep}`)||s.isAbsolute(i)?[]:[{kind:"directory"===String(t.match_type||t.matchType||"file").toLowerCase()?"directory":"file",name:xr(t.file_name)||xr(t.fileName)||s.basename(i),path:i.split(s.sep).join("/")}]}).slice(0,200)),"fuzzyFileSearch/sessionCompleted"===e.method&&(m=!0,u?.()))};r.on("notification",f);const y=()=>{l||(l=!0,r.off("notification",f),c.call(r,p).catch(()=>{}),this.activeSearches.get(d)?.stop===y&&this.activeSearches.delete(d),u?.())};this.activeSearches.set(d,{stop:y});try{return await o.call(r,p,i.cwd),await a.call(r,p,t),await Promise.race([g,new Promise(e=>setTimeout(e,1200))]),Is.parse({sessionId:e.id,cwd:i.cwd,query:t,requestId:p,candidates:h,complete:m})}finally{y()}}async client(){const e=await this.options.readyClient();return this.attachedClient!==e&&(this.detachClient(),this.attachedClient=e,e.on("notification",this.notification)),e}detachClient(){this.attachedClient?.off("notification",this.notification),this.attachedClient=void 0}handleNotification(e){"skills/changed"!==e.method&&"app/list/updated"!==e.method&&"plugin/list/updated"!==e.method||this.cache.clear()}requireContext(e){if("codex"!==e.agent)throw xt("AI_SESSION_MENTIONS_UNSUPPORTED","Mentions are only supported for Codex sessions.",400);if(!e.providerSessionId)throw xt("AI_SESSION_THREAD_NOT_FOUND","AI session is not bound to a Codex thread.",409);if(!e.cwd||!s.isAbsolute(e.cwd))throw xt("AI_SESSION_CWD_NOT_FOUND","AI session has no accessible working directory.",409);return{threadId:e.providerSessionId,cwd:s.resolve(e.cwd)}}requireMethod(e,t){if(!e)throw xt("AI_SESSION_MENTIONS_UNSUPPORTED",`Codex app-server does not support ${t}.`,409);return e}collect(e,t,s,n,i){"fulfilled"===e.status?s.push(...i(e.value)):n.push({category:t,code:"CATALOG_QUERY_FAILED",message:e.reason instanceof Error?e.reason.message:String(e.reason)})}}function Ir(e){return Or(e.data).flatMap(e=>Or(Tr(e).skills)).flatMap(e=>{const t=Tr(e);if(!0!==t.enabled||"string"!=typeof t.name||"string"!=typeof t.path||!s.isAbsolute(t.path))return[];const n=Tr(t.interface);return[{kind:"skill",name:"string"==typeof n.displayName?n.displayName:t.name,description:xr(n.shortDescription)||xr(t.shortDescription)||xr(t.description),path:t.path}]})}function Ar(e){return Or(e.marketplaces).flatMap(e=>Or(Tr(e).plugins)).flatMap(e=>{const t=Tr(e);if(!0!==t.installed||!0!==t.enabled||"DISABLED_BY_ADMIN"===t.availability||"string"!=typeof t.id||"string"!=typeof t.name)return[];const s=Tr(t.interface);return[{kind:"plugin",name:xr(s.displayName)||t.name,description:xr(s.shortDescription)||xr(s.description),path:`plugin://${t.id}`}]})}function br(e){return Or(e.data).flatMap(e=>{const t=Tr(e);return!0!==t.isAccessible||!0!==t.isEnabled||"string"!=typeof t.id||"string"!=typeof t.name?[]:[{kind:"app",name:t.name,description:xr(t.description),path:`app://${t.id}`,icon:xr(t.logoUrl)}]})}function _r(e){return[...new Map(e.map(e=>[`${e.kind}:${e.path}`,e])).values()]}function Tr(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}function Or(e){return Array.isArray(e)?e:[]}function xr(e){return"string"==typeof e&&e.trim()?e.trim():void 0}class Er{registry;id="codex-app-server";agent="codex";binding=new nr;connection;approvalCoordinator;control;discovery;projector;mentions;injectedClient;options;constructor(e,t={},s={}){this.registry=e,"start"in t&&"listLoadedThreadIds"in t?(this.injectedClient=t,this.options={allowSpawn:!0,...s}):this.options=t,this.connection=new Qi({injectedClient:this.injectedClient,createClient:e=>this.createClient(e),onEvent:e=>this.applyProviderEvent(e),onInvalidate:()=>{this.options.onEventSourceClose?.(),this.approvalCoordinator?.resetConnection(),this.projector?.resetConnection(),this.mentions?.resetConnection()}}),this.approvalCoordinator=new Zi({registry:e,currentClient:()=>this.connection.client,readyClient:()=>this.requireReadyClient(),findSession:e=>this.registry.getByProviderSessionId("codex",e),applyThreadSnapshot:e=>this.upsertThread(e,{bindAppSession:!0})}),this.projector=new Sr({registry:e,findSession:e=>this.registry.getByProviderSessionId("codex",e),clearApprovalSession:e=>this.approvalCoordinator.clearSession(e),attachApprovalLifecycle:(e,t)=>this.approvalCoordinator.attachLifecycle(e,t),latestApprovalSummary:e=>this.approvalCoordinator.latestForSession(e)?.summary,onMessageDelta:e=>this.options.onMessageDelta?.(e)}),this.mentions=new wr({readyClient:()=>this.requireReadyClient(),connectionEpoch:()=>this.connection.epoch}),this.control=new ir({registry:e,readyClient:()=>this.requireReadyClient(),validateReferences:(e,t)=>this.mentions.validateReferences(e,t)}),this.discovery=new or({applyThreadSnapshot:e=>this.upsertThread(e,{bindAppSession:!0}),ensureThreadSubscribed:(e,t)=>{const s=this.connection.connectionFor(e);return s?this.connection.ensureThreadSubscribed(s,t):Promise.resolve(void 0)}})}async sync(e=[]){const t=this.binding.socketPath,s=this.binding.update(e);if(!this.injectedClient&&!s&&!this.options.allowSpawn)return void this.stop();if(this.injectedClient||this.connection.client&&t===s?this.injectedClient&&!this.connection.client&&this.connection.configure():this.connection.configure(s),!this.connection.client)return;let n;try{n=await this.connection.ready({respectRetry:!0})}catch{return}if(n&&this.connection.isCurrent(n))try{await this.discovery.sync(n.client,()=>this.connection.isCurrent(n))}catch{this.connection.markUnhealthy(n)}}async refresh(e){await this.sync(e.appSessions)}stop(){this.connection.stop(),this.binding.clear()}async sendMessage(e,t){return this.control.sendMessage(e,t)}async startMessage(e,t){return this.control.startMessage(e,t)}async steerMessage(e,t){return this.control.steerMessage(e,t)}async interrupt(e){return this.control.interrupt(e)}async resolveApproval(e,t){return this.approvalCoordinator.resolve(e,t)}mentionCatalog(e){return this.mentions.catalog(e)}searchMentionFiles(e,t){return this.mentions.searchFiles(e,t)}async executeCommand(e,t){if("codex"!==e.agent||!e.providerSessionId)throw xt("AI_SESSION_COMMAND_UNSUPPORTED","Only Codex app-server sessions support commands.",400);if(!("review"!==t.command&&"compact"!==t.command||"running"!==e.status&&"waiting"!==e.status))throw xt("AI_SESSION_BUSY",`${t.command} is unavailable while the session is busy.`,409);const s=await this.requireReadyClient(),n=e.providerSessionId;if("review"===t.command){if(!s.startReview)throw xt("AI_SESSION_COMMAND_UNSUPPORTED","Codex app-server does not support review.",409);const e=await s.startReview(n);return{command:t.command,turnId:e.turnId}}if("compact"===t.command){if(!s.compactThread)throw xt("AI_SESSION_COMMAND_UNSUPPORTED","Codex app-server does not support compaction.",409);return await s.compactThread(n),{command:t.command}}if("rename"===t.command){if(!s.setThreadName)throw xt("AI_SESSION_COMMAND_UNSUPPORTED","Codex app-server does not support renaming threads.",409);return await s.setThreadName(n,t.argument||""),{command:t.command,value:t.argument}}if(t.argument){if(!s.setThreadGoal)throw xt("AI_SESSION_COMMAND_UNSUPPORTED","Codex app-server does not support goals.",409);return await s.setThreadGoal(n,t.argument),{command:t.command,value:t.argument}}if(!s.getThreadGoal)throw xt("AI_SESSION_COMMAND_UNSUPPORTED","Codex app-server does not support goals.",409);const i=await s.getThreadGoal(n),r=i.goal&&"object"==typeof i.goal?i.goal:void 0;return{command:t.command,value:"string"==typeof r?.objective?r.objective:"No active goal."}}createClient(e){return this.options.createClient?this.options.createClient(e):new Xi(e)}applyProviderEvent(e){if("thread"!==e.type)if("approval-request"!==e.type){if("thread-name"===e.type){const t=this.registry.getByProviderSessionId("codex",e.threadId);return void(t&&this.registry.applyAdapterSnapshot({source:"adapter-snapshot",agent:"codex",appId:t.appId,appSessionId:t.appSessionId,providerSessionId:e.threadId,title:e.name}))}this.projector.apply(e)}else this.approvalCoordinator.register(e.request);else this.upsertThread(e.thread,{bindAppSession:!0})}upsertThread(e,t){const s="string"==typeof e.id?e.id:void 0;if(!s||!0===e.ephemeral)return;const n=t.bindAppSession?this.binding.appSessionIdForThread(s):void 0;this.projector.applyThreadSnapshot(e,{appSessionId:n})}async requireReadyClient(){if(!this.connection.client)throw xt("AI_SESSION_CONTROL_NOT_CONNECTED","Codex app-server is not connected.",503);try{const e=await this.connection.ready();if(e)return e.client}catch(e){if(e&&"object"==typeof e&&"code"in e)throw e;throw xt("AI_SESSION_CONTROL_NOT_CONNECTED",e instanceof Error?e.message:"Codex app-server is not connected.",503)}throw xt("AI_SESSION_CONTROL_NOT_CONNECTED","Codex app-server is not connected.",503)}}class kr{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,appInventory:e.appInventory,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,appInventory:t.appInventory,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",signal:AbortSignal.timeout(5e3),headers:{"content-type":"application/json",authorization:`Bearer ${this.config.registrationToken}`},body:JSON.stringify((i=t,Object.fromEntries(Object.entries(i).filter(([,e])=>void 0!==e))))});var i;const r=await n.json().catch(()=>({}));if(!n.ok)throw new Error(r.error?.message||`Node agent request failed with HTTP ${n.status}`);return r.data||{}}requiredInstanceId(){if(!this.config.instanceId)throw new Error("Instance id is required for controlled mode registration.");return this.config.instanceId}}const zr={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)};function Nr(e){return JSON.stringify([e.instanceId,e.sessionId,e.turnId??null,e.itemId??null])}class Pr{windowMs;clock;emit;pending=new Map;diagnosticState={rawDeltaCount:0,emittedEventCount:0,totalBatchSize:0,maxBatchSize:0,flushReasons:{},totalFirstBatchWaitMs:0,maxFirstBatchWaitMs:0};isClosed=!1;constructor(e){this.emit=e.emit,this.clock=e.clock??zr,this.windowMs=function(e){if(!Number.isFinite(e)||e<20||e>50)throw new RangeError("AI session message delta coalescing window must be between 20ms and 50ms");return e}(e.windowMs??32)}get pendingCount(){return this.pending.size}get closed(){return this.isClosed}push(e){if(this.isClosed)throw new Error("AI session message delta coalescer is closed");this.diagnosticState.rawDeltaCount+=1;const t=Nr(e),s=this.pending.get(t);if(s)return s.chunks.push(e.delta),void(s.lastPayload=e);const n={chunks:[e.delta],firstReceivedAtMs:this.clock.now(),lastPayload:e,timer:void 0};n.timer=this.clock.setTimeout(()=>{this.flushByKey(t,"window")},this.windowMs),this.pending.set(t,n)}flush(e,t="manual"){return this.flushByKey(Nr(e),t)}flushAll(e="manual"){let t=0;for(const s of[...this.pending.keys()])this.flushByKey(s,e)&&(t+=1);return t}close(e="service-close"){return this.isClosed?0:(this.isClosed=!0,this.flushAll(e))}diagnostics(){return{...this.diagnosticState,flushReasons:{...this.diagnosticState.flushReasons}}}flushByKey(e,t){const s=this.pending.get(e);if(!s)return!1;this.pending.delete(e),this.clock.clearTimeout(s.timer);const n=s.chunks.length,i=Math.max(0,this.clock.now()-s.firstReceivedAtMs);return this.diagnosticState.emittedEventCount+=1,this.diagnosticState.totalBatchSize+=n,this.diagnosticState.maxBatchSize=Math.max(this.diagnosticState.maxBatchSize,n),this.diagnosticState.flushReasons[t]=(this.diagnosticState.flushReasons[t]??0)+1,this.diagnosticState.totalFirstBatchWaitMs+=i,this.diagnosticState.maxFirstBatchWaitMs=Math.max(this.diagnosticState.maxFirstBatchWaitMs,i),this.emit({...s.lastPayload,delta:s.chunks.join("")}),!0}}function Rr(e){return e.startsWith("ai-session.")||e.startsWith("ai.session.")?"ai.sessions":e.startsWith("app-session.")?"app.sessions":e.startsWith("app.management")?"apps":e.startsWith("trigger.")?"triggers":e.startsWith("instance.")?"instances":e.startsWith("node.")?"nodes":e.startsWith("project.")?"projects":e.startsWith("model.")?"models":e.startsWith("image.")?"images":"system"}const Cr=l.z.enum(["ai.sessions","app.sessions"]),Dr=l.z.object({topic:Cr,instanceId:l.z.string().trim().min(1).max(160),streamId:l.z.string().trim().min(1).max(240),latestRevision:l.z.number().int().min(0),earliestRetainedRevision:l.z.number().int().min(0)}).strict();l.z.object({protocolVersion:l.z.literal(1),streams:l.z.array(Dr)}).strict();class Mr{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,i=JSON.stringify(s);for(const t of this.clients)t.readyState===t.OPEN&&Fr(t.topics,n,e)&&t.send(i);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:Rr(e),createdAt:(new Date).toISOString(),payload:t}}}function Fr(e,t,s){return!e||e.has("*")||e.has(t)||e.has(s)}const jr="2026-07-25",Lr=l.z.string(),$r=l.z.string().trim().min(1).max(120).regex(/^[a-zA-Z0-9][a-zA-Z0-9_.:-]*$/),Hr=l.z.string().datetime(),Ur=l.z.record(l.z.string(),l.z.string()).default({}),qr=l.z.record(l.z.string(),l.z.string()).default({}),Br=/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$/,Kr=/^sha256:([a-fA-F0-9]{64})$/,Vr=/^(?:localhost|[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?)(?::[1-9][0-9]{0,4})?$/,Gr=/^[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*$/,Wr=l.z.string().trim().min(1).max(512).transform((e,t)=>{try{return function(e){const t=e.trim();if(!t||t.length>512||t.includes("://")||/\s/.test(t))throw new Error("Docker image reference must not contain a URL scheme or whitespace.");const s=t.indexOf("@");if(-1!==s&&s!==t.lastIndexOf("@"))throw new Error("Docker image reference contains more than one digest separator.");const n=-1===s?void 0:t.slice(s+1),i=-1===s?t:t.slice(0,s),r=n?Kr.exec(n):void 0;if(n&&!r)throw new Error("Docker image digest must use sha256 followed by 64 hexadecimal characters.");const o=i.lastIndexOf("/"),a=i.lastIndexOf(":"),c=a>o,d=c?i.slice(a+1):void 0,p=c?i.slice(0,a):i;if(d&&!Br.test(d))throw new Error("Docker image tag is invalid.");if(!d&&!r)throw new Error("Docker image reference must include an explicit tag or sha256 digest.");const u=p.split("/");if(!u.length||u.some(e=>!e))throw new Error("Docker image repository path is invalid.");const l=u.length>1&&(u[0].includes(".")||u[0].includes(":")||"localhost"===u[0]),m=l?u.slice(1):u;if(l&&!Vr.test(u[0].toLowerCase()))throw new Error("Docker image registry host or port is invalid.");if(!m.length||m.some(e=>!Gr.test(e)))throw new Error("Docker image repository names must be lowercase and use valid separators.");const h=u.map((e,t)=>l&&0===t?e.toLowerCase():e).join("/"),g=r?`sha256:${r[1].toLowerCase()}`:void 0;return`${h}${d?`:${d}`:""}${g?`@${g}`:""}`}(e)}catch(e){return t.addIssue({code:"custom",message:e instanceof Error?e.message:String(e)}),l.z.NEVER}}),Yr=l.z.string().trim().transform((e,t)=>{const s=Kr.exec(e);return s?`sha256:${s[1].toLowerCase()}`:(t.addIssue({code:"custom",message:"Docker image digest must use sha256 followed by 64 hexadecimal characters."}),l.z.NEVER)}),Jr=l.z.object({codexModelHash:$r.nullable().optional(),claudeModelHash:$r.nullable().optional()}).strict().default({}),Xr=l.z.object({id:$r,name:l.z.string().trim().min(1).max(120),kind:l.z.enum(["tty","gui","web"]),source:l.z.enum(["builtin","custom"]),availability:l.z.enum(["available","missing-dependency"]),capabilities:l.z.object({automation:l.z.enum(["cdp"]).optional(),supportsCwdSelection:l.z.boolean().default(!1)}).strict().default({supportsCwdSelection:!1}),diagnosticCode:l.z.enum(["APP_EXECUTABLE_NOT_FOUND"]).optional()}).strict(),Qr=l.z.object({code:l.z.enum(["APP_CATALOG_INVALID"]),message:l.z.string().trim().min(1).max(500)}).strict(),Zr=l.z.object({items:l.z.array(Xr).max(256),observedAt:Hr,issues:l.z.array(Qr).max(32).default([])}).strict(),eo=l.z.enum(["linux","darwin","win32","freebsd","openbsd","aix","sunos","unknown"]),to=l.z.enum(["x64","arm64","arm","ia32","ppc64","s390x","riscv64","unknown"]),so=l.z.enum(["apt","dnf","brew","npm"]),no=l.z.enum(["user","passwordless-sudo","root"]),io=l.z.object({platform:eo,arch:to,installers:l.z.array(so).max(8),privilege:no,installerAccess:l.z.object({npmGlobalWritable:l.z.boolean().optional()}).strict().optional()}).strict(),ro=l.z.enum(["installed","not-installed","broken","unsupported"]),oo=l.z.enum(["recipe","bundled","external","none"]),ao=l.z.object({code:l.z.enum(["BUNDLED","EXTERNALLY_MANAGED","ALREADY_INSTALLED","NOT_INSTALLED","UNSUPPORTED_PLATFORM","INSTALLER_UNAVAILABLE","INSTALLER_NOT_WRITABLE","INSUFFICIENT_PRIVILEGE","OPERATION_IN_PROGRESS"]),message:l.z.string().trim().min(1).max(500)}).strict(),co=l.z.object({id:$r,name:l.z.string().trim().min(1).max(120),kind:l.z.enum(["tty","gui","web"]),description:l.z.string().trim().max(500).optional(),state:ro,managementSource:oo,version:l.z.string().trim().max(120).optional(),canInstall:l.z.boolean(),canUninstall:l.z.boolean(),installReason:ao.optional(),uninstallReason:ao.optional(),activeJobId:$r.optional()}).strict(),po=l.z.enum(["install","uninstall"]),uo=l.z.enum(["queued","running","succeeded","failed","cancelled","interrupted"]),lo=l.z.object({current:l.z.number().finite().nonnegative().optional(),total:l.z.number().finite().positive().optional(),unit:l.z.string().trim().min(1).max(40).optional()}).strict().refine(e=>void 0===e.total||void 0===e.current||e.current<=e.total,{message:"Progress current must not exceed total.",path:["current"]}),mo=l.z.object({executable:l.z.string().trim().min(1).max(4096),args:l.z.array(l.z.string().max(4096)).max(128)}).strict(),ho=l.z.object({code:l.z.string().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),message:l.z.string().trim().min(1).max(4096),retryable:l.z.boolean(),sessionIds:l.z.array($r).max(64).optional()}).strict(),go=l.z.object({id:$r,requestId:$r.optional(),appId:$r,operation:po,state:uo,phase:l.z.string().trim().min(1).max(120).optional(),progress:lo.optional(),command:mo.optional(),logTail:l.z.string().max(32768).optional(),logTruncated:l.z.boolean().optional(),error:ho.optional(),requestedAt:Hr,startedAt:Hr.optional(),finishedAt:Hr.optional(),updatedAt:Hr}).strict(),fo=l.z.object({streamId:$r,sequence:l.z.number().int().nonnegative(),capabilities:io,apps:l.z.array(co).max(256),activeJobs:l.z.array(go).max(256),recentJobs:l.z.array(go).max(256),observedAt:Hr}).strict(),yo=l.z.object({requestId:$r.optional()}).strict();l.z.object({job:go}).strict(),l.z.object({type:l.z.literal("app-management"),streamId:$r,sequence:l.z.number().int().nonnegative(),observedAt:Hr,job:go.optional(),snapshot:fo.optional()}).strict().refine(e=>void 0!==e.job||void 0!==e.snapshot,{message:"An app management event requires a job or snapshot."});const vo=l.z.object({component:l.z.enum(["control-plane","node-agent","controlled-instance"]),packageName:l.z.string().trim().max(160).optional(),packageVersion:l.z.string().trim().max(80).optional(),protocolVersion:Lr.optional(),buildId:l.z.string().trim().max(160).optional(),builtAt:l.z.string().trim().max(120).optional(),gitCommit:l.z.string().trim().max(120).optional(),imageRef:l.z.string().trim().max(512).optional(),imageDigest:l.z.string().trim().max(240).optional()}).strict(),So=l.z.enum(["stable","beta","alpha"]),wo=l.z.discriminatedUnion("component",[l.z.object({component:l.z.literal("node-agent")}).strict(),l.z.object({component:l.z.literal("controlled-instance"),instanceId:$r}).strict()]);l.z.object({target:wo,channel:So.default("stable")}).strict(),l.z.object({target:wo,source:l.z.enum(["npm","docker-registry"]),channel:So,currentVersion:l.z.string().trim().max(240).optional(),availableVersion:l.z.string().trim().min(1).max(240),artifactRef:l.z.string().trim().min(1).max(512).optional(),updateAvailable:l.z.boolean(),supported:l.z.boolean().default(!0),reason:l.z.string().trim().max(2048).optional(),checkedAt:Hr}).strict(),l.z.object({id:$r,nodeId:$r,target:wo,source:l.z.enum(["npm","docker-registry"]),channel:So,fromVersion:l.z.string().trim().max(240).optional(),toVersion:l.z.string().trim().min(1).max(240),artifactRef:l.z.string().trim().min(1).max(512).optional(),status:l.z.enum(["queued","updating","restarting","succeeded","failed"]),error:l.z.string().trim().max(4096).optional(),startedAt:Hr.optional(),completedAt:Hr.optional(),createdAt:Hr,updatedAt:Hr}).strict();const Io=l.z.object({type:l.z.enum(["branch","tag","commit"]),name:l.z.string().trim().min(1).max(240).optional(),commit:l.z.string().trim().max(80).optional()}).strict(),Ao=l.z.object({type:l.z.enum(["none","ssh-key","https-token"]).default("none"),secretId:l.z.string().trim().min(1).max(120).optional()}).strict(),bo=l.z.object({depth:l.z.number().int().positive().max(1e5).optional(),submodules:l.z.boolean().default(!1),lfs:l.z.boolean().default(!1),subdirectory:l.z.string().trim().max(240).default("")}).strict();l.z.object({id:$r,name:l.z.string().trim().min(1).max(160),url:l.z.string().trim().min(1).max(2048),provider:l.z.string().trim().max(80).optional(),ref:Io.default({type:"branch",name:"main"}),auth:Ao.default({type:"none"}),clone:bo.default({submodules:!1,lfs:!1,subdirectory:""}),defaultImageId:$r.optional(),labels:Ur,createdAt:Hr,updatedAt:Hr}).strict(),l.z.object({id:$r,nodeId:$r,name:l.z.string().trim().min(1).max(160),path:l.z.string().trim().min(1).max(4096),defaultImageId:$r.optional(),labels:Ur,createdAt:Hr,updatedAt:Hr}).strict();const _o=l.z.discriminatedUnion("type",[l.z.object({type:l.z.literal("git-repository"),repositoryId:$r.optional(),url:l.z.string().trim().min(1).max(2048),provider:l.z.string().trim().max(80).optional(),ref:Io.default({type:"branch",name:"main"}),auth:Ao.default({type:"none"}),clone:bo.default({submodules:!1,lfs:!1,subdirectory:""})}).strict(),l.z.object({type:l.z.literal("git-template"),url:l.z.string().trim().min(1).max(2048),templateId:l.z.string().trim().min(1).max(120).optional(),ref:Io.default({type:"branch",name:"main"}),auth:Ao.default({type:"none"}),clone:bo.default({submodules:!1,lfs:!1,subdirectory:""})}).strict(),l.z.object({type:l.z.literal("local-folder"),localFolderId:$r.optional(),path:l.z.string().trim().min(1).max(4096),ownerNodeId:$r.optional()}).strict()]),To=l.z.object({mode:l.z.enum(["local-bind","git-clone","empty-volume","persistent-volume"]),path:l.z.string().trim().min(1).max(4096).default("/workspace"),volumeName:l.z.string().trim().max(240).optional(),readOnly:l.z.boolean().default(!1)}).strict(),Oo=l.z.enum(["codex","claude"]);l.z.object({id:$r,name:l.z.string().trim().min(1).max(160),source:_o,defaultImageId:$r.optional(),defaultNodeId:$r.optional(),defaultRuntimeId:$r.optional(),workspacePolicy:To,labels:Ur,createdAt:Hr,updatedAt:Hr}).strict();const xo=l.z.object({id:$r,name:l.z.string().trim().min(1).max(160),endpoint:l.z.string().trim().min(1).max(2048),key:l.z.string().trim().min(1).max(4096),model:l.z.string().trim().min(1).max(240),app:Oo,enabled:l.z.boolean().default(!0),order:l.z.number().int().min(0).max(1e6).default(0),labels:Ur,createdAt:Hr,updatedAt:Hr}).strict(),Eo=xo.omit({key:!0}).extend({keyPreview:l.z.string().trim().min(1).max(160),keySet:l.z.boolean()}).strict();Eo.extend({referenceCount:l.z.number().int().min(0)}).strict(),l.z.object({instanceId:$r,codexModelHash:$r.optional(),claudeModelHash:$r.optional(),updatedAt:Hr}).strict();const ko=l.z.discriminatedUnion("type",[l.z.object({type:l.z.literal("control-plane"),name:xo.shape.name,enabled:xo.shape.enabled,order:xo.shape.order}).strict(),l.z.object({type:l.z.literal("node"),nodeId:$r,name:xo.shape.name,enabled:xo.shape.enabled,order:xo.shape.order,referenceCount:l.z.number().int().min(0)}).strict()]),zo=l.z.object({id:$r,model:Eo,locations:l.z.array(ko).min(1),referenceCount:l.z.number().int().min(0).default(0)}).strict(),No=l.z.object({nodeId:$r,code:l.z.string().trim().min(1).max(120),message:l.z.string().trim().min(1).max(2e3)}).strict();l.z.object({models:l.z.array(zo),nodeDiagnostics:l.z.array(No).default([]),updatedAt:Hr}).strict(),xo.omit({id:!0,createdAt:!0,updatedAt:!0}).strict().partial().strict(),l.z.object({modelSelection:Jr,codexModelHash:$r.optional(),claudeModelHash:$r.optional()}).strict();const Po=l.z.object({id:$r,name:l.z.string().trim().min(1).max(160),reference:Wr,pullPolicy:l.z.literal("if-not-present").default("if-not-present"),capabilities:l.z.array(l.z.string().trim().min(1).max(80)).default([]),optionalApps:l.z.array(l.z.string().trim().min(1).max(120)).default([]),defaultEnv:qr,labels:Ur,createdAt:Hr,updatedAt:Hr}).strict(),Ro=Po.omit({reference:!0}).extend({requestedReference:Wr,resolvedDigest:Yr.optional(),resolvedReference:Wr.optional()}).strict(),Co=l.z.object({phase:l.z.enum(["checking-image","pulling-image","resolving-image","ready","failed"]),requestedReference:Wr,generation:l.z.number().int().nonnegative().default(0),error:l.z.string().trim().max(4096).optional(),startedAt:Hr,updatedAt:Hr}).strict();l.z.object({id:$r,name:l.z.string().trim().min(1).max(160),connectionMode:l.z.enum(["local-ipc","local-loopback","direct-http","reverse-wss"]).default("direct-http"),auth:l.z.object({mode:l.z.enum(["local-static-key","paired-hmac"]).default("local-static-key"),keyId:$r.optional(),secret:l.z.string().trim().max(4096).optional(),pairedAt:Hr.optional(),pairing:l.z.object({status:l.z.enum(["pending","paired","expired"]).default("pending"),joinToken:l.z.string().trim().max(4096).optional(),expiresAt:Hr.optional()}).strict().optional()}).strict().default({mode:"local-static-key"}),endpoint:l.z.string().trim().max(2048).optional(),controlEndpoint:l.z.string().trim().max(2048).optional(),containerEndpoint:l.z.string().trim().max(2048).optional(),publicWebBase:l.z.string().trim().max(2048).optional(),status:l.z.enum(["unknown","online","offline","degraded"]).default("unknown"),health:l.z.enum(["unknown","ok","degraded","failed"]).default("unknown"),capabilities:l.z.record(l.z.string(),l.z.unknown()).default({}),appInventory:Zr.optional(),labels:Ur,lastSeenAt:Hr.optional(),createdAt:Hr,updatedAt:Hr}).strict(),l.z.object({id:$r,nodeId:$r,name:l.z.string().trim().min(1).max(160),type:l.z.enum(["docker","kubernetes","local"]),status:l.z.enum(["unknown","online","offline","degraded"]).default("unknown"),accessStrategy:l.z.enum(["node-proxy","direct-port","kubernetes-ingress","kubernetes-port-forward"]).default("node-proxy"),capabilities:l.z.record(l.z.string(),l.z.unknown()).default({}),labels:Ur,createdAt:Hr,updatedAt:Hr}).strict(),l.z.object({instanceId:$r,runtimeKind:l.z.literal("docker"),state:l.z.enum(["pending","available","stopped","unavailable"]),sampledAt:Hr,cpu:l.z.object({usagePercent:l.z.number().nonnegative()}).strict().optional(),memory:l.z.object({usageBytes:l.z.number().nonnegative(),limitBytes:l.z.number().nonnegative().optional(),usagePercent:l.z.number().nonnegative().optional()}).strict().optional(),network:l.z.object({rxBytes:l.z.number().nonnegative(),txBytes:l.z.number().nonnegative()}).strict().optional(),blockIo:l.z.object({readBytes:l.z.number().nonnegative(),writeBytes:l.z.number().nonnegative()}).strict().optional(),pids:l.z.number().int().nonnegative().optional(),error:l.z.string().trim().max(2048).optional()}).strict(),l.z.object({ok:l.z.boolean().optional(),role:l.z.string().optional(),nodeId:$r.optional()}).passthrough(),l.z.object({bindScope:l.z.enum(["loopback","all-ipv4"]),port:l.z.number().int().min(1).max(65535)}).strict().extend({host:l.z.enum(["127.0.0.1","0.0.0.0"]),status:l.z.enum(["listening","error"]),source:l.z.enum(["bootstrap","persisted"]),error:l.z.string().trim().max(2048).optional()}).strict(),l.z.object({nodeId:$r,joinToken:l.z.string().trim().min(1),expiresAt:Hr}).passthrough(),l.z.object({id:$r,keyId:$r,url:l.z.string().trim().min(1).max(2048).optional(),name:l.z.string().trim().min(1).max(160).optional(),pairedAt:Hr,updatedAt:Hr.optional(),active:l.z.boolean().optional(),current:l.z.boolean().optional()}).passthrough(),l.z.object({remote:l.z.object({id:$r,url:l.z.string().trim().min(1).max(2048).optional(),keyId:$r,pairedAt:Hr,active:l.z.boolean()}).passthrough(),tunnel:l.z.object({status:l.z.enum(["disabled","saved","connecting","connected","failed"]),error:l.z.string().trim().max(2048).optional()}).passthrough()}).passthrough(),l.z.object({deleted:l.z.boolean().optional()}).passthrough();const Do=l.z.object({repository:l.z.string().trim().optional(),tag:l.z.string().trim().optional(),id:l.z.string().trim(),createdSince:l.z.string().trim().optional(),size:l.z.string().trim().optional(),reference:l.z.string().trim().min(1),repoDigests:l.z.array(l.z.string().trim().min(1).max(512)).default([])}).passthrough();l.z.object({image:Po,status:l.z.enum(["available","pull-required","unknown"]),localImage:Do.optional(),error:l.z.string().trim().max(2048).optional()}).strict();const Mo=l.z.lazy(()=>l.z.object({name:l.z.string().trim().min(1),path:l.z.string().trim().min(1).max(4096),children:l.z.array(Mo)}).passthrough());l.z.object({status:l.z.number().int().min(100).max(599).optional(),headers:l.z.record(l.z.string(),l.z.string()).optional(),bodyBase64:l.z.string().optional()}).passthrough();const Fo=l.z.object({strategy:l.z.enum(["node-proxy","direct-port","kubernetes-ingress","kubernetes-port-forward"]).default("node-proxy"),web:l.z.string().trim().max(2048).optional(),api:l.z.string().trim().max(2048).optional(),vnc:l.z.string().trim().max(2048).optional(),tty:l.z.string().trim().max(2048).optional(),logs:l.z.string().trim().max(2048).optional(),status:l.z.enum(["unknown","reachable","endpoint-unreachable"]).default("unknown")}).strict(),jo=l.z.object({strategy:l.z.enum(["control-plane-proxy","direct-port","node-proxy","kubernetes-ingress","kubernetes-port-forward"]).default("control-plane-proxy"),web:l.z.string().trim().max(2048).optional(),api:l.z.string().trim().max(2048).optional(),ws:l.z.string().trim().max(2048).optional(),status:l.z.enum(["unknown","reachable","endpoint-unreachable"]).default("unknown")}).strict().default({strategy:"control-plane-proxy",status:"unknown"}),Lo=l.z.object({mode:l.z.enum(["local-bind","git-clone","empty-volume","persistent-volume"]).optional(),status:l.z.enum(["unknown","pending","ready","failed"]).default("unknown"),path:l.z.string().trim().max(4096).optional(),resolvedCommit:l.z.string().trim().max(120).optional(),error:l.z.string().trim().max(2048).optional()}).passthrough(),$o=l.z.object({id:$r,name:l.z.string().trim().min(1).max(160),projectId:$r.optional(),source:_o,sourceSnapshot:l.z.record(l.z.string(),l.z.unknown()).default({}),modelSelection:Jr,nodeId:$r,runtimeId:$r,imageId:$r.optional(),imageSnapshot:Ro.optional(),imageProvisioning:Co.optional(),status:l.z.enum(["created","provisioning","starting","registering","registered","running","stopping","stopped","failed","unhealthy"]).default("created"),health:l.z.enum(["unknown","ok","degraded","failed"]).default("unknown"),connectionStatus:l.z.enum(["unknown","online","offline","endpoint-unreachable"]).default("unknown"),agentStatus:l.z.enum(["unknown","online","offline"]).default("unknown"),targetStatus:l.z.enum(["unknown","reachable","endpoint-unreachable"]).default("unknown"),uiAccessStatus:l.z.enum(["unknown","reachable","endpoint-unreachable"]).default("unknown"),controlMode:l.z.enum(["standalone","controlled"]).default("controlled"),protocolVersion:Lr.optional(),instanceVersion:l.z.string().trim().max(80).optional(),build:vo.optional(),capabilities:l.z.record(l.z.string(),l.z.unknown()).default({}),appInventory:Zr.optional(),config:l.z.object({autoImportAgentConfigs:l.z.boolean().default(!0)}).strict().default({autoImportAgentConfigs:!0}),workspace:Lo.default({status:"unknown"}),target:Fo.default({strategy:"direct-port",status:"unknown"}),access:jo,apps:l.z.object({runningCount:l.z.number().int().min(0).default(0),problemCount:l.z.number().int().min(0).default(0),updatedAt:Hr.optional(),revision:l.z.number().int().min(0).optional()}).strict().default({runningCount:0,problemCount:0}),aiSessions:Hs.default(()=>({runningCount:0,waitingCount:0,staleCount:0,sessions:[],updatedAt:(new Date).toISOString()})),triggers:l.z.object({enabledCount:l.z.number().int().min(0).default(0),runningCount:l.z.number().int().min(0).default(0),errorCount:l.z.number().int().min(0).default(0),configs:l.z.array(l.z.object({configHash:l.z.string().trim().min(1),config:$,deployments:l.z.array(U).default([]),runtime:l.z.array(q).default([])}).strict()).default([]),recentRuns:l.z.array(B).default([])}).strict().optional(),runtime:l.z.object({kind:l.z.string().trim().max(80).optional(),containerName:l.z.string().trim().max(240).optional(),containerId:l.z.string().trim().max(240).optional(),workspacePath:l.z.string().trim().max(4096).optional(),pid:l.z.number().int().positive().optional(),port:l.z.number().int().positive().max(65535).optional(),labels:l.z.record(l.z.string(),l.z.string()).default({})}).strict().default({labels:{}}),registrationToken:l.z.string().trim().min(1).max(240).optional(),lastHeartbeatAt:Hr.optional(),createdAt:Hr,updatedAt:Hr}).strict();l.z.object({instanceId:$r.optional(),name:l.z.string().trim().min(1).max(160),projectId:$r.optional(),source:_o.optional(),nodeId:$r.optional(),runtimeId:$r.optional(),imageId:$r.optional(),instanceVersion:l.z.string().trim().max(80).optional(),protocolVersion:Lr,build:vo.optional(),controlMode:l.z.enum(["standalone","controlled"]).default("controlled"),capabilities:l.z.record(l.z.string(),l.z.unknown()).default({}),appInventory:Zr.optional(),target:Fo.default({strategy:"direct-port",status:"unknown"}),workspace:Lo.default({status:"unknown"}),registrationToken:l.z.string().trim().max(240).optional()}).strict().superRefine((e,t)=>{e.protocolVersion!==jr||e.appInventory||t.addIssue({code:"custom",path:["appInventory"],message:"Current protocol register payload requires appInventory."})}),l.z.object({status:$o.shape.status.optional(),health:$o.shape.health.optional(),protocolVersion:Lr,build:vo.optional(),capabilities:$o.shape.capabilities.optional(),appInventory:Zr.optional(),apps:$o.shape.apps.optional(),aiSessions:$o.shape.aiSessions.optional(),triggers:$o.shape.triggers.optional(),workspace:Lo.optional(),target:Fo.partial().optional()}).strict().superRefine((e,t)=>{e.protocolVersion!==jr||e.appInventory||t.addIssue({code:"custom",path:["appInventory"],message:"Current protocol heartbeat payload requires appInventory."})});const Ho=l.z.enum(["web","telegram","wechat","dingding"]);l.z.object({id:$r,channel:Ho,name:l.z.string().trim().min(1).max(160),enabled:l.z.boolean().default(!1),token:l.z.string().trim().max(4096).optional(),defaultChatId:l.z.string().trim().max(240).optional(),allowedUserIds:l.z.array(l.z.string().trim().min(1).max(240)).default([]),pollIntervalMs:l.z.number().int().positive().max(6e4).default(3e3),settings:l.z.record(l.z.string(),l.z.unknown()).default({}),createdAt:Hr,updatedAt:Hr}).strict(),l.z.object({id:$r,channel:Ho,bridgeId:$r.optional(),chatSessionId:l.z.string().trim().min(1).max(240),userId:l.z.string().trim().max(240).optional(),activeProjectId:$r.optional(),activeInstanceId:$r.optional(),activeAiSessionId:l.z.string().trim().min(1).max(120).optional(),lastUsedAt:Hr,createdAt:Hr,updatedAt:Hr}).strict(),l.z.object({source:l.z.object({type:l.z.literal("chat-gateway").default("chat-gateway"),channel:Ho,bridgeId:$r.optional(),chatSessionId:l.z.string().trim().min(1).max(240),userId:l.z.string().trim().max(240).optional()}).strict(),message:l.z.object({text:l.z.string().trim().max(2e4).default(""),attachments:l.z.array(os).max(6).default([])}).strict().superRefine((e,t)=>{e.attachments.reduce((e,t)=>e+t.size,0)>Yt&&t.addIssue({code:l.z.ZodIssueCode.custom,path:["attachments"],message:"Images must be 41943040 bytes or less in total."})}),target:l.z.object({instanceId:$r,aiSessionId:l.z.string().trim().min(1).max(120)}).strict().optional()}).strict(),l.z.object({id:$r,instanceId:$r,projectId:$r.optional(),aiSessionId:l.z.string().trim().min(1).max(120),providerSessionId:l.z.string().trim().max(240).optional(),result:l.z.string().default(""),timeoutMs:l.z.number().positive().optional(),source:l.z.string().trim().max(120).optional(),kind:l.z.enum(["task","approval"]).default("task"),status:l.z.enum(["pending","unreachable"]).default("pending"),error:l.z.string().trim().max(2048).optional(),lastSeenAt:Hr}).strict();const Uo=536870912,qo=/^[a-zA-Z0-9][a-zA-Z0-9+._:@/-]{0,199}$/,Bo=/^(?:@[a-z0-9][a-z0-9._-]{0,99}\/)?[a-z0-9][a-z0-9._-]{0,99}$/i;class Ko extends Error{code;retryable;constructor(e,t,s=!1){super(t),this.name="AppRecipeExecutionError",this.code=e,this.retryable=s}}function Vo(e){return e.length<=8192?e:e.slice(e.length-8192)}function Go(e,t={}){return new Promise((s,n)=>{const i="win32"!==process.platform,r=m.spawn(e.executable,e.args,{shell:!1,detached:i,stdio:["ignore","pipe","pipe"]});let o,a="",c="",d=!1;r.stdout.on("data",e=>{const s=String(e);a=Vo(a+s),t.onOutput?.("stdout",s)}),r.stderr.on("data",e=>{const s=String(e);c=Vo(c+s),t.onOutput?.("stderr",s)});const p=setTimeout(()=>{d=!0,Wo(r,i,"SIGTERM"),o=setTimeout(()=>Wo(r,i,"SIGKILL"),e.terminationGraceMs??5e3),o.unref?.()},e.timeoutMs);p.unref?.(),r.once("error",e=>{clearTimeout(p),o&&clearTimeout(o),n(new Ko("command_start_failed",e.message,!0))}),r.once("close",t=>{clearTimeout(p),o&&clearTimeout(o),d?n(new Ko("command_timeout",`App installer command timed out after ${e.timeoutMs}ms.`,!0)):s({exitCode:t??-1,stdout:a,stderr:c})})})}function Wo(e,t,s){if(e.pid)try{process.kill(t?-e.pid:e.pid,s)}catch{try{e.kill(s)}catch{}}}function Yo(e){const t=e.replaceAll("\\","/").replace(/^(?:\.\/)+/,"");if(!t||t.startsWith("/")||/^[a-zA-Z]:\//.test(t))return;const s=t.split("/").filter(e=>e&&"."!==e);return s.length&&!s.some(e=>".."===e)?s.join("/"):void 0}function Jo(e){const t=[];for(const s of e){const e=Yo(s.path);if(!e||"symlink"===s.type||"hardlink"===s.type)throw new Ko("unsafe_archive","The built-in artifact contains an unsafe path or link.");t.push(e)}return t}function Xo(e,t){if(s.isAbsolute(t))throw new Ko("invalid_builtin_recipe","Archive installRoot must be relative to the managed app root.");const n=s.resolve(e),i=s.resolve(n,t);if(i===n||!i.startsWith(`${n}${s.sep}`))throw new Ko("invalid_builtin_recipe","Archive installRoot escapes the managed app root.");return i}function Qo(e,t){return s.join(e,"manifests",`${t}.json`)}function Zo(e,n=e){const i=[];for(const r of t.readdirSync(n,{withFileTypes:!0})){const o=s.join(n,r.name),a=s.relative(e,o),c=t.lstatSync(o);if(c.isSymbolicLink())throw new Ko("unsafe_archive","Extracted archive contains a symbolic link.");if(c.isDirectory())i.push(...Zo(e,o));else{if(!c.isFile())throw new Ko("unsafe_archive","Extracted archive contains an unsupported file type.");i.push(a)}}return i}function ea(){const e=new Set;let t=0,s=0;return n=>{if(n.meta)return!0;const i=function(e){return["File","OldFile","ContiguousFile"].includes(e.type)?"file":["Directory","GNUDumpDir"].includes(e.type)?"directory":"SymbolicLink"===e.type?"symlink":"Link"===e.type?"hardlink":void 0}(n);if(!i)throw new Ko("unsafe_archive",`Archive contains unsupported entry type ${n.type}.`);if(n.path.includes("\\")||n.path.includes("\0"))throw new Ko("unsafe_archive","The built-in artifact contains an unsafe path.");const[r]=Jo([{path:n.path,type:i}]);if(e.has(r))throw new Ko("unsafe_archive",`Archive contains duplicate path: ${r}`);if(e.add(r),t+=1,t>1e5)throw new Ko("archive_too_large","Artifact contains too many entries.");if(!Number.isSafeInteger(n.size)||n.size<0)throw new Ko("unsafe_archive","Artifact contains an invalid entry size.");if(s+=n.size,s>2147483648)throw new Ko("archive_too_large","Extracted artifact exceeds the managed size limit.");return!0}}async function ta(e,s,n,i){if("zip"===e.format)throw new Ko("unsupported_archive_format","ZIP managed artifacts are not enabled by this controlled instance.");if("tar.gz"===e.format){const e=t.createReadStream(s).pipe(I.createGunzip()),r=setTimeout(()=>e.destroy(new Error(`Archive decompression timed out after ${i}ms.`)),i);r.unref?.();try{await sa(e,n)}finally{clearTimeout(r)}return}const r=m.spawn("xz",["-dc","--",s],{shell:!1,stdio:["ignore","pipe","pipe"]});let o="",a=!1;r.stderr.on("data",e=>{o=Vo(o+String(e))});const c=new Promise((e,t)=>{r.once("error",t),r.once("close",s=>0===s?e():t(new Error(a?`Archive decompression timed out after ${i}ms.`:o||`xz exited with code ${s}`)))}),d=setTimeout(()=>{a=!0,r.kill("SIGKILL")},i);d.unref?.();try{await Promise.all([sa(r.stdout,n),c])}catch(e){throw null===r.exitCode&&r.kill("SIGKILL"),e}finally{clearTimeout(d)}}async function sa(e,t){let s,n=()=>{};const i=new Promise(i=>{const r=()=>{n(),i()},o=t=>{s=t,function(e,t){const s=e.destroy;"function"==typeof s&&s.call(e,t instanceof Error?t:new Error(String(t)))}(e,t),r()};n=()=>{t.off("error",o),t.off("close",r),t.off("finish",r),t.off("end",r)},t.once("error",o),t.once("close",r),t.once("finish",r),t.once("end",r)});try{for await(const n of e){if(s)throw s;t.write(n)||await na(t)}if(s)throw s;if(t.end(),await i,s)throw s}catch(e){throw function(e,t){const s=e.abort;"function"==typeof s&&s.call(e,t instanceof Error?t:new Error(String(t)))}(t,e),e}finally{n()}}function na(e){return new Promise((t,s)=>{const n=()=>{e.off("drain",i),e.off("error",r),e.off("close",o)},i=()=>{n(),t()},r=e=>{n(),s(e)},o=()=>{n(),s(new Error("Archive parser closed before accepting the complete stream."))};e.once("drain",i),e.once("error",r),e.once("close",o)})}async function ia(e,i,r){const o=Xo(r.installBaseDir,e.installRoot);if(t.existsSync(o))throw new Ko("install_target_exists","The managed install target already exists.");t.mkdirSync(s.dirname(o),{recursive:!0});const a=t.mkdtempSync(s.join(s.dirname(o),`.install-${i.appId}-`)),c=s.join(a,`artifact.${e.format.replace(".","-")}`),d=s.join(a,"root");try{i.onPhase?.("download"),await async function(e,s,i,r,o){if(!e.startsWith("https://")||!/^[a-f0-9]{64}$/i.test(i))throw new Ko("invalid_builtin_recipe","Archive recipes require HTTPS and a SHA-256 checksum.");const a=await r(e,{redirect:"follow"});if(!a.ok||!a.body)throw new Ko("download_failed",`Artifact download failed with HTTP ${a.status}.`,!0);const c=Number(a.headers.get("content-length"));if(Number.isFinite(c)&&c>Uo)throw new Ko("artifact_too_large","Artifact exceeds the managed download limit.");const d=t.openSync(s,"wx",384),p=n.createHash("sha256");let u=0;try{for await(const e of a.body){if(u+=e.byteLength,u>Uo)throw new Ko("artifact_too_large","Artifact exceeds the managed download limit.");t.writeSync(d,e),p.update(e),o?.("download",{current:u,...Number.isFinite(c)&&c>0?{total:c}:{},unit:"bytes"})}}finally{t.closeSync(d)}if(p.digest("hex")!==i.toLowerCase())throw new Ko("checksum_mismatch","Artifact checksum does not match the built-in recipe.")}(e.url,c,e.sha256,r.fetcher,i.onPhase),i.onPhase?.("inspect");try{await async function(e,t){const s=ea(),n=A.list({strict:!0,maxMetaEntrySize:1048576,filter:(e,t)=>s(t)});await ta(e,t,n,6e4)}(e,c)}catch(e){if(e instanceof Ko)throw e;throw new Ko("archive_inspection_failed",e instanceof Error?e.message:"Artifact could not be inspected.")}t.mkdirSync(d,{recursive:!0}),i.onPhase?.("extract");try{await async function(e,t,s){const n=ea(),i=A.extract({cwd:s,strict:!0,preservePaths:!1,preserveOwner:!1,chmod:!1,maxDepth:100,unlink:!0,maxMetaEntrySize:1048576,filter:(e,t)=>n(t)});await ta(e,t,i,3e5)}(e,c,d)}catch(e){if(e instanceof Ko)throw e;throw new Ko("archive_extraction_failed",e instanceof Error?e.message:"Artifact could not be extracted.")}const s=Zo(d),a=Qo(r.stateDir,i.appId);W(a,{schemaVersion:1,appId:i.appId,installRoot:o,files:s});try{t.renameSync(d,o)}catch(e){throw t.rmSync(a,{force:!0}),e}}finally{t.rmSync(a,{recursive:!0,force:!0})}}const ra=new Set(["queued","running"]),oa=new Set(["id","requestId","appId","operation","state","phase","progress","command","logTail","logTruncated","error","requestedAt","startedAt","finishedAt","updatedAt"]);function aa(e){return/^[A-Za-z0-9_./:@%+=,-]+$/.test(e)?e:JSON.stringify(e)}function ca(e){return[e.executable,...e.args].map(aa).join(" ")}function da(e,t){const s=`${e.logTail||""}${function(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/\r(?!\n)/g,"\n")}(t)}`,n=s.length>32768;return{logTail:n?s.slice(-32768):s,...e.logTruncated||n?{logTruncated:!0}:{}}}class pa extends Error{code;statusCode;details;constructor(e,t,s,n){super(t),this.name="AppManagementRequestError",this.code=e,this.statusCode=s,this.details=n}}class ua{filePath;warn;jobs=new Map;constructor(e,t=()=>{}){this.filePath=e,this.warn=t,this.load()}list(){return[...this.jobs.values()].sort((e,t)=>t.requestedAt.localeCompare(e.requestedAt))}get(e){return this.jobs.get(e)}save(e){const t=go.parse(e);return this.jobs.set(t.id,t),this.flush(),t}load(){if(t.existsSync(this.filePath))try{const e=JSON.parse(t.readFileSync(this.filePath,"utf8")),s=e&&"object"==typeof e&&!Array.isArray(e)?e:{},n=Array.isArray(s.jobs)?s.jobs:[];Object.keys(s).some(e=>!["schemaVersion","jobs"].includes(e))&&this.warn("App management job store contains unknown top-level fields; they were ignored.");for(const e of n){if(!e||"object"!=typeof e||Array.isArray(e)){this.warn("An invalid app management job was ignored.");continue}const t=e;Object.keys(t).filter(e=>!oa.has(e)).length&&this.warn(`App management job ${String(t.id||"unknown")} contains unknown fields; they were ignored.`);const s=Object.fromEntries([...oa].filter(e=>Object.hasOwn(t,e)).map(e=>[e,t[e]])),n=go.safeParse(s);n.success?this.jobs.set(n.data.id,n.data):this.warn(`App management job ${String(t.id||"unknown")} is invalid and was ignored.`)}}catch(e){this.warn(`App management job store could not be read: ${e instanceof Error?e.message:String(e)}`)}}flush(){const e={schemaVersion:1,jobs:this.list()};W(this.filePath,e)}}class la{store;definitions;capabilities;refreshCapabilities;capabilitiesSnapshot;capabilitiesObservedAt=0;capabilitiesRefresh;detection;ownership;execute;sessions;publishEvent;now;onTerminal;warn;ownershipByApp=new Map;ownershipRefresh;streamId=`appstream_${n.randomUUID().replaceAll("-","")}`;sequence=0;queue=Promise.resolve();constructor(e){this.store=new ua(s.join(e.stateDir,"jobs.json"),e.warn),this.definitions=e.definitions||(()=>ot()),this.capabilities=e.capabilities||(()=>this.capabilitiesSnapshot||(this.capabilitiesSnapshot=function(e={}){const t=fe(e.platform||process.platform),n=ye(e.arch||process.arch),i=e.env||process.env,r=e.executable||(t=>ge(t,{env:i,platform:e.platform||process.platform})),o=["apt","dnf","brew","npm"].filter(e=>r(e)),a=(e.getuid||(()=>"function"==typeof process.getuid?process.getuid():-1))(),c=e.canPasswordlessSudo||(()=>{if(!r("sudo"))return!1;const t=ve("sudo",["-n","true"],{env:i,platform:e.platform||process.platform});return 0===m.spawnSync(t.executable,t.args,{env:i,stdio:"ignore",timeout:2e3}).status}),d=e.npmGlobalWritable||(()=>{const n=ve("npm",["prefix","--global"],{env:i,platform:e.platform||process.platform}),r=ve("npm",["root","--global"],{env:i,platform:e.platform||process.platform}),o=m.spawnSync(n.executable,n.args,{env:i,encoding:"utf8",timeout:2e3}),a=m.spawnSync(r.executable,r.args,{env:i,encoding:"utf8",timeout:2e3}),c=0===o.status?o.stdout.trim():"",d=0===a.status?a.stdout.trim():"";return!!(c&&d&&s.isAbsolute(c)&&s.isAbsolute(d))&&[d,"win32"===t?c:s.join(c,"bin")].every(Ie)});return{platform:t,arch:n,installers:o,privilege:0===a?"root":c()?"passwordless-sudo":"user",...o.includes("npm")?{installerAccess:{npmGlobalWritable:d()}}:{}}}())),this.refreshCapabilities=e.capabilities?async()=>e.capabilities():()=>async function(e={}){const t=fe(e.platform||process.platform),n=ye(e.arch||process.arch),i=e.env||process.env,r=e.executable||(t=>ge(t,{env:i,platform:e.platform||process.platform})),o=["apt","dnf","brew","npm"].filter(e=>r(e)),a=(e.getuid||(()=>"function"==typeof process.getuid?process.getuid():-1))(),c=0!==a&&(e.canPasswordlessSudo?await e.canPasswordlessSudo():Boolean(r("sudo")&&0===(await be("sudo",["-n","true"],{env:i,platform:e.platform||process.platform})).exitCode));let d;if(o.includes("npm"))if(e.npmGlobalWritable)d=await e.npmGlobalWritable();else{const[n,r]=await Promise.all([be("npm",["prefix","--global"],{env:i,platform:e.platform||process.platform}),be("npm",["root","--global"],{env:i,platform:e.platform||process.platform})]),o=0===n.exitCode?n.stdout.trim():"",a=0===r.exitCode?r.stdout.trim():"";if(o&&a&&s.isAbsolute(o)&&s.isAbsolute(a)){const e="win32"===t?o:s.join(o,"bin");d=(await Promise.all([a,e].map(Ae))).every(Boolean)}else d=!1}return{platform:t,arch:n,installers:o,privilege:0===a?"root":c?"passwordless-sudo":"user",...void 0!==d?{installerAccess:{npmGlobalWritable:d}}:{}}}(),this.detection=e.detection||(e=>function(e,t={}){const s=t.executable||((e,t,s)=>ge(e,{env:t,cwd:s})),n=e.detection.map(t=>{const n="launcher-executable"===t.type?e.launcher.command:t.command;return n?s(n,{...process.env,...e.launcher.env},e.launcher.cwd):void 0}).filter(e=>Boolean(e)),i=0===n.length?"not-installed":n.length===e.detection.length?"installed":"broken",r="installed"===i?e.detection.find(e=>e.versionArgs?.length):void 0,o="launcher-executable"===r?.type?e.launcher.command:r?.command,a=r&&o&&t.version?t.version(o,r.versionArgs||[]):void 0;return{state:i,executablePaths:n,...a?.trim()?{version:a.trim().slice(0,120)}:{}}}(e)),this.ownership=e.ownership||(e.managementSource?async(t,s,n)=>({source:await e.managementSource(t,s,n)}):(n,i,r)=>async function(e,s,n,i={}){if("not-installed"===s.state)return{source:"none"};const r=e.distribution.recipes.filter(t=>Se({...e,distribution:{recipes:[t]}},n).recipe),o=r.find(e=>"bundled"===e.type);if(o)return{source:"bundled",recipe:o};const a={runCommand:i.runCommand||be,realpath:i.realpath||(e=>t.promises.realpath(e)),readFile:i.readFile||(e=>t.promises.readFile(e,"utf8"))};for(const t of r)if("bundled"!==t.type&&("node-package"===t.type?await Oe(t,s,n,a):"system-package"===t.type?await xe(t,s,a):Boolean(i.archiveManifestOwned&&await i.archiveManifestOwned(e,t,s))))return{source:"recipe",recipe:t};return{source:"external"}}(n,i,r,{archiveManifestOwned:async(i,r,o)=>{const a=s.resolve(e.installBaseDir,r.installRoot),c=s.join(e.stateDir,"manifests",`${n.launcher.id}.json`);try{const e=JSON.parse(await t.promises.readFile(c,"utf8"));if(e.installRoot!==a||!Array.isArray(e.files))return!1;const n=new Set(e.files.map(e=>s.resolve(a,String(e))));return o.executablePaths.some(e=>n.has(s.resolve(e)))}catch{return!1}}})),this.execute=e.execute||function(e){const n={...e,commandRunner:e.commandRunner||Go,fetcher:e.fetcher||fetch};return async(e,i,r)=>{const o=e=>(r.onCommand?.({executable:e.executable,args:[...e.args]}),n.commandRunner(e,{onOutput:r.onOutput}));if("bundled"===i.type)throw new Ko("bundled_app","Bundled apps do not support managed installation or removal.");if("system-package"===i.type){r.onPhase?.("install"===e?"install-package":"uninstall-package");const t=function(e,t,s){if(!e.packages.length||e.packages.some(e=>!qo.test(e)))throw new Ko("invalid_builtin_recipe","The built-in system package recipe contains an invalid package name.");if(!s.installers.includes(e.installer))throw new Ko("installer_unavailable",`The ${e.installer} installer is unavailable.`);const n={apt:{executable:"apt-get",install:["install","-y","--no-install-recommends"],uninstall:["remove","-y"]},dnf:{executable:"dnf",install:["install","-y"],uninstall:["remove","-y"]},brew:{executable:"brew",install:["install"],uninstall:["uninstall"]}}[e.installer],i=[...n[t],...e.packages];if("root"===s.privilege||"user"===e.privilege)return{executable:n.executable,args:i,timeoutMs:9e5};if("passwordless-sudo"===s.privilege)return{executable:"sudo",args:["-n",n.executable,...i],timeoutMs:9e5};throw new Ko("insufficient_privilege","The controlled instance cannot run this system package recipe.")}(i,e,r.capabilities);if("install"===e&&"apt"===i.installer){const e=await o(function(e,t){if("root"===e.privilege||"user"===t.privilege)return{executable:"apt-get",args:["update"],timeoutMs:9e5};if("passwordless-sudo"===e.privilege)return{executable:"sudo",args:["-n","apt-get","update"],timeoutMs:9e5};throw new Ko("insufficient_privilege","The controlled instance cannot refresh the apt package index.")}(r.capabilities,i));if(0!==e.exitCode)throw new Ko("package_manager_failed",Vo(e.stderr)||"The apt package index could not be refreshed.",!0)}const s=await o(t);if(0!==s.exitCode)throw new Ko("package_manager_failed",Vo(s.stderr)||"The system package manager failed.",!0);return{log:Vo(s.stdout||s.stderr)}}if("node-package"===i.type){r.onPhase?.("install"===e?"install-node-package":"uninstall-node-package");const t=function(e,t,s){if(!e.packages.length||e.packages.some(e=>!Bo.test(e)))throw new Ko("invalid_builtin_recipe","The built-in Node package recipe contains an invalid package name.");if(!s.installers.includes(e.installer))throw new Ko("installer_unavailable",`The ${e.installer} installer is unavailable.`);const n="install"===t?["install","--global","--include=optional","--no-audit","--no-fund",...e.packages]:["uninstall","--global",...e.packages],i="win32"===s.platform?ge(e.installer,{platform:"win32"})||`${e.installer}.cmd`:e.installer,r="win32"===s.platform?{executable:process.env.ComSpec||"cmd.exe",args:["/d","/s","/c","call",i,...n],timeoutMs:9e5}:{executable:i,args:n,timeoutMs:9e5};if("root"===s.privilege||"user"===e.privilege)return r;if("passwordless-sudo"===s.privilege)return{executable:"sudo",args:["-n",e.installer,...n],timeoutMs:9e5};throw new Ko("insufficient_privilege","The controlled instance cannot run this Node package recipe.")}(i,e,r.capabilities);let n=await o(t);const a=0===n.exitCode?void 0:function(e,t){if(!/(?:^|\n)npm ERR! code ENOTEMPTY\r?$/m.test(e))return;const n=e.match(/(?:^|\n)npm ERR! path (.+)\r?$/m)?.[1]?.trim(),i=e.match(/(?:^|\n)npm ERR! dest (.+)\r?$/m)?.[1]?.trim();if(!(n&&i&&s.isAbsolute(n)&&s.isAbsolute(i)))return;const r=1===t.packages.length?t.packages[0]:void 0,o=r?.split("/").filter(Boolean),a=o?.at(-1);if(!o?.length||!a||!n.endsWith(s.join("node_modules",...o)))return;if(s.dirname(n)!==s.dirname(i))return;const c=a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^\\.${c}-[A-Za-z0-9_-]+$`).test(s.basename(i))?i:void 0}(n.stderr,i);if(a){r.onPhase?.("cleanup-node-package");const e=await o(function(e,t,s){if("win32"===s.platform)return{executable:process.env.ComSpec||"cmd.exe",args:["/d","/s","/c","rmdir","/s","/q",t],timeoutMs:6e4};const n="sudo"===e.executable?["-n"]:[];return"sudo"===e.executable?{executable:"sudo",args:[...n,"rm","-rf","--",t],timeoutMs:6e4}:{executable:"rm",args:["-rf","--",t],timeoutMs:6e4}}(t,a,r.capabilities));if(0!==e.exitCode)throw new Ko("package_cleanup_failed",Vo(e.stderr)||"The stale Node package directory could not be removed.",!0);n=await o(t)}if(0!==n.exitCode)throw new Ko("package_manager_failed",Vo(n.stderr)||"The Node package manager failed.",!0);return{log:Vo(n.stdout||n.stderr)}}return"install"===e?await ia(i,r,n):function(e,n,i){const r=Xo(i.installBaseDir,e.installRoot),o=Qo(i.stateDir,n.appId);if(!t.existsSync(o))throw new Ko("ownership_manifest_missing","The archive ownership manifest is missing.");const a=JSON.parse(t.readFileSync(o,"utf8"));if(a.installRoot!==r||!Array.isArray(a.files))throw new Ko("ownership_manifest_invalid","The archive ownership manifest is invalid.");const c=Jo(a.files.map(e=>({path:String(e),type:"file"})));for(const e of c){const n=s.resolve(r,e);if(!n.startsWith(`${r}${s.sep}`))throw new Ko("ownership_manifest_invalid","An owned path escapes the managed install root.");try{t.unlinkSync(n)}catch(e){if("ENOENT"!==e.code)throw e}}const d=new Set(c.map(e=>s.dirname(s.join(r,e))));for(const e of[...d].sort((e,t)=>t.length-e.length))try{t.rmdirSync(e)}catch(e){if(!["ENOENT","ENOTEMPTY"].includes(e.code||""))throw e}try{t.rmdirSync(r)}catch(e){if(!["ENOENT","ENOTEMPTY"].includes(e.code||""))throw e}t.unlinkSync(o)}(i,r,n),{log:""}}}({installBaseDir:e.installBaseDir,stateDir:e.stateDir}),this.sessions=e.sessions||(()=>[]),this.publishEvent=e.publish||(()=>{}),this.now=e.now||(()=>(new Date).toISOString()),this.onTerminal=e.onTerminal||(()=>{}),this.warn=e.warn||(()=>{}),this.recoverInterrupted()}snapshot(){const e=this.capabilities(),t=this.store.list(),s=t.filter(e=>ra.has(e.state)),n=new Map(s.map(e=>[e.appId,e])),i=this.definitions().map(t=>{const s=this.detection(t),i=this.ownershipByApp.get(t.launcher.id),r=this.ownershipFingerprint(s,e),o=Se(t,e).recipe,a="not-installed"===s.state?"none":"bundled"===o?.type?"bundled":i?.fingerprint===r?i.source:"external",c=Ee(t,s,e,a),d=n.get(c.id);return d?{...c,canInstall:!1,canUninstall:!1,installReason:{code:"OPERATION_IN_PROGRESS",message:"An app management operation is already in progress."},uninstallReason:{code:"OPERATION_IN_PROGRESS",message:"An app management operation is already in progress."},activeJobId:d.id}:c});return fo.parse({streamId:this.streamId,sequence:this.sequence,capabilities:e,apps:i,activeJobs:s,recentJobs:t.filter(e=>!ra.has(e.state)).slice(0,50),observedAt:this.now()})}async refreshSnapshot(e=!1){return this.ownershipRefresh||(this.ownershipRefresh=(async()=>{const t=await this.ensureCapabilities(e);await Promise.all(this.definitions().map(async e=>{const s=this.detection(e);await this.refreshOwnership(e,s,t)}))})().finally(()=>{this.ownershipRefresh=void 0})),await this.ownershipRefresh,this.snapshot()}getJob(e){const t=this.store.get(e);if(!t)throw new pa("app_job_not_found","App management job not found.",404);return t}request(e,t,s){const i=this.definitions().find(t=>t.launcher.id===e);if(!i)throw new pa("unknown_app","The requested built-in app does not exist.",404);if(s){const n=this.store.list().find(e=>e.requestId===s);if(n){if(n.appId===e&&n.operation===t)return n;throw new pa("app_request_id_conflict","The app management request id is already bound to a different operation.",409,{jobId:n.id,appId:n.appId,operation:n.operation})}}const r=this.store.list().find(t=>t.appId===e&&ra.has(t.state));if(r){if(r.operation===t)return r;throw new pa("app_operation_conflict","A conflicting app operation is already active.",409,{activeJobId:r.id})}const o="uninstall"===t?this.sessions().filter(t=>t.appId===e&&["created","running","stopping"].includes(t.status)):[];if(o.length)throw new pa("app_sessions_running","The app has running sessions and cannot be uninstalled.",409,{sessionIds:o.map(e=>e.id)});const a=this.capabilities(),c=Se(i,a),d=this.detection(i),p=this.ownershipByApp.get(i.launcher.id),u=this.ownershipFingerprint(d,a),l="not-installed"===d.state?"none":"bundled"===c.recipe?.type?"bundled":p?.fingerprint===u?p.source:"external",m=Ee(i,d,a,l),h="uninstall"===t&&p?.fingerprint===u&&p.recipe?p.recipe:c.recipe;if(!h||("install"===t?!m.canInstall:!m.canUninstall)){const e="install"===t?m.installReason:m.uninstallReason;throw new pa("app_operation_unavailable",e?.message||"The requested app operation is unavailable.",409,{reason:e})}const g=this.now(),f=this.store.save({id:`appjob_${n.randomUUID().replaceAll("-","")}`,...s?{requestId:s}:{},appId:e,operation:t,state:"queued",requestedAt:g,updatedAt:g});return this.emit(f,!0),this.queue=this.queue.then(()=>this.run(f.id,i,h)).catch(()=>{}),f}waitForIdle(){return this.queue}snapshotEvent(){return{type:"app-management",streamId:this.streamId,sequence:this.sequence,observedAt:this.now(),snapshot:this.snapshot()}}publishSnapshot(){const e={type:"app-management",streamId:this.streamId,sequence:++this.sequence,observedAt:this.now(),snapshot:this.snapshot()};return this.publishEvent(e),e}recoverInterrupted(){let e=!1;for(const t of this.store.list()){if(!ra.has(t.state))continue;e=!0;const s=this.now();this.store.save({...t,state:"interrupted",error:{code:"controlled_instance_restarted",message:"The controlled instance restarted before the operation completed.",retryable:!0},finishedAt:s,updatedAt:s})}if(e)for(const e of this.definitions())this.detection(e)}async run(e,t,s){let n,i=this.getJob(e),r="";const o=()=>{if(n&&clearTimeout(n),n=void 0,!r)return;const t=r;r="";const s=this.getJob(e),i=this.store.save({...s,...da(s,t),updatedAt:this.now()});this.emit(i)},a=this.now();i=this.store.save({...i,state:"running",phase:"starting",startedAt:a,updatedAt:a}),this.emit(i,!0);try{await this.execute(i.operation,s,{appId:i.appId,capabilities:this.capabilities(),onPhase:(t,s)=>{o();const n=this.getJob(e),i=this.store.save({...n,phase:t,progress:s,updatedAt:this.now()});this.emit(i)},onCommand:t=>{o();const s=this.getJob(e),n=this.store.save({...s,command:t,...da(s,`${s.logTail&&!s.logTail.endsWith("\n")?"\n":""}$ ${ca(t)}\n`),updatedAt:this.now()});this.emit(n)},onOutput:(e,t)=>{r+=t,n||(n=setTimeout(o,100),n.unref?.())}}),o();const a=this.detection(t);if(!("install"===i.operation?"installed"===a.state:"not-installed"===a.state))throw new Ko("postcondition_failed",`App ${i.operation} completed but detection did not confirm the required state.`,!0);await this.refreshOwnership(t,a,await this.ensureCapabilities(!0));const c=this.now();i=this.store.save({...this.getJob(e),state:"succeeded",phase:"verify",progress:void 0,finishedAt:c,updatedAt:c})}catch(t){o();const s=this.now(),n=t instanceof Ko?t.code:"app_operation_failed",r=!(t instanceof Ko)||t.retryable;i=this.store.save({...this.getJob(e),state:"failed",progress:void 0,error:{code:n,message:t instanceof Error?t.message:String(t),retryable:r},finishedAt:s,updatedAt:s})}this.emit(i,!0),Promise.resolve(this.onTerminal(i)).catch(e=>{this.warn(`App inventory refresh failed after ${i.operation} for ${i.appId}: ${e instanceof Error?e.message:String(e)}`)})}ownershipFingerprint(e,t){return JSON.stringify({state:e.state,executablePaths:e.executablePaths,platform:t.platform,arch:t.arch,privilege:t.privilege})}async ensureCapabilities(e=!1){return!e&&this.capabilitiesSnapshot&&Date.now()-this.capabilitiesObservedAt<1e4?this.capabilitiesSnapshot:(this.capabilitiesRefresh||(this.capabilitiesRefresh=this.refreshCapabilities().then(e=>(this.capabilitiesSnapshot=e,this.capabilitiesObservedAt=Date.now(),e)).finally(()=>{this.capabilitiesRefresh=void 0})),this.capabilitiesRefresh)}async refreshOwnership(e,t,s){let n;try{const i=await this.ownership(e,t,s);return n=i.source,this.ownershipByApp.set(e.launcher.id,{fingerprint:this.ownershipFingerprint(t,s),source:n,recipe:i.recipe}),n}catch(i){n="not-installed"===t.state?"none":"bundled"===Se(e,s).recipe?.type?"bundled":"external",this.warn(`App ownership detection failed for ${e.launcher.id}: ${i instanceof Error?i.message:String(i)}`)}return this.ownershipByApp.set(e.launcher.id,{fingerprint:this.ownershipFingerprint(t,s),source:n}),n}emit(e,t=!1){this.publishEvent({type:"app-management",streamId:this.streamId,sequence:++this.sequence,observedAt:this.now(),job:e,...t?{snapshot:this.snapshot()}:{}})}}function ma(){return process.env.HOME||r.homedir()||"/home/agent"}function ha(){return process.env.TASK_HANDOFF_WORKSPACE||process.env.WORKSPACE||"/workspace"}function ga(){const e=ma(),t=function(){const e=[s.join(ma(),".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 fa(e,n,i){return t.existsSync(n)?(t.mkdirSync(s.dirname(i),{recursive:!0}),"dir"===e?t.cpSync(n,i,{recursive:!0,force:!0}):t.copyFileSync(n,i),"copied"):"skipped_missing_source"}function ya(e,t,n){const i=n||ga().find(e=>e.id===t);if(!i){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 r=i.items.map(t=>{const n=function(e,t){const n=s.resolve(ha(),e),i=s.resolve(n,t);if(i!==n&&!i.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 i}(i.projectRoot,t.projectPath),r=function(e){const t=s.resolve(function(e){const t={HOME:ma(),WORKSPACE:ha(),CODEX_HOME:process.env.CODEX_HOME||s.join(ma(),".codex"),CLAUDE_HOME:process.env.CLAUDE_HOME||s.join(ma(),".claude")};return e.replace(/\$\{([A-Z_]+)\}/g,(e,s)=>t[s]||e)}(e));if(![s.resolve(ma()),s.resolve(ha()),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:r,a="import"===e?r:n;try{return{...t,source:o,target:a,status:fa(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:i.id,label:i.label,projectRoot:i.projectRoot},direction:e,items:r}}function va(e,t){G(e,t)}function Sa(e=process.env){if("controlled"!==e.TASK_HANDOFF_CONTROL_MODE)return{applied:!1};const n=(e.TASK_HANDOFF_CODEX_MODEL||"").trim(),i=(e.TASK_HANDOFF_CODEX_BASE_URL||"").trim(),o=(e.OPENAI_API_KEY||"").trim();if(!n||!i||!o)return{applied:!1};const a=function(e){const t=e.CODEX_HOME?.trim();return s.resolve(t||s.join(e.HOME||r.homedir(),".codex"))}(e),c=s.join(a,"config.toml"),d=s.join(a,"auth.json");let p=!1;if(o){let e="";try{const s=JSON.parse(t.readFileSync(d,"utf8"));e="apikey"===s.auth_mode&&"string"==typeof s.OPENAI_API_KEY?s.OPENAI_API_KEY:""}catch{e=""}e!==o&&(va(d,`${JSON.stringify({auth_mode:"apikey",OPENAI_API_KEY:o},null,2)}\n`),p=!0)}const u=function(e){try{const n=t.readFileSync(e,"utf8");return{contents:n,config:(s=n.trim()?b.parse(n):{},s&&"object"==typeof s&&!Array.isArray(s)?s:{})}}catch(t){if(t&&"object"==typeof t&&"code"in t&&"ENOENT"===t.code)return{contents:"",config:{}};throw Object.assign(new Error(`Codex config could not be read or parsed at ${e}: ${t instanceof Error?t.message:String(t)}`),{code:"CODEX_MODEL_CONFIG_INVALID"})}var s}(c);if(u.config.model===n&&"openai"===u.config.model_provider&&u.config.openai_base_url===i)return{applied:p,configPath:c,authPath:d};const l={...u.config,model:n,model_provider:"openai",openai_base_url:i};let m;return u.contents&&(m=`${c}.bak.${(new Date).toISOString().replace(/[:.]/g,"-")}`,t.copyFileSync(c,m),t.chmodSync(m,384)),va(c,b.stringify(l)),{applied:!0,configPath:c,authPath:d,backupPath:m}}function wa(){try{const e=s.resolve(__dirname,"..","package.json");return JSON.parse(t.readFileSync(e,"utf8")).version||"unknown"}catch{return"unknown"}}function Ia(e){const t=process.env[e]?.trim();return t||void 0}function Aa(e,n){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=ut(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 i=s.resolve(n),r=e.endsWith("Path"),o=r?s.dirname(i):i;let a=!1,c=!1,d="missing";try{const e=t.existsSync(i)?t.statSync(i):void 0;a=Boolean(e),d=e?.isFile()?"file":e?.isDirectory()?"directory":"missing";const n=a?r?i: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),c=!0}catch{c=!1}return{key:e,path:i,exists:a,type:d,writable:c}})}(e),a="linux"===process.platform;return{ok:a&&i.every(e=>e.available)&&Boolean(n)&&o.every(e=>e.writable),runtime:{platform:process.platform,arch:process.arch,linuxRuntime:a,node:process.version,pid:process.pid,hostname:r.hostname(),uptimeSeconds:Math.round(process.uptime())},noVnc:{available:Boolean(n),root:n},commands:i,storage:o}}function ba(){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 _a(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 Ta(e){const t=e.catalog();return{protocolVersion:jr,features:{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 Oa(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 xa(e,t,s=oi(),n){const i=e.listSessions();return{status:"running",health:"ok",instanceVersion:wa(),protocolVersion:jr,build:{component:"controlled-instance",packageName:"@task-handoff/controlled-instance",packageVersion:wa(),protocolVersion:jr,buildId:Ia("TASK_HANDOFF_BUILD_ID"),builtAt:Ia("TASK_HANDOFF_BUILT_AT"),gitCommit:Ia("TASK_HANDOFF_GIT_COMMIT"),imageRef:Ia("TASK_HANDOFF_IMAGE_REF"),imageDigest:Ia("TASK_HANDOFF_IMAGE_DIGEST")},controlMode:"controlled"===process.env.TASK_HANDOFF_CONTROL_MODE?"controlled":"standalone",capabilities:Ta(e),appInventory:e.appInventory(),apps:{runningCount:e.runningSessionCount(),problemCount:e.problemSessionCount()},aiSessions:s.boundSnapshot(i),triggers:n?Oa(n):void 0,workspace:_a(t),target:ba()}}const Ea=new Set(["ECONNREFUSED","ECONNRESET","EHOSTUNREACH"]);function ka(e){return new Promise(t=>setTimeout(t,e))}function za(e){const t=e?.code;return Boolean(t&&Ea.has(t))}function Na(e,t="/"){const s=new URL(t,"http://task-handoff.local"),n=`/api/apps/sessions/${e}/web`,i=s.pathname.startsWith(n)?s.pathname.slice(n.length):"/";return`${i.startsWith("/")?i:`/${i}`}${s.search}`}function Pa(){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 Ra(e,t,s,n={}){const i=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 i.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 Ca(e,t,s,n={}){return Object.fromEntries(Object.entries(Ra(e,t,s,n)).filter(([e])=>{const t=e.toLowerCase();return!t.startsWith("sec-websocket-")||"sec-websocket-origin"===t}))}function Da(e,t){const s=e[t];return Array.isArray(s)?s.join(","):s||""}function Ma(e){if(Da(e,"content-encoding"))return!1;const t=Da(e,"content-type").toLowerCase();return t.includes("text/css")||t.includes("text/html")}function Fa(e,t){const s=Da(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 ja(e){const t={};e.forEach((e,s)=>{t[s]=e});const s=e.getSetCookie?.();return s?.length&&(t["set-cookie"]=s),t}function La(e){const t={};e.forEach((e,s)=>{t[s]=e});const s=e.getSetCookie?.();return s?.length&&(t["set-cookie"]=s),t}const $a="app-session.snapshot",Ha="app-session.patch",Ua="app-session.removed",qa=36e5,Ba=l.z.enum(["created","starting","running","stopping","stopped","exited","failed","closed","terminated","unknown"]),Ka=l.z.object({type:l.z.enum(["app-session","provider-session","adapter-key"]),id:l.z.string().trim().min(1).max(240),agent:l.z.string().trim().min(1).max(80).optional(),adapter:l.z.string().trim().min(1).max(80).optional(),key:l.z.string().trim().min(1).max(240).optional()}).strict(),Va=l.z.record(l.z.string(),l.z.unknown()).and(l.z.object({id:l.z.string().trim().min(1).max(160),appId:l.z.string().trim().min(1).max(160).optional(),title:l.z.string().trim().max(240).optional(),kind:l.z.string().trim().max(80).optional(),status:Ba.default("unknown"),bindings:l.z.array(Ka).max(40).default([]),workspace:l.z.object({cwd:l.z.string().trim().max(4096).optional()}).strict().optional(),createdAt:l.z.string().datetime().optional(),updatedAt:l.z.string().datetime().optional()})),Ga=l.z.object({runningCount:l.z.number().int().min(0).default(0),problemCount:l.z.number().int().min(0).default(0),sessions:l.z.array(Va).default([]),updatedAt:l.z.string().datetime()}).strict();l.z.object({streamId:l.z.string().trim().min(1).max(240),revision:l.z.number().int().min(0),lastEventAt:l.z.string().datetime(),snapshot:Ga}).strict(),Ga.pick({runningCount:!0,problemCount:!0,updatedAt:!0}).extend({revision:l.z.number().int().min(0).optional()});const Wa=l.z.enum(["app-session-created","app-session-updated","app-session-deleted","app-session-recovered","control-action","heartbeat-sync","startup"]),Ya=l.z.object({streamId:l.z.string().trim().min(1).max(240),instanceId:l.z.string().trim().min(1).max(160),nodeId:l.z.string().trim().min(1).max(160).optional(),revision:l.z.number().int().min(0),previousRevision:l.z.number().int().min(0).optional(),traceId:l.z.string().trim().min(1).max(160),generatedAt:l.z.string().datetime(),reason:Wa}).strict(),Ja=l.z.object({meta:Ya,snapshot:Ga}).strict(),Xa=l.z.object({meta:Ya,session:Va}).strict(),Qa=l.z.object({meta:Ya,sessionId:l.z.string().trim().min(1).max(160),tombstone:Va.optional(),expiresAt:l.z.string().datetime().optional()}).strict(),Za=l.z.object({streamId:l.z.string().trim().min(1).max(240),instanceId:l.z.string().trim().min(1).max(160),sinceRevision:l.z.number().int().min(0),latestRevision:l.z.number().int().min(0),earliestRetainedRevision:l.z.number().int().min(0),syncRequired:l.z.boolean().default(!1),events:l.z.array(l.z.discriminatedUnion("type",[l.z.object({type:l.z.literal($a),payload:Ja}).strict(),l.z.object({type:l.z.literal(Ha),payload:Xa}).strict(),l.z.object({type:l.z.literal(Ua),payload:Qa}).strict()])).default([])}).strict();function ec(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":Ba.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=ic(e.workspace),s=ic(e.tty),n=ic(e.launch),i=ic(e.ai),r=ic(i.claude),o=rc(t.cwd)||rc(s.cwd)||rc(r.cwd)||rc(n.cwd);return o?{cwd:o}:void 0}(e),{workspace:i,...r}=e;return Va.parse({...r,status:t,bindings:nc([...(o=e.bindings,Array.isArray(o)?o.flatMap(e=>{const t=Ka.safeParse(e);return t.success?[t.data]:[]}):[]),...s?[{type:"app-session",id:s}]:[],...sc(e)]),...n?{workspace:n}:{}});var o}(e));return Ga.parse({runningCount:s.filter(e=>"running"===e.status).length,problemCount:s.filter(e=>"failed"===e.status).length,sessions:s,updatedAt:t})}function tc(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 sc(e){const t=ic(e.ai),s=ic(t.claude),n=ic(t.appServer),i=[],r=rc(s.short);r&&i.push({type:"adapter-key",adapter:"claude",agent:"claude",id:`short:${r}`,key:`short:${r}`});const o=rc(s.providerSessionId);o&&i.push({type:"provider-session",agent:"claude",id:o});const a=Array.isArray(t.threadIds)?t.threadIds.filter(e=>"string"==typeof e&&Boolean(e.trim())):[],c=rc(t.activeThreadId);for(const e of[...new Set([c,...a].filter(Boolean))])i.push({type:"provider-session",agent:"codex",id:e});const d=rc(n.socketPath);return d&&i.push({type:"adapter-key",adapter:"codex-app-server",agent:"codex",id:`socket:${d}`,key:`socket:${d}`}),i}function nc(e){const t=new Map;for(const s of e)t.set(tc(s),s);return[...t.values()]}function ic(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}function rc(e){return"string"==typeof e&&e.trim()?e.trim():""}function oc(e){return e.readyState===(e.OPEN??1)}function ac(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 cc(e,t){e.send(t.data,{binary:t.isBinary})}function dc(e,t){if(oc(e))for(const s of t.splice(0))cc(e,s)}const pc=l.z.string().trim().min(1).max(160).regex(/^[a-zA-Z0-9][a-zA-Z0-9_.:-]*$/),uc=l.z.string().datetime(),lc=l.z.string().trim().min(1).max(255).refine(e=>!(/[\u0000-\u001f\u007f ~^:?*[\\]/.test(e)||e.includes("..")||e.endsWith(".")||e.endsWith("/")),"Invalid Git name."),mc=l.z.string().min(1).max(4096).refine(e=>!(e.includes("\0")||e.startsWith("/")||e.startsWith("\\")||/^[a-zA-Z]:[\\/]/.test(e))&&e.split("/").every(e=>e.length>0&&"."!==e&&".."!==e&&".git"!==e),"Path must be a safe repository-relative path."),hc=l.z.enum(["ai-session","app-session"]),gc=l.z.enum(["available","session-not-found","session-inactive","cwd-missing","cwd-inaccessible","git-unavailable","not-worktree"]),fc=l.z.enum(["branch","detached","unborn"]),yc=l.z.enum(["review-changes","resolve-conflicts","publish-branch","push","pull","diverged","up-to-date"]),vc=l.z.enum(["conflict","staged","unstaged","untracked"]),Sc=l.z.enum(["added","modified","deleted","renamed","copied","type-changed","unmerged","untracked"]),wc=l.z.object({state:fc,oid:l.z.string().regex(/^[0-9a-f]{40,64}$/).optional(),branch:l.z.string().min(1).max(1024).optional()}).strict(),Ic=l.z.object({ref:l.z.string().min(1).max(2048),remote:lc,branch:l.z.string().min(1).max(1024),ahead:l.z.number().int().nonnegative(),behind:l.z.number().int().nonnegative()}).strict(),Ac=l.z.object({id:pc,isCurrent:l.z.boolean(),isMain:l.z.boolean(),managed:l.z.boolean(),head:wc,dirty:l.z.boolean(),locked:l.z.boolean(),lockReason:l.z.string().max(1e3).optional(),prunable:l.z.boolean(),activeAiSessionIds:l.z.array(pc).max(256).default([]),activeAppSessionIds:l.z.array(pc).max(256).default([])}).strict(),bc=l.z.enum(["main-worktree","external-worktree","outside-workspace-roots","dirty","locked","prunable","session-occupied","path-inaccessible"]),_c=Ac.extend({canCreateAiSession:l.z.boolean(),canRemove:l.z.boolean(),createAiSessionBlockers:l.z.array(bc).max(16).default([]),removeBlockers:l.z.array(bc).max(16).default([])}).strict(),Tc=l.z.object({repositoryId:pc,repositoryContextId:pc,snapshotId:pc,items:l.z.array(_c).max(1e4)}).strict(),Oc=l.z.object({conflicts:l.z.number().int().nonnegative(),staged:l.z.number().int().nonnegative(),unstaged:l.z.number().int().nonnegative(),untracked:l.z.number().int().nonnegative()}).strict(),xc=l.z.object({name:lc,fetchUrl:l.z.string().max(4096).optional(),pushUrl:l.z.string().max(4096).optional()}).strict(),Ec=l.z.object({availability:gc,sessionKind:hc,sessionId:pc,observedAt:uc,snapshotId:pc.optional(),repositoryId:pc.optional(),repositoryContextId:pc.optional(),repositoryRoot:l.z.string().min(1).max(4096).optional(),displayName:l.z.string().trim().min(1).max(255).optional(),cwdRelativePath:l.z.string().max(4096).optional(),head:wc.optional(),upstream:Ic.optional(),currentWorktree:Ac.optional(),changes:Oc.optional(),remotes:l.z.array(xc).max(128).optional(),primaryAction:yc.optional()}).strict(),kc=l.z.enum(["directory","file","symlink","submodule","nested-repository","special"]),zc=l.z.object({executable:l.z.boolean(),gitMode:l.z.enum(["100644","100755","120000","160000"]).optional()}).strict(),Nc=l.z.object({name:l.z.string().min(1).max(1024),path:mc,kind:kc,traversable:l.z.boolean(),editable:l.z.boolean(),size:l.z.number().int().nonnegative().optional(),mode:zc.optional()}).strict();l.z.object({path:l.z.string().max(4096),entries:l.z.array(Nc).max(1e4),snapshotId:pc}).strict();const Pc=l.z.string().min(16).max(160).regex(/^[a-zA-Z0-9_.:-]+$/),Rc=l.z.object({path:mc,content:l.z.string(),byteLength:l.z.number().int().nonnegative(),version:Pc,mode:zc}).strict(),Cc=l.z.object({path:mc,oldPath:mc.optional(),scope:vc,status:Sc,version:Pc,binary:l.z.boolean().default(!1)}).strict(),Dc=l.z.object({snapshotId:pc,summary:Oc,entries:l.z.array(Cc).max(1e5)}).strict();l.z.object({file:Rc.optional(),snapshotId:pc,context:Ec,changes:Dc}).strict();const Mc=l.z.object({kind:l.z.enum(["metadata","hunk","context","addition","deletion"]),content:l.z.string(),oldLine:l.z.number().int().positive().optional(),newLine:l.z.number().int().positive().optional(),oldStart:l.z.number().int().nonnegative().optional(),oldCount:l.z.number().int().nonnegative().optional(),newStart:l.z.number().int().nonnegative().optional(),newCount:l.z.number().int().nonnegative().optional(),heading:l.z.string().optional(),hunkId:l.z.string().min(1).max(200).optional()}).strict();l.z.object({path:mc,oldPath:mc.optional(),scope:vc,binary:l.z.boolean(),complete:l.z.boolean(),truncated:l.z.boolean(),byteLimit:l.z.number().int().positive(),content:l.z.string(),lines:l.z.array(Mc).max(2e5),contextGaps:l.z.array(l.z.object({gapId:l.z.string().min(1).max(500),beforeHunkId:l.z.string().min(1).max(200).optional(),afterHunkId:l.z.string().min(1).max(200).optional(),lines:l.z.array(Mc).max(6e3),startLineCount:l.z.number().int().nonnegative().max(3e3),hasMore:l.z.boolean()}).strict()).max(2e4),version:Pc,snapshotId:pc}).strict();const Fc=l.z.object({name:l.z.string().min(1).max(1024),oid:l.z.string().regex(/^[0-9a-f]{40,64}$/),kind:l.z.enum(["local","remote-tracking"]),current:l.z.boolean(),upstream:l.z.string().min(1).max(2048).optional(),ahead:l.z.number().int().nonnegative().optional(),behind:l.z.number().int().nonnegative().optional(),checkedOutWorktreeIds:l.z.array(pc).max(256).default([])}).strict(),jc=l.z.object({snapshotId:pc,branches:l.z.array(Fc).max(1e5)}).strict();l.z.object({snapshotId:pc,context:Ec,branches:jc}).strict(),l.z.object({ok:l.z.literal(!0),snapshotId:pc,context:Ec,changes:Dc.optional(),commitOid:l.z.string().regex(/^[0-9a-f]{40,64}$/).optional()}).strict();const Lc=l.z.enum(["REPOSITORY_REQUEST_INVALID","REPOSITORY_SESSION_NOT_FOUND","REPOSITORY_SESSION_INACTIVE","REPOSITORY_CWD_MISSING","REPOSITORY_CWD_INACCESSIBLE","REPOSITORY_GIT_UNAVAILABLE","REPOSITORY_NOT_WORKTREE","REPOSITORY_PATH_INVALID","REPOSITORY_PATH_FORBIDDEN","REPOSITORY_FILE_NOT_FOUND","REPOSITORY_FILE_EXISTS","REPOSITORY_FILE_UNSUPPORTED","REPOSITORY_FILE_TOO_LARGE","REPOSITORY_FILE_BINARY","REPOSITORY_FILE_STALE","REPOSITORY_STATE_STALE","REPOSITORY_WORKTREE_NOT_FOUND","REPOSITORY_WORKTREE_OCCUPIED","REPOSITORY_WORKTREE_UNSAFE","REPOSITORY_BRANCH_INVALID","REPOSITORY_BRANCH_OCCUPIED","REPOSITORY_BRANCH_UNMERGED","REPOSITORY_CONFLICT","REPOSITORY_DIRTY","REPOSITORY_NOTHING_TO_COMMIT","REPOSITORY_IDENTITY_MISSING","REPOSITORY_HOOK_FAILED","REPOSITORY_SIGNING_FAILED","REPOSITORY_AUTHENTICATION_FAILED","REPOSITORY_NON_FAST_FORWARD","REPOSITORY_UPSTREAM_MISSING","REPOSITORY_COMMAND_TIMEOUT","REPOSITORY_OUTPUT_LIMIT","REPOSITORY_OPERATION_ABORTED","REPOSITORY_OPERATION_FAILED"]);l.z.object({ok:l.z.literal(!1),error:l.z.object({code:Lc,message:l.z.string().trim().min(1).max(2e3),retryable:l.z.boolean(),details:l.z.record(l.z.string(),l.z.union([l.z.string(),l.z.number(),l.z.boolean()])).optional()}).strict()}).strict();const $c=l.z.object({expectedSnapshotId:pc}).strict(),Hc=l.z.object({path:mc,expectedVersion:Pc}).strict(),Uc=l.z.object({path:mc,content:l.z.string().max(4194304),expectedAbsent:l.z.literal(!0),expectedSnapshotId:pc}).strict(),qc=l.z.object({path:mc,content:l.z.string().max(4194304),expectedVersion:Pc,expectedSnapshotId:pc}).strict(),Bc=l.z.object({path:mc,destination:mc,expectedVersion:Pc,expectedDestinationAbsent:l.z.literal(!0),expectedSnapshotId:pc}).strict(),Kc=l.z.object({path:mc,expectedVersion:Pc,expectedSnapshotId:pc,confirm:l.z.literal(!0)}).strict(),Vc=$c.extend({paths:l.z.array(Hc).min(1).max(1e3)}).strict(),Gc=$c.extend({paths:l.z.array(Hc).min(1).max(1e3)}).strict(),Wc=$c.extend({paths:l.z.array(Hc).min(1).max(1e3),confirm:l.z.literal(!0)}).strict(),Yc=$c.extend({paths:l.z.array(Hc).min(1).max(1e3),confirm:l.z.literal(!0)}).strict(),Jc=$c.extend({message:l.z.string().trim().min(1).max(65536)}).strict(),Xc=l.z.discriminatedUnion("mode",[l.z.object({mode:l.z.literal("new-branch"),branchName:lc,startRef:l.z.string().trim().min(1).max(2048),expectedSnapshotId:pc}).strict(),l.z.object({mode:l.z.literal("existing-branch"),branchName:lc,expectedSnapshotId:pc}).strict()]),Qc=$c.extend({worktreeId:pc,confirm:l.z.literal(!0)}).strict();l.z.object({worktreeId:pc,worktrees:Tc}).strict(),l.z.object({removedWorktreeId:pc,branchRetained:l.z.boolean(),worktrees:Tc}).strict();const Zc=l.z.discriminatedUnion("type",[l.z.object({type:l.z.literal("current")}).strict(),l.z.object({type:l.z.literal("worktree"),repositoryContextId:pc,worktreeId:pc}).strict()]),ed=l.z.object({agent:l.z.enum(["codex","claude"]),workspaceSelection:Zc}).strict(),td=l.z.object({agent:l.z.enum(["codex","claude"]),worktree:Xc}).strict();l.z.object({appSessionId:pc,worktreeId:pc,disposition:l.z.literal("started")}).strict();const sd=$c.extend({name:lc}).strict(),nd=$c.extend({branch:l.z.string().trim().min(1).max(2048)}).strict(),id=$c.extend({name:lc,remoteTrackingRef:l.z.string().trim().min(1).max(2048)}).strict(),rd=$c.extend({name:lc,confirm:l.z.literal(!0)}).strict(),od=$c.extend({remote:lc}).strict(),ad=$c,cd=$c.extend({remote:lc,sourceBranch:lc,targetBranch:lc,setUpstream:l.z.boolean(),confirmSetUpstream:l.z.boolean().optional()}).strict().refine(e=>!e.setUpstream||!0===e.confirmSetUpstream,{message:"Setting an upstream requires explicit confirmation.",path:["confirmSetUpstream"]}),dd=$c.extend({remote:lc,sourceBranch:lc,targetBranch:lc}).strict();class pd extends Error{code;constructor(e,t){super(t),this.code=e,this.name="RepositoryFileError"}}class ud{maxFileBytes;root;constructor(e,s=4194304){if(this.maxFileBytes=s,this.root=t.realpathSync(e),!t.statSync(this.root).isDirectory())throw new pd("REPOSITORY_CWD_INACCESSIBLE","Repository root is not a directory.")}list(e=""){const n=this.resolve(e,{allowRoot:!0,mustExist:!0});if(!t.lstatSync(n.absolutePath).isDirectory())throw new pd("REPOSITORY_PATH_INVALID","Directory path does not identify a directory.");this.assertRepositoryBoundary(n.absolutePath,e);const i=t.readdirSync(n.absolutePath,{withFileTypes:!0}).filter(e=>".git"!==e.name.toLowerCase()).map(i=>{const r=e?`${e}/${i.name}`:i.name,o=s.join(n.absolutePath,i.name),a=t.lstatSync(o),c=this.kind(o,a);return{name:i.name,path:r,kind:c,traversable:"directory"===c,editable:"file"===c&&a.size<=this.maxFileBytes,..."file"===c?{size:a.size,mode:gd(a)}:{}}}).sort((e,t)=>e.name.localeCompare(t.name));return{path:e,entries:i,snapshotId:yd(i)}}read(e){const s=this.resolve(e,{mustExist:!0}),n=t.lstatSync(s.absolutePath);if(this.assertRegularFile(s.absolutePath,n),n.size>this.maxFileBytes)throw new pd("REPOSITORY_FILE_TOO_LARGE",`File exceeds ${this.maxFileBytes} bytes.`);const i=t.readFileSync(s.absolutePath);if(i.includes(0))throw new pd("REPOSITORY_FILE_BINARY","Binary files cannot be opened in the text editor.");let r;try{r=new TextDecoder("utf-8",{fatal:!0}).decode(i)}catch{throw new pd("REPOSITORY_FILE_BINARY","File is not valid UTF-8 text.")}return{path:e,content:r,byteLength:i.length,version:fd(i,n),mode:gd(n)}}create(e,s){const n=this.resolve(e,{mustExist:!1});if(t.existsSync(n.absolutePath))throw new pd("REPOSITORY_FILE_EXISTS","Destination already exists.");const i=hd(s,this.maxFileBytes);try{t.writeFileSync(n.absolutePath,i,{flag:"wx",mode:420})}catch(e){if("EEXIST"===e.code)throw new pd("REPOSITORY_FILE_EXISTS","Destination already exists.");throw e}return this.read(e)}write(e,i,r){if(this.read(e).version!==r)throw new pd("REPOSITORY_FILE_STALE","File changed after it was opened.");const o=this.resolve(e,{mustExist:!0}),a=hd(i,this.maxFileBytes),c=t.statSync(o.absolutePath),d=s.join(s.dirname(o.absolutePath),`.${s.basename(o.absolutePath)}.task-handoff-${n.randomUUID()}.tmp`);try{if(t.writeFileSync(d,a,{flag:"wx",mode:511&c.mode}),this.read(e).version!==r)throw new pd("REPOSITORY_FILE_STALE","File changed while it was being saved.");t.renameSync(d,o.absolutePath),t.chmodSync(o.absolutePath,511&c.mode)}finally{try{t.unlinkSync(d)}catch{}}return this.read(e)}rename(e,s,n){if(this.read(e).version!==n)throw new pd("REPOSITORY_FILE_STALE","File changed before it was renamed.");const i=this.resolve(e,{mustExist:!0}),r=this.resolve(s,{mustExist:!1});if(t.existsSync(r.absolutePath))throw new pd("REPOSITORY_FILE_EXISTS","Destination already exists.");try{t.linkSync(i.absolutePath,r.absolutePath)}catch(e){if("EEXIST"===e.code)throw new pd("REPOSITORY_FILE_EXISTS","Destination already exists.");throw e}try{t.unlinkSync(i.absolutePath)}catch(e){try{t.unlinkSync(r.absolutePath)}catch{}throw e}return this.read(s)}delete(e,s){if(this.read(e).version!==s)throw new pd("REPOSITORY_FILE_STALE","File changed before it was deleted.");t.unlinkSync(this.resolve(e,{mustExist:!0}).absolutePath)}resolve(e,n){const i=""===e&&n.allowRoot?[]:md(e);let r=this.root;for(let e=0;e<i.length;e+=1){r=s.join(r,i[e]);const o=e===i.length-1;if(!t.existsSync(r)){if(!o||n.mustExist)throw new pd("REPOSITORY_FILE_NOT_FOUND","Repository path does not exist.");continue}const a=t.lstatSync(r);if(a.isSymbolicLink())throw new pd("REPOSITORY_PATH_FORBIDDEN","Symbolic links are outside the repository file boundary.");if(!o&&!a.isDirectory())throw new pd("REPOSITORY_PATH_INVALID","A parent path is not a directory.");a.isDirectory()&&this.assertRepositoryBoundary(r,i.slice(0,e+1).join("/"))}const o=s.relative(this.root,r);if(o.startsWith("..")||s.isAbsolute(o))throw new pd("REPOSITORY_PATH_FORBIDDEN","Path escapes the repository root.");return{absolutePath:r}}assertRepositoryBoundary(e,n){if(e===this.root)return;const i=s.join(e,".git");if(!t.existsSync(i))return;const r=t.lstatSync(i).isFile()?"submodule":"nested repository";throw new pd("REPOSITORY_PATH_FORBIDDEN",`Cannot enter ${r}: ${n}.`)}kind(e,n){if(n.isSymbolicLink())return"symlink";if(n.isFile())return"file";if(n.isDirectory()){const n=s.join(e,".git");return t.existsSync(n)?t.lstatSync(n).isFile()?"submodule":"nested-repository":"directory"}return"special"}assertRegularFile(e,t){if(!t.isFile())throw new pd("REPOSITORY_FILE_UNSUPPORTED",`Only regular files can be edited: ${e}.`)}}function ld(e){if(!e||e.includes("\0")||s.isAbsolute(e)||e.startsWith("\\")||/^[a-zA-Z]:[\\/]/.test(e))throw new pd("REPOSITORY_PATH_INVALID","Path must be repository-relative.");const t=e.split("/");if(t.some(e=>!e||"."===e||".."===e||".git"===e.toLowerCase()))throw new pd("REPOSITORY_PATH_INVALID","Path contains a forbidden segment.");return t}const md=ld;function hd(e,t){if(e.includes("\0"))throw new pd("REPOSITORY_FILE_BINARY","Text content cannot contain NUL bytes.");const s=Buffer.from(e,"utf8");if(s.length>t)throw new pd("REPOSITORY_FILE_TOO_LARGE",`File exceeds ${t} bytes.`);return s}function gd(e){return{executable:Boolean(73&e.mode),gitMode:73&e.mode?"100755":"100644"}}function fd(e,t){return`version:${n.createHash("sha256").update(e).update(String(511&t.mode)).digest("hex")}`}function yd(e){return`snapshot:${n.createHash("sha256").update(JSON.stringify(e)).digest("hex")}`}const vd=new Set(["add","branch","checkout","commit","diff","fetch","for-each-ref","ls-files","pull","push","remote","reset","restore","rev-list","rev-parse","show","status","symbolic-ref","update-index","worktree","write-tree"]);class Sd extends Error{code;exitCode;stderr;constructor(e,t,s={}){super(t),this.name="GitProcessError",this.code=e,this.exitCode=s.exitCode,this.stderr=s.stderr}}class wd{cwd;defaults;constructor(e,t={}){this.cwd=e,this.defaults=t}run(e,t=[],s={}){if(!vd.has(e))throw new Sd("GIT_EXIT",`Git subcommand is not allowed: ${e}`);if(t.some(e=>"string"!=typeof e||e.includes("\0")))throw new Sd("GIT_EXIT","Git arguments must be NUL-free strings.");const n=s.gitCommand||this.defaults.gitCommand||process.env.TASK_HANDOFF_GIT_COMMAND||"git",i=s.timeoutMs??this.defaults.timeoutMs??15e3,r=s.outputLimitBytes??this.defaults.outputLimitBytes??8388608,o=s.signal||this.defaults.signal,a=s.remote??this.defaults.remote??!1,c=["-c","color.ui=false","-c","core.pager=cat","-c","pager.branch=false","-c","diff.external=","-c","diff.trustExitCode=false","-c","diff.colorMoved=false",e,..."diff"===e||"show"===e?["--no-ext-diff","--no-textconv",...t]:t];return new Promise((e,t)=>{let d=!1,p=0,u=0;const l=[],h=[],g=m.spawn(n,c,{cwd:this.cwd,shell:!1,windowsHide:!0,stdio:["ignore","pipe","pipe"],env:Id(a)}),f=(s,n)=>{d||(d=!0,clearTimeout(S),o?.removeEventListener("abort",v),s?t(s):e(n))},y=e=>{g.kill("SIGKILL"),f(e)},v=()=>y(new Sd("GIT_ABORTED","Git operation was aborted.")),S=setTimeout(()=>y(new Sd("GIT_TIMEOUT",`Git operation exceeded ${i}ms.`)),i);if(o?.addEventListener("abort",v,{once:!0}),o?.aborted)return v();g.stdout.on("data",e=>{if(p+=e.length,p+u>r)return y(new Sd("GIT_OUTPUT_LIMIT",`Git output exceeded ${r} bytes.`));l.push(e)}),g.stderr.on("data",e=>{if(u+=e.length,p+u>r)return y(new Sd("GIT_OUTPUT_LIMIT",`Git output exceeded ${r} bytes.`));h.push(e)}),g.on("error",e=>{f("ENOENT"===e.code?new Sd("GIT_NOT_FOUND","Git executable is unavailable."):new Sd("GIT_EXIT",Ad(e.message)))}),g.on("close",e=>{if(d)return;const t=Buffer.concat(l).toString("utf8"),n=Ad(Buffer.concat(h).toString("utf8")),i=s.acceptedExitCodes||this.defaults.acceptedExitCodes||[];if(0!==e&&!i.includes(e??-1))return f(new Sd("GIT_EXIT",n.trim()||`Git exited with code ${e}.`,{exitCode:e??void 0,stderr:n}));f(void 0,{stdout:t,stderr:n,exitCode:e??0})})})}}function Id(e){const t={...process.env,GIT_PAGER:"cat",GIT_CONFIG_NOSYSTEM:"1",GIT_EXTERNAL_DIFF:"",GIT_TERMINAL_PROMPT:"0"};return e&&(t.GCM_INTERACTIVE="Never",t.GIT_ASKPASS="win32"===process.platform?"cmd /c exit 1":"/bin/false",t.SSH_ASKPASS=t.GIT_ASKPASS,t.SSH_ASKPASS_REQUIRE="force",t.GIT_SSH_COMMAND="ssh -oBatchMode=yes -oStrictHostKeyChecking=yes"),t}function Ad(e){return e.replace(/([a-z][a-z0-9+.-]*:\/\/)([^\s/@:]+)(?::[^\s/@]*)?@/gi,"$1***@").replace(/\b(?:ghp|github_pat|glpat|xox[baprs])-[-_a-zA-Z0-9]+\b/g,"***").replace(/([?&](?:access_token|token|key|password|signature)=)[^&\s]+/gi,"$1***").replace(/(Authorization:\s*(?:Bearer|Basic)\s+)[^\s]+/gi,"$1***")}class bd{tails=new Map;async withRepository(e,t){return this.enqueue(`repository:${e}`,t)}async withWorktree(e,t){return this.enqueue(`worktree:${e}`,t)}async withRepositoryAndWorktree(e,t,s){return this.withRepository(e,()=>this.withWorktree(t,s))}async enqueue(e,t){const s=this.tails.get(e)||Promise.resolve();let n;const i=new Promise(e=>{n=e});this.tails.set(e,i),await s;try{return await t()}finally{n(),this.tails.get(e)===i&&this.tails.delete(e)}}}class _d extends Error{code;current;details;constructor(e,t,s,n){super(t),this.code=e,this.current=s,this.details=n,this.name="RepositoryOperationError"}}class Td{resolve;queue;gitOptions;constructor(e,t=new bd,s={}){this.resolve=e,this.queue=t,this.gitOptions=s}async diff(e,n,i=524288,r=!1,o=20){if(!Number.isInteger(i)||i<1||i>2097152)throw new _d("REPOSITORY_PATH_INVALID","Diff byte limit is invalid.");if(!Number.isInteger(o)||o<1||o>3e3)throw new _d("REPOSITORY_PATH_INVALID","Diff context line limit is invalid.");ld(n);const a=await this.requireAvailable(),c=a.changes.entries.find(t=>t.scope===e&&t.path===n);if(!c)throw new _d("REPOSITORY_FILE_NOT_FOUND","Change entry no longer exists.",a);const d=a.worktreeRoot;let p,u=!1;if("untracked"===e){const e=function(e,n,i){const r=s.join(e,...ld(n)),o=t.realpathSync(s.dirname(r));if(o!==e&&!o.startsWith(`${e}${s.sep}`))throw new _d("REPOSITORY_PATH_FORBIDDEN","Untracked path crosses the repository boundary.");const a=t.lstatSync(r);if(!a.isFile()||a.isSymbolicLink())return{content:"",binary:!0};const c=Math.max(4*i,65536),d=t.openSync(r,"r");try{const e=Buffer.alloc(Math.min(a.size,c));if(t.readSync(d,e,0,e.length,0),e.includes(0))return{content:"",binary:!0};let s;try{s=new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch{return{content:"",binary:!0}}const i=s.split("\n"),r=i.map((e,t)=>t===i.length-1&&""===e?"":`+${e}`).filter((e,t)=>""!==e||t!==i.length-1).join("\n");return{content:`${[`diff --git a/${n} b/${n}`,"new file mode 100644","--- /dev/null",`+++ b/${n}`,`@@ -0,0 +1,${Math.max(0,i.length-(s.endsWith("\n")?1:0))} @@`].join("\n")}\n${r}${r?"\n":""}`,binary:!1}}finally{t.closeSync(d)}}(d,n,i);p=e.content,u=e.binary}else{const t=new wd(d,this.gitOptions),s="staged"===e?["--cached","--unified=3","--",n]:"conflict"===e?["--base","--unified=3","--",n]:["--unified=3","--",n];p=(await t.run("diff",s,{outputLimitBytes:Math.max(8*i,8388608)})).stdout,u=/(?:Binary files .* differ|GIT binary patch)/.test(p)}const l=function(e,t){const s=Buffer.from(e,"utf8");if(s.length<=t)return{content:e,truncated:!1};let n=t;for(;n>0&&128==(192&s[n]);)n-=1;return{content:s.subarray(0,n).toString("utf8"),truncated:!0}}(p,i),m=u?[]:Od(l.content);let h=[];if(r&&!u&&!l.truncated&&"untracked"!==e&&m.some(e=>"hunk"===e.kind&&e.hunkId)){const t=new wd(d,this.gitOptions),s=o+4,r="staged"===e?["--cached",`--unified=${s}`,"--",n]:"conflict"===e?["--base",`--unified=${s}`,"--",n]:[`--unified=${s}`,"--",n];h=function(e,t,s=20){const n=e.filter(e=>"hunk"===e.kind&&e.hunkId&&void 0!==e.newStart&&void 0!==e.newCount);if(!n.length)return[];const i=new Set(e.filter(e=>"context"===e.kind).map(xd)),r=new Map;for(const e of t){if("context"!==e.kind||void 0===e.newLine||i.has(xd(e)))continue;let t=0,s=Number.POSITIVE_INFINITY;for(const[i,r]of n.entries()){const n=r.newStart,o=n+r.newCount-1,a=e.newLine<n?n-e.newLine:e.newLine>o?e.newLine-o:0;a<s&&(t=i,s=a)}const o=n[t],a=e.newLine<o.newStart?"before":"after",c=`${o.hunkId}:${a}`,d=r.get(c)||{hunkIndex:t,position:a,lines:[]};d.lines.push(e),r.set(c,d)}const o=new Map;for(const e of r.values()){const t=e.lines.sort((e,t)=>(e.newLine||0)-(t.newLine||0)),i=s<3e3&&t.length>s,r="before"===e.position?t.slice(-s):t.slice(0,s),a="before"===e.position?n[e.hunkIndex-1]?.hunkId:n[e.hunkIndex]?.hunkId,c="before"===e.position?n[e.hunkIndex]?.hunkId:n[e.hunkIndex+1]?.hunkId,d=`gap:${a||"start"}:${c||"end"}`,p=o.get(d)||{gapId:d,beforeHunkId:a,afterHunkId:c,lines:[],startLineKeys:new Set,hasMore:!1};p.lines.push(...r),"after"===e.position&&r.forEach(e=>p.startLineKeys.add(xd(e))),p.hasMore||=i,o.set(d,p)}return[...o.values()].map(e=>{const t=[...new Map(e.lines.map(e=>[xd(e),e])).values()].sort((e,t)=>(e.newLine||0)-(t.newLine||0));return{gapId:e.gapId,beforeHunkId:e.beforeHunkId,afterHunkId:e.afterHunkId,lines:t,startLineCount:t.filter(t=>e.startLineKeys.has(xd(t))).length,hasMore:e.hasMore}})}(m,Od((await t.run("diff",r,{outputLimitBytes:Math.max(8*i,8388608)})).stdout),o)}return{path:c.path,oldPath:c.oldPath,scope:e,binary:u,complete:!u&&!l.truncated,truncated:l.truncated,byteLimit:i,content:u?"":l.content,lines:m,contextGaps:h,version:c.version,snapshotId:a.context.snapshotId}}stage(e){return this.mutate(e,["unstaged","untracked","conflict"],async(e,t)=>{await e.run("add",["--",...t])})}unstage(e){return this.mutate(e,["staged"],async(e,t,s)=>{"unborn"===s.context.head?.state?await e.run("reset",["--",...t]):await e.run("restore",["--staged","--",...t])})}discardWorktree(e){return this.mutate(e,["unstaged"],async(e,t)=>{await e.run("restore",["--worktree","--",...t])},["untracked","conflict"])}discardAllTracked(e){return this.mutate(e,["staged","unstaged"],async(e,t,s)=>{if("unborn"===s.context.head?.state)throw new _d("REPOSITORY_OPERATION_FAILED","Discarding all tracked changes requires an existing HEAD.",s);for(const e of t)if(s.changes.entries.filter(t=>t.path===e).some(e=>"untracked"===e.scope||"conflict"===e.scope))throw new _d("REPOSITORY_CONFLICT","Untracked and conflicted paths cannot be discarded by this action.",s);await e.run("restore",["--source=HEAD","--staged","--worktree","--",...t])},["untracked","conflict"])}async commit(e){const t=await this.requireAvailable();return this.queue.withWorktree(t.worktreeRoot,async()=>{const t=await this.requireAvailable();if(this.assertSnapshot(t,e.expectedSnapshotId),!e.message.trim())throw new _d("REPOSITORY_NOTHING_TO_COMMIT","Commit message is required.",t);if(!t.changes.entries.some(e=>"staged"===e.scope))throw new _d("REPOSITORY_NOTHING_TO_COMMIT","The index has no staged changes.",t);const s=new wd(t.worktreeRoot,this.gitOptions);try{await s.run("commit",["-m",e.message]);const t=(await s.run("rev-parse",["HEAD"])).stdout.trim();return this.result(await this.requireAvailable(),t)}catch(e){throw Ed(e,await this.resolve())}})}async mutate(e,t,s,n=[]){const i=await this.requireAvailable();return this.queue.withWorktree(i.worktreeRoot,async()=>{const i=await this.requireAvailable();this.assertSnapshot(i,e.expectedSnapshotId);for(const t of e.paths){const e=i.changes.entries.find(e=>e.path===t.path&&e.version===t.expectedVersion&&n.includes(e.scope));if(e)throw new _d("REPOSITORY_CONFLICT",`${e.scope} paths are not supported by this discard action.`,i)}const r=this.assertVersions(i,e.paths,t);try{return await s(new wd(i.worktreeRoot,this.gitOptions),r,i),this.result(await this.requireAvailable())}catch(e){if(e instanceof _d)throw e;throw Ed(e,await this.resolve())}})}async requireAvailable(){const e=await this.resolve();if("available"!==e.context.availability||!e.worktreeRoot||!e.gitCommonDir||!e.changes)throw new _d("REPOSITORY_NOT_WORKTREE","Repository is unavailable.",e);return e}assertSnapshot(e,t){if(e.context.snapshotId!==t)throw new _d("REPOSITORY_STATE_STALE","Repository state changed after it was loaded.",e)}assertVersions(e,t,s){if(!t.length)throw new _d("REPOSITORY_PATH_INVALID","At least one path is required.",e);const n=new Set;for(const i of t){if(ld(i.path),n.has(i.path))throw new _d("REPOSITORY_PATH_INVALID","Duplicate paths are not allowed.",e);n.add(i.path);const t=e.changes.entries.find(e=>e.path===i.path&&s.includes(e.scope));if(!t||t.version!==i.expectedVersion)throw new _d("REPOSITORY_STATE_STALE",`Change version is stale: ${i.path}.`,e)}return[...n]}result(e,t){return{ok:!0,snapshotId:e.context.snapshotId,context:e.context,changes:e.changes,...t?{commitOid:t}:{}}}}function Od(e){const t=[];let s,n;const i=e?e.split("\n"):[];e.endsWith("\n")&&i.pop();for(const e of i){const i=e.match(/^@@ -(?<oldStart>\d+)(?:,(?<oldCount>\d+))? \+(?<newStart>\d+)(?:,(?<newCount>\d+))? @@(?: ?(?<heading>.*))?$/);if(i?.groups){const r=Number(i.groups.oldStart),o=void 0===i.groups.oldCount?1:Number(i.groups.oldCount),a=Number(i.groups.newStart),c=void 0===i.groups.newCount?1:Number(i.groups.newCount),d=i.groups.heading||void 0,p=`hunk:${r}:${o}:${a}:${c}`;s=r,n=a,t.push({kind:"hunk",content:e,oldStart:r,oldCount:o,newStart:a,newCount:c,hunkId:p,...d?{heading:d}:{}});continue}if(e.startsWith("@@@")){s=void 0,n=void 0,t.push({kind:"hunk",content:e});continue}if(void 0===s||void 0===n||e.startsWith("diff --git ")||e.startsWith("index ")||e.startsWith("--- ")||e.startsWith("+++ ")||e.startsWith("\\ No newline")){t.push({kind:"metadata",content:e});continue}if(e.startsWith("+")){t.push({kind:"addition",content:e.slice(1),newLine:n}),n+=1;continue}if(e.startsWith("-")){t.push({kind:"deletion",content:e.slice(1),oldLine:s}),s+=1;continue}const r=e.startsWith(" ")?e.slice(1):e;t.push({kind:"context",content:r,oldLine:s,newLine:n}),s+=1,n+=1}return t}function xd(e){return`${e.oldLine||0}:${e.newLine||0}`}function Ed(e,t){if(!(e instanceof Sd))return new _d("REPOSITORY_OPERATION_FAILED","Repository operation failed.",t);if("GIT_TIMEOUT"===e.code)return new _d("REPOSITORY_COMMAND_TIMEOUT","Git operation timed out.",t);if("GIT_OUTPUT_LIMIT"===e.code)return new _d("REPOSITORY_OUTPUT_LIMIT","Git operation exceeded its output limit.",t);if("GIT_ABORTED"===e.code)return new _d("REPOSITORY_OPERATION_ABORTED","Git operation was aborted.",t);const s=`${e.message}\n${e.stderr||""}`;return/Author identity unknown|unable to auto-detect email address|Please tell me who you are/i.test(s)?new _d("REPOSITORY_IDENTITY_MISSING","Git user identity is not configured for this repository.",t):/gpg failed to sign|failed to write commit object|signing failed/i.test(s)?new _d("REPOSITORY_SIGNING_FAILED","Git could not sign the commit.",t):/hook declined|hook.*failed|pre-commit|commit-msg/i.test(s)?new _d("REPOSITORY_HOOK_FAILED","A Git commit hook rejected the commit.",t):new _d("REPOSITORY_OPERATION_FAILED","Git rejected the repository operation.",t)}class kd{resolve;worktrees;queue;gitOptions;constructor(e,t,s=new bd,n={}){this.resolve=e,this.worktrees=t,this.queue=s,this.gitOptions=n}async list(){const e=await this.requireAvailable();return this.listFromState(e)}create(e){return this.checkoutMutation(e.expectedSnapshotId,async t=>{await t.run("checkout",["-b",e.name])})}checkout(e){return this.checkoutMutation(e.expectedSnapshotId,async(t,s)=>{const n=(await this.listFromState(s)).branches.find(t=>"local"===t.kind&&t.name===e.branch);if(!n)throw new _d("REPOSITORY_BRANCH_INVALID","Local branch does not exist.",s);if(n.checkedOutWorktreeIds.length&&!n.current)throw new _d("REPOSITORY_BRANCH_OCCUPIED","Branch is checked out in another worktree.",s);await t.run("checkout",[e.branch])})}createTracking(e){return this.checkoutMutation(e.expectedSnapshotId,async(t,s)=>{if(!(await this.listFromState(s)).branches.some(t=>"remote-tracking"===t.kind&&t.name===e.remoteTrackingRef))throw new _d("REPOSITORY_BRANCH_INVALID","Remote-tracking branch does not exist in local refs.",s);await t.run("checkout",["-b",e.name,"--track",e.remoteTrackingRef])})}async delete(e){const t=await this.requireAvailable();return this.queue.withRepository(t.gitCommonDir,async()=>{const t=await this.requireAvailable();this.assertSnapshot(t,e.expectedSnapshotId);const s=(await this.listFromState(t)).branches.find(t=>"local"===t.kind&&t.name===e.name);if(!s)throw new _d("REPOSITORY_BRANCH_INVALID","Local branch does not exist.",t);if(s.current||s.checkedOutWorktreeIds.length)throw new _d("REPOSITORY_BRANCH_OCCUPIED","Current or checked-out branches cannot be deleted.",t);try{return await new wd(t.worktreeRoot,this.gitOptions).run("branch",["-d","--",e.name]),this.result(await this.requireAvailable())}catch(e){throw await this.gitError(e,"delete","Git rejected safe branch deletion.")}})}async fetch(e){const t=await this.requireAvailable();return this.queue.withRepository(t.gitCommonDir,async()=>{const t=await this.requireAvailable();this.assertSnapshot(t,e.expectedSnapshotId),await this.assertRemote(t,e.remote);try{return await new wd(t.worktreeRoot,this.gitOptions).run("fetch",[e.remote],{remote:!0,timeoutMs:6e4}),this.result(await this.requireAvailable())}catch(e){throw await this.gitError(e,"fetch","Git fetch failed.")}})}async pull(e){const t=await this.requireAvailable();return this.queue.withRepositoryAndWorktree(t.gitCommonDir,t.worktreeRoot,async()=>{const t=await this.requireAvailable();if(this.assertSnapshot(t,e.expectedSnapshotId),!zd(t))throw new _d("REPOSITORY_DIRTY","Pull requires a clean worktree and index.",t);const s=t.context.upstream;if(!s)throw new _d("REPOSITORY_UPSTREAM_MISSING","Current branch has no upstream.",t);if(s.ahead>0&&s.behind>0)throw new _d("REPOSITORY_NON_FAST_FORWARD","Current branch has diverged from its upstream.",t);try{return await new wd(t.worktreeRoot,this.gitOptions).run("pull",["--ff-only",s.remote,s.branch],{remote:!0,timeoutMs:6e4}),this.result(await this.requireAvailable())}catch(e){throw await this.gitError(e,"pull","Git pull could not fast-forward.")}})}publish(e){return this.pushMutation(e,!0)}push(e){return this.pushMutation({...e,setUpstream:!1},!1)}async pushMutation(e,t){const s=await this.requireAvailable();return this.queue.withRepository(s.gitCommonDir,async()=>{const s=await this.requireAvailable();if(this.assertSnapshot(s,e.expectedSnapshotId),!zd(s))throw new _d("REPOSITORY_DIRTY","Push requires a clean worktree and index.",s);if("branch"!==s.context.head?.state||s.context.head.branch!==e.sourceBranch)throw new _d("REPOSITORY_BRANCH_INVALID","Push source must be the current local branch.",s);if(t&&e.setUpstream&&!0!==e.confirmSetUpstream)throw new _d("REPOSITORY_REQUEST_INVALID","Setting upstream requires explicit confirmation.",s);if(!t&&s.context.upstream?.behind)throw new _d("REPOSITORY_NON_FAST_FORWARD","Local branch is behind its upstream.",s);await this.assertRemote(s,e.remote);const n=`refs/heads/${e.sourceBranch}:refs/heads/${e.targetBranch}`;try{return await new wd(s.worktreeRoot,this.gitOptions).run("push",[...e.setUpstream?["--set-upstream"]:[],e.remote,n],{remote:!0,timeoutMs:6e4}),this.result(await this.requireAvailable())}catch(e){throw await this.gitError(e,"push","Git push failed.")}})}async checkoutMutation(e,t){const s=await this.requireAvailable();return this.queue.withRepositoryAndWorktree(s.gitCommonDir,s.worktreeRoot,async()=>{const s=await this.requireAvailable();this.assertSnapshot(s,e);try{return await t(new wd(s.worktreeRoot,this.gitOptions),s),this.result(await this.requireAvailable())}catch(e){if(e instanceof _d)throw e;throw await this.gitError(e,"checkout","Git could not switch branches without overwriting changes.")}})}async listFromState(e){const t=new wd(e.worktreeRoot,this.gitOptions),s=await t.run("for-each-ref",["--format=%(refname)%00%(objectname)%00%(upstream:short)%00%(upstream:track,nobracket)","refs/heads","refs/remotes"]),n=await this.worktrees.list(),i=new Map;for(const e of n.items)"branch"===e.head.state&&e.head.branch&&i.set(e.head.branch,[...i.get(e.head.branch)||[],e.id]);const r=s.stdout.split("\n").filter(Boolean).flatMap(t=>{const[s,n,r,o]=t.split("\0");if(!s||!n||s.endsWith("/HEAD"))return[];const a=s.startsWith("refs/heads/"),c=s.replace(a?/^refs\/heads\//:/^refs\/remotes\//,""),d=(p=o||"",{ahead:Number(/ahead (\d+)/.exec(p)?.[1]||0),behind:Number(/behind (\d+)/.exec(p)?.[1]||0)});var p;return[{name:c,oid:n,kind:a?"local":"remote-tracking",current:a&&"branch"===e.context.head?.state&&e.context.head.branch===c,upstream:r||void 0,ahead:a?d.ahead:void 0,behind:a?d.behind:void 0,checkedOutWorktreeIds:a&&i.get(c)||[]}]});return{snapshotId:e.context.snapshotId,branches:r}}async assertRemote(e,t){if(!e.context.remotes?.some(e=>e.name===t))throw new _d("REPOSITORY_BRANCH_INVALID","Configured remote does not exist.",e)}assertSnapshot(e,t){if(e.context.snapshotId!==t)throw new _d("REPOSITORY_STATE_STALE","Repository state changed after it was loaded.",e)}async requireAvailable(){const e=await this.resolve();if("available"!==e.context.availability||!e.worktreeRoot||!e.gitCommonDir||!e.changes)throw new _d("REPOSITORY_NOT_WORKTREE","Repository is unavailable.",e);return e}async result(e){return{snapshotId:e.context.snapshotId,context:e.context,branches:await this.listFromState(e)}}async gitError(e,t,s){const n=await this.resolve();if(e instanceof Sd){const i=`${e.message}\n${e.stderr||""}`;if(/non-fast-forward|fetch first|rejected.*behind|Not possible to fast-forward/i.test(i))return new _d("REPOSITORY_NON_FAST_FORWARD",s,n);if(/authentication failed|permission denied|could not read Username|terminal prompts disabled|publickey/i.test(i))return new _d("REPOSITORY_AUTHENTICATION_FAILED","Git authentication failed in the controlled instance.",n);if("delete"===t&&/not fully merged|not merged/i.test(i))return new _d("REPOSITORY_BRANCH_UNMERGED","Branch contains commits that are not merged.",n);if("checkout"===t&&/already checked out|used by worktree/i.test(i))return new _d("REPOSITORY_BRANCH_OCCUPIED",s,n);if("checkout"===t&&/would be overwritten|local changes|untracked working tree files/i.test(i))return new _d("REPOSITORY_DIRTY",s,n);if("GIT_TIMEOUT"===e.code)return new _d("REPOSITORY_COMMAND_TIMEOUT",s,n)}return new _d("REPOSITORY_OPERATION_FAILED",s,n)}}function zd(e){const t=e.changes.summary;return t.conflicts+t.staged+t.unstaged+t.untracked===0}class Nd{sessions;gitOptions;constructor(e,t={}){this.sessions=e,this.gitOptions=t}resolveAiSession(e){return this.resolve("ai-session",e,this.sessions.aiSession(e))}resolveAppSession(e){const t=this.sessions.appSession(e);return this.resolve("app-session",e,t?{cwd:t.workspace?.cwd,status:t.status}:void 0)}async resolve(e,i,r){const o=(new Date).toISOString(),a=t=>({context:{availability:t,sessionKind:e,sessionId:i,observedAt:o}});if(!r)return a("session-not-found");if(["closed","terminated"].includes(r.status||"")||"ai-session"===e&&"stopped"===r.status)return a("session-inactive");if(!r.cwd?.trim())return a("cwd-missing");const c=s.resolve(r.cwd);try{if(!t.statSync(c).isDirectory())return a("cwd-inaccessible");t.accessSync(c,t.constants.R_OK)}catch{return a("cwd-inaccessible")}const d=new wd(c,this.gitOptions);let p,u,l,m;try{const e=await d.run("rev-parse",["--show-toplevel","--absolute-git-dir","--git-common-dir","--show-prefix"]),[s,n,i,r=""]=e.stdout.split("\n");p=t.realpathSync(s),u=Pd(n,c),l=Pd(i,c),m=r.replace(/\/$/,"")}catch(e){return e instanceof Sd&&"GIT_NOT_FOUND"===e.code?a("git-unavailable"):a("not-worktree")}const h=function(e){const t={ahead:0,behind:0,records:[]},s=e.split("\0");for(let e=0;e<s.length;e+=1){const n=s[e];if(n)if(n.startsWith("# branch.oid "))t.headOid="(initial)"===n.slice(13)?void 0:n.slice(13);else if(n.startsWith("# branch.head "))t.branch=n.slice(14);else if(n.startsWith("# branch.upstream "))t.upstreamRef=n.slice(18);else if(n.startsWith("# branch.ab ")){const e=/^# branch\.ab \+(\d+) -(\d+)$/.exec(n);e&&([t.ahead,t.behind]=[Number(e[1]),Number(e[2])])}else if(n.startsWith("1 ")){const e=n.split(" ");t.records.push({kind:"ordinary",xy:e[1],path:e.slice(8).join(" ")})}else if(n.startsWith("2 ")){const i=n.split(" ");t.records.push({kind:"renamed",xy:i[1],path:i.slice(9).join(" "),oldPath:s[++e]})}else if(n.startsWith("u ")){const e=n.split(" ");t.records.push({kind:"unmerged",xy:e[1],path:e.slice(10).join(" ")})}else n.startsWith("? ")&&t.records.push({kind:"untracked",xy:"??",path:n.slice(2)})}return t}((await d.run("status",["--porcelain=v2","--branch","-z","--untracked-files=all"])).stdout),g=await d.run("ls-files",["--stage","-z"]),f=await d.run("for-each-ref",["--format=%(refname)%00%(objectname)","refs/heads","refs/remotes"]),y=function(e,i,r){const o=new Map;for(const a of i){const i=s.join(e,...a.path.split("/"));let c="missing";try{const e=t.lstatSync(i);c=e.isFile()?n.createHash("sha256").update(t.readFileSync(i)).digest("hex"):`${e.mode}:${e.size}:${e.mtimeMs}:${e.isSymbolicLink()?t.readlinkSync(i):"special"}`}catch{}const d=r.split("\0").filter(e=>e.endsWith(`\t${a.path}`)||a.oldPath&&e.endsWith(`\t${a.oldPath}`)).join("\0");o.set(a.path,Md("version",[a.xy,c,d]))}return o}(p,h.records,g.stdout),v="(detached)"===h.branch?{state:"detached",oid:h.headOid}:h.headOid?{state:"branch",oid:h.headOid,branch:h.branch}:{state:"unborn",branch:h.branch},S=function(e,t,s){const n=[];for(const s of e.records){const e=Rd(s),i={path:s.path,oldPath:s.oldPath,status:e,binary:!1},r=e=>({...i,scope:e,version:Md("version",[t.get(s.path),e])});"unmerged"===s.kind?n.push(r("conflict")):"untracked"===s.kind?n.push(r("untracked")):("."!==s.xy[0]&&n.push(r("staged")),"."!==s.xy[1]&&n.push(r("unstaged")))}return{snapshotId:s,summary:{conflicts:n.filter(e=>"conflict"===e.scope).length,staged:n.filter(e=>"staged"===e.scope).length,unstaged:n.filter(e=>"unstaged"===e.scope).length,untracked:n.filter(e=>"untracked"===e.scope).length},entries:n}}(h,y,Md("snapshot",[h.headOid||"unborn",f.stdout,g.stdout,...[...y.entries()].flat()])),w=await async function(e){const t=(await e.run("remote")).stdout.split("\n").map(e=>e.trim()).filter(Boolean);return Promise.all(t.map(async t=>({name:t,fetchUrl:Cd((await e.run("remote",["get-url",t])).stdout.trim()),pushUrl:Cd((await e.run("remote",["get-url","--push",t])).stdout.trim())})))}(d),I=h.upstreamRef?function(e){const t=e.upstreamRef,s=t.indexOf("/");return{ref:t,remote:s>0?t.slice(0,s):".",branch:s>0?t.slice(s+1):t,ahead:e.ahead,behind:e.behind}}(h):void 0,A=Md("repo",[l]),b=Fd(A,p),_=Md("context",[e,i,A,b]),T=S.summary;return{context:{availability:"available",sessionKind:e,sessionId:i,observedAt:o,snapshotId:S.snapshotId,repositoryId:A,repositoryContextId:_,repositoryRoot:p,displayName:s.basename(p),cwdRelativePath:m,head:v,upstream:I,currentWorktree:{id:b,isCurrent:!0,isMain:u===l,managed:!1,head:v,dirty:T.conflicts+T.staged+T.unstaged+T.untracked>0,locked:!1,prunable:!1,activeAiSessionIds:"ai-session"===e?[i]:[],activeAppSessionIds:"app-session"===e?[i]:[]},changes:T,remotes:w,primaryAction:Dd(T,I)},changes:S,worktreeRoot:p,gitDir:u,gitCommonDir:l}}}function Pd(e,n){return t.realpathSync(s.resolve(n,e))}function Rd(e){return"unmerged"===e.kind?"unmerged":"untracked"===e.kind?"untracked":{A:"added",M:"modified",D:"deleted",R:"renamed",C:"copied",T:"type-changed"}[e.xy.replaceAll(".","")[0]]||"modified"}function Cd(e){return Ad(e).replace(/^([^@\s]+)@([^:\s]+):/,"***@$2:")}function Dd(e,t){return e.conflicts>0?"resolve-conflicts":e.staged+e.unstaged+e.untracked>0?"review-changes":t?t.ahead>0&&t.behind>0?"diverged":t.ahead>0?"push":t.behind>0?"pull":"up-to-date":"publish-branch"}function Md(e,t){return`${e}:${n.createHash("sha256").update(t.join("\0")).digest("hex")}`}function Fd(e,t){return Md("wt",[e,t])}class jd{root;registryPath;entries=new Map;constructor(e){const n=s.resolve(e);this.root=t.existsSync(n)?t.realpathSync(n):n,this.registryPath=s.join(this.root,"registry.json"),this.load()}allocate(e,i){this.ensureRoot();const r=s.join(this.root,e.replace(/^repo:/,""));t.mkdirSync(r,{recursive:!0,mode:448});const o=i.normalize("NFKD").replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"worktree";return s.join(r,`${o}-${n.randomUUID()}`)}add(e,s,n){const i=t.realpathSync(n);if(!Hd(i,this.root))throw new Error("Managed worktree path is outside the managed root.");this.entries.set(s,{repositoryId:e,worktreeId:s,path:i,createdAt:(new Date).toISOString()}),this.persist()}remove(e){this.entries.delete(e),this.persist()}isManaged(e,t,n){const i=this.entries.get(t);return Boolean(i&&i.repositoryId===e&&s.resolve(i.path)===s.resolve(n)&&Hd(i.path,this.root))}load(){if(t.existsSync(this.registryPath))try{const e=JSON.parse(t.readFileSync(this.registryPath,"utf8")),n=Array.isArray(e?.entries)?e.entries:[];for(const e of n){if(!e||"object"!=typeof e)continue;if("string"!=typeof e.repositoryId||"string"!=typeof e.worktreeId||"string"!=typeof e.path||"string"!=typeof e.createdAt)continue;const t=s.resolve(e.path);Hd(t,this.root)&&this.entries.set(e.worktreeId,{repositoryId:e.repositoryId,worktreeId:e.worktreeId,path:t,createdAt:e.createdAt})}}catch{}}persist(){this.ensureRoot();const e=`${this.registryPath}.${n.randomUUID()}.tmp`;t.writeFileSync(e,`${JSON.stringify({version:1,entries:[...this.entries.values()]},null,2)}\n`,{mode:384}),t.renameSync(e,this.registryPath)}ensureRoot(){t.mkdirSync(this.root,{recursive:!0,mode:448});const e=t.realpathSync(this.root);e!==this.root&&(this.root=e,this.registryPath=s.join(this.root,"registry.json"))}}class Ld{resolve;registry;sessions;queue;gitOptions;workspaceRoots;constructor(e,s,n,i,r=new bd,o={}){this.resolve=e,this.registry=s,this.sessions=n,this.queue=r,this.gitOptions=o,this.workspaceRoots=i.flatMap(e=>{try{return[t.realpathSync(e)]}catch{return[]}})}async list(){const e=await this.requireAvailable();return this.listFromState(e)}async create(e){const s=await this.requireAvailable();return this.queue.withRepository(s.gitCommonDir,async()=>{const s=await this.requireAvailable();if(s.context.snapshotId!==e.expectedSnapshotId)throw new _d("REPOSITORY_STATE_STALE","Repository state changed before worktree creation.",s);if((await this.listFromStateInternal(s)).some(t=>t.head.branch===e.branchName))throw new _d("REPOSITORY_BRANCH_OCCUPIED","Branch is already checked out in another worktree.",s);const n=new wd(s.worktreeRoot,this.gitOptions),i=this.registry.allocate(s.context.repositoryId,e.branchName);let r=!1;try{if("new-branch"===e.mode){const t=(await n.run("rev-parse",["--verify","--end-of-options",`${e.startRef}^{commit}`])).stdout.trim();await n.run("worktree",["add","-b",e.branchName,i,t])}else await n.run("rev-parse",["--verify","--end-of-options",`refs/heads/${e.branchName}^{commit}`]),await n.run("worktree",["add",i,e.branchName]);r=!0;const o=t.realpathSync(i),a=Fd(s.context.repositoryId,o);return this.registry.add(s.context.repositoryId,a,o),{worktreeId:a,worktrees:await this.listFromState(await this.requireAvailable())}}catch(e){if(r)try{await n.run("worktree",["remove",i])}catch{}try{t.rmSync(i,{recursive:!0})}catch{}if(e instanceof _d)throw e;throw new _d("REPOSITORY_OPERATION_FAILED","Git could not create the worktree.",await this.resolve())}})}async remove(e){const t=await this.requireAvailable(),s=(await this.listFromStateInternal(t)).find(t=>t.id===e.worktreeId);if(!s)throw new _d("REPOSITORY_WORKTREE_NOT_FOUND","Worktree no longer exists.",t);return this.queue.withRepositoryAndWorktree(t.gitCommonDir,s.canonicalPath,async()=>{const t=await this.requireAvailable();if((await this.listFromState(t)).snapshotId!==e.expectedSnapshotId)throw new _d("REPOSITORY_STATE_STALE","Worktree state changed before removal.",t);const s=(await this.listFromStateInternal(t)).find(t=>t.id===e.worktreeId);if(!s)throw new _d("REPOSITORY_WORKTREE_NOT_FOUND","Worktree no longer exists.",t);if(!s.canRemove)throw new _d("REPOSITORY_WORKTREE_UNSAFE",`Worktree cannot be removed: ${s.removeBlockers.join(", ")}.`,t);try{return await new wd(t.worktreeRoot,this.gitOptions).run("worktree",["remove",s.canonicalPath]),this.registry.remove(s.id),{removedWorktreeId:s.id,branchRetained:!0,worktrees:await this.listFromState(await this.requireAvailable())}}catch(e){if(e instanceof _d)throw e;throw new _d("REPOSITORY_OPERATION_FAILED","Git could not remove the worktree.",await this.resolve())}})}async resolveWorkspace(e,s){const n=await this.requireAvailable();if(n.context.repositoryContextId!==e)throw new _d("REPOSITORY_STATE_STALE","Repository context is stale.",n);const i=(await this.listFromStateInternal(n)).find(e=>e.id===s);if(!i)throw new _d("REPOSITORY_WORKTREE_NOT_FOUND","Worktree no longer exists.",n);if(!i.canCreateAiSession)throw new _d("REPOSITORY_WORKTREE_UNSAFE",`Worktree cannot host a new session: ${i.createAiSessionBlockers.join(", ")}.`,n);try{const e=t.realpathSync(i.canonicalPath);if(!t.statSync(e).isDirectory())throw new Error("not a directory");return e}catch{throw new _d("REPOSITORY_WORKTREE_NOT_FOUND","Worktree path is no longer accessible.",await this.resolve())}}async listFromState(e){const t=(await this.listFromStateInternal(e)).map(({canonicalPath:e,...t})=>t);return{repositoryId:e.context.repositoryId,repositoryContextId:e.context.repositoryContextId,snapshotId:(s=JSON.stringify(t),`worktrees:${n.createHash("sha256").update(s).digest("hex")}`),items:t};var s}async listFromStateInternal(e){const n=function(e){const t=[];let s;for(const n of e.split("\0"))n?n.startsWith("worktree ")?(s&&t.push(s),s={path:n.slice(9),detached:!1,locked:!1,prunable:!1}):s&&n.startsWith("HEAD ")?s.headOid=n.slice(5):s&&n.startsWith("branch refs/heads/")?s.branch=n.slice(18):s&&"detached"===n?s.detached=!0:s&&n.startsWith("locked")?(s.locked=!0,s.lockReason=n.slice(6).trim()||void 0):s&&n.startsWith("prunable")&&(s.prunable=!0):(s&&t.push(s),s=void 0);return s&&t.push(s),t}((await new wd(e.worktreeRoot,this.gitOptions).run("worktree",["list","--porcelain","-z"])).stdout);return Promise.all(n.map(async(n,i)=>{const r=function(e){try{return t.realpathSync(e)}catch{return s.resolve(e)}}(n.path),o=Fd(e.context.repositoryId,r),a=this.registry.isManaged(e.context.repositoryId,o,r),c=r===e.worktreeRoot,d=c||a||this.workspaceRoots.some(e=>Hd(r,e)),p=d&&t.existsSync(r),u=!(!p||n.prunable)&&await async function(e,t){try{return Boolean((await new wd(e,t).run("status",["--porcelain=v2","-z","--untracked-files=all"])).stdout)}catch{return!1}}(r,this.gitOptions),l=$d(this.sessions.aiSessions(),r,e=>e.cwd),m=l.map(e=>e.id),h=new Set(l.map(e=>e.appSessionId).filter(e=>Boolean(e))),g=$d(this.sessions.appSessions(),r,e=>e.workspace?.cwd).filter(e=>!h.has(e.id)).map(e=>e.id),f=[];d||f.push("outside-workspace-roots"),p||f.push("path-inaccessible"),n.locked&&f.push("locked"),n.prunable&&f.push("prunable");const y=[];0===i&&y.push("main-worktree"),a||y.push("external-worktree"),d||y.push("outside-workspace-roots"),p||y.push("path-inaccessible"),u&&y.push("dirty"),n.locked&&y.push("locked"),n.prunable&&y.push("prunable"),(m.length||g.length)&&y.push("session-occupied");const v=n.detached?{state:"detached",oid:n.headOid}:n.headOid?{state:"branch",oid:n.headOid,branch:n.branch}:{state:"unborn",branch:n.branch};return{id:o,canonicalPath:r,isCurrent:c,isMain:0===i,managed:a,head:v,dirty:u,locked:n.locked,lockReason:n.lockReason,prunable:n.prunable,activeAiSessionIds:m,activeAppSessionIds:g,canCreateAiSession:0===f.length,canRemove:0===y.length,createAiSessionBlockers:f,removeBlockers:y}}))}async requireAvailable(){const e=await this.resolve();if(!("available"===e.context.availability&&e.worktreeRoot&&e.gitCommonDir&&e.context.repositoryId&&e.context.repositoryContextId))throw new _d("REPOSITORY_NOT_WORKTREE","Repository is unavailable.",e);return e}}function $d(e,s,n){return e.filter(e=>{if(["stopped","exited","failed","closed","terminated","completed"].includes(e.status||""))return!1;const i=n(e);if(!i)return!1;try{return Hd(t.realpathSync(i),s)}catch{return!1}})}function Hd(e,t){const n=s.relative(s.resolve(t),s.resolve(e));return""===n||!n.startsWith("..")&&!s.isAbsolute(n)}const Ud=l.z.object({}).strict(),qd=l.z.object({path:l.z.string().max(4096).default("")}).strict(),Bd=l.z.object({path:l.z.string().min(1).max(4096)}).strict(),Kd=l.z.object({path:l.z.string().min(1).max(4096),scope:l.z.enum(["conflict","staged","unstaged","untracked"]),byteLimit:l.z.coerce.number().int().min(1).max(2097152).default(524288),includeContext:l.z.enum(["true","false"]).default("false").transform(e=>"true"===e),contextLines:l.z.coerce.number().int().min(1).max(3e3).default(20)}).strict();function Vd(e){return e instanceof l.z.ZodError||e instanceof _d||e instanceof pd?e:new _d("REPOSITORY_OPERATION_FAILED","AI session could not be started.")}async function Gd(e,t,s,n){const i=await Wd(e);return t.withWorktree(i.worktreeRoot,async()=>{const t=await Wd(e);if(t.context.snapshotId!==s)throw new _d("REPOSITORY_STATE_STALE","Repository state changed after the file was loaded.",t);const i=n(new ud(t.worktreeRoot)),r=await Wd(e);return{file:i,snapshotId:r.context.snapshotId,context:r.context,changes:r.changes}})}async function Wd(e){const t=await e();if("available"!==t.context.availability||!t.worktreeRoot||!t.changes)throw new _d({"session-not-found":"REPOSITORY_SESSION_NOT_FOUND","session-inactive":"REPOSITORY_SESSION_INACTIVE","cwd-missing":"REPOSITORY_CWD_MISSING","cwd-inaccessible":"REPOSITORY_CWD_INACCESSIBLE","git-unavailable":"REPOSITORY_GIT_UNAVAILABLE","not-worktree":"REPOSITORY_NOT_WORKTREE"}[t.context.availability]||"REPOSITORY_NOT_WORKTREE","Repository is unavailable for this session.",t);return t}function Yd(e,t){if(t instanceof l.z.ZodError)return e.code(400).send({error:{code:"REPOSITORY_REQUEST_INVALID",message:t.issues.map(e=>e.message).join("; "),retryable:!1}});const s=t instanceof _d||t instanceof pd?t.code:"REPOSITORY_OPERATION_FAILED",n=t instanceof _d||t instanceof pd?t.message:"Repository operation failed.",i=t instanceof _d?t.current:void 0,r=t instanceof _d?t.details:void 0,o=function(e){return"REPOSITORY_SESSION_NOT_FOUND"===e||"REPOSITORY_FILE_NOT_FOUND"===e||"REPOSITORY_WORKTREE_NOT_FOUND"===e?404:"REPOSITORY_GIT_UNAVAILABLE"===e?503:"REPOSITORY_FILE_TOO_LARGE"===e||"REPOSITORY_OUTPUT_LIMIT"===e?413:e.includes("STALE")||e.includes("CONFLICT")||e.includes("DIRTY")||e.includes("OCCUPIED")||e.includes("UNSAFE")?409:400}(s);return e.code(o).send({error:{code:s,message:n,retryable:"REPOSITORY_STATE_STALE"===s||"REPOSITORY_COMMAND_TIMEOUT"===s,...r?{details:r}:{}},...i?{current:{context:i.context,changes:i.changes}}:{}})}const Jd=require("ws");function Xd(e){return{method:e.method,headers:e.headers,body:e.streamRawRequest?e.rawRequest:e.requestBody,...e.streamRawRequest?{duplex:"half"}:{}}}function Qd(e){return o.Readable.fromWeb(e)}class Zd{refresh;publish;requestedRevision=0;completedRevision=0;latestReason="discovery-scan";inFlight;constructor(e,t){this.refresh=e,this.publish=t}request(e="discovery-scan"){return this.requestedRevision+=1,this.latestReason=e,this.inFlight||(this.inFlight=this.drain().finally(()=>{this.inFlight=void 0})),this.inFlight}async drain(){for(;this.completedRevision<this.requestedRevision;){const e=this.requestedRevision,t=this.latestReason;await this.refresh(),this.publish(t),this.completedRevision=e}}}const ep=l.z.object({id:l.z.string().trim().min(1).max(120),label:l.z.string().trim().min(1).max(120),projectRoot:l.z.string().trim().min(1).max(500),items:l.z.array(l.z.object({id:l.z.string().trim().min(1).max(120),type:l.z.enum(["file","dir"]),projectPath:l.z.string().trim().min(1).max(500),containerPath:l.z.string().trim().min(1).max(500)}).strip()).min(1).max(50)}).strip(),tp=l.z.object({preset:ep.optional()}).strip().default({}),sp=l.z.object({appId:l.z.string().min(1).max(80).regex(/^[a-z0-9][a-z0-9_.-]*$/).optional(),title:l.z.string().trim().min(1).max(120).optional(),args:l.z.array(l.z.string().max(4096)).max(64).optional(),cwd:l.z.string().trim().min(1).max(512).optional(),env:l.z.record(l.z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),l.z.string().max(4096)).optional(),display:l.z.object({width:l.z.number().int().min(320).max(7680).optional(),height:l.z.number().int().min(240).max(4320).optional(),depth:l.z.union([l.z.literal(16),l.z.literal(24),l.z.literal(32)]).optional()}).optional(),displayTarget:l.z.object({mode:l.z.enum(["isolated","shared"]),id:l.z.string().trim().min(1).max(80).regex(/^[a-z0-9][a-z0-9._-]*$/).optional(),autoCreate:l.z.boolean().optional()}).optional()}).strict(),np=l.z.object({OPENAI_API_KEY:l.z.string().max(4096).optional(),OPENAI_BASE_URL:l.z.string().max(4096).optional(),TASK_HANDOFF_CODEX_BASE_URL:l.z.string().max(4096).optional(),TASK_HANDOFF_CODEX_MODEL:l.z.string().max(4096).optional(),ANTHROPIC_API_KEY:l.z.string().max(4096).optional(),ANTHROPIC_BASE_URL:l.z.string().max(4096).optional(),TASK_HANDOFF_CLAUDE_MODEL:l.z.string().max(4096).optional()}).strict(),ip=Object.keys(np.shape),rp=l.z.object({width:l.z.number().int().min(320).max(7680).optional(),height:l.z.number().int().min(240).max(4320).optional(),depth:l.z.number().int().min(8).max(32).optional()}).strip(),op=l.z.object({title:l.z.string().trim().min(1).max(120)}).strict(),ap=l.z.object({name:l.z.string().trim().min(1).max(160),description:l.z.string().trim().max(1e3).optional(),source:F,action:j,policy:L.partial().optional(),deployment:l.z.object({deploymentId:l.z.string().trim().min(1).max(240).optional(),origin:l.z.enum(["control-plane","controlled-instance"]).optional(),enabled:l.z.boolean().optional(),target:H,localName:l.z.string().trim().min(1).max(160).optional()}).strict().optional()}).strict(),cp=l.z.object({name:l.z.string().trim().min(1).max(160).optional(),description:l.z.string().trim().max(1e3).nullable().optional()}).strict(),dp=l.z.object({promptOverride:l.z.string().trim().min(1).max(2e4).optional(),eventSummary:l.z.string().trim().max(1e3).optional(),deploymentId:l.z.string().trim().min(1).max(240).optional()}).strict().default({});function pp(e){return e instanceof l.z.ZodError?e.issues.map(e=>`${e.path.join(".")||"body"}: ${e.message}`).join("; "):e instanceof Error?e.message:String(e)}function up(e,t){if(t instanceof l.z.ZodError)return e.code(400).send({error:Os.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",i="number"==typeof s.statusCode?s.statusCode:"AI_SESSION_NOT_FOUND"===n?404:400;return e.code(i).send({error:Os.parse({code:n,message:t instanceof Error?t.message:String(t)})})}function lp(e,t=!1){const s=process.env[e];return void 0===s||""===s?t:["1","true","yes","on"].includes(s.toLowerCase())}function mp(e,s=200){const n=Math.min(Math.max(1,Number(s)||200),1e3),i=t.readFileSync(e,"utf8").split(/\r?\n/);return{path:e,lineCount:i.length,tail:i.slice(-n).join("\n")}}async function hp(e={}){const o=(new Date).toISOString(),m=pe(),h={...process.env};!function(e,t){if(lp("TASK_HANDOFF_DIAGNOSTIC_LOGS"))try{const n=s.join(e,"controlled-instance.log");k(n,{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,logPath:n,process:{pid:process.pid,ppid:process.ppid,cwd:process.cwd(),argv:process.argv,parent:E(process.ppid),env:x()}})}catch{}}(m.logDir,m.dataDir),Sa(h);const g=function(e){if("off"===process.env.TASK_HANDOFF_WEB_AUTH)return{enabled:!1};const s=process.env.TASK_HANDOFF_WEB_TOKEN?.trim();if(s)return{enabled:!0,source:"env",token:s};const i=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(i)return{enabled:!0,source:"file",token:i,tokenFile:e.webTokenPath};if("required"===process.env.TASK_HANDOFF_WEB_AUTH){const t=n.randomBytes(24).toString("base64url");return function(e,t){G(e,`${t}\n`)}(e.webTokenPath,t),{enabled:!0,source:"generated",token:t,tokenFile:e.webTokenPath}}return{enabled:!1,tokenFile:e.webTokenPath}}(m),f=new Mr,y=e.appRuntime||new wt(m);var v;y.replaceManagedEnvironment((v=h,np.parse(Object.fromEntries(ip.flatMap(e=>"string"==typeof v[e]?[[e,v[e]]]:[])))));const S=p({logger:e.logger??!0});let w;const I=e.appManagement||new la({stateDir:s.join(m.runtimeDir,"app-management"),installBaseDir:process.env.TASK_HANDOFF_MANAGED_APP_ROOT||s.join(m.dataDir,"managed-apps"),sessions:()=>y.listSessions(),publish:e=>f.publish("app.management",e),warn:e=>S.log?.warn?.({message:e},"app management persistence warning"),onTerminal:async()=>{w.enabled()&&await w.heartbeat()}}),A=e.aiSessionRegistry||oi();!function(e,t){const s=new Nd({aiSession:e=>t.aiSessions.get(e),appSession:e=>t.appRuntime.getSession(e)}),n=new jd(t.managedWorktreesRoot),i=new bd,r={aiSessions:()=>t.aiSessions.boundSnapshot(t.appRuntime.listSessions(),1e4).sessions,appSessions:()=>t.appRuntime.listSessions()},o=(e,o)=>{const a=((e,t)=>()=>"ai-session"===e?s.resolveAiSession(t):s.resolveAppSession(t))(e,o),c=new Ld(a,n,r,t.workspaceRoots,i);return{resolve:a,changes:new Td(a,i),worktrees:c,branches:new kd(a,c,i)}};for(const t of["ai-session","app-session"]){const s=`/api/${"ai-session"===t?"ai-sessions":"apps/sessions"}/:id/repository`;e.get(`${s}/context`,async(e,s)=>{try{return Ud.parse(e.query||{}),{data:(await o(t,e.params.id).resolve()).context}}catch(e){return Yd(s,e)}}),e.get(`${s}/worktrees`,async(e,s)=>{try{return Ud.parse(e.query||{}),{data:await o(t,e.params.id).worktrees.list()}}catch(e){return Yd(s,e)}}),e.post(`${s}/worktrees`,async(e,s)=>{try{const s=Xc.parse(e.body||{});return{data:await o(t,e.params.id).worktrees.create(s)}}catch(e){return Yd(s,e)}}),e.post(`${s}/worktrees/remove`,async(e,s)=>{try{const s=Qc.parse(e.body||{});return{data:await o(t,e.params.id).worktrees.remove(s)}}catch(e){return Yd(s,e)}}),e.get(`${s}/directories`,async(e,s)=>{try{const s=qd.parse(e.query||{}),n=await Wd(o(t,e.params.id).resolve);return{data:new ud(n.worktreeRoot).list(s.path)}}catch(e){return Yd(s,e)}}),e.get(`${s}/files`,async(e,s)=>{try{const s=Bd.parse(e.query||{}),n=await Wd(o(t,e.params.id).resolve);return{data:new ud(n.worktreeRoot).read(s.path)}}catch(e){return Yd(s,e)}}),e.post(`${s}/files`,{bodyLimit:5242880},async(e,s)=>{try{const s=Uc.parse(e.body||{});return{data:await Gd(o(t,e.params.id).resolve,i,s.expectedSnapshotId,e=>e.create(s.path,s.content))}}catch(e){return Yd(s,e)}}),e.put(`${s}/files`,{bodyLimit:5242880},async(e,s)=>{try{const s=qc.parse(e.body||{});return{data:await Gd(o(t,e.params.id).resolve,i,s.expectedSnapshotId,e=>e.write(s.path,s.content,s.expectedVersion))}}catch(e){return Yd(s,e)}}),e.post(`${s}/files/rename`,async(e,s)=>{try{const s=Bc.parse(e.body||{});return{data:await Gd(o(t,e.params.id).resolve,i,s.expectedSnapshotId,e=>e.rename(s.path,s.destination,s.expectedVersion))}}catch(e){return Yd(s,e)}}),e.delete(`${s}/files`,async(e,s)=>{try{const s=Kc.parse(e.body||{});return{data:await Gd(o(t,e.params.id).resolve,i,s.expectedSnapshotId,e=>e.delete(s.path,s.expectedVersion))}}catch(e){return Yd(s,e)}}),e.get(`${s}/changes`,async(e,s)=>{try{return Ud.parse(e.query||{}),{data:(await Wd(o(t,e.params.id).resolve)).changes}}catch(e){return Yd(s,e)}}),e.get(`${s}/diff`,async(e,s)=>{try{const s=Kd.parse(e.query||{});return{data:await o(t,e.params.id).changes.diff(s.scope,s.path,s.byteLimit,s.includeContext,s.contextLines)}}catch(e){return Yd(s,e)}}),e.post(`${s}/index/stage`,async(e,s)=>{try{return{data:await o(t,e.params.id).changes.stage(Vc.parse(e.body||{}))}}catch(e){return Yd(s,e)}}),e.post(`${s}/index/unstage`,async(e,s)=>{try{return{data:await o(t,e.params.id).changes.unstage(Gc.parse(e.body||{}))}}catch(e){return Yd(s,e)}}),e.post(`${s}/discard/worktree`,async(e,s)=>{try{return{data:await o(t,e.params.id).changes.discardWorktree(Wc.parse(e.body||{}))}}catch(e){return Yd(s,e)}}),e.post(`${s}/discard/all-tracked`,async(e,s)=>{try{return{data:await o(t,e.params.id).changes.discardAllTracked(Yc.parse(e.body||{}))}}catch(e){return Yd(s,e)}}),e.post(`${s}/commits`,async(e,s)=>{try{return{data:await o(t,e.params.id).changes.commit(Jc.parse(e.body||{}))}}catch(e){return Yd(s,e)}}),e.get(`${s}/branches`,async(e,s)=>{try{return Ud.parse(e.query||{}),{data:await o(t,e.params.id).branches.list()}}catch(e){return Yd(s,e)}}),e.post(`${s}/branches/create`,async(e,s)=>{try{return{data:await o(t,e.params.id).branches.create(sd.parse(e.body||{}))}}catch(e){return Yd(s,e)}}),e.post(`${s}/branches/checkout`,async(e,s)=>{try{return{data:await o(t,e.params.id).branches.checkout(nd.parse(e.body||{}))}}catch(e){return Yd(s,e)}}),e.post(`${s}/branches/tracking`,async(e,s)=>{try{return{data:await o(t,e.params.id).branches.createTracking(id.parse(e.body||{}))}}catch(e){return Yd(s,e)}}),e.post(`${s}/branches/delete`,async(e,s)=>{try{return{data:await o(t,e.params.id).branches.delete(rd.parse(e.body||{}))}}catch(e){return Yd(s,e)}}),e.get(`${s}/remotes`,async(e,s)=>{try{Ud.parse(e.query||{});const s=await Wd(o(t,e.params.id).resolve);return{data:{snapshotId:s.context.snapshotId,remotes:s.context.remotes||[]}}}catch(e){return Yd(s,e)}}),e.post(`${s}/delivery/fetch`,async(e,s)=>{try{return{data:await o(t,e.params.id).branches.fetch(od.parse(e.body||{}))}}catch(e){return Yd(s,e)}}),e.post(`${s}/delivery/pull`,async(e,s)=>{try{return{data:await o(t,e.params.id).branches.pull(ad.parse(e.body||{}))}}catch(e){return Yd(s,e)}}),e.post(`${s}/delivery/publish`,async(e,s)=>{try{return{data:await o(t,e.params.id).branches.publish(cd.parse(e.body||{}))}}catch(e){return Yd(s,e)}}),e.post(`${s}/delivery/push`,async(e,s)=>{try{return{data:await o(t,e.params.id).branches.push(dd.parse(e.body||{}))}}catch(e){return Yd(s,e)}})}e.post("/api/ai-sessions/:id/repository/ai-sessions",async(e,s)=>{try{const s=ed.parse(e.body||{}),n=o("ai-session",e.params.id),i=await Wd(n.resolve),r="current"===s.workspaceSelection.type?i.worktreeRoot:await n.worktrees.resolveWorkspace(s.workspaceSelection.repositoryContextId,s.workspaceSelection.worktreeId),a=await n.worktrees.list(),c="current"===s.workspaceSelection.type?a.items.find(e=>e.isCurrent)?.id:s.workspaceSelection.worktreeId;if(!c)throw new _d("REPOSITORY_WORKTREE_NOT_FOUND","Current worktree no longer exists.",i);return{data:{appSessionId:t.appRuntime.start(s.agent,{cwd:r}).id,worktreeId:c,disposition:"started"}}}catch(e){return Yd(s,Vd(e))}}),e.post("/api/ai-sessions/:id/repository/worktrees/ai-sessions",async(e,s)=>{try{const s=td.parse(e.body||{}),n=o("ai-session",e.params.id),i=await n.worktrees.create(s.worktree);try{const e=await n.worktrees.resolveWorkspace(i.worktrees.repositoryContextId,i.worktreeId);return{data:{appSessionId:t.appRuntime.start(s.agent,{cwd:e}).id,worktreeId:i.worktreeId,disposition:"started"}}}catch(e){const t=await async function(e,t){try{const s=await e.list(),n=s.items.find(e=>e.id===t);return n?.canRemove?(await e.remove({worktreeId:t,expectedSnapshotId:s.snapshotId,confirm:!0}),{removed:!0}):{removed:!1}}catch{return{removed:!1}}}(n.worktrees,i.worktreeId);throw new _d("REPOSITORY_OPERATION_FAILED",t.removed?"AI session launch failed; the newly created worktree was removed and its branch was retained.":"AI session launch failed; the newly created worktree was retained for recovery.",await n.resolve(),{worktreeId:i.worktreeId,worktreeRemoved:t.removed,branchRetained:!0,recoverable:!t.removed})}}catch(e){return Yd(s,Vd(e))}})}(S,{appRuntime:y,aiSessions:A,managedWorktreesRoot:process.env.TASK_HANDOFF_MANAGED_WORKTREES_ROOT||s.join(m.dataDir,"managed-worktrees"),workspaceRoots:[...(process.env.TASK_HANDOFF_WORKSPACE_ROOTS||"").split(s.delimiter),process.env.TASK_HANDOFF_WORKSPACE||""].map(e=>e.trim()).filter(Boolean)});const b=new Ai(m,{onWarning:e=>S.log.warn({warning:e},"AI session history entry was sanitized")}),_=new hi(b),T=new Tt(A),O=new se(m),P=new z(O,T),R=new N(O,P,m,(e,t)=>f.publish(e,t));w=new kr(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}}(),()=>xa(y,m,A,O)),await S.register(d),function(e,t){e.addHook("preHandler",async(e,s)=>{if(t.enabled&&"/api/health"!==e.url&&"/api/auth/status"!==e.url&&"/api/internal/model-environment"!==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."}})})}(S,g),S.addHook("onReady",async()=>{w.enabled()&&await w.start()}),S.addHook("onClose",async()=>{w.stop(),R.stop()});let C="";const D=process.env.TASK_HANDOFF_INSTANCE_ID||"standalone",M=`ais_${D}_${n.randomUUID()}`,F=`aps_${D}_${n.randomUUID()}`;let j=0,L={runningCount:0,waitingCount:0,staleCount:0,sessions:[],updatedAt:o};const $=[],H=new Set,U=new Map;let q,B="",K=0;const V={aiDiscoveryUnchanged:0,aiDiscoveryCorrections:0,appUnchanged:0},W=[];let Y=ec([]);const J=new ci,X=process.env.TASK_HANDOFF_AI_SESSION_DELTA_COALESCE_MS,Q=new Pr({emit:e=>f.publish("ai-session.message-delta",e),windowMs:void 0===X?void 0:Number(X)}),Z=e.codexAppServer||new Er(A,{onMessageDelta:e=>{const t=Gs.parse({instanceId:D,nodeId:process.env.TASK_HANDOFF_NODE_ID,...e,generatedAt:(new Date).toISOString()});Q.push(t)},onEventSourceClose:()=>Q.flushAll("event-source-close")}),ee=new Ei(A);T.register(Z),T.register(ee),J.register(new di),J.register(ee),J.register(new pi),J.register(Z);const te=()=>{const e=y.sharedResourceSessionAi("codex")?.appServer;return e?[...y.listSessions(),{id:"__shared_codex_app_server__",appId:"codex",title:"Codex app-server",status:"running",createdAt:o,ai:{appServer:e}}]:y.listSessions()},ne=new bi({history:b,registry:A,appSessions:te,startApp:e=>y.start(e.agent,{cwd:e.cwd,aiSessionResume:{aiSessionId:e.id,providerSessionId:e.providerSessionId}})}),ie=new Zd(async()=>{const e=te();_.reconcile(A.all(),e),A.reconcileAppSessionBindings(e),await J.refresh({registry:A,appSessions:e}),_.reconcile(A.all(),e)},e=>ae(e)),re=(e="discovery-scan")=>ie.request(e),oe=()=>{const e=Date.now()-36e5;for(;$.length&&$[0].createdAtMs<e;)$.shift()},ae=(e="provider-event")=>{Q.flushAll("authoritative-event");const t=A.boundSnapshot(te()),s=JSON.stringify(t.sessions);if(s!==C){C=s,L=t,j+=1;const n=((e,t)=>({meta:{streamId:M,instanceId:D,nodeId:process.env.TASK_HANDOFF_NODE_ID,revision:j,previousRevision:j>0?j-1:void 0,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=>{$.push({type:Jt,payload:e,createdAtMs:Date.now()}),oe()})(n),f.publish(Jt,n),S.log.info({traceId:n.meta.traceId,instanceId:n.meta.instanceId,streamId:n.meta.streamId,revision:n.meta.revision,reason:e,sessionCount:t.sessions.length,runningCount:t.runningCount,waitingCount:t.waitingCount},"ai-session.snapshot.published"),R.handleAiSessions(t),"discovery-scan"===e&&(V.aiDiscoveryCorrections+=1,S.log.info({instanceId:D,streamId:M,revision:j,correctionCount:V.aiDiscoveryCorrections},"ai-session.discovery.corrected"))}else"discovery-scan"===e&&(V.aiDiscoveryUnchanged+=1,S.log.info({instanceId:D,streamId:M,revision:j,unchangedCount:V.aiDiscoveryUnchanged},"ai-session.discovery.unchanged"))},ce=()=>{const e=Date.now()-qa;for(;W.length&&W[0].createdAtMs<e;)W.shift()},de=e=>({streamId:F,instanceId:D,nodeId:process.env.TASK_HANDOFF_NODE_ID,revision:K,previousRevision:K>0?K-1:void 0,traceId:`aps_evt_${Date.now().toString(36)}_${Math.random().toString(16).slice(2,10)}`,generatedAt:(new Date).toISOString(),reason:e}),ue=(e,t)=>({meta:de(t),session:e}),le=(e,t,s)=>({meta:de(s),sessionId:e,tombstone:t,expiresAt:new Date(Date.now()+qa).toISOString()}),me=(e,t,s)=>{(e=>{W.push({...e,createdAtMs:Date.now()}),ce()})(e),f.publish(e.type,e.payload),S.log.info({traceId:e.payload.meta.traceId,instanceId:e.payload.meta.instanceId,streamId:e.payload.meta.streamId,revision:e.payload.meta.revision,reason:s,eventType:e.type,sessionCount:t.sessions.length,runningCount:t.runningCount,problemCount:t.problemCount},"app-session.event.published")},he=(e,t)=>{ce();const s=K,n=W[0]?.payload.meta.revision??s+1;if(e!==F||t>s)return Za.parse({streamId:F,instanceId:D,sinceRevision:t,latestRevision:s,earliestRetainedRevision:n,syncRequired:!0,events:[]});if(t===s)return Za.parse({streamId:F,instanceId:D,sinceRevision:t,latestRevision:s,earliestRetainedRevision:n,syncRequired:!1,events:[]});const i=W.filter(e=>e.payload.meta.revision>t),r=i[0]?.payload.meta.revision,o=!i.length||r!==t+1;return Za.parse({streamId:F,instanceId:D,sinceRevision:t,latestRevision:s,earliestRetainedRevision:n,syncRequired:o,events:o?[]:i.map(e=>({type:e.type,payload:e.payload}))})},ge=(e,t)=>{oe();const s=j,n=$[0]?.payload.meta.revision??s+1;if(e!==M||t>s)return Ws.parse({streamId:M,instanceId:D,sinceRevision:t,latestRevision:s,earliestRetainedRevision:n,syncRequired:!0,events:[]});if(t===s)return Ws.parse({streamId:M,instanceId:D,sinceRevision:t,latestRevision:s,earliestRetainedRevision:n,syncRequired:!1,events:[]});const i=$.filter(e=>e.payload.meta.revision>t),r=i[0]?.payload.meta.revision,o=!i.length||r!==t+1;return Ws.parse({streamId:M,instanceId:D,sinceRevision:t,latestRevision:s,earliestRetainedRevision:n,syncRequired:o,events:o?[]:i.map(e=>({type:e.type,payload:e.payload}))})},fe=async e=>{if(H.has(e))return;const t=A.get(e);if(t&&"idle"===t.status&&A.nextQueuedMessage(e)){H.add(e);try{await T.sendNextQueuedMessage(e)}catch(t){S.log.warn({err:t,sessionId:e},"failed to drain AI session message queue")}finally{H.delete(e),ae("control-action")}}};let ye;const ve=A.onChange(()=>{ye||(ye=setTimeout(()=>{ye=void 0,ae()},Number(process.env.TASK_HANDOFF_AI_SESSION_PUBLISH_DEBOUNCE_MS)||50));for(const e of A.list()){const t=U.get(e.id);U.set(e.id,e.status),t&&"idle"!==t&&"idle"===e.status&&e.queue.pendingCount>0&&fe(e.id)}});S.addHook("onReady",async()=>{if(R.start(),lp("TASK_HANDOFF_CODEX_APP_SERVER",!1))try{y.ensureSharedResource("codex")}catch(e){S.log.warn({err:e},"failed to start shared Codex app-server")}}),S.addHook("onReady",async()=>{await re("startup"),q=setInterval(()=>{re()},Number(process.env.TASK_HANDOFF_AI_SESSION_SCAN_INTERVAL_MS)||3e4)}),S.addHook("onClose",async()=>{ve(),ye&&(clearTimeout(ye),ye=void 0),q&&(clearInterval(q),q=void 0),Z.stop(),ee.stop()}),S.addHook("preClose",async()=>{Z.stop(),Q.close("service-close")});const Se=(e,t)=>{(e=>{const t=ec(y.listSessions()),s=JSON.stringify(t.sessions);if(s===B)return V.appUnchanged+=1,void S.log.info({instanceId:D,streamId:F,revision:K,reason:e,sessionCount:t.sessions.length,unchangedCount:V.appUnchanged},"app-session.snapshot.skipped-unchanged");B=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])),i=[];for(const e of t.sessions){const t=s.get(e.id);t&&JSON.stringify(t)===JSON.stringify(e)||i.push({type:"upsert",session:e})}for(const t of e.sessions)n.has(t.id)||i.push({type:"removed",sessionId:t.id,tombstone:t});return i}(Y,t);if(0===K||1!==n.length){K+=1;const s=((e,t)=>({meta:{streamId:F,instanceId:D,nodeId:process.env.TASK_HANDOFF_NODE_ID,revision:K,previousRevision:K>0?K-1:void 0,traceId:`aps_evt_${Date.now().toString(36)}_${Math.random().toString(16).slice(2,10)}`,generatedAt:(new Date).toISOString(),reason:t},snapshot:e}))(t,e);me({type:$a,payload:s},t,e)}else{K+=1;const s=n[0],i="removed"===s.type?{type:Ua,payload:le(s.sessionId,s.tombstone,e)}:{type:Ha,payload:ue(s.session,e)};me(i,t,e)}Y=t})(e),re("app-session-recovered"===e?"discovery-scan":e).catch(s=>{S.log.warn({err:s,reason:e,sessionId:t.id},"failed to refresh AI sessions after app session event")})};y.on("created",e=>Se("app-session-created",e)),y.on("updated",e=>Se("app-session-updated",e)),y.on("deleted",e=>Se("app-session-deleted",e)),S.addHook("onClose",async()=>{y.stopAll()});const we=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}}();we?await S.register(c,{root:we,prefix:"/api/novnc/",decorateReply:!1}):S.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 Ie=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(Ie)&&await S.register(c,{root:Ie,prefix:"/"}),S.get("/api/health",async()=>({data:{ok:!0,version:wa(),startedAt:o}})),S.get("/api/auth/status",async()=>({data:{enabled:g.enabled,source:g.source,tokenFile:g.tokenFile}})),S.get("/api/events",{websocket:!0},e=>{f.connect(e),f.send(e,"streams.hello",{protocolVersion:1,streams:[{topic:"ai.sessions",instanceId:D,streamId:M,latestRevision:j,earliestRetainedRevision:$[0]?.payload.meta.revision??j+1},{topic:"app.sessions",instanceId:D,streamId:F,latestRevision:K,earliestRetainedRevision:W[0]?.payload.meta.revision??K+1}]}),f.send(e,"app.management",I.snapshotEvent()),I.refreshSnapshot().then(()=>I.publishSnapshot()).catch(e=>S.log.warn({err:e},"failed to refresh app management ownership for event snapshot"))}),S.get("/api/status",async()=>({data:{version:wa(),startedAt:o,runningAppCount:y.runningSessionCount(),storage:m}})),S.get("/api/instance/status",async()=>{const e=await xa(y,m,A,O);return{data:{id:process.env.TASK_HANDOFF_INSTANCE_ID,name:process.env.TASK_HANDOFF_INSTANCE_NAME||r.hostname(),...e,startedAt:o}}}),S.get("/api/instance/capabilities",async()=>({data:Ta(y)})),S.get("/api/workspace/status",async()=>({data:_a(m)})),S.get("/api/ai-sessions",async(e,t)=>{const s=void 0===e.query.sinceRevision?void 0:Number(e.query.sinceRevision);return Number.isInteger(s)&&s>=0?e.query.streamId?{data:ge(e.query.streamId,s)}:t.code(400).send({error:{code:"AI_SESSION_DELTA_INVALID",message:"streamId is required with sinceRevision."}}):{data:{streamId:M,revision:j,lastEventAt:$.at(-1)?.payload.meta.generatedAt||o,snapshot:L}}}),S.get("/api/ai-sessions/state",async()=>({data:{streamId:M,revision:j,lastEventAt:$.at(-1)?.payload.meta.generatedAt||o,snapshot:L}})),S.get("/api/triggers",async()=>({data:O.list()})),S.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."}})}),S.post("/api/triggers",async(e,t)=>{try{const t=ap.parse(e.body||{}),s=O.create(t);return R.restart(),f.publish("trigger.created",s),f.publish("trigger.updated",Oa(O)),{data:s}}catch(e){return t.code(400).send({error:{code:"TRIGGER_INVALID",message:pp(e)}})}}),S.patch("/api/triggers/:configHash",async(e,t)=>{try{const s=cp.parse(e.body||{}),n=O.patch(e.params.configHash,s);return n?(R.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:pp(e)}})}}),S.delete("/api/triggers/:configHash",async(e,t)=>{const s=O.delete(e.params.configHash);return s?(R.restart(),f.publish("trigger.deleted",{configHash:e.params.configHash}),f.publish("trigger.updated",Oa(O)),{data:{deleted:s}}):t.code(404).send({error:{code:"TRIGGER_NOT_FOUND",message:"Trigger not found."}})}),S.delete("/api/triggers/:configHash/deployments/:deploymentId",async(e,t)=>{const s=O.deleteDeployment(e.params.configHash,e.params.deploymentId);return s?(R.restart(),f.publish("trigger.deployment.deleted",{configHash:e.params.configHash,deploymentId:e.params.deploymentId}),f.publish("trigger.updated",Oa(O)),{data:{deleted:s}}):t.code(404).send({error:{code:"TRIGGER_DEPLOYMENT_NOT_FOUND",message:"Trigger deployment not found."}})}),S.post("/api/triggers/:configHash/enable",async(e,t)=>{const s=O.setEnabled(e.params.configHash,!0);return s?(R.restart(),f.publish("trigger.enabled",s),f.publish("trigger.updated",Oa(O)),{data:s}):t.code(404).send({error:{code:"TRIGGER_NOT_FOUND",message:"Trigger not found."}})}),S.post("/api/triggers/:configHash/disable",async(e,t)=>{const s=O.setEnabled(e.params.configHash,!1);return s?(R.restart(),f.publish("trigger.disabled",s),f.publish("trigger.updated",Oa(O)),{data:s}):t.code(404).send({error:{code:"TRIGGER_NOT_FOUND",message:"Trigger not found."}})}),S.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 i=dp.parse(n||{}),r=e.get(s);if(!r)throw Object.assign(new Error("Trigger not found."),{code:"TRIGGER_NOT_FOUND",statusCode:404});const o=i.deploymentId?r.deployments.find(e=>(e.deploymentId||e.configHash)===i.deploymentId):r.deployments[0];if(!o)throw Object.assign(new Error("Trigger has no deployment."),{code:"TRIGGER_DEPLOYMENT_NOT_FOUND",statusCode:404});return t.execute({config:r.config,deployment:o,eventType:"manual",eventSummary:i.eventSummary,promptOverride:i.promptOverride})}(O,P,e.params.configHash,e.body||{});return f.publish("trigger.run.completed",t),f.publish("trigger.updated",Oa(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:pp(s)}),t.code("TRIGGER_NOT_FOUND"===n?404:400).send({error:{code:n,message:pp(s)}})}}),S.get("/api/triggers/runs",async()=>({data:O.list().recentRuns})),S.get("/api/ai-sessions/history",async()=>({data:Fs.parse({items:b.list()})})),S.get("/api/ai-sessions/history/:id",async(e,t)=>{const s=b.detail(e.params.id);return s?{data:js.parse(s)}:t.code(404).send({error:Os.parse({code:"AI_SESSION_HISTORY_NOT_FOUND",message:"AI session history entry not found."})})}),S.post("/api/ai-sessions/:id/resume",async(e,t)=>{try{l.z.object({}).strict().parse(e.body||{});const t=Ls.parse(await ne.resume(e.params.id));return await re("control-action"),{data:t}}catch(e){return up(t,e)}}),S.get("/api/ai-sessions/:id",async(e,t)=>{const s=A.get(e.params.id);return s?{data:s}:t.code(404).send({error:{code:"AI_SESSION_NOT_FOUND",message:"AI session not found."}})}),S.get("/api/ai-sessions/:id/turns",async(e,t)=>{const s=A.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(),i=Number(e.query.afterRevision),r=s.turns||[],o=n?r.findIndex(e=>e.id===n):-1,a=r.filter(e=>!n||o<0||(e.id!==n?r.findIndex(t=>t.id===e.id)>o:!!Number.isFinite(i)&&e.revision>i)),c=a.at(-1);return{data:{sessionId:s.id,turns:a,nextCursor:c?{turnId:c.id,revision:c.revision}:n?{turnId:n,revision:Number.isFinite(i)?i:0}:void 0}}}),S.get("/api/ai-sessions/:id/transcript",async(e,t)=>{const s=A.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:mp(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)}})}}),S.post("/api/ai-sessions/:id/messages",{bodyLimit:67108864},async(e,t)=>{try{const t=bs.parse(e.body||{}),s=Cs.parse(await T.sendMessage(e.params.id,t));return ae("control-action"),{data:s}}catch(e){return up(t,e)}}),S.get("/api/ai-sessions/:id/mentions",async(e,t)=>{const s=A.get(e.params.id);if(!s)return t.code(404).send({error:{code:"AI_SESSION_NOT_FOUND",message:"AI session not found."}});try{return{data:await Z.mentionCatalog(s)}}catch(e){return up(t,e)}}),S.post("/api/ai-sessions/:id/mentions/files",async(e,t)=>{const s=A.get(e.params.id);if(!s)return t.code(404).send({error:{code:"AI_SESSION_NOT_FOUND",message:"AI session not found."}});try{const t=ws.parse(e.body||{});return{data:await Z.searchMentionFiles(s,t.query)}}catch(e){return up(t,e)}}),S.post("/api/ai-sessions/:id/commands",async(e,t)=>{const s=A.get(e.params.id);if(!s)return t.code(404).send({error:{code:"AI_SESSION_NOT_FOUND",message:"AI session not found."}});try{const t=us.parse(e.body||{}),n=ls.parse(await Z.executeCommand(s,t));return ae("control-action"),{data:n}}catch(e){return up(t,e)}}),S.get("/api/ai-sessions/:id/queue",async(e,t)=>{const s=A.get(e.params.id);return s?{data:s.queue}:t.code(404).send({error:{code:"AI_SESSION_NOT_FOUND",message:"AI session not found."}})}),S.post("/api/ai-sessions/:id/queue/:queueId/steer",async(e,t)=>{try{const t=Cs.parse(await T.steerQueuedMessage(e.params.id,e.params.queueId));return ae("control-action"),{data:t}}catch(e){return up(t,e)}}),S.post("/api/ai-sessions/:id/queue/:queueId/retry",async(e,t)=>{try{const t=T.retryQueuedMessage(e.params.id,e.params.queueId);return ae("control-action"),{data:t}}catch(e){return up(t,e)}}),S.delete("/api/ai-sessions/:id/queue/:queueId",async(e,t)=>{try{const t=T.removeQueuedMessage(e.params.id,e.params.queueId);return ae("control-action"),{data:t}}catch(e){return up(t,e)}}),S.patch("/api/ai-sessions/:id/queue/reorder",async(e,t)=>{try{const t=Ts.parse(e.body||{}),s=T.reorderQueuedMessages(e.params.id,t.queueIds);return ae("control-action"),{data:s}}catch(e){return up(t,e)}}),S.post("/api/ai-sessions/:id/interrupt",async(e,t)=>{try{const t=Cs.parse(await T.interrupt(e.params.id));return ae("control-action"),{data:t}}catch(e){return up(t,e)}}),S.post("/api/ai-sessions/:id/approval",async(e,t)=>{try{const t=_s.parse(e.body||{}),s=Cs.parse(await T.resolveApproval(e.params.id,t.decision));return ae("control-action"),{data:s}}catch(e){return up(t,e)}}),S.get("/api/diagnostics",async()=>({data:{...Aa(m,we),sessionStreams:{ai:{streamId:M,revision:j,retainedEventCount:$.length,discoveryUnchanged:V.aiDiscoveryUnchanged,discoveryCorrections:V.aiDiscoveryCorrections,messageDeltaCoalescing:{windowMs:Q.windowMs,pendingMessageCount:Q.pendingCount,...Q.diagnostics()}},app:{streamId:F,revision:K,retainedEventCount:W.length,unchangedRefreshes:V.appUnchanged}}}})),S.get("/api/apps/catalog",async()=>({data:y.catalog()})),S.get("/api/apps/management",async()=>({data:await I.refreshSnapshot()}));const Ae=(e,t)=>t instanceof l.z.ZodError?e.code(400).send({error:{code:"app_management_input_invalid",message:pp(t)}}):t instanceof pa?e.code(t.statusCode).send({error:{code:t.code,message:t.message,...t.details?{details:t.details}:{}}}):e.code(500).send({error:{code:"app_management_failed",message:t instanceof Error?t.message:String(t)}});S.post("/api/apps/:appId/install",async(e,t)=>{try{const s=yo.parse(e.body||{});return await I.refreshSnapshot(),t.code(202).send({data:{job:I.request(e.params.appId,"install",s.requestId)}})}catch(e){return Ae(t,e)}}),S.post("/api/apps/:appId/uninstall",async(e,t)=>{try{const s=yo.parse(e.body||{});return await I.refreshSnapshot(),t.code(202).send({data:{job:I.request(e.params.appId,"uninstall",s.requestId)}})}catch(e){return Ae(t,e)}}),S.get("/api/apps/jobs/:jobId",async(e,t)=>{try{return{data:{job:I.getJob(e.params.jobId)}}}catch(e){return Ae(t,e)}}),S.put("/api/internal/model-environment",async(e,t)=>{const s=process.env.TASK_HANDOFF_REGISTRATION_TOKEN?.trim(),n=e.headers.authorization||"";if(!s||n!==`Bearer ${s}`)return t.code(403).send({error:{code:"MANAGED_MODEL_ENVIRONMENT_FORBIDDEN",message:"Instance registration token is required."}});const i=np.parse(e.body||{});for(const e of ip)delete h[e];Object.assign(h,i),y.replaceManagedEnvironment(i);const r=Sa(h);return{data:{applied:!0,codexAuthConfigured:Boolean(i.OPENAI_API_KEY),configUpdated:r.applied}}}),S.get("/api/config-sync/presets",async()=>({data:ga()})),S.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=tp.parse(e.body||{}),n=ya(s,e.params.preset,t.preset);return"import"===s&&"codex"===e.params.preset&&Sa(h),{data:n}}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)}})}}),S.get("/api/apps/catalog/custom",async(e,t)=>{const s=y.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}}),S.patch("/api/apps/catalog/custom",async(e,t)=>{try{return{data:y.saveCustomCatalog(e.body?.items||[])}}catch(e){return t.code(400).send({error:{code:"APP_CATALOG_INVALID",message:e instanceof Error?e.message:String(e)}})}}),S.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."}}):e.query.streamId?{data:he(e.query.streamId,s)}:t.code(400).send({error:{code:"APP_SESSION_DELTA_INVALID",message:"streamId is required with sinceRevision."}})}return{data:{streamId:F,revision:K,lastEventAt:W.at(-1)?.payload.meta.generatedAt||o,snapshot:ec(y.listSessions())}}}),S.get("/api/apps/sessions/state",async()=>({data:{streamId:F,revision:K,lastEventAt:W.at(-1)?.payload.meta.generatedAt||o,snapshot:ec(y.listSessions())}})),S.post("/api/apps/sessions",async(e,t)=>{try{const t=function(e={}){const t=sp.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:y.start(t.appId,t.options)}}catch(e){if(e instanceof l.z.ZodError)return t.code(400).send({error:{code:"APP_LAUNCH_INVALID",message:pp(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)}})}}),S.get("/api/apps/sessions/:id",async(e,t)=>{const s=y.getSession(e.params.id);return s?{data:s}:t.code(404).send({error:{code:"APP_SESSION_NOT_FOUND",message:"App session not found."}})}),S.patch("/api/apps/sessions/:id",async(e,t)=>{try{const{title:t}=op.parse(e.body||{});return{data:y.rename(e.params.id,t)}}catch(e){if(e instanceof l.z.ZodError)return t.code(400).send({error:{code:"APP_SESSION_UPDATE_INVALID",message:pp(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)}})}}),S.post("/api/apps/sessions/:id/stop",async(e,t)=>{try{return{data:y.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)}})}}),S.post("/api/apps/sessions/:id/restart",async(e,t)=>{try{return{data:y.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)}})}}),S.post("/api/apps/sessions/:id/display",async(e,t)=>{try{return{data:y.resizeDisplay(e.params.id,rp.parse(e.body||{}))}}catch(e){const s=e&&"object"==typeof e&&"code"in e?String(e.code):"APP_DISPLAY_RESIZE_FAILED";return e instanceof l.z.ZodError?t.code(400).send({error:{code:"APP_DISPLAY_INVALID",message:pp(e)}}):t.code("APP_DISPLAY_NOT_FOUND"===s?404:400).send({error:{code:s,message:e instanceof Error?e.message:String(e)}})}}),S.delete("/api/apps/sessions/:id",async(e,t)=>{try{return{data:await y.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)}})}}),S.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:y.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)}})}}),S.get("/api/apps/sessions/:id/screenshot",async(e,t)=>{try{const s=y.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)}})}}),S.get("/api/apps/sessions/:id/snapshot",async(e,t)=>{try{const s=y.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)}})}}),S.get("/api/apps/sessions/:id/automation",async(e,t)=>{try{return{data:await y.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)}})}}),S.get("/api/apps/sessions/:id/tty",{websocket:!0},(e,t)=>{y.attachTty(t.params.id,e)}),S.get("/api/apps/sessions/:id/vnc",{websocket:!0},(e,t)=>{const s=y.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=i.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 be=async(e,t)=>{const s=y.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"===y.getSession(e.params.id)?.vnc?.backend,i=n?{authorization:Pa()}:{};t.hijack();const r=function(e){if(void 0!==e)return Buffer.isBuffer(e)||"string"==typeof e?e:JSON.stringify(e)}(e.body),o=void 0!==r||"GET"===e.method||"HEAD"===e.method||"OPTIONS"===e.method,c=Date.now(),d=`http://${s.host}:${s.port}`,p=new URL(Na(e.params.id,e.raw.url),`${d}/`).toString();for(;;)try{const c=await u.proxyFetch(d,p,Xd({method:e.method,headers:Ra(e.headers,s.host,s.port,i),requestBody:r,rawRequest:e.raw,streamRawRequest:void 0===r&&!o})),l=ja(c.headers);if("HEAD"!==e.method&&n&&Ma(l)){const e=Buffer.from(Fa(Buffer.from(await c.arrayBuffer()),l),"utf8"),s={...l,"content-length":String(e.byteLength)};delete s.etag,t.raw.writeHead(c.status||502,c.statusText,s),t.raw.end(e);break}if(t.raw.writeHead(c.status||502,c.statusText,La(c.headers)),!c.body||"HEAD"===e.method){t.raw.end();break}await a.pipeline(Qd(c.body),t.raw);break}catch(e){if(o&&za(e)&&Date.now()-c<8e3){await ka(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};S.route({method:"GET",url:"/api/apps/sessions/:id/web/*",wsHandler:(e,t)=>{const s=y.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}`,i="kasmvnc"===y.getSession(t.params.id)?.vnc?.backend?{authorization:Pa(),origin:n,"sec-websocket-origin":t.headers.origin||n}:{origin:n},r=Date.now(),o=`ws://${s.host}:${s.port}${Na(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"===y.getSession(t.params.id)?.vnc?.backend?["binary"]:void 0),c=()=>{if(e.readyState!==e.OPEN)return;const n=new Jd(o,a,{headers:Ca(t.headers,s.host,s.port,i)});!function(e,t,s={}){const n=s.pendingFrameLimit??256;let i=!1,r=oc(t);const o=[],a=[];let c;const d=()=>{c&&(clearTimeout(c),c=void 0)},p=(s,i)=>{if(s.length>=n)return ac(e,1011,"WebSocket bridge pending frame limit exceeded."),void ac(t,1011,"WebSocket bridge pending frame limit exceeded.");s.push(i)};s.upstreamOpenTimeoutMs&&!r&&(c=setTimeout(()=>{r||i||(ac(e,1011,"Upstream websocket did not open."),ac(t))},s.upstreamOpenTimeoutMs)),e.on("open",()=>dc(e,a)),t.on("open",()=>{d(),r=!0,s.onUpstreamOpen?.(),dc(t,o)}),e.on("message",(e,s=!1)=>{const n={data:e,isBinary:Boolean(s)};oc(t)?cc(t,n):p(o,n)}),t.on("message",(t,s=!1)=>{const n={data:t,isBinary:Boolean(s)};oc(e)?cc(e,n):p(a,n)}),t.on("close",(t,n)=>{d(),s.onUpstreamClose?.(t,n),(r||i||!s.onUpstreamCloseBeforeOpen?.())&&ac(e,t,n)}),t.on("error",t=>{s.onUpstreamError?.(t),(r||i||!s.onUpstreamErrorBeforeOpen?.(t))&&ac(e)}),e.on("close",(e,n)=>{d(),i=!0,s.onClientClose?.(e,n),ac(t,e,n)}),e.on("error",e=>{d(),i=!0,s.onClientError?.(e),ac(t,1011,"WebSocket bridge client failed.")})}(e,n,{onUpstreamCloseBeforeOpen:()=>Date.now()-r<8e3&&(ka(200).then(c),!0),onUpstreamErrorBeforeOpen:e=>za(e)})};c()},handler:be});for(const e of["DELETE","OPTIONS","PATCH","POST","PUT"])S.route({method:e,url:"/api/apps/sessions/:id/web/*",bodyLimit:67108864,handler:be});return S.get("/api/apps/sessions/:id/novnc/vnc.html",async(e,t)=>{const s=y.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",i=new URLSearchParams({path:s.vnc.webPath.replace(/^\//,""),autoconnect:"1",resize:n});return t.redirect(`/api/novnc/vnc.html?${i.toString()}`)}),S.setNotFoundHandler(async(e,n)=>{if(e.url.startsWith("/api/"))return n.code(404).send({error:{code:"NOT_FOUND",message:"Not found."}});const i=s.join(Ie,"index.html");return t.existsSync(i)?n.type("text/html").send(t.readFileSync(i,"utf8")):n.type("text/plain").send("TaskHandoff Web UI has not been built yet. Run pnpm web:build.")}),S}function gp(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 i;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",gp,Number(process.env.TASK_HANDOFF_WEB_PORT)||8080).option("--static-dir <path>","Web UI static directory",process.env.TASK_HANDOFF_WEB_STATIC_DIR||s.resolve(__dirname,"..","ui")).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 hp(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")},i=()=>{s("SIGTERM")};process.once("SIGINT",n),process.once("SIGTERM",i),e.addHook("onClose",async()=>{process.off("SIGINT",n),process.off("SIGTERM",i)})}(n),await n.listen({host:t,port:s}),n}({host:e.host,port:e.port,staticDir:e.staticDir})}),void 0===(i=process.argv)[2]&&i.push("web"),await n.parseAsync(process.argv)})().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});