@task-handoff/controlled-instance 0.0.3-alpha.7 → 0.0.4

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 (72) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +4 -0
  3. package/dist/controlled-instance-cli.js +1 -1
  4. package/package.json +6 -11
  5. package/ui/assets/{abnfDiagram-VRR7QNED-DTXXsV9S.js → abnfDiagram-VRR7QNED-BFiN2Q76.js} +1 -1
  6. package/ui/assets/{arc-DbU830GA.js → arc-Dq--sBDV.js} +1 -1
  7. package/ui/assets/{architectureDiagram-ZJ3FMSHR-T7U2B9Eh.js → architectureDiagram-ZJ3FMSHR-Db4PxmuE.js} +1 -1
  8. package/ui/assets/{blockDiagram-677ZJIJ3-Cm4Pjgex.js → blockDiagram-677ZJIJ3-BFrzsRE9.js} +1 -1
  9. package/ui/assets/{c4Diagram-LMCZKHZV-DSvkiizq.js → c4Diagram-LMCZKHZV-CUMWfjX6.js} +1 -1
  10. package/ui/assets/channel-D6D-Wcdm.js +1 -0
  11. package/ui/assets/{chunk-2Q5K7J3B-tPvOUUzT.js → chunk-2Q5K7J3B-CB1EgF5j.js} +1 -1
  12. package/ui/assets/{chunk-32BRIVSS-BDyLZeQy.js → chunk-32BRIVSS-BpsgCkbk.js} +1 -1
  13. package/ui/assets/{chunk-5VM5RSS4-clhOpzjE.js → chunk-5VM5RSS4-D2CmjJTK.js} +1 -1
  14. package/ui/assets/{chunk-EX3LRPZG-DR0T3pv9.js → chunk-EX3LRPZG-B6a-4QdQ.js} +1 -1
  15. package/ui/assets/{chunk-JWPE2WC7-DT-rU0K-.js → chunk-JWPE2WC7-CaAhbnco.js} +1 -1
  16. package/ui/assets/{chunk-MOJQB5TN-NgE2EuWv.js → chunk-MOJQB5TN-BVrVauq9.js} +1 -1
  17. package/ui/assets/{chunk-RYQCIY6F-Dkc7wIJ9.js → chunk-RYQCIY6F-floPzgi_.js} +1 -1
  18. package/ui/assets/{chunk-V7JOEXUC-BPhVL617.js → chunk-V7JOEXUC-CsI-g__8.js} +1 -1
  19. package/ui/assets/{chunk-VR4S4FIN-CywXYKIG.js → chunk-VR4S4FIN-D8Y1VI2b.js} +1 -1
  20. package/ui/assets/{chunk-XXDRQBXY-CsJHjuxY.js → chunk-XXDRQBXY-Cekf3q84.js} +1 -1
  21. package/ui/assets/classDiagram-OUVF2IWQ-B5JBH9Fz.js +1 -0
  22. package/ui/assets/classDiagram-v2-EOCWNBFH-B5JBH9Fz.js +1 -0
  23. package/ui/assets/{cose-bilkent-JH36ORCC-D65J_2Hn.js → cose-bilkent-JH36ORCC-RBmo63PX.js} +1 -1
  24. package/ui/assets/{cynefin-VYW2F7L2-Jga_52OU.js → cynefin-VYW2F7L2-BN3xSlwd.js} +1 -1
  25. package/ui/assets/{cynefinDiagram-TSTJHNR4-DoTu2Xxg.js → cynefinDiagram-TSTJHNR4-3l4UENpc.js} +1 -1
  26. package/ui/assets/{dagre-VKFMJZFB-Dn5Kb2I5.js → dagre-VKFMJZFB-COl79Q4K.js} +1 -1
  27. package/ui/assets/{diagram-FQU43EPY-DzRAYGCd.js → diagram-FQU43EPY-CdXE7bBS.js} +1 -1
  28. package/ui/assets/{diagram-G47NLZAW-CIT6Bdw1.js → diagram-G47NLZAW-DFA0Bju6.js} +1 -1
  29. package/ui/assets/{diagram-NH7WQ7WH-ClFAStmQ.js → diagram-NH7WQ7WH-Dy9tUKxS.js} +1 -1
  30. package/ui/assets/{diagram-OA4YK3LP-ZCfQYdzp.js → diagram-OA4YK3LP-D1FLe4Ab.js} +1 -1
  31. package/ui/assets/{diagram-WEI45ONY-DFwg8mBG.js → diagram-WEI45ONY-BUQTU_sh.js} +1 -1
  32. package/ui/assets/{ebnfDiagram-CCIWWBDH-DxecgAVi.js → ebnfDiagram-CCIWWBDH-DE_ci1oj.js} +1 -1
  33. package/ui/assets/{erDiagram-Q63AITRT-g6MB3uft.js → erDiagram-Q63AITRT-ChWjJ4b9.js} +1 -1
  34. package/ui/assets/{flowDiagram-23GEKE2U-CTure2lW.js → flowDiagram-23GEKE2U-LF29m1FZ.js} +1 -1
  35. package/ui/assets/{ganttDiagram-NO4QXBWP-DNm98BgC.js → ganttDiagram-NO4QXBWP-C6b_JCSo.js} +1 -1
  36. package/ui/assets/{gitGraphDiagram-IHSO6WYX-oIcnD29Y.js → gitGraphDiagram-IHSO6WYX-xE_MdkYR.js} +1 -1
  37. package/ui/assets/index-6FZ7v5dX.css +1 -0
  38. package/ui/assets/index-BIbw48nC.js +387 -0
  39. package/ui/assets/{infoDiagram-FWYZ7A6U-TR4jFZxP.js → infoDiagram-FWYZ7A6U-CEtNx7ws.js} +1 -1
  40. package/ui/assets/{ishikawaDiagram-FXEZZL3T-CPBYwjGv.js → ishikawaDiagram-FXEZZL3T-DW7bDtHL.js} +1 -1
  41. package/ui/assets/{journeyDiagram-5HDEW3XC-B0ke-LAX.js → journeyDiagram-5HDEW3XC-DCxHm0_Y.js} +1 -1
  42. package/ui/assets/{kanban-definition-HUTT4EX6-CIE0hAJm.js → kanban-definition-HUTT4EX6-lVRMOBLe.js} +1 -1
  43. package/ui/assets/{linear-C4xmSfoN.js → linear-BIwYlsDY.js} +1 -1
  44. package/ui/assets/{mermaid.core-BR8Poq2r.js → mermaid.core-B01IBkDW.js} +4 -4
  45. package/ui/assets/{mindmap-definition-LN4V7U3C-xm_0TNmj.js → mindmap-definition-LN4V7U3C-BErgcbhL.js} +1 -1
  46. package/ui/assets/{pegDiagram-2B236MQR-Bx7UVUjC.js → pegDiagram-2B236MQR-Cus1G4uH.js} +1 -1
  47. package/ui/assets/{pieDiagram-ENE6RG2P-Chq7ZhLC.js → pieDiagram-ENE6RG2P-Cy8c84gb.js} +1 -1
  48. package/ui/assets/{quadrantDiagram-ABIIQ3AL-DNui-rFa.js → quadrantDiagram-ABIIQ3AL-DfxzIOIK.js} +1 -1
  49. package/ui/assets/{railroadDiagram-RFXS5EU6-Vw-dt80v.js → railroadDiagram-RFXS5EU6-DPZcn8Wr.js} +1 -1
  50. package/ui/assets/{requirementDiagram-TGXJPOKE-BuW8FV9W.js → requirementDiagram-TGXJPOKE-CaIpeFc_.js} +1 -1
  51. package/ui/assets/{sankeyDiagram-HTMAVEWB-1BB0MXof.js → sankeyDiagram-HTMAVEWB-CrGNRaMm.js} +1 -1
  52. package/ui/assets/{sequenceDiagram-DBY2YBRQ-CHrkPabg.js → sequenceDiagram-DBY2YBRQ-C18kcqQK.js} +1 -1
  53. package/ui/assets/{sizeCapture-X5ZJPWSS-DPtwgI8Y.js → sizeCapture-X5ZJPWSS-CerMxLH-.js} +1 -1
  54. package/ui/assets/{stateDiagram-2N3HPSRC-CXok3iq7.js → stateDiagram-2N3HPSRC-BohrrPCg.js} +1 -1
  55. package/ui/assets/stateDiagram-v2-6OUMAXLB-D8nDa8ho.js +1 -0
  56. package/ui/assets/{swimlanes-5IMT3BWC-Du-OMsoU.js → swimlanes-5IMT3BWC-DsNmdb0L.js} +2 -2
  57. package/ui/assets/swimlanesDiagram-G3AALYLV-BvmD64a2.js +8 -0
  58. package/ui/assets/{timeline-definition-FHXFAJF6-D5shM9Hc.js → timeline-definition-FHXFAJF6-BgshrCBA.js} +1 -1
  59. package/ui/assets/ui-vendor-CYGfnfwU.js +3 -0
  60. package/ui/assets/{vennDiagram-L72KCM5P-CCmD3YaH.js → vennDiagram-L72KCM5P-B6hkO7gb.js} +1 -1
  61. package/ui/assets/{wardleyDiagram-EHGQE667-COAc0ADq.js → wardleyDiagram-EHGQE667-ChCeQ23d.js} +1 -1
  62. package/ui/assets/{xychartDiagram-FW5EYKEG-CphWD7q9.js → xychartDiagram-FW5EYKEG-VLWto9yh.js} +1 -1
  63. package/ui/index.html +3 -3
  64. package/dist/receiver-ink.mjs +0 -1
  65. package/ui/assets/channel-CsByyHGJ.js +0 -1
  66. package/ui/assets/classDiagram-OUVF2IWQ-Bkc2wpXA.js +0 -1
  67. package/ui/assets/classDiagram-v2-EOCWNBFH-Bkc2wpXA.js +0 -1
  68. package/ui/assets/index-C8yNGtsY.css +0 -1
  69. package/ui/assets/index-DMsXr75W.js +0 -387
  70. package/ui/assets/stateDiagram-v2-6OUMAXLB-DcwGHZgb.js +0 -1
  71. package/ui/assets/swimlanesDiagram-G3AALYLV-Cyuhb3By.js +0 -8
  72. package/ui/assets/ui-vendor-5uLhTuQK.js +0 -3
@@ -1 +1 @@
1
- "use strict";var e=require("commander"),t=require("node:fs"),s=require("node:path"),n=require("node:os"),r=require("write-file-atomic"),i=require("zod"),o=require("node:crypto"),a=require("node:net"),d=require("node:stream"),c=require("node:stream/promises"),p=require("@fastify/static"),u=require("@fastify/websocket"),l=require("fastify"),m=require("httpxy"),h=require("node:child_process"),g=require("node:events"),f=require("node-pty"),y=require("ws"),v=require("node:url");const S=process.env.TASK_HANDOFF_CONFIG||s.join(process.env.XDG_CONFIG_HOME||s.join(n.homedir(),".config"),"task-handoff","config.json"),I=i.z.record(i.z.string(),i.z.unknown());function A(){try{return I.parse(JSON.parse(t.readFileSync(S,"utf8")))}catch(e){return e&&"object"==typeof e&&"code"in e&&e.code,{}}}function b(e,t){const s={...e};for(const[e,n]of Object.entries(t))if(n&&"object"==typeof n&&!Array.isArray(n)){const t=s[e];s[e]=b(t&&"object"==typeof t&&!Array.isArray(t)?I.parse(t):{},n)}else void 0===n?delete s[e]:s[e]=n;return s}function _(e){const n=b(A(),e);return function(e){t.mkdirSync(s.dirname(S),{recursive:!0}),r.sync(S,`${JSON.stringify(I.parse(e),null,2)}\n`,{mode:384})}(n),n}const w=A(),T=Number(w.defaultConversationId)||1,N=process.env.TASK_HANDOFF_SOCKET||s.join(n.tmpdir(),`task-handoff-${process.getuid?process.getuid():"user"}.sock`),z=w.chatTools?.telegram?.default||{},O=z.defaultChatId,E=O?w.chatBindings?.telegram?.default?.[O]:void 0;function x(e){return Array.isArray(e)?e.map(e=>String(e).trim()).filter(Boolean):String(e||"").split(",").map(e=>e.trim()).filter(Boolean)}const k=O,D=z.token,C=x(z.allowedUserIds),P=Number(E?.conversationId)||T,F=w.wechat||{},R=F.baseUrl,M=F.chatId,j=F.contextToken,L=F.token,H=F.updatesBuf,$=Number(F.conversationId)||T,U=w.chatTools?.dingding?.default||{},q=U.defaultChatId,V=q?w.chatBindings?.dingding?.default?.[q]:void 0,B=U.clientId,K=U.clientSecret,G=U.corpId,W=U.robotCode,X=U.cardTemplateId||"13fc6717-12e4-43ed-8533-111a310d4995.schema",J=U.cardCallbackRouteKey||"bi_workflow_ticket",Y=Number(U.cardUserIdType)||1,Q=q,Z=x(U.allowedUserIds),ee=Number(V?.conversationId)||T,te=/(TOKEN|KEY|SECRET|AUTH|PASSWORD|COOKIE)/i,se=/^(TASK_HANDOFF|CODEX|CLAUDE|PWD$|OLDPWD$|SHELL$|TERM$)/;function ne(e,t){if(void 0!==t)return te.test(e)?"[redacted]":t}function re(e=process.env){return Object.fromEntries(Object.entries(e).filter(([e])=>se.test(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,ne(e,t)]))}function ie(e){if(e)try{return h.execFileSync("ps",["-p",String(e),"-o","pid=,ppid=,comm=,args="],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e3}).trim()||void 0}catch{return}}function oe(e,n){t.mkdirSync(s.dirname(e),{recursive:!0}),t.appendFileSync(e,`${JSON.stringify({time:(new Date).toISOString(),...n})}\n`,{mode:384})}function ae(e){const t=Number(String(e||"").trim());return Number.isInteger(t)&&t>0?t:void 0}function de(e){return"codex"===e||"claude"===e||"passive"===e?e:void 0}function ce(e){const t=Number(e);return Number.isFinite(t)&&t>0?t:void 0}function pe(e){return"codex"===e||"claude"===e?e:void 0}function ue(e,t="open"){return function(e,t="passive",s="open"){const n=(new Date).toISOString();return{id:e,mode:t,status:s,createdAt:n,updatedAt:n,agent:"codex"===t||"claude"===t?t:void 0}}(e,"passive",t)}const le=i.z.record(i.z.string(),i.z.unknown());class me{filePath;options;constructor(e,t){this.filePath=e,this.options=t}path(){return this.filePath}load(){try{const e=JSON.parse(t.readFileSync(this.filePath,"utf8"));return this.options.schema.parse(e)}catch(e){if(e&&"object"==typeof e&&"code"in e&&"ENOENT"===e.code)return this.options.defaultValue();throw e}}save(e){t.mkdirSync(s.dirname(this.filePath),{recursive:!0}),r.sync(this.filePath,`${JSON.stringify(this.options.schema.parse(e),null,2)}\n`,{mode:384})}patch(e){const t=this.load(),s=he(le.parse(t),e),n=this.options.schema.parse(s);return this.save(n),n}}function he(e,t){const s={...e};for(const[e,n]of Object.entries(t))if(n&&"object"==typeof n&&!Array.isArray(n)){const t=s[e];s[e]=he(t&&"object"==typeof t&&!Array.isArray(t)?le.parse(t):{},le.parse(n))}else void 0===n?delete s[e]:s[e]=n;return s}const ge=i.z.enum(["passive","codex","claude"]),fe=i.z.enum(["open","closed"]),ye=i.z.enum(["codex","claude"]),ve=i.z.object({schemaVersion:i.z.literal(1).default(1),id:i.z.number().int().positive(),mode:ge.default("passive"),status:fe.default("open"),title:i.z.string().optional(),cwd:i.z.string().optional(),timeoutMs:i.z.number().positive().optional(),agent:ye.optional(),agentSessionId:i.z.string().optional(),codexSessionId:i.z.string().optional(),createdAt:i.z.string(),updatedAt:i.z.string(),closedAt:i.z.string().optional()}),Se=i.z.object({id:i.z.number().int().positive(),status:fe.default("open"),mode:ge.default("passive"),title:i.z.string().optional(),updatedAt:i.z.string()}),Ie=i.z.object({schemaVersion:i.z.literal(1).default(1),defaultConversationId:i.z.number().int().positive().default(T),nextConversationId:i.z.number().int().positive().default(T+1),items:i.z.array(Se).default([])}),Ae=i.z.object({mode:ge.optional(),status:fe.optional(),title:i.z.string().trim().min(1).optional(),cwd:i.z.string().trim().min(1).optional(),timeoutMs:i.z.number().positive().optional(),agent:ye.optional(),agentSessionId:i.z.string().trim().min(1).optional(),codexSessionId:i.z.string().trim().min(1).optional()});function be(){return(new Date).toISOString()}function _e(e){const t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}function we(e){return Array.isArray(e)?e.map(we):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).filter(([,e])=>null!=e&&""!==e).map(([e,t])=>[e,we(t)])):e}function Te(e){return{id:e.id,status:e.status,mode:e.mode,title:e.title,updatedAt:e.updatedAt}}class Ne{paths;indexStore;constructor(e){this.paths=e,this.indexStore=new me(s.join(e.conversationsDir,"index.json"),{schema:Ie,defaultValue:()=>({schemaVersion:1,defaultConversationId:T,nextConversationId:T+1,items:[]})})}indexPath(){return this.indexStore.path()}list(){const e=this.ensureSeeded(),t=e.items.map(e=>this.loadRecord(e.id)).filter(e=>Boolean(e)).sort((e,t)=>e.id-t.id);return{schemaVersion:1,defaultConversationId:e.defaultConversationId,nextConversationId:e.nextConversationId,indexPath:this.indexStore.path(),items:t}}get(e){return this.ensureSeeded(),this.loadRecord(e)}create(e={}){const t=this.ensureSeeded(),s=be(),n=_e(e.id)||t.nextConversationId;if(this.loadRecord(n))throw Object.assign(new Error(`Conversation ${n} already exists.`),{code:"CONVERSATION_EXISTS"});const r=Ae.parse(we(e)),i=ve.parse({schemaVersion:1,id:n,mode:r.mode||"passive",status:r.status||"open",title:r.title,cwd:r.cwd,timeoutMs:r.timeoutMs,agent:r.agent||("codex"===r.mode||"claude"===r.mode?r.mode:void 0),agentSessionId:r.agentSessionId,codexSessionId:r.codexSessionId,createdAt:s,updatedAt:s});return this.saveRecord(i),this.saveIndex({...t,nextConversationId:Math.max(t.nextConversationId,n+1),items:[...t.items,Te(i)].sort((e,t)=>e.id-t.id)}),i}update(e,t){const s=this.getRequired(e),n=Ae.parse(we(t)),r=be(),i=ve.parse({...s,...n,agent:n.agent||("codex"===n.mode||"claude"===n.mode?n.mode:s.agent),updatedAt:r,closedAt:"closed"===n.status?s.closedAt||r:"open"===n.status?void 0:s.closedAt});return this.saveRecord(i),this.updateIndexItem(i),i}use(e){const t=this.getRequired(e),s=this.ensureSeeded();return this.saveIndex({...s,defaultConversationId:e}),_({defaultConversationId:e}),t}close(e){return this.update(e,{status:"closed"})}reopen(e){return this.update(e,{status:"open"})}delete(e){const s=this.ensureSeeded();if(e===s.defaultConversationId)throw Object.assign(new Error("Default conversation cannot be deleted."),{code:"CONVERSATION_DEFAULT"});const n=this.getRequired(e),r=this.recordPath(e);return t.existsSync(r)&&t.unlinkSync(r),this.saveIndex({...s,items:s.items.filter(t=>t.id!==e)}),n}ensureSeeded(){if(t.existsSync(this.indexStore.path()))return this.indexStore.load();const e=A(),s=function(e){const t=new Map;for(const s of Array.isArray(e.conversations)?e.conversations:[]){const e=ae(s?.id);if(!e)continue;const n=de(s.mode)||"passive",r=pe(s.agent)||("codex"===n||"claude"===n?n:void 0),i="string"==typeof s.agentSessionId&&s.agentSessionId.trim()?s.agentSessionId.trim():"codex"===r&&"string"==typeof s.codexSessionId&&s.codexSessionId.trim()?s.codexSessionId.trim():void 0;t.set(e,{id:e,mode:n,status:"closed"===s.status?"closed":"open",createdAt:s.createdAt||(new Date).toISOString(),updatedAt:s.updatedAt||(new Date).toISOString(),closedAt:s.closedAt,cwd:"string"==typeof s.cwd&&s.cwd.trim()?s.cwd.trim():void 0,timeoutMs:ce(s.timeoutMs),agent:r,aiSessionId:"string"==typeof s.aiSessionId&&s.aiSessionId.trim()?s.aiSessionId.trim():void 0,agentSessionId:i,codexSessionId:"string"==typeof s.codexSessionId&&s.codexSessionId.trim()?s.codexSessionId.trim():"codex"===r&&i?i:void 0})}const s=ae(e.defaultConversationId)||T;t.has(s)||t.set(s,ue(s)),t.has(T)||t.set(T,ue(T));const n=[...t.values()].sort((e,t)=>e.id-t.id),r=Math.max(Number(e.nextConversationId)||1,n.reduce((e,t)=>Math.max(e,t.id+1),1));return{conversations:n,defaultConversationId:s,nextConversationId:r}}(e),n=s.conversations.map(e=>ve.parse({schemaVersion:1,...e,agentSessionId:e.agentSessionId,codexSessionId:e.codexSessionId}));for(const e of n)this.saveRecord(e);const r=_e(e.defaultConversationId)||s.defaultConversationId||T,i=Ie.parse({schemaVersion:1,defaultConversationId:r,nextConversationId:s.nextConversationId,items:n.map(Te)});return this.saveIndex(i),_({defaultConversationId:r}),i}getRequired(e){const t=this.get(e);if(!t)throw Object.assign(new Error("Conversation not found."),{code:"CONVERSATION_NOT_FOUND"});return t}recordPath(e){return s.join(this.paths.conversationsDir,`conversation-${e}.json`)}loadRecord(e){const s=this.recordPath(e);try{return ve.parse(JSON.parse(t.readFileSync(s,"utf8")))}catch(e){if(e&&"object"==typeof e&&"code"in e&&"ENOENT"===e.code)return;throw e}}saveRecord(e){new me(this.recordPath(e.id),{schema:ve,defaultValue:()=>e}).save(e)}saveIndex(e){this.indexStore.save(Ie.parse(e))}updateIndexItem(e){const t=this.ensureSeeded();this.saveIndex({...t,items:t.items.map(t=>t.id===e.id?Te(e):t).sort((e,t)=>e.id-t.id)})}}function ze(e){const t=_e(e);if(!t)throw Object.assign(new Error("Conversation id must be a positive integer."),{code:"CONVERSATION_ID_INVALID"});return t}class Oe{store;receiverControl;aiSessionController;constructor(e,t,s){this.store=e,this.receiverControl=t,this.aiSessionController=s}async execute(e){const t=this.store.startRun(e.config,e.deployment,e.eventType,e.eventSummary),s=e.promptOverride||(n=e.config.action.promptTemplate,r={trigger:e.config,event:{type:e.eventType,summary:e.eventSummary||""}},n.replaceAll("{{trigger.configHash}}",r.trigger.configHash).replaceAll("{{trigger.name}}",r.trigger.name).replaceAll("{{event.type}}",r.event.type).replaceAll("{{event.summary}}",r.event.summary));var n,r;try{if("ai-session"===e.deployment.target.type){if(!this.aiSessionController)throw Object.assign(new Error("AI session trigger targets are not available."),{code:"TRIGGER_AI_SESSION_TARGET_UNAVAILABLE",statusCode:400});let n;try{n=await this.aiSessionController.sendMessage(e.deployment.target.aiSessionId,{message:s})}catch(t){throw t&&"object"==typeof t&&"code"in t&&"AI_SESSION_NOT_FOUND"===String(t.code)&&this.store.deleteDeployment(e.deployment.configHash,e.deployment.deploymentId||e.deployment.configHash),t}return{run:this.store.completeRun(t),result:n}}const n=await this.receiverControl.message({channel:"web",chatSessionId:`trigger:${e.deployment.deploymentId||e.deployment.configHash}`,userId:"trigger",conversationId:e.deployment.target.conversationId,text:s,attachments:[]});return{run:this.store.completeRun(t),result:n}}catch(e){const s=this.store.completeRun(t,e);throw Object.assign(e instanceof Error?e:new Error(String(e)),{run:s})}}}class Ee{store;executor;paths;publish;timers=new Map;watches=new Map;running=new Set;queued=new Map;lastRunAt=new Map;previousAiSessions=new Map;constructor(e,t,s,n){this.store=e,this.executor=t,this.paths=s,this.publish=n}start(){this.stop();const e=this.store.list();for(const t of e.deployments.filter(e=>e.enabled)){const s=e.configs.find(e=>e.configHash===t.configHash);s&&("schedule"===s.source.type&&this.startSchedule(s,t),"file-change"===s.source.type&&this.startFileWatch(s,t))}}restart(){this.start()}stop(){for(const e of this.timers.values())clearInterval(e);this.timers.clear();for(const e of this.watches.values()){for(const t of e.watchers)t.close();e.debounce&&clearTimeout(e.debounce)}this.watches.clear()}handleAiSessions(e){const t=new Map(e.sessions.map(e=>[e.id,e])),s=this.store.pruneMissingAiSessionDeployments(new Set(t.keys()));s.length&&(this.restart(),this.publish?.("trigger.deployment.pruned",{deployments:s}),this.publish?.("trigger.updated",this.store.list()));const n=this.store.list();for(const t of n.deployments.filter(e=>e.enabled)){const s=n.configs.find(e=>e.configHash===t.configHash);if(s&&"ai-session"===s.source.type)for(const n of e.sessions){const e=this.previousAiSessions.get(n.id);if(!e||!this.aiSessionMatches(s,n))continue;const r=e.status!==n.status,i=e.phase!==n.phase;if(!r&&!i)continue;const o=`AI session ${n.id}: ${e.status}/${e.phase} -> ${n.status}/${n.phase}`;this.execute(s,t,"ai-session",o)}}this.previousAiSessions=t}startSchedule(e,t){if("schedule"!==e.source.type)return;const s=e.source,n=xe(t);if("intervalMs"in s)return void this.timers.set(n,setInterval(()=>{this.execute(e,t,"schedule",`Interval ${s.intervalMs}ms`)},s.intervalMs));const r=()=>{const i=function(e){if("intervalMs"in e)return new Date(Date.now()+e.intervalMs);const[t,s]=e.timeOfDay.split(":").map(Number),n=new Date;for(let r=0;r<=14;r+=1){const i=new Date(n.getTime()+864e5*r);if("weekly"===e.scheduleKind&&!e.weekdays.includes(De(i,e.timezone).weekday))continue;const o=ke(i,e.timezone,t,s);if(o.getTime()>n.getTime()+500)return o}return new Date(Date.now()+864e5)}(s),o=Math.max(1e3,i.getTime()-Date.now()),a=setTimeout(()=>{this.execute(e,t,"schedule",function(e){return"intervalMs"in e?`Interval ${e.intervalMs}ms`:"daily"===e.scheduleKind?`Daily at ${e.timeOfDay} ${e.timezone}`:`Weekly on ${e.weekdays.join(",")} at ${e.timeOfDay} ${e.timezone}`}(s)),r()},o);this.timers.set(n,a)};r()}startFileWatch(e,n){if("file-change"!==e.source.type)return;const r=e.source,i=xe(n),o={watchers:[],changed:new Set};for(const i of e.source.roots){const a=s.resolve(i),d=Ce();if(a.startsWith(d)&&t.existsSync(a))for(const i of Re(a)){const a=t.watch(i,(t,a)=>{const c=a?s.join(i,String(a)):i;this.fileMatches(e,c)&&(o.changed.add(s.relative(d,c)),o.debounce&&clearTimeout(o.debounce),o.debounce=setTimeout(()=>{const t=[...o.changed].sort();o.changed.clear(),this.execute(e,n,"file-change",`Changed files:\n${t.join("\n")}`)},r.debounceMs))});o.watchers.push(a)}}o.watchers.length&&this.watches.set(i,o)}fileMatches(e,t){if("file-change"!==e.source.type)return!1;const n=s.relative(Ce(),t).replaceAll(s.sep,"/");return!Pe(n)&&!(e.source.ignore||[]).some(e=>Fe(e,n))&&e.source.globs.some(e=>Fe(e,n))}aiSessionMatches(e,t){return!("ai-session"!==e.source.type||e.source.conversationId&&t.conversationId!==e.source.conversationId||e.source.agent&&t.agent!==e.source.agent||e.source.statuses?.length&&!e.source.statuses.includes(t.status)||e.source.phases?.length&&!e.source.phases.includes(t.phase))}async execute(e,t,s,n){const r=xe(t),i=Date.now(),o=e.policy.cooldownMs||0,a=this.lastRunAt.get(r)||0;if(o&&i-a<o)return this.store.skipRun(e,t,s,"Skipped by cooldown policy."),void this.publish?.("trigger.run.skipped",{configHash:e.configHash,deploymentId:t.deploymentId,reason:"cooldown"});if(this.running.has(r))"queue"===e.policy.whenBusy?this.queued.set(r,{config:e,deployment:t,eventType:s,eventSummary:n}):(this.store.skipRun(e,t,s,"Skipped because trigger is already running."),this.publish?.("trigger.run.skipped",{configHash:e.configHash,deploymentId:t.deploymentId,reason:"busy"}));else{this.running.add(r),this.lastRunAt.set(r,i),this.publish?.("trigger.run.started",{configHash:e.configHash,deploymentId:t.deploymentId,eventType:s});try{const r=await this.executor.execute({config:e,deployment:t,eventType:s,eventSummary:n});this.publish?.("trigger.run.completed",r),this.publish?.("trigger.updated",this.store.list())}catch(t){this.publish?.("trigger.run.failed",{configHash:e.configHash,error:t instanceof Error?t.message:String(t)}),this.publish?.("trigger.updated",this.store.list())}finally{this.running.delete(r);const e=this.queued.get(r);e&&(this.queued.delete(r),setTimeout(()=>{this.execute(e.config,e.deployment,e.eventType,e.eventSummary)},0))}}}}function xe(e){return e.deploymentId||e.configHash}function ke(e,t,s,n){const r=De(e,t),i=Date.UTC(r.year,r.month-1,r.day,s,n,0,0),o=new Date(i),a=De(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 De(e,t){const s=new Intl.DateTimeFormat("en-US",{timeZone:t,weekday:"short",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).formatToParts(e),n=e=>s.find(t=>t.type===e)?.value||"";return{year:Number(n("year")),month:Number(n("month")),day:Number(n("day")),hour:Number(n("hour")),minute:Number(n("minute")),weekday:{Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6}[n("weekday")]??0}}function Ce(){return s.resolve(process.env.TASK_HANDOFF_WORKSPACE||process.env.WORKSPACE||"/workspace")}function Pe(e){return/(^|\/)(\.git|node_modules|dist|build)\//.test(e)||/\.(log|tmp|swp)$/.test(e)}function Fe(e,t){if("**/*"===e||"**"===e)return!0;const s=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replaceAll("**",".*").replaceAll("*","[^/]*");return new RegExp(`^${s}$`).test(t)}function Re(e){if("darwin"===process.platform||"win32"===process.platform)return[e];const n=[e],r=[e];for(;r.length;){const e=r.pop();let i=[];try{i=t.readdirSync(e,{withFileTypes:!0})}catch{continue}for(const t of i){if(!t.isDirectory())continue;const i=s.join(e,t.name);Pe(`${s.relative(Ce(),i).replaceAll(s.sep,"/")}/`)||(n.push(i),r.push(i))}}return n}const Me=i.z.union([i.z.object({type:i.z.literal("schedule"),scheduleKind:i.z.literal("interval").default("interval"),intervalMs:i.z.number().int().min(1e3)}).strict(),i.z.object({type:i.z.literal("schedule"),scheduleKind:i.z.literal("daily"),timeOfDay:i.z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/),timezone:i.z.string().trim().min(1).max(120)}).strict(),i.z.object({type:i.z.literal("schedule"),scheduleKind:i.z.literal("weekly"),weekdays:i.z.array(i.z.number().int().min(0).max(6)).min(1).max(7),timeOfDay:i.z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/),timezone:i.z.string().trim().min(1).max(120)}).strict()]),je=i.z.union([Me,i.z.object({type:i.z.literal("file-change"),roots:i.z.array(i.z.string().trim().min(1).max(4096)).min(1).max(50),globs:i.z.array(i.z.string().trim().min(1).max(500)).min(1).max(100),ignore:i.z.array(i.z.string().trim().min(1).max(500)).max(100).optional(),debounceMs:i.z.number().int().min(100).max(6e4).default(1500)}).strict(),i.z.object({type:i.z.literal("ai-session"),conversationId:i.z.number().int().positive().optional(),agent:i.z.string().trim().min(1).max(80).optional(),statuses:i.z.array(i.z.enum(["running","waiting","idle","failed"])).max(20).optional(),phases:i.z.array(i.z.enum(["thinking","tool","editing","approval","responding","unknown"])).max(20).optional()}).strict()]),Le=i.z.object({promptTemplate:i.z.string().trim().min(1).max(2e4)}).strict(),He=i.z.object({cooldownMs:i.z.number().int().min(0).max(864e5).optional(),maxConcurrentRuns:i.z.number().int().min(1).max(20).default(1),whenBusy:i.z.enum(["skip","queue"]).default("skip")}).strict(),$e=i.z.object({configHash:i.z.string().trim().min(8).max(80),name:i.z.string().trim().min(1).max(160),description:i.z.string().trim().max(1e3).optional(),source:je,action:Le,policy:He.default({maxConcurrentRuns:1,whenBusy:"skip"}),createdAt:i.z.string().datetime(),updatedAt:i.z.string().datetime()}).strict(),Ue=i.z.discriminatedUnion("type",[i.z.object({type:i.z.literal("conversation"),conversationId:i.z.number().int().positive()}).strict(),i.z.object({type:i.z.literal("ai-session"),aiSessionId:i.z.string().trim().min(1).max(160)}).strict()]),qe=i.z.object({configHash:i.z.string().trim().min(8).max(80),deploymentId:i.z.string().trim().min(1).max(240).optional(),instanceId:i.z.string().trim().min(1).max(160),origin:i.z.enum(["control-plane","controlled-instance"]).default("controlled-instance"),enabled:i.z.boolean().default(!0),target:Ue,localName:i.z.string().trim().min(1).max(160).optional(),createdAt:i.z.string().datetime(),updatedAt:i.z.string().datetime()}).strict(),Ve=i.z.object({configHash:i.z.string().trim().min(8).max(80),deploymentId:i.z.string().trim().min(1).max(240).optional(),instanceId:i.z.string().trim().min(1).max(160),status:i.z.enum(["idle","running","disabled","error"]).default("idle"),lastTriggeredAt:i.z.string().datetime().optional(),lastCompletedAt:i.z.string().datetime().optional(),lastSkippedAt:i.z.string().datetime().optional(),lastError:i.z.string().trim().max(4e3).optional(),runCount:i.z.number().int().min(0).default(0),skippedCount:i.z.number().int().min(0).default(0)}).strict(),Be=i.z.object({id:i.z.string().trim().min(1).max(160),configHash:i.z.string().trim().min(8).max(80),deploymentId:i.z.string().trim().min(1).max(240).optional(),instanceId:i.z.string().trim().min(1).max(160),eventType:i.z.enum(["manual","schedule","file-change","ai-session"]),status:i.z.enum(["started","completed","failed","skipped"]),target:Ue,promptPreview:i.z.string().trim().max(500),eventSummary:i.z.string().trim().max(1e3).optional(),error:i.z.string().trim().max(4e3).optional(),startedAt:i.z.string().datetime(),completedAt:i.z.string().datetime().optional()}).strict(),Ke=i.z.object({schemaVersion:i.z.literal(1).default(1),configs:i.z.array($e).default([]),deployments:i.z.array(qe).default([]),runtime:i.z.array(Ve).default([]),recentRuns:i.z.array(Be).default([])}).strict();function Ge(e){return Array.isArray(e)?e.map(Ge):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,Ge(t)])):e}function We(){return(new Date).toISOString()}function Xe(e){return e.deploymentId||e.configHash}function Je(e){return Ve.parse({configHash:e.configHash,deploymentId:e.deploymentId,instanceId:e.instanceId,status:e.enabled?"idle":"disabled",runCount:0,skippedCount:0})}function Ye(e){return e.trim().slice(0,500)}class Qe{indexStore;constructor(e){this.indexStore=new me(s.join(e.triggersDir,"index.json"),{schema:Ke,defaultValue:()=>({schemaVersion:1,configs:[],deployments:[],runtime:[],recentRuns:[]})})}indexPath(){return this.indexStore.path()}list(){return this.indexStore.load()}get(e){const t=this.list(),s=t.configs.find(t=>t.configHash===e),n=t.deployments.filter(t=>t.configHash===e);if(s)return{config:s,deployments:n,runtime:t.runtime.filter(t=>t.configHash===e),recentRuns:t.recentRuns.filter(t=>t.configHash===e)}}create(e){const t=We(),s={maxConcurrentRuns:e.policy?.maxConcurrentRuns??1,whenBusy:e.policy?.whenBusy??"skip",cooldownMs:e.policy?.cooldownMs},n=function(e){const t=Ge({source:e.source,action:e.action,policy:He.parse(e.policy||{})});return`trg_${o.createHash("sha256").update(JSON.stringify(t)).digest("hex").slice(0,24)}`}({source:e.source,action:e.action,policy:s}),r=$e.parse({configHash:n,name:e.name,description:e.description,source:e.source,action:e.action,policy:s,createdAt:t,updatedAt:t}),i=function(e,t={}){const s=We();return qe.parse({configHash:e,deploymentId:t.deploymentId,instanceId:process.env.TASK_HANDOFF_INSTANCE_ID||"local",origin:t.origin||"controlled-instance",enabled:t.enabled??!0,target:t.target||{type:"conversation",conversationId:1},localName:t.localName,createdAt:s,updatedAt:s})}(n,e.deployment),a=this.list(),d=a.configs.some(e=>e.configHash===n)?a.configs:[...a.configs,r],c=Xe(i),p=[...a.deployments.filter(e=>Xe(e)!==c),i],u=[...a.runtime.filter(e=>Xe(e)!==c),Je(i)];return this.save({...a,configs:d,deployments:p,runtime:u}),{config:r,deployment:i,runtime:Je(i)}}patch(e,t){const s=this.list(),n=s.configs.find(t=>t.configHash===e);if(!n)return;const r=$e.parse({...n,name:t.name??n.name,description:null===t.description?void 0:t.description??n.description,updatedAt:We()});return this.save({...s,configs:s.configs.map(t=>t.configHash===e?r:t)}),r}setEnabled(e,t){const s=this.list(),n=We();let r=!1;const i=s.deployments.map(s=>s.configHash!==e?s:(r=!0,qe.parse({...s,enabled:t,updatedAt:n})));if(!r)return;const o=s.runtime.map(s=>s.configHash===e?Ve.parse({...s,status:t?"idle":"disabled"}):s);return this.save({...s,deployments:i,runtime:o}),this.get(e)}delete(e){const t=this.list();return!!t.configs.some(t=>t.configHash===e)&&(this.save({...t,configs:t.configs.filter(t=>t.configHash!==e),deployments:t.deployments.filter(t=>t.configHash!==e),runtime:t.runtime.filter(t=>t.configHash!==e),recentRuns:t.recentRuns.filter(t=>t.configHash!==e)}),!0)}deleteDeployment(e,t){const s=this.list();if(!s.deployments.some(s=>s.configHash===e&&Xe(s)===t))return!1;const n=s.deployments.filter(s=>!(s.configHash===e&&Xe(s)===t)),r=n.some(t=>t.configHash===e);return this.save({...s,configs:r?s.configs:s.configs.filter(t=>t.configHash!==e),deployments:n,runtime:s.runtime.filter(s=>!(s.configHash===e&&Xe(s)===t))}),!0}pruneMissingAiSessionDeployments(e){const t=this.list(),s=t.deployments.filter(t=>"ai-session"===t.target.type&&!e.has(t.target.aiSessionId));if(!s.length)return[];const n=new Set(s.map(e=>Xe(e))),r=t.deployments.filter(e=>!n.has(Xe(e))),i=new Set(r.map(e=>e.configHash));return this.save({...t,configs:t.configs.filter(e=>i.has(e.configHash)),deployments:r,runtime:t.runtime.filter(e=>!n.has(Xe(e)))}),s}startRun(e,t,s,n){const r=We(),i=Be.parse({id:`run_${Date.now().toString(36)}_${Math.random().toString(16).slice(2)}`,configHash:e.configHash,deploymentId:t.deploymentId,instanceId:t.instanceId,eventType:s,status:"started",target:t.target,promptPreview:Ye(e.action.promptTemplate),eventSummary:n,startedAt:r}),o=this.list(),a=this.upsertRuntime(o,t,{status:"running",lastTriggeredAt:r});return this.save({...o,runtime:a,recentRuns:[i,...o.recentRuns].slice(0,100)}),i}completeRun(e,t){const s=We(),n=Boolean(t),r=this.list(),i=r.recentRuns.map(r=>r.id===e.id?Be.parse({...r,status:n?"failed":"completed",error:t instanceof Error?t.message:t?String(t):void 0,completedAt:s}):r),o=r.deployments.find(t=>t.configHash===e.configHash&&Xe(t)===(e.deploymentId||e.configHash)),a=o?this.upsertRuntime(r,o,{status:n?"error":o.enabled?"idle":"disabled",lastCompletedAt:s,lastError:n?t instanceof Error?t.message:String(t):void 0,runCount:(r.runtime.find(t=>t.configHash===e.configHash&&Xe(t)===Xe(o))?.runCount||0)+1}):r.runtime;return this.save({...r,runtime:a,recentRuns:i}),i.find(t=>t.id===e.id)}skipRun(e,t,s,n){const r=We(),i=Be.parse({id:`run_${Date.now().toString(36)}_${Math.random().toString(16).slice(2)}`,configHash:e.configHash,deploymentId:t.deploymentId,instanceId:t.instanceId,eventType:s,status:"skipped",target:t.target,promptPreview:Ye(e.action.promptTemplate),eventSummary:n,startedAt:r,completedAt:r}),o=this.list(),a=this.upsertRuntime(o,t,{status:t.enabled?"idle":"disabled",lastSkippedAt:r,skippedCount:(o.runtime.find(e=>Xe(e)===Xe(t))?.skippedCount||0)+1});return this.save({...o,runtime:a,recentRuns:[i,...o.recentRuns].slice(0,100)}),i}primaryDeployment(e){return this.list().deployments.find(t=>t.configHash===e)}upsertRuntime(e,t,s){const n=Xe(t),r=e.runtime.find(e=>Xe(e)===n)||Je(t),i=Ve.parse({...r,...s});return[...e.runtime.filter(e=>Xe(e)!==n),i]}save(e){this.indexStore.save(Ke.parse(e))}}function Ze(e,t){const n=process.env[e];return n&&n.trim()?s.resolve(n.trim()):t}function et(){const e=s.join(process.env.XDG_DATA_HOME||s.join(n.homedir(),".local","share"),"task-handoff"),t=Ze("TASK_HANDOFF_CONFIG",S),r=Ze("TASK_HANDOFF_DATA_DIR",s.dirname(t)||e);return{configPath:t,dataDir:r,channelsDir:Ze("TASK_HANDOFF_CHANNELS_DIR",s.join(r,"channels")),conversationsDir:Ze("TASK_HANDOFF_CONVERSATIONS_DIR",s.join(r,"conversations")),appCatalogDir:Ze("TASK_HANDOFF_APP_CATALOG_DIR",s.join(r,"app-catalog")),appSessionsDir:Ze("TASK_HANDOFF_APP_SESSION_DIR",s.join(r,"app-sessions")),triggersDir:Ze("TASK_HANDOFF_TRIGGERS_DIR",s.join(r,"triggers")),runtimeDir:Ze("TASK_HANDOFF_RUNTIME_DIR",s.join(r,"runtime")),eventsDir:Ze("TASK_HANDOFF_EVENTS_DIR",s.join(r,"events")),artifactDir:Ze("TASK_HANDOFF_ARTIFACT_DIR",s.join(r,"artifacts")),logDir:Ze("TASK_HANDOFF_LOG_DIR",s.join(r,"logs")),webTokenPath:Ze("TASK_HANDOFF_WEB_TOKEN_FILE",s.join(r,"web-token"))}}const tt=i.z.object({schemaVersion:i.z.literal(1).default(1),channel:i.z.enum(["telegram","wechat","dingding"]),instanceId:i.z.string().default("default"),enabled:i.z.boolean().default(!1),defaultChatId:i.z.string().optional(),allowedUserIds:i.z.array(i.z.string()).optional(),bindings:i.z.record(i.z.string(),i.z.object({conversationId:i.z.number(),contextToken:i.z.string().optional()})).optional(),secrets:i.z.record(i.z.string(),i.z.unknown()).optional(),state:i.z.record(i.z.string(),i.z.unknown()).optional()}),st=i.z.object({schemaVersion:i.z.literal(1).default(1),defaultConversationId:i.z.number().default(1),nextConversationId:i.z.number().default(2),items:i.z.array(i.z.record(i.z.string(),i.z.unknown())).default([])}),nt=i.z.object({schemaVersion:i.z.literal(1).default(1),items:i.z.array(i.z.record(i.z.string(),i.z.unknown())).default([])}),rt=/^[a-f0-9]{8}$/;function it(e=process.env){return e.CLAUDE_CONTROL_SOCK||s.join(function(e=process.env){const t=process.getuid?.()??0,r=e.TERMUX_VERSION&&e.PREFIX?s.join(e.PREFIX,"tmp"):"/tmp",i=(e.CLAUDE_CONFIG_DIR??s.join(n.homedir(),".claude")).normalize("NFC"),a=o.createHash("sha256").update(s.resolve(i)).digest("hex").slice(0,8);return s.join(r,`cc-daemon-${t}`,a)}(e),"control.sock")}function ot(e,t={}){const s=t.sockPath||it(),n=t.timeoutMs??5e3;return new Promise(t=>{let r;try{r=a.connect(s)}catch(e){return void t({ok:!1,code:"ENOCONN",error:String(e)})}let i=!1,o="";const d=e=>{i||(i=!0,r.destroy(),t(e))};r.setTimeout(n,()=>d({ok:!1,code:"ETIMEOUT",error:"control socket timeout"})),r.on("error",e=>d({ok:!1,code:"ENOCONN",error:String(e)})),r.once("connect",()=>{r.write(`${JSON.stringify({proto:1,...e})}\n`)}),r.on("data",e=>{o+=e.toString("utf8");const t=o.indexOf("\n");if(t<0)return;const s=o.slice(0,t);try{d(JSON.parse(s))}catch(e){d({ok:!1,code:"EBADJSON",error:String(e),raw:s})}}),r.once("close",()=>{i||d({ok:!1,code:"ENOCONN",error:"connection dropped mid-request"})})})}function at(e,t,s){return pt(e),ot({op:"reply",short:e,text:t},s)}function dt(e,t="SIGTERM",s){return pt(e),ot({op:"kill",short:e,signal:t},s)}function ct(e,{tail:t,onMessage:s,options:n={}}={}){pt(e);const r=a.connect(n.sockPath||it());let i="";return r.on("connect",()=>{r.write(`${JSON.stringify({proto:1,op:"subscribe",short:e,tail:t})}\n`)}),r.on("data",e=>{i+=e.toString("utf8");let t=i.indexOf("\n");for(;t>=0;){const e=i.slice(0,t);if(i=i.slice(t+1),e.trim())try{s?.(JSON.parse(e))}catch{s?.({raw:e})}t=i.indexOf("\n")}}),r.on("error",()=>{}),()=>r.destroy()}function pt(e){if(!rt.test(e))throw new Error(`Claude worker short id must be 8 hex chars: ${e}`)}function ut(e,t=!1){const s=process.env[e];return void 0===s||""===s?t:["1","true","yes","on"].includes(s.toLowerCase())}function lt(...e){for(const t of e){const e=process.env[t]?.trim();if(e)return["--model",e]}return[]}const mt=i.z.string().trim().min(1).max(512).refine(e=>!/\s/.test(e)&&!/[;&|<>`$]/.test(e),"Command must be a single executable path or name."),ht=i.z.object({id:i.z.string().trim().min(1).max(80).regex(/^[a-z0-9][a-z0-9._-]*$/),name:i.z.string().trim().min(1).max(120),kind:i.z.enum(["tty","gui"]),description:i.z.string().max(500).optional(),command:mt,args:i.z.array(i.z.string().max(1024)).max(64).default([]).optional(),cwd:i.z.string().max(512).optional(),env:i.z.record(i.z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),i.z.string().max(4096)).optional(),display:i.z.object({width:i.z.number().int().min(320).max(7680).optional(),height:i.z.number().int().min(240).max(4320).optional(),depth:i.z.union([i.z.literal(16),i.z.literal(24),i.z.literal(32)]).optional()}).optional(),defaultDisplayTarget:i.z.object({mode:i.z.enum(["isolated","shared"]),id:i.z.string().trim().min(1).max(80).regex(/^[a-z0-9][a-z0-9._-]*$/).optional(),autoCreate:i.z.boolean().optional()}).optional(),automation:i.z.object({type:i.z.literal("cdp"),portArg:i.z.string().optional(),endpointPath:i.z.string().optional()}).optional()}),gt=i.z.object({schemaVersion:i.z.literal(1).default(1),items:i.z.array(ht).default([])}).superRefine((e,t)=>{const s=new Set(vt({includeOptional:!0}).map(e=>e.id)),n=new Set;for(const[r,o]of e.items.entries())s.has(o.id)&&t.addIssue({code:i.z.ZodIssueCode.custom,path:["items",r,"id"],message:"Custom apps cannot override built-in app ids."}),n.has(o.id)&&t.addIssue({code:i.z.ZodIssueCode.custom,path:["items",r,"id"],message:"Custom app ids must be unique."}),n.add(o.id)}),ft=[{id:"terminal-tty",name:"Terminal",kind:"tty",description:"Interactive shell in the task workspace.",command:process.env.SHELL||"/bin/bash"},{id:"codex",name:"Codex",kind:"tty",description:"OpenAI Codex CLI in the task workspace.",command:process.env.TASK_HANDOFF_CODEX_COMMAND||"codex"},{id:"claude",name:"Claude",kind:"tty",description:"Claude Code CLI in the task workspace.",command:process.env.TASK_HANDOFF_CLAUDE_COMMAND||"claude"},{id:"terminal-gui",name:"GUI Terminal",kind:"gui",description:"xterm terminal in an isolated virtual desktop with VNC access.",command:process.env.TASK_HANDOFF_XTERM_COMMAND||"xterm",args:["-geometry","120x32"],display:{width:1024,height:768,depth:24}},{id:"chromium",name:"Browser",kind:"gui",description:"Chromium browser with VNC and CDP endpoints.",command:process.env.TASK_HANDOFF_CHROMIUM_COMMAND||"chromium",args:["about:blank"],display:{width:1440,height:900,depth:24},automation:{type:"cdp",portArg:"--remote-debugging-port={port}"}},{id:"vscode-web",name:"VS Code",kind:"web",description:"VS Code Web in the task workspace.",command:process.env.TASK_HANDOFF_VSCODE_WEB_COMMAND||"code-server",args:["--auth","none","--bind-addr","127.0.0.1:{port}","--disable-telemetry","--user-data-dir","{sessionDir}/user-data","--extensions-dir","{sessionDir}/extensions","{cwd}"],web:{readyPath:"/"}}];function yt(e){return"codex"===e.id?{...e,command:process.env.TASK_HANDOFF_CODEX_COMMAND||e.command,args:lt("TASK_HANDOFF_CODEX_MODEL","CODEX_MODEL")}:"claude"===e.id?{...e,command:process.env.TASK_HANDOFF_CLAUDE_COMMAND||e.command,args:[...ut("TASK_HANDOFF_CLAUDE_DANGEROUSLY_SKIP_PERMISSIONS")||ut("TASK_HANDOFF_CLAUDE_SKIP_PERMISSIONS")?["--dangerously-skip-permissions"]:[],...lt("TASK_HANDOFF_CLAUDE_MODEL","CLAUDE_MODEL")]}:"terminal-tty"===e.id?{...e,command:process.env.SHELL||e.command}:"terminal-gui"===e.id?{...e,command:process.env.TASK_HANDOFF_XTERM_COMMAND||e.command}:"chromium"===e.id?{...e,command:process.env.TASK_HANDOFF_CHROMIUM_COMMAND||e.command}:"vscode-web"===e.id?{...e,command:process.env.TASK_HANDOFF_VSCODE_WEB_COMMAND||e.command}:e}function vt(e={}){return[...ft.map(yt),...e.includeOptional||ut("TASK_HANDOFF_ENABLE_CC_SWITCH")?[{id:"cc-switch",name:"CC Switch",kind:"gui",description:"CC Switch desktop app in an isolated virtual desktop.",command:process.env.TASK_HANDOFF_CC_SWITCH_COMMAND||"cc-switch",display:{width:1440,height:900,depth:24}}].map(yt):[]]}function St(e){try{return t.accessSync(e,t.constants.X_OK),t.statSync(e).isFile()}catch{return!1}}function It(e,t=process.env,n=process.cwd()){const r="win32"===process.platform?(t.PATHEXT||".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean):[""],i=e=>{for(const t of r){const n="win32"!==process.platform||s.extname(e)?e:`${e}${t}`;if(St(n))return n}};if(s.isAbsolute(e))return i(e);if(e.includes("/")||e.includes("\\"))return i(s.resolve(n,e));for(const n of(t.PATH||"").split(s.delimiter).filter(Boolean)){const t=i(s.join(n,e));if(t)return t}}function At(e){const t=e.command?.trim();return Boolean(t&&It(t,{...process.env,...e.env},e.cwd))}vt({includeOptional:!0});class bt{customStore;constructor(e){this.customStore=new me(s.join(e.appCatalogDir,"custom.json"),{schema:gt,defaultValue:()=>({schemaVersion:1,items:[]})})}list(){const e=new Map;for(const t of vt())e.set(t.id,t);const t=this.safeCustom();if(t.data)for(const s of t.data.items)e.set(s.id,s);return Array.from(e.values())}available(){return this.list().filter(At)}find(e){return this.list().find(t=>t.id===e)}custom(){return this.customStore.load()}safeCustom(){try{return{data:this.customStore.load(),error:void 0}}catch(e){return{data:void 0,error:{code:"APP_CATALOG_INVALID",message:e instanceof Error?e.message:String(e)}}}}saveCustom(e){return this.customStore.save(gt.parse(e)),this.customStore.load()}customPath(){return this.customStore.path()}}class _t{socketPath;onThreadBound;server;port;stopped=!1;constructor(e,t){this.socketPath=e,this.onThreadBound=t}get endpoint(){return this.port?`ws://127.0.0.1:${this.port}`:void 0}start(e){if(this.server)return;this.port=e;const t=new y.WebSocketServer({host:"127.0.0.1",port:e});this.server=t,t.on("connection",e=>this.attach(e))}stop(){this.stopped=!0,this.server?.close();for(const e of this.server?.clients||[])e.close();this.server=void 0}attach(e){if(this.stopped)return void e.close();const t=new y("ws://localhost/rpc",{createConnection:()=>a.createConnection(this.socketPath),perMessageDeflate:!1}),s=new Map,n=[];e.on("message",(e,r)=>{r||this.observeClientMessage(e.toString(),s),t.readyState===y.OPEN?t.send(e,{binary:r}):t.readyState===y.CONNECTING&&n.push({data:e,isBinary:r})}),t.on("open",()=>{for(;t.readyState===y.OPEN&&n.length>0;){const e=n.shift();e&&t.send(e.data,{binary:e.isBinary})}}),t.on("message",(t,n)=>{n||this.observeServerMessage(t.toString(),s),e.readyState===y.OPEN&&e.send(t,{binary:n})});const r=()=>{e.readyState!==y.OPEN&&e.readyState!==y.CONNECTING||e.close(),t.readyState!==y.OPEN&&t.readyState!==y.CONNECTING||t.close()};e.on("close",r),e.on("error",r),t.on("close",r),t.on("error",r)}observeClientMessage(e,t){const s=wt(e);if(!s)return;const n=Tt(s.id),r="string"==typeof s.method?s.method:"",i=s.params&&"object"==typeof s.params?s.params:{};if(n&&("thread/start"===r||"thread/resume"===r||"thread/fork"===r))return t.set(n,{method:r,threadId:"string"==typeof i.threadId?i.threadId:void 0}),void("string"==typeof i.threadId&&this.onThreadBound(i.threadId));"string"!=typeof i.threadId||"turn/start"!==r&&"turn/steer"!==r&&"turn/interrupt"!==r&&"thread/unsubscribe"!==r||this.onThreadBound(i.threadId)}observeServerMessage(e,t){const s=wt(e);if(!s)return;const n=Tt(s.id);if(!n)return;const r=t.get(n);if(!r)return;if(t.delete(n),s.error)return;const i=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return;const t=e,s=t.thread&&"object"==typeof t.thread&&!Array.isArray(t.thread)?t.thread:void 0;return"string"==typeof s?.id?s.id:"string"==typeof t.threadId?t.threadId:void 0}(s.result)||r.threadId;i&&this.onThreadBound(i)}}function wt(e){try{const t=JSON.parse(e);return t&&"object"==typeof t&&!Array.isArray(t)?t:void 0}catch{return}}function Tt(e){return"string"==typeof e&&e?e:"number"==typeof e&&Number.isFinite(e)?String(e):void 0}function Nt(e){const t=Number(e.TASK_HANDOFF_GUI_SCALE||process.env.TASK_HANDOFF_GUI_SCALE||"1");return Number.isFinite(t)?Math.min(3,Math.max(1,t)):1}function zt(e){return e.toFixed(2).replace(/\.?0+$/,"")}function Ot(){return process.env.TASK_HANDOFF_GUI_APP_HOME||process.env.HOME||n.homedir()}function Et(){return`app_${Date.now().toString(36)}_${Math.random().toString(16).slice(2)}`}function xt(){return(new Date).toISOString()}function kt(e,t=!1){const s=process.env[e];return void 0===s||""===s?t:["1","true","yes","on"].includes(s.toLowerCase())}const Dt=new Set(["stopped","exited","failed"]),Ct={"workbench.colorTheme":"Default Dark Modern","workbench.preferredDarkColorTheme":"Default Dark Modern"};class Pt extends g.EventEmitter{paths;sessions=new Map;persistedSessions=new Map;nextDisplay=101;nextVncPort=6101;nextWebsockifyPort=7101;nextWebPort=8101;nextCdpPort=9201;sharedDisplays=new Map;sharedCodexAppServer;catalogRepository;persistSessionMetadata;constructor(e){super(),this.paths=e,this.catalogRepository=new bt(e),this.persistSessionMetadata=kt("TASK_HANDOFF_APP_SESSION_PERSIST"),this.persistSessionMetadata&&(this.loadPersistedSessions(),this.cleanupExpiredSessions())}catalog(){return this.catalogRepository.available()}customCatalog(){const e=this.catalogRepository.safeCustom();return e.data?{data:{path:this.catalogRepository.customPath(),...e.data},error:void 0}:{data:void 0,error:e.error}}saveCustomCatalog(e){return{path:this.catalogRepository.customPath(),...this.catalogRepository.saveCustom({schemaVersion:1,items:e})}}listSessions(){return Array.from(this.persistedSessions.values()).sort((e,t)=>t.createdAt.localeCompare(e.createdAt))}sharedCodexAppServerInfo(){const e=this.sharedCodexAppServer;if(e&&!e.child.killed&&null===e.child.exitCode&&t.existsSync(e.socketPath))return{transport:"unix",endpoint:e.endpoint,socketPath:e.socketPath,pid:e.child.pid,command:e.command,args:e.args,logPath:e.logPath,status:"running"}}ensureSharedCodexAppServer(){const e=this.catalogRepository.find("codex"),t=e?.command||process.env.TASK_HANDOFF_CODEX_COMMAND||"codex";if(!this.hasCommand(t))throw Object.assign(new Error(`Missing required command: ${t}`),{code:"APP_DEPENDENCY_MISSING"});const s=e?.cwd||process.env.TASK_HANDOFF_WORKSPACE||process.cwd(),n={...process.env,...e?.env,TERM:"xterm-256color"};return this.acquireSharedCodexAppServer(t,s,n,"__shared_codex_app_server__")}_createCodexAppServerConnectionProxyForTest(e,t){return new _t(e,t)}getSession(e){return this.sessions.get(e)?.metadata||this.persistedSessions.get(e)}runningSessionCount(){return Array.from(this.sessions.values()).filter(e=>"running"===e.metadata.status).length}problemSessionCount(){return Array.from(this.sessions.values()).filter(e=>"failed"===e.metadata.status).length}readLogs(e,n=65536){const r=this.getSession(e);if(!r)throw Object.assign(new Error("App session not found."),{code:"APP_SESSION_NOT_FOUND"});const i=s.resolve(r.paths.logDir),o=(t.existsSync(i)?t.readdirSync(i,{withFileTypes:!0}):[]).filter(e=>e.isFile()&&e.name.endsWith(".log")).sort((e,t)=>e.name.localeCompare(t.name)).map(e=>{const r=s.resolve(i,e.name);if(!r.startsWith(`${i}${s.sep}`))throw Object.assign(new Error("Invalid log path."),{code:"APP_LOG_PATH_INVALID"});const o=t.statSync(r),a=Math.max(0,o.size-n),d=t.openSync(r,"r");try{const s=Buffer.alloc(o.size-a);return t.readSync(d,s,0,s.length,a),{name:e.name,size:o.size,updatedAt:o.mtime.toISOString(),truncated:a>0,content:s.toString("utf8")}}finally{t.closeSync(d)}});return{sessionId:e,logDir:i,maxBytes:n,files:o}}start(e="terminal-tty",n={}){const r=this.catalogRepository.find(e);if(!r)throw Object.assign(new Error("App not found."),{code:"APP_NOT_FOUND"});if(!this.hasCommand(r.command||r.id,{...process.env,...r.env},n.cwd||r.cwd))throw Object.assign(new Error(`Missing required command: ${r.command||r.id}`),{code:"APP_DEPENDENCY_MISSING"});if("gui"===r.kind)return this.startGuiApp(r,n);if("web"===r.kind)return this.startWebApp(r,n);if("tty"!==r.kind)throw Object.assign(new Error("App kind is not implemented yet."),{code:"APP_NOT_IMPLEMENTED"});const i=Et(),o=r.command||process.env.SHELL||"/bin/bash",a=n.cwd||r.cwd||process.env.TASK_HANDOFF_WORKSPACE||process.cwd(),d=this.normalizeLaunchOptions(n);let c=[...r.args||[],...d.args||[]],p={...process.env,...r.env,...d.env,TERM:"xterm-256color"};const u=s.join(this.paths.appSessionsDir,i),l=s.join(this.paths.logDir,"app-sessions",i);t.mkdirSync(u,{recursive:!0}),t.mkdirSync(l,{recursive:!0});const m="codex"!==r.id||kt("TASK_HANDOFF_CODEX_APP_SERVER_DISABLED")?void 0:this.acquireSharedCodexAppServer(o,a,p,i);let h,g,f,y=m?.endpoint;if(m){const e=this.allocatePort("web");h=new _t(m.socketPath,e=>this.bindCodexThreadToAppSession(i,e)),h.start(e),g=e,y=h.endpoint||m.endpoint,c=[...r.args||[],"--remote",y,"--cd",a,...d.args||[]],p={...p,TASK_HANDOFF_APP_SESSION_ID:i,TASK_HANDOFF_CODEX_APP_SERVER_SOCKET:m.socketPath,TASK_HANDOFF_CODEX_APP_SERVER_URL:m.endpoint,TASK_HANDOFF_CODEX_APP_SERVER_PROXY_URL:y}}"claude"!==r.id||kt("TASK_HANDOFF_CLAUDE_BG_DISABLED")||(f=this.launchClaudeBackground(o,c,a,p),c=["attach",f.short],p={...p,TASK_HANDOFF_APP_SESSION_ID:i,TASK_HANDOFF_CLAUDE_SHORT:f.short,TASK_HANDOFF_CLAUDE_CONTROL_SOCK:f.controlSock});const v={id:i,appId:e,title:d.title||r.name,kind:"tty",status:"running",createdAt:xt(),updatedAt:xt(),launch:d,tty:{webPath:`/api/apps/sessions/${i}/tty`,shell:o,cwd:a,mode:f?"claude-attach":"pty"},process:{command:o},ai:f?{agent:"claude",claude:{short:f.short,controlSock:f.controlSock,cwd:a}}:m?{agent:"codex",appServer:{transport:"unix",endpoint:m.endpoint,socketPath:m.socketPath,proxyEndpoint:y,proxyPort:g,pid:m.child.pid,command:m.command,args:m.args,logPath:m.logPath,status:"running"}}:void 0,paths:{sessionDir:u,logDir:l}},S=t.createWriteStream(s.join(l,"tty.log"),{flags:"a"}),I={metadata:v,processes:[],codexAppServerProxy:h,ttyDimensions:{cols:120,rows:32},ttyLogStream:S,outputBacklog:"",clients:new Set};S.on("error",()=>{I.ttyLogClosed=!0}),S.on("close",()=>{I.ttyLogClosed=!0});const A=(e,t)=>{I.stopping||(v.status="exited",v.updatedAt=xt(),v.process={...v.process,exitCode:e,signal:void 0===t?void 0:String(t)},this.persist(v),this.emit("updated",v)),"codex"===r.id&&(I.codexAppServerProxy?.stop(),this.releaseSharedCodexAppServer(i)),this.broadcast(I,{type:"exit",code:e,signal:t}),this.closeTtyLog(I)};let b;try{b=this.spawnTerminalPty(o,c,a,p)}catch(e){throw"codex"===r.id&&(h?.stop(),this.releaseSharedCodexAppServer(i)),f&&this.stopClaudeBackgroundLaunch(f.command,f.short,a,p),e}return v.process={...v.process,pid:b.pid},I.pty=b,b.onData(e=>{this.writeTtyLog(I,e),I.outputBacklog=`${I.outputBacklog}${e}`.slice(-65536),this.broadcast(I,{type:"output",data:e})}),b.onExit(({exitCode:e,signal:t})=>A(e,t)),this.sessions.set(i,I),this.persist(v),this.emit("created",v),v}launchClaudeBackground(e,t,s,n){const r=["--bg",...t],i=h.spawnSync(e,r,{cwd:s,env:n,encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:Number(process.env.TASK_HANDOFF_CLAUDE_BG_TIMEOUT_MS)||15e3}),o=`${i.stdout||""}\n${i.stderr||""}`;if(i.error)throw Object.assign(new Error(`Claude background launch failed: ${i.error.message}`),{code:"APP_LAUNCH_FAILED"});if(0!==i.status)throw Object.assign(new Error(`Claude background launch exited with code ${i.status}: ${o.trim()}`),{code:"APP_LAUNCH_FAILED"});const a=function(e){const t=e.match(/\b(?:short|id|worker|session)\D+([a-f0-9]{8})\b/i)?.[1];return t||e.match(/\b([a-f0-9]{8})\b/i)?.[1]}(o);if(!a)throw Object.assign(new Error("Claude background launch did not report a worker id."),{code:"APP_LAUNCH_FAILED"});return{short:a,controlSock:it(n),command:e,bgArgs:r}}stopClaudeBackgroundLaunch(e,t,s,n){try{h.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=Et(),o=s.join(this.paths.appSessionsDir,i),a=s.join(this.paths.logDir,"app-sessions",i);t.mkdirSync(o,{recursive:!0}),t.mkdirSync(a,{recursive:!0});const d=this.normalizeLaunchOptions(n),c=d.cwd||e.cwd||process.env.TASK_HANDOFF_WORKSPACE||process.cwd(),p=this.allocatePort("web"),u={...process.env,...e.env,...d.env},l=this.webArgs(e,o,c,p,d.args||[]);this.prepareWebAppSession(e,o);const m=this.spawnLogged(r,l,u,a,`${e.id}.log`,c),h={id:i,appId:e.id,title:d.title||e.name,kind:"web",status:"running",createdAt:xt(),updatedAt:xt(),launch:d,web:{host:"127.0.0.1",port:p,webPath:`/api/apps/sessions/${i}/web/`,readyPath:e.web?.readyPath},process:{pid:m.pid,command:r},paths:{sessionDir:o,logDir:a}},g={metadata:h,processes:[m],outputBacklog:"",clients:new Set};return this.sessions.set(i,g),this.persist(h),this.watchLoggedProcess(g,m,e.id,!1),this.emit("created",h),h}startGuiApp(e,n){const r=e.command||e.id,i="kasmvnc"===process.env.TASK_HANDOFF_VNC_BACKEND?"kasmvnc":"novnc",o="kasmvnc"===i?["vncserver","vncpasswd","openssl","xrdb","xrandr","openbox",r]:["Xvfb","openbox","x11vnc","websockify",r];for(const e of o)if(!this.hasCommand(e))throw Object.assign(new Error(`Missing required command: ${e}`),{code:"APP_DEPENDENCY_MISSING"});const a=Et(),d=s.join(this.paths.appSessionsDir,a),c=s.join(this.paths.logDir,"app-sessions",a);t.mkdirSync(d,{recursive:!0}),t.mkdirSync(c,{recursive:!0});const p=this.normalizeLaunchOptions(n),u=p.displayTarget||this.normalizeDisplayTarget(e.defaultDisplayTarget)||{mode:"isolated"};p.displayTarget=u;const l=p.cwd||e.cwd||process.env.TASK_HANDOFF_WORKSPACE||process.cwd(),m=this.allocatePort("cdp"),h=this.guiArgs(e,d,m,p.args||[]);if("shared"===u.mode){const t=this.ensureSharedDisplay(e,p,i,l),s=this.appEnvForDisplay(e,p,t),n=this.spawnLogged(r,h,s,c,`${e.id}.log`,l),o=e.automation?{type:e.automation.type,port:m,endpoint:`http://127.0.0.1:${m}${e.automation.endpointPath||""}`}:void 0,u={id:a,appId:e.id,title:p.title||e.name,kind:"gui",status:"running",createdAt:xt(),updatedAt:xt(),launch:p,display:{display:t.display,mode:"shared",displaySessionId:t.id,width:t.width,height:t.height,depth:t.depth,xPid:t.xPid,wmPid:t.wmPid,compositorPid:t.compositorPid,xauthority:t.xauthority},vnc:{backend:t.backend,host:"127.0.0.1",port:t.vncPort,websockifyPort:t.websockifyPort,webPath:"kasmvnc"===t.backend?`/api/apps/sessions/${a}/web/`:`/api/apps/sessions/${a}/vnc`,noVncPath:"kasmvnc"===t.backend?`/api/apps/sessions/${a}/web/`:`/api/apps/sessions/${a}/novnc/vnc.html`},web:"kasmvnc"===t.backend?{host:"127.0.0.1",port:t.vncPort,webPath:`/api/apps/sessions/${a}/web/`}:void 0,automation:o,process:{pid:n.pid,command:r},paths:{sessionDir:d,logDir:c}},g={metadata:u,processes:[n],outputBacklog:"",clients:new Set};return t.appSessionIds.add(a),this.sessions.set(a,g),this.persist(u),this.watchLoggedProcess(g,n,e.id,!1,()=>this.releaseSharedDisplaySession(t.id,a)),this.emit("created",u),u}const g=`:${this.allocateDisplay()}`,f="kasmvnc"===i?this.allocatePort("web"):this.allocatePort("vnc"),y="novnc"===i?this.allocatePort("websockify"):void 0,v=p.display?.width||e.display?.width||1440,S=p.display?.height||e.display?.height||900,I=p.display?.depth||e.display?.depth||24,A={...process.env,...e.env,...p.env,DISPLAY:g},b=Nt(A),_=s.join(d,"home"),w="kasmvnc"===i?s.join(_,".Xauthority"):void 0,T="kasmvnc"===i?this.startKasmVncDisplay(g,v,S,I,f,A,d,c,b):this.startNoVncDisplay(g,v,S,I,f,y,A,c,l),N="kasmvnc"===i?this.guiScaleEnv({...A,HOME:Ot(),XAUTHORITY:w},b):A;try{this.waitForXDisplay(g)}catch(e){for(const e of T)e.killed||e.kill("SIGTERM");throw Object.assign(e instanceof Error?e:new Error(String(e)),{code:"APP_DISPLAY_START_FAILED"})}"kasmvnc"===i&&this.applyGuiScale(N,d,b);const z=this.spawnLogged("openbox",[],N,c,"openbox.log"),O=this.startCompositor(N,c,l),E=this.spawnLogged(r,h,N,c,`${e.id}.log`,l),x=e.automation?{type:e.automation.type,port:m,endpoint:`http://127.0.0.1:${m}${e.automation.endpointPath||""}`}:void 0,k={id:a,appId:e.id,title:p.title||e.name,kind:"gui",status:"running",createdAt:xt(),updatedAt:xt(),launch:p,display:{display:g,mode:"isolated",width:v,height:S,depth:I,xPid:T[0]?.pid,wmPid:z.pid,compositorPid:O?.pid,xauthority:w},vnc:{backend:i,host:"127.0.0.1",port:f,websockifyPort:y,webPath:"kasmvnc"===i?`/api/apps/sessions/${a}/web/`:`/api/apps/sessions/${a}/vnc`,noVncPath:"kasmvnc"===i?`/api/apps/sessions/${a}/web/`:`/api/apps/sessions/${a}/novnc/vnc.html`},web:"kasmvnc"===i?{host:"127.0.0.1",port:f,webPath:`/api/apps/sessions/${a}/web/`}:void 0,automation:x,process:{pid:E.pid,command:r},paths:{sessionDir:d,logDir:c}},D={metadata:k,processes:[E,...T,z,...O?[O]:[]],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,E,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,DISPLAY:l},S=Nt(v),I=s.join(p,"home"),A="kasmvnc"===r?s.join(I,".Xauthority"):void 0,b="kasmvnc"===r?this.startKasmVncDisplay(l,g,f,y,m,v,p,u,S):this.startNoVncDisplay(l,g,f,y,m,h,v,u,i),_="kasmvnc"===r?this.guiScaleEnv({...v,HOME:Ot(),XAUTHORITY:A},S):v;try{this.waitForXDisplay(l)}catch(e){for(const e of b)e.killed||e.kill("SIGTERM");throw Object.assign(e instanceof Error?e:new Error(String(e)),{code:"APP_DISPLAY_START_FAILED"})}"kasmvnc"===r&&this.applyGuiScale(_,p,S);const w=this.spawnLogged("openbox",[],_,u,"openbox.log"),T=this.startCompositor(_,u,i),N={id:a,display:l,width:g,height:f,depth:y,backend:r,vncPort:m,websockifyPort:h,xPid:b[0]?.pid,wmPid:w.pid,compositorPid:T?.pid,xauthority:A,sessionDir:p,logDir:u,processes:[...b,w,...T?[T]:[]],appSessionIds:new Set};this.sharedDisplays.set(a,N);for(const e of[...b,w])this.watchSharedDisplayProcess(N,e);return N}appEnvForDisplay(e,t,s){const n={...process.env,...e.env,...t.env,DISPLAY:s.display},r=Nt(n);return"kasmvnc"===s.backend?this.guiScaleEnv({...n,HOME:Ot(),XAUTHORITY:s.xauthority},r):n}releaseSharedDisplaySession(e,t){const s=this.sharedDisplays.get(e);s&&(s.appSessionIds.delete(t),s.appSessionIds.size>0||this.stopSharedDisplay(e))}stopSharedDisplay(e){const t=this.sharedDisplays.get(e);if(t){this.sharedDisplays.delete(e);for(const e of t.processes)e.killed||e.kill("SIGTERM")}}acquireSharedCodexAppServer(e,r,i,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(),i=r?t.realpathSync(r):"darwin"===process.platform?"/private/tmp":t.realpathSync(n.tmpdir()),a=o.createHash("sha256").update(e).digest("hex").slice(0,16);return s.join(i,`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,i,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=xt(),this.persist(r.metadata),this.emit("updated",r.metadata))}bindCodexThreadToAppSession(e,t){const s=this.sessions.get(e);if(!s?.metadata.ai||"codex"!==s.metadata.appId)return;const n=Array.isArray(s.metadata.ai.threadIds)?s.metadata.ai.threadIds:[];s.metadata.ai={...s.metadata.ai,activeThreadId:t,threadIds:n.includes(t)?n:[...n,t]},s.metadata.updatedAt=xt(),this.persist(s.metadata),this.emit("updated",s.metadata)}watchSharedDisplayProcess(e,t){t.on("exit",(t,s)=>{if(this.sharedDisplays.has(e.id)&&0!==t&&0!==e.appSessionIds.size){this.sharedDisplays.delete(e.id);for(const n of e.appSessionIds){const r=this.sessions.get(n);r&&this.markFailed(r,"APP_DISPLAY_PROCESS_EXITED",`Shared display ${e.id} exited unexpectedly with code ${t??"null"} signal ${s??"null"}.`)}}})}startCompositor(e,t,s){if(this.hasCommand("picom"))return this.spawnLogged("picom",["--config","/dev/null","--backend","xrender"],e,t,"picom.log",s)}startNoVncDisplay(e,t,s,n,r,i,o,a,d){return[this.spawnLogged("Xvfb",[e,"-screen","0",`${t}x${s}x${n}`,"-nolisten","tcp"],o,a,"xvfb.log"),this.spawnLogged("x11vnc",["-display",e,"-localhost","-forever","-shared","-nopw","-xrandr","resize","-rfbport",String(r)],o,a,"x11vnc.log"),this.spawnLogged("websockify",[String(i),`127.0.0.1:${r}`],o,a,"websockify.log",d)]}waitForXDisplay(e,n=5e3){const r=e.replace(/^:/,"").split(".")[0],i=s.join("/tmp/.X11-unix",`X${r}`),o=Date.now();for(;Date.now()-o<n;){if(t.existsSync(i))return;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,50)}throw new Error(`Display ${e} did not become ready within ${n}ms.`)}startKasmVncDisplay(e,t,n,r,i,o,a,d,c){this.prepareKasmVncHome(a,t,n,r,i,c);const p={...o,HOME:s.join(a,"home")},u=this.writeKasmVncLauncher(a,e,t,n,r);return[this.spawnLogged("bash",[u],p,d,"kasmvnc.log")]}guiScaleEnv(e,t){return{...e,TASK_HANDOFF_GUI_SCALE:zt(t),XCURSOR_SIZE:"24"}}applyGuiScale(e,n,r){if(r<=1)return;const i=s.join(n,"home",".Xresources");if(t.existsSync(i))try{h.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),m=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}),h.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=${m}`,"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 = ${m}`,"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")),h.execFileSync("vncpasswd",["-u",g,"-w","-r"],{env:{...process.env,HOME:d},input:`${f}\n${f}\n`,stdio:["pipe","ignore","pipe"]})}stop(e){const t=this.sessions.get(e);if(!t){const t=this.persistedSessions.get(e);if(t)return t;throw Object.assign(new Error("App session not found."),{code:"APP_SESSION_NOT_FOUND"})}t.metadata.status="stopping",t.metadata.updatedAt=xt(),t.stopping=!0,this.persist(t.metadata),this.stopClaudeDaemonForSession(t.metadata),t.pty?.kill("SIGTERM"),this.closeTtyLog(t);for(const e of t.clients)e.send(JSON.stringify({type:"exit",code:null,signal:"SIGTERM"})),e.close?.();t.clients.clear();for(const e of t.processes)e.killed||e.kill("SIGTERM");return t.codexAppServerProxy?.stop(),"codex"===t.metadata.appId&&this.releaseSharedCodexAppServer(e),"shared"===t.metadata.display?.mode&&t.metadata.display.displaySessionId&&this.releaseSharedDisplaySession(t.metadata.display.displaySessionId,e),t.metadata.status="stopped",t.metadata.updatedAt=xt(),this.persist(t.metadata),this.sessions.delete(e),this.emit("updated",t.metadata),t.metadata}stopClaudeDaemonForSession(e){const t=e.ai?.claude?.short;t&&dt(t,"SIGTERM",{sockPath:e.ai?.claude?.controlSock,timeoutMs:Number(process.env.TASK_HANDOFF_CLAUDE_CONTROL_TIMEOUT_MS)||5e3})}restart(e){const t=this.getSession(e);if(!t)throw Object.assign(new Error("App session not found."),{code:"APP_SESSION_NOT_FOUND"});const{appId:s,title:n}=t,r={...t.launch,title:n};return this.sessions.has(e)&&this.stop(e),this.start(s,r)}rename(e,t){const s=this.getSession(e);if(!s)throw Object.assign(new Error("App session not found."),{code:"APP_SESSION_NOT_FOUND"});const n="string"==typeof t?t.trim():"";if(!n||n.length>120)throw Object.assign(new Error("App session title must contain between 1 and 120 characters."),{code:"APP_SESSION_TITLE_INVALID"});return s.title=n,s.launch={...s.launch,title:n},s.updatedAt=xt(),this.persist(s),this.emit("updated",s),s}async delete(e){const t=this.getSession(e);if(!t)throw Object.assign(new Error("App session not found."),{code:"APP_SESSION_NOT_FOUND"});const s=this.sessions.get(e);if(s){const t=[...s.processes],n=t.map(e=>this.waitForProcessClose(e,5e3));this.stop(e);const r=await Promise.all(n);let i=t.filter((e,t)=>!r[t]);if(i.length>0){const e=i.map(e=>this.waitForProcessClose(e,1e3));for(const e of i)null===e.exitCode&&null===e.signalCode&&e.kill("SIGKILL");const t=await Promise.all(e);i=i.filter((e,s)=>!t[s])}if(i.length>0)throw Object.assign(new Error(`App session processes did not exit: ${i.map(e=>e.pid??"unknown").join(", ")}.`),{code:"APP_PROCESS_STOP_TIMEOUT"})}return this.sessions.delete(e),this.persistedSessions.delete(e),this.removeSessionFiles(t),this.emit("deleted",t),t}cleanupExpiredSessions(e=new Date){const t=this.sessionRetentionMs();if(!t)return[];const s=e.getTime()-t,n=[];for(const e of this.persistedSessions.values()){if(this.sessions.has(e.id)||!Dt.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 h.execFileSync("import",["-window","root","png:-"],{env:{...process.env,DISPLAY:t.metadata.display.display,...e?{XAUTHORITY:e,HOME:s.dirname(e)}:{}},maxBuffer:20971520})}catch(e){throw Object.assign(new Error(`Screenshot failed: ${e instanceof Error?e.message:String(e)}`),{code:"APP_SCREENSHOT_FAILED"})}}resizeDisplay(e,t){const s=this.sessions.get(e),n=s?.metadata;if(!s||!n?.display)throw Object.assign(new Error("Display session not found."),{code:"APP_DISPLAY_NOT_FOUND"});const r=this.normalizeDisplayOptions(t),i=r.width||n.display.width,o=r.height||n.display.height,a=r.depth||n.display.depth,d=this.displayCommandEnv(n);try{this.resizeDisplayWithXrandr(d,i,o)}catch(e){throw Object.assign(new Error(`Display resize failed: ${e instanceof Error?e.message:String(e)}`),{code:"APP_DISPLAY_RESIZE_FAILED"})}return n.display={...n.display,width:i,height:o,depth:a},this.persist(n),this.emit("updated",n),n}async automationStatus(e){const t=this.sessions.get(e),s=t?.metadata||this.persistedSessions.get(e);if(!s)throw Object.assign(new Error("App session not found."),{code:"APP_SESSION_NOT_FOUND"});if(!s.automation)throw Object.assign(new Error("Automation is not configured for this app session."),{code:"APP_AUTOMATION_UNAVAILABLE"});const n={sessionId:e,type:s.automation.type,endpoint:s.automation.endpoint,port:s.automation.port,ready:!1};if(!t||"running"!==s.status)return{...n,error:{code:"APP_AUTOMATION_NOT_RUNNING",message:"Automation endpoint is only available while the app session is running."}};try{const e=await this.fetchCdpVersion(s.automation.endpoint);return{...n,ready:!0,browser:"string"==typeof e.Browser?e.Browser:void 0,protocolVersion:"string"==typeof e["Protocol-Version"]?e["Protocol-Version"]:void 0,webSocketDebuggerUrl:"string"==typeof e.webSocketDebuggerUrl?e.webSocketDebuggerUrl:void 0}}catch(e){return{...n,error:{code:"APP_AUTOMATION_NOT_READY",message:e instanceof Error?e.message:String(e)}}}}stopAll(){for(const e of this.sessions.values()){e.stopping=!0,e.metadata.status="stopped",e.metadata.updatedAt=xt(),this.persist(e.metadata),this.stopClaudeDaemonForSession(e.metadata),e.pty?.kill("SIGTERM"),this.closeTtyLog(e);for(const t of e.processes)t.kill("SIGTERM")}for(const e of Array.from(this.sharedDisplays.keys()))this.stopSharedDisplay(e);this.stopSharedCodexAppServer(),this.sessions.clear()}vncTarget(e){const t=this.sessions.get(e);if(t?.metadata.vnc)return{host:t.metadata.vnc.host,port:t.metadata.vnc.port}}webTarget(e){const t=this.sessions.get(e);if(t?.metadata.web&&"running"===t.metadata.status)return{host:t.metadata.web.host,port:t.metadata.web.port}}attachTty(e,t){const s=this.sessions.get(e);if(!s||"running"!==s.metadata.status)return t.send(JSON.stringify({type:"error",message:"TTY session not found."})),void t.close?.();s.clients.add(t),t.send(JSON.stringify({type:"connected",session:s.metadata,dimensions:s.ttyDimensions})),s.outputBacklog&&t.send(JSON.stringify({type:"output",data:s.outputBacklog})),t.on("message",e=>{const n=Buffer.isBuffer(e)?e.toString("utf8"):String(e||"");try{const e=JSON.parse(n);if("input"===e.type&&"string"==typeof e.data)s.pty?.write(e.data);else if("resize"===e.type&&Number.isInteger(e.cols)&&Number.isInteger(e.rows)){const n=e.cols,r=e.rows;s.ttyDimensions={cols:n,rows:r},s.pty?.resize(n,r);for(const e of s.clients)e!==t&&e.send(JSON.stringify({type:"resize",cols:n,rows:r}))}}catch{s.pty?.write(n)}}),t.on("close",()=>{s.clients.delete(t)})}broadcast(e,t){const s=JSON.stringify(t);for(const t of e.clients)t.send(s)}writeTtyLog(e,t){const s=e.ttyLogStream;!s||e.ttyLogClosed||s.destroyed||s.closed||s.writableEnded||s.write(t,t=>{t&&(e.ttyLogClosed=!0)})}closeTtyLog(e){const t=e.ttyLogStream;!t||e.ttyLogClosed||t.destroyed||t.closed||t.writableEnded?e.ttyLogClosed=!0:(e.ttyLogClosed=!0,t.end())}persist(e){this.persistedSessions.set(e.id,e),this.persistSessionMetadata&&(t.mkdirSync(e.paths.sessionDir,{recursive:!0}),r.sync(s.join(e.paths.sessionDir,"metadata.json"),`${JSON.stringify(e,null,2)}\n`,{mode:384}))}removeSessionFiles(e){t.rmSync(e.paths.sessionDir,{recursive:!0,force:!0}),t.rmSync(e.paths.logDir,{recursive:!0,force:!0})}sessionRetentionMs(){const e=process.env.TASK_HANDOFF_APP_SESSION_RETENTION_DAYS;if(!e)return;const t=Number(e);return!Number.isFinite(t)||t<=0?void 0:24*t*60*60*1e3}loadPersistedSessions(){if(t.existsSync(this.paths.appSessionsDir))for(const e of t.readdirSync(this.paths.appSessionsDir,{withFileTypes:!0})){if(!e.isDirectory())continue;const n=s.join(this.paths.appSessionsDir,e.name,"metadata.json");if(t.existsSync(n))try{const s=JSON.parse(t.readFileSync(n,"utf8"));if(!s.id||!s.paths?.sessionDir||s.id!==e.name)continue;const r=this.recoverPersistedSession(s);this.persistedSessions.set(r.id,r),r!==s&&this.persist(r)}catch{continue}}}recoverPersistedSession(e){return"running"!==e.status&&"stopping"!==e.status?e:{...e,status:"exited",updatedAt:xt(),error:e.error||{code:"APP_SESSION_RESTORED_WITHOUT_PROCESS",message:"Runtime restarted; previous app processes are not attached. Use restart to launch a new session."},process:{...e.process,exitCode:e.process?.exitCode??null,signal:e.process?.signal??null}}}allocateDisplay(){const e=new Set([...Array.from(this.sessions.values()).map(e=>e.metadata.display?.display),...Array.from(this.sharedDisplays.values()).map(e=>e.display)].filter(e=>Boolean(e)).map(e=>Number(e.replace(/^:/,""))).filter(e=>Number.isInteger(e))),s=this.findAvailableNumber(this.nextDisplay,101,199,s=>!e.has(s)&&!t.existsSync(`/tmp/.X${s}-lock`)&&!t.existsSync(`/tmp/.X11-unix/X${s}`));return this.nextDisplay=this.nextNumber(s,101,199),s}allocatePort(e){const t="vnc"===e?{start:6101,end:6199,next:this.nextVncPort}:"websockify"===e?{start:7101,end:7199,next:this.nextWebsockifyPort}:"web"===e?{start:8101,end:8199,next:this.nextWebPort}:{start:9201,end:9299,next:this.nextCdpPort},s=new Set([...Array.from(this.sessions.values()).flatMap(e=>[e.metadata.vnc?.port,e.metadata.vnc?.websockifyPort,e.metadata.web?.port,e.metadata.automation?.port,e.metadata.ai?.appServer?.proxyPort]),...Array.from(this.sharedDisplays.values()).flatMap(e=>[e.vncPort,e.websockifyPort,"kasmvnc"===e.backend?e.vncPort:void 0])].filter(e=>Number.isInteger(e))),n=this.findAvailableNumber(t.next,t.start,t.end,e=>!s.has(e)&&this.isPortAvailable(e)),r=this.nextNumber(n,t.start,t.end);return"vnc"===e?this.nextVncPort=r:"websockify"===e?this.nextWebsockifyPort=r:"web"===e?this.nextWebPort=r:this.nextCdpPort=r,n}findAvailableNumber(e,t,s,n){const r=s-t+1;for(let s=0;s<r;s+=1){const i=t+(Math.max(e,t)-t+s)%r;if(n(i))return i}throw Object.assign(new Error(`No available allocation in range ${t}-${s}.`),{code:"APP_RESOURCE_EXHAUSTED"})}nextNumber(e,t,s){return e>=s?t:e+1}isPortAvailable(e){const t=["const net=require('node:net');","const server=net.createServer();","server.once('error',()=>process.exit(1));","server.listen(Number(process.argv[1]),'127.0.0.1',()=>server.close(()=>process.exit(0)));"].join("");return 0===h.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===h.spawnSync(process.execPath,["-e",t,e],{stdio:"ignore"}).status}markFailed(e,t,s){e.stopping||"stopped"===e.metadata.status||"failed"===e.metadata.status||(e.metadata.status="failed",e.metadata.updatedAt=xt(),e.metadata.error={code:t,message:s},this.persist(e.metadata),this.emit("updated",e.metadata))}waitForProcessClose(e,t){return null!==e.exitCode||null!==e.signalCode?Promise.resolve(!0):new Promise(s=>{let n=!1;const r=t=>{n||(n=!0,clearTimeout(a),e.off("close",i),e.off("error",o),s(t))},i=()=>r(!0),o=()=>r(!0),a=setTimeout(()=>r(!1),t);e.once("close",i),e.once("error",o)})}watchLoggedProcess(e,t,s,n,r){t.on("error",t=>{this.markFailed(e,"APP_PROCESS_ERROR",`${s} failed: ${t.message}`)}),t.on("exit",(t,i)=>{if(e.stopping)r?.();else{if(n&&0!==t)return this.markFailed(e,"APP_PROCESS_EXITED",`${s} exited unexpectedly with code ${t??"null"} signal ${i??"null"}.`),void r?.();n||(e.metadata.status=0===t?"exited":"failed",e.metadata.updatedAt=xt(),e.metadata.process={...e.metadata.process,exitCode:t,signal:i},0!==t&&(e.metadata.error={code:"APP_PROCESS_EXITED",message:`${s} exited with code ${t??"null"} signal ${i??"null"}.`}),this.persist(e.metadata),this.emit("updated",e.metadata)),r?.()}})}guiArgs(e,t,n,r){const i=[...e.args||[],...r].map(e=>e.replaceAll("{sessionDir}",t).replaceAll("{cdpPort}",String(n)));if("chromium"===e.id){const r=kt("TASK_HANDOFF_CHROMIUM_NO_SANDBOX")?["--no-sandbox"]:[],o=function(e){const t=process.env.TASK_HANDOFF_CHROMIUM_USER_DATA_DIR?.trim();return t||s.join(e,"profile")}(t);return[...r,"--disable-dev-shm-usage","--no-first-run",...this.chromiumExtensionArgs(),"--remote-debugging-address=127.0.0.1",...o?[`--user-data-dir=${o}`]:[],...e.automation?.portArg?[e.automation.portArg.replaceAll("{port}",String(n))]:[`--remote-debugging-port=${n}`],...i]}return e.automation?.portArg&&i.unshift(e.automation.portArg.replaceAll("{port}",String(n))),this.isXtermApp(e)?["-fa",process.env.TASK_HANDOFF_XTERM_FONT_FAMILY||"Monospace","-fs",process.env.TASK_HANDOFF_XTERM_FONT_SIZE||"11",...i]:i}chromiumExtensionArgs(){const e=this.chromiumExtensionDirs();return e.length>0?[`--load-extension=${e.join(",")}`]:[]}chromiumExtensionDirs(){const e=process.env.TASK_HANDOFF_CHROMIUM_EXTENSION_DIRS;if(e)return e.split(/[,;]/).map(e=>e.trim()).filter(e=>this.isChromiumExtensionDir(e));const n=process.env.TASK_HANDOFF_CHROMIUM_EXTENSION_DIR||"/opt/task-handoff/chromium-extensions";return t.existsSync(n)?t.readdirSync(n,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>s.join(n,e.name)).filter(e=>this.isChromiumExtensionDir(e)).sort():[]}isChromiumExtensionDir(e){return t.existsSync(s.join(e,"manifest.json"))}isXtermApp(e){const t=s.basename(e.command||e.id);return"terminal-gui"===e.id||"xterm"===t}webArgs(e,t,s,n,r){const i=e=>e.replaceAll("{sessionDir}",t).replaceAll("{cwd}",s).replaceAll("{port}",String(n)),o=[...e.args||[],...r].map(i);return e.web?.portArg&&o.unshift(i(e.web.portArg)),o}prepareWebAppSession(e,n){if("vscode-web"!==e.id)return;const i=s.join(n,"user-data","User"),o=s.join(i,"settings.json");let a={};if(t.mkdirSync(i,{recursive:!0}),t.existsSync(o))try{const e=JSON.parse(t.readFileSync(o,"utf8"));e&&"object"==typeof e&&!Array.isArray(e)&&(a=e)}catch{a={}}r.sync(o,`${JSON.stringify({...Ct,...a},null,2)}\n`,{mode:384})}async fetchCdpVersion(e){const t=new URL(e);t.pathname=s.posix.join(t.pathname,"json","version");const n=new AbortController,r=setTimeout(()=>n.abort(),1e3);try{const e=await fetch(t,{signal:n.signal});if(!e.ok)throw new Error(`CDP version endpoint returned HTTP ${e.status}.`);return await e.json()}finally{clearTimeout(r)}}normalizeLaunchOptions(e={}){const t={};"string"==typeof e.title&&e.title.trim()&&(t.title=e.title.trim()),Array.isArray(e.args)&&(t.args=e.args.filter(e=>"string"==typeof e)),"string"==typeof e.cwd&&e.cwd.trim()&&(t.cwd=e.cwd.trim()),e.env&&"object"==typeof e.env&&!Array.isArray(e.env)&&(t.env=Object.fromEntries(Object.entries(e.env).filter(e=>"string"==typeof e[0]&&"string"==typeof e[1]&&e[0].trim().length>0).map(([e,t])=>[e.trim(),t])));const s=this.normalizeDisplayOptions(e.display||{});Object.keys(s).length>0&&(t.display=s);const n=this.normalizeDisplayTarget(e.displayTarget);return n&&(t.displayTarget=n),t}normalizeDisplayTarget(e){if(e&&"object"==typeof e){if("isolated"===e.mode)return{mode:"isolated"};if("shared"===e.mode)return{mode:"shared",id:"string"==typeof e.id&&e.id.trim()?e.id.trim():"main",autoCreate:!1!==e.autoCreate}}}normalizeDisplayOptions(e){const t=Number(e.width),s=Number(e.height),n=Number(e.depth),r={};return Number.isInteger(t)&&t>=320&&t<=7680&&(r.width=t),Number.isInteger(s)&&s>=240&&s<=4320&&(r.height=s),Number.isInteger(n)&&n>=8&&n<=32&&(r.depth=n),r}displayCommandEnv(e){const t=e.paths?.sessionDir,n=e.display?.xauthority?s.dirname(e.display.xauthority):t?s.join(t,"home"):void 0;return{...process.env,DISPLAY:e.display?.display,...n?{HOME:n,XAUTHORITY:e.display?.xauthority||s.join(n,".Xauthority")}:{}}}resizeDisplayWithXrandr(e,t,s){const n=`${t}x${s}`,r=this.connectedDisplayOutput(e),i=r?[["--output",r,"--mode",n],["--fb",n]]:[["--fb",n]];let o;for(const t of i)try{return void h.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=h.execFileSync("xrandr",["--query"],{env:e,encoding:"utf8"});return t.match(/^(\S+)\s+connected\b/m)?.[1]}catch{return}}hasCommand(e,t=process.env,s=process.cwd()){return Boolean(It(e,t,s))}spawnTerminalPty(e,n,r,i){try{return function(){if("darwin"===process.platform||"linux"===process.platform)try{const e=s.resolve(s.dirname(require.resolve("node-pty")),".."),n=s.join(e,"prebuilds",`${process.platform}-${process.arch}`,"spawn-helper"),r=t.statSync(n);73&r.mode||t.chmodSync(n,493|r.mode)}catch{}}(),f.spawn(e,n,{name:"xterm-256color",cols:120,rows:32,cwd:r,env:i})}catch(e){throw Object.assign(new Error(`PTY unavailable: ${e instanceof Error?e.message:String(e)}`),{code:"PTY_UNAVAILABLE"})}}spawnLogged(e,n,r,i,o,a){const d=t.createWriteStream(s.join(i,o),{flags:"a"}),c=h.spawn(e,n,{cwd:a,env:r,stdio:["ignore","pipe","pipe"]});return c.stdout.pipe(d),c.stderr.pipe(d),c}}const Ft={"image/bmp":".bmp","image/gif":".gif","image/jpeg":".jpg","image/png":".png","image/webp":".webp"};function Rt(e=[]){if(!e.length)return[];const r=function(){const e=process.env.TASK_HANDOFF_AI_SESSION_ATTACHMENT_DIR?.trim();return e?s.resolve(e):s.join(n.tmpdir(),"task-handoff-ai-session-attachments")}();return t.mkdirSync(r,{recursive:!0}),function(e){const n=Date.now()-function(){const e=Number(process.env.TASK_HANDOFF_AI_SESSION_ATTACHMENT_RETENTION_MS);return Number.isFinite(e)&&e>0?e:864e5}();try{for(const r of t.readdirSync(e,{withFileTypes:!0})){if(!r.isFile())continue;const i=s.join(e,r.name);try{t.statSync(i).mtimeMs<n&&t.unlinkSync(i)}catch{}}}catch{}}(r),e.map(e=>{const n=Ft[e.mime.toLowerCase()]||s.extname(e.name)||".img",i=`${e.id}-${(o=e.name,s.basename(o).replace(/[^\w.\- ()\u4e00-\u9fff]/g,"_").slice(0,160)||"image").replace(/\.[^.]+$/,"")}${n}`;var o;const a=s.join(r,i);return t.writeFileSync(a,Buffer.from(e.data,"base64")),{...e,path:a}})}async function Mt(e,t=[],s){const n=Rt(t);if(!n.length)return s(e);const r=n.map((e,t)=>`图片${n.length>1?t+1:""}路径:${e.path}`);return s([e.trim(),r.join("\n")].filter(Boolean).join("\n\n"))}class jt{approvals=new Map;register(e){return this.approvals.set(e.id,e),e}latestForSession(e){return[...this.approvals.values()].filter(t=>t.sessionId===e).at(-1)}async resolveForSession(e,t){const s=this.latestForSession(e);if(s)return await s.resolve(t),this.approvals.delete(s.id),s}remove(e){return this.approvals.delete(e)}clearSession(e){for(const t of this.approvals.values())t.sessionId===e&&this.approvals.delete(t.id)}}class Lt{registry;providers=new Map;constructor(e){this.registry=e}register(e){this.providers.set(e.agent,e)}async sendMessage(e,t){const s=this.requireSession(e),n=t.message.trim();if(!n)throw $t("AI_SESSION_MESSAGE_EMPTY","Message is required.");const r=t.mode||"auto";if("queue"===r||"auto"===r&&Ht(s)){const e=this.registry.enqueueMessage(s.id,n,t.attachments||[]);if(!e)throw $t("AI_SESSION_NOT_FOUND","AI session not found.",404);return{session:e.session,provider:s.agent,action:"queue",queueId:e.item.id}}if("steer"===r)return this.steerMessage(s.id,{message:n,attachments:t.attachments||[]});if(Ht(s))throw $t("AI_SESSION_BUSY","AI session is busy. Queue the message or steer it into the running turn.",409);return this.startMessage(s.id,{message:n,attachments:t.attachments||[]})}async startMessage(e,t){const s=this.requireSession(e);if(Ht(s))throw $t("AI_SESSION_BUSY","AI session is busy. Queue the message or steer it into the running turn.",409);const n=this.requireProvider(s),r=n.startMessage||n.sendMessage;if(!r)throw $t("AI_SESSION_SEND_UNSUPPORTED",`${s.agent} sessions do not support starting turns.`,400);return r.call(n,s,t)}async steerMessage(e,t){const s=this.requireSession(e);if(!Ht(s))throw $t("AI_SESSION_NOT_ACTIVE","AI session is not active.",409);const n=this.requireProvider(s),r=n.steerMessage||n.sendMessage;if(!r)throw $t("AI_SESSION_STEER_UNSUPPORTED",`${s.agent} sessions do not support turn steering.`,400);const i="string"==typeof t?{message:t}:t;return r.call(n,s,i)}async sendNextQueuedMessage(e){const t=this.requireSession(e);if(Ht(t))return;const s=this.registry.nextQueuedMessage(t.id);if(s){this.registry.markQueuedMessageSending(t.id,s.id);try{const e=await this.startMessage(t.id,{message:s.message,attachments:this.registry.queuedMessageAttachments(s.id)}),n=this.registry.removeQueuedMessage(t.id,s.id);return{...e,session:n||e.session,queueId:s.id}}catch(e){throw this.registry.markQueuedMessageFailed(t.id,s.id,e),e}}}async steerQueuedMessage(e,t){const s=this.requireSession(e),n=s.queue.items.find(e=>e.id===t);if(!n)throw $t("AI_SESSION_QUEUE_ITEM_NOT_FOUND","Queued message not found.",404);const r=await this.steerMessage(s.id,{message:n.message,attachments:this.registry.queuedMessageAttachments(n.id)}),i=this.registry.removeQueuedMessage(s.id,n.id);return{...r,session:i||r.session,action:"steer",queueId:n.id}}retryQueuedMessage(e,t){const s=this.registry.retryQueuedMessage(e,t);if(!s)throw $t("AI_SESSION_QUEUE_ITEM_NOT_FOUND","Queued message not found.",404);return s}removeQueuedMessage(e,t){const s=this.registry.removeQueuedMessage(e,t);if(!s)throw $t("AI_SESSION_NOT_FOUND","AI session not found.",404);return s}reorderQueuedMessages(e,t){const s=this.registry.reorderQueuedMessages(e,t);if(!s)throw $t("AI_SESSION_NOT_FOUND","AI session not found.",404);return s}async interrupt(e){const t=this.requireSession(e);if("running"!==t.status&&"waiting"!==t.status)throw $t("AI_SESSION_NOT_ACTIVE","AI session is not active.",400);return this.requireProvider(t).interrupt(t)}async resolveApproval(e,t){const s=this.requireSession(e),n=this.requireProvider(s);if(n.resolveApproval)return n.resolveApproval(s,t);throw $t("AI_SESSION_APPROVAL_UNSUPPORTED",`${s.agent} sessions do not expose structured approval control.`,400)}requireSession(e){const t=this.registry.get(e);if(!t)throw $t("AI_SESSION_NOT_FOUND","AI session not found.",404);return t}requireProvider(e){const t=this.providers.get(e.agent);if(!t)throw $t("AI_SESSION_CONTROL_UNSUPPORTED",`${e.agent} sessions do not support direct control yet.`,400);return t}}function Ht(e){return"running"===e.status||"waiting"===e.status}function $t(e,t,s=400){const n=new Error(t);return n.code=e,n.statusCode=s,n}function Ut(e){const t=Qt(e);return/^\[(?:request interrupted by user|user interrupted request)\]$/i.test(t)}function qt(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}function Vt(e){if(e.timestamp)return e;const{timestamp:t,...s}=e;return s}function Bt(e){return Array.isArray(e)?e:[]}function Kt(e){return"tool_use"===e.type}function Gt(e){return"tool_result"===e.type}function Wt(e){return"text"===e.type}function Xt(e){return"text"!==e.type&&"output_text"!==e.type&&"input_text"!==e.type||"string"!=typeof e.text?"":e.text}function Jt(e){if("string"==typeof e)return Qt(e);const t=Bt(e).map(Xt).filter(Boolean).join("\n");return t?Qt(t):""}function Yt(e,t=180){const s=String(e??"").replace(/\s+/g," ").trim();return s.length>t?`${s.slice(0,t-3)}...`:s}function Qt(e){return String(e??"").trim()}function Zt(e){try{const t=qt(JSON.parse(String(e||"{}")));return Yt(t.cmd||t.command||t.path||t.ref_id||t.pattern||"")}catch{return""}}function es(e){if(e&&"object"==typeof e&&!Array.isArray(e)){const t=e;return Yt(t.command||t.cmd||t.file_path||t.filePath||t.path||t.ref_id||t.pattern||t.description||"")}return Zt(e)}function ts(e){return/\b(task-handoff|result-ipc)(\.js)?\b/.test(e)}function ss(e){return["edit","multiedit","write","notebookedit"].includes(e.toLowerCase())}function ns(e,r,i=s.join(n.homedir(),".claude")){const o=Yt(e,200);if(!o)return;const a=s.join(i,"projects"),d=Yt(r);if(d){const e=s.join(a,function(e){return s.resolve(e).split(s.sep).join("-")}(d),`${o}.jsonl`);if(t.existsSync(e))return e}const c=[a];for(;c.length>0;){const e=c.pop();if(!e)continue;let n;try{n=t.readdirSync(e,{withFileTypes:!0})}catch{continue}for(const t of n){const n=s.join(e,t.name);if(t.isDirectory())c.push(n);else if(t.isFile()&&t.name.endsWith(".jsonl")&&t.name.includes(o))return n}}}function rs(e,t){let n;try{n=JSON.parse(e)}catch{return}const r=qt(n),i=qt(r.payload),o="string"==typeof qt(n).timestamp?qt(n).timestamp:void 0;if("turn_context"===r.type)return;if("event_msg"===r.type)return"agent_message"===i.type?Vt({text:Qt(i.message),kind:"assistant",timestamp:o}):void 0;if("assistant"===r.type){const e=Bt(r.message?.content);let s,n;for(const r of e){if(Kt(r)){const e=Yt(r.name||"tool",80),n=es(r.input),i=ts(n),a=ss(e)?"edit":void 0;if(r.id&&t.calls.set(r.id,{tool:e,command:n,ignored:i,action:a}),i)continue;s??=Vt({key:r.id,text:"edit"===a?`Editing ${n||"files"}`:n?`Running ${e}: ${n}`:`Running ${e}`,kind:"tool",timestamp:o});continue}Wt(r)&&r.text&&(n??=Qt(r.text))}return s||(n?Vt({text:n,kind:"assistant",timestamp:o}):void 0)}if("user"===r.type){const e=Jt(r.message?.content);if(e&&!Ut(e))return Vt({text:e,kind:"user",timestamp:o});const s=Bt(r.message?.content);for(const e of s){if(!Gt(e))continue;const s=e.tool_use_id?t.calls.get(e.tool_use_id):void 0;if(!s||s.ignored)continue;const n=Boolean(e.is_error);return Vt({key:e.tool_use_id,text:"edit"===s.action?n?`Edit failed: ${s.command||"files"}`:`Finished editing ${s.command||"files"}`:n?`Failed ${s.tool}${s.command?`: ${s.command}`:""}`:s.command?`Finished ${s.tool}: ${s.command}`:`Finished ${s.tool}`,kind:"tool",timestamp:o})}return}if("response_item"!==r.type)return;const a=r.payload;if(a){if("custom_tool_call"===a.type){const e=Yt(a.name||"custom_tool",80);if("apply_patch"!==e)return;const n=function(e){const t=[...String(e||"").matchAll(/^\*\*\* (?:Add|Delete|Update) File: (.+)$/gm)].map(e=>function(e){if(!s.isAbsolute(e))return e;const t=s.relative(process.cwd(),e);return!t||t.startsWith("..")||s.isAbsolute(t)?e:t}(e[1].trim()));if(0===t.length)return"files";const n=t.slice(0,2).join(", ");return t.length>2?`${n} +${t.length-2} more`:n}(a.input);return a.call_id&&t.calls.set(a.call_id,{tool:e,command:n,ignored:!1,action:"edit"}),Vt({key:a.call_id,text:`Editing ${n}`,kind:"tool",timestamp:o})}if("custom_tool_call_output"===a.type){const e=a.call_id?t.calls.get(a.call_id):void 0;if(!e||e.ignored||"edit"!==e.action)return;const s=Yt(a.output,120),n=/failed|error/i.test(s);return Vt({key:a.call_id,text:n?`Edit failed: ${e.command}`:`Finished editing ${e.command}`,kind:"tool",timestamp:o})}if("function_call"===a.type){const e=Yt(a.name||"tool",80),s=Zt(a.arguments),n="write_stdin"===e||ts(s);if(a.call_id&&t.calls.set(a.call_id,{tool:e,command:s,ignored:n}),n)return;return Vt({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 Vt({key:a.call_id,text:e.command?`Finished ${e.tool}: ${e.command}`:`Finished ${e.tool}`,kind:"tool",timestamp:o})}if("message"===a.type){const e=Jt(a.content);if(!e)return;return Vt({text:Qt(e),kind:"user"===a.role?"user":"assistant",timestamp:o})}}}const is=41943040,os="ai-session.snapshot",as=i.z.string().trim().min(1).max(80),ds=i.z.enum(["running","waiting","idle","failed"]),cs=i.z.enum(["thinking","tool","editing","approval","responding","unknown"]),ps=i.z.object({name:i.z.string().trim().min(1).max(120),inputPreview:i.z.string().trim().max(500).optional(),startedAt:i.z.string().datetime().optional()}).strict(),us=i.z.object({toolCalls:i.z.number().int().min(0).default(0),edits:i.z.number().int().min(0).default(0),approvals:i.z.number().int().min(0).default(0)}).strict().default({toolCalls:0,edits:0,approvals:0}),ls=i.z.object({send:i.z.boolean().optional(),interrupt:i.z.boolean().optional(),approval:i.z.boolean().optional()}).strict(),ms=i.z.object({id:i.z.string().trim().min(1).max(120),kind:i.z.enum(["image"]),name:i.z.string().trim().min(1).max(240),mime:i.z.string().trim().min(1).max(120),size:i.z.number().int().min(0).max(20971520),data:i.z.string().min(1).max(31457280)}).strict(),hs=ms.omit({data:!0}),gs=i.z.object({id:i.z.string().trim().min(1).max(120),kind:i.z.enum(["image"]).optional()}).strict(),fs=i.z.enum(["auto","queue","steer","immediate"]),ys=i.z.object({message:i.z.string().trim().min(1).max(2e4),mode:fs.optional()}),vs=ys.extend({attachments:i.z.array(ms).max(6).default([])}).strict().superRefine((e,t)=>{e.attachments.reduce((e,t)=>e+t.size,0)>is&&t.addIssue({code:i.z.ZodIssueCode.custom,path:["attachments"],message:"Images must be 41943040 bytes or less in total."})});ys.extend({attachments:i.z.array(gs).max(6).default([])}).strict();const Ss=i.z.object({decision:i.z.enum(["allow","deny","skip"])}).strict(),Is=i.z.object({queueIds:i.z.array(i.z.string().trim().min(1).max(120)).max(100)}).strict(),As=i.z.object({code:i.z.string().trim().min(1).max(160),message:i.z.string(),instanceId:i.z.string().trim().min(1).max(160).optional(),nodeId:i.z.string().trim().min(1).max(160).optional(),route:i.z.string().trim().min(1).max(4096).optional()}).strict(),bs=i.z.object({id:i.z.string().trim().min(1).max(120),message:i.z.string().trim().min(1).max(2e4),attachments:i.z.array(hs).max(6).default([]),status:i.z.enum(["queued","sending","failed"]).default("queued"),createdAt:i.z.string().datetime(),updatedAt:i.z.string().datetime(),error:i.z.string().trim().max(4e3).optional()}).strict(),_s=i.z.object({pendingCount:i.z.number().int().min(0).default(0),items:i.z.array(bs).max(100).default([])}).strict().default({pendingCount:0,items:[]}),ws=i.z.enum(["control","realtime","adapter-snapshot","transcript-tail","transcript-scan","process-scan","app-session"]),Ts=i.z.object({id:i.z.string().trim().min(1).max(240),providerTurnId:i.z.string().trim().max(240).optional(),source:ws.optional(),userPrompt:i.z.string().trim().optional(),status:i.z.enum(["queued","running","waiting","completed","failed"]).default("running"),phase:cs.optional(),summary:i.z.string().trim().max(1e3).optional(),lastMessage:i.z.string().trim().optional(),revision:i.z.number().int().min(0).default(0),sourcePriority:i.z.number().int().min(0).max(100).optional(),snapshotVersion:i.z.number().int().min(0).optional(),observedAt:i.z.string().datetime().optional(),startedAt:i.z.string().datetime().optional(),updatedAt:i.z.string().datetime().optional(),completedAt:i.z.string().datetime().optional()}).strict(),Ns=i.z.object({id:i.z.string().trim().min(1).max(120),agent:as,appSessionId:i.z.string().trim().max(120).optional(),appId:i.z.string().trim().max(120).optional(),providerSessionId:i.z.string().trim().max(240).optional(),providerMeta:i.z.record(i.z.string(),i.z.unknown()).optional(),appBindingKeys:i.z.array(i.z.string().trim().min(1).max(240)).max(20).optional(),actions:ls.optional(),activeTurnId:i.z.string().trim().max(240).optional(),conversationId:i.z.number().int().positive().optional(),title:i.z.string().trim().max(240).optional(),cwd:i.z.string().trim().max(4096).optional(),userPrompt:i.z.string().trim().optional(),turns:i.z.array(Ts).max(50).optional(),status:ds.default("running"),phase:cs.default("unknown"),summary:i.z.string().trim().max(1e3).optional(),lastMessage:i.z.string().trim().optional(),currentTool:ps.optional(),transcriptPath:i.z.string().trim().max(4096).optional(),transcriptSize:i.z.number().int().min(0).optional(),startedAt:i.z.string().datetime(),updatedAt:i.z.string().datetime(),completedAt:i.z.string().datetime().optional(),error:i.z.string().trim().max(4e3).optional(),counters:us,queue:_s}).strict(),zs=i.z.object({session:Ns,provider:i.z.string().trim().min(1).max(80),action:i.z.enum(["send","queue","steer","interrupt","approval"]),decision:i.z.enum(["allow","deny","skip"]).optional(),turnId:i.z.string().trim().min(1).max(240).optional(),providerTurnId:i.z.string().trim().min(1).max(240).optional(),queueId:i.z.string().trim().min(1).max(120).optional()}).strict(),Os=Ns.pick({id:!0,agent:!0,appSessionId:!0,appId:!0,providerSessionId:!0,providerMeta:!0,appBindingKeys:!0,actions:!0,activeTurnId:!0,conversationId:!0,title:!0,cwd:!0,userPrompt:!0,turns:!0,status:!0,phase:!0,summary:!0,lastMessage:!0,currentTool:!0,queue:!0,startedAt:!0,updatedAt:!0,error:!0}),Es=i.z.object({runningCount:i.z.number().int().min(0).default(0),waitingCount:i.z.number().int().min(0).default(0),staleCount:i.z.number().int().min(0).default(0),sessions:i.z.array(Os).default([]),updatedAt:i.z.string().datetime()}).strict();i.z.object({streamId:i.z.string().trim().min(1).max(240),revision:i.z.number().int().min(0),lastEventAt:i.z.string().datetime(),snapshot:Es}).strict(),Es.pick({runningCount:!0,waitingCount:!0,staleCount:!0,updatedAt:!0}).extend({idleCount:i.z.number().int().min(0).default(0),problemCount:i.z.number().int().min(0).default(0),revision:i.z.number().int().min(0).optional()});const xs=i.z.enum(["provider-event","app-session-created","app-session-updated","app-session-deleted","discovery-scan","control-action","heartbeat-sync","startup"]),ks=i.z.object({streamId:i.z.string().trim().min(1).max(240),instanceId:i.z.string().trim().min(1).max(160),nodeId:i.z.string().trim().min(1).max(160).optional(),revision:i.z.number().int().min(0),previousRevision:i.z.number().int().min(0).optional(),traceId:i.z.string().trim().min(1).max(160),generatedAt:i.z.string().datetime(),reason:xs}).strict(),Ds=i.z.object({meta:ks,snapshot:Es}).strict(),Cs=i.z.object({meta:ks,upserted:i.z.array(Os).default([]),removed:i.z.array(i.z.string().trim().min(1).max(120)).default([])}).strict(),Ps=i.z.object({meta:ks,sessionIds:i.z.array(i.z.string().trim().min(1).max(120)).default([]),expiresAt:i.z.string().datetime()}).strict(),Fs=i.z.object({streamId:i.z.string().trim().min(1).max(240),instanceId:i.z.string().trim().min(1).max(160),sinceRevision:i.z.number().int().min(0),latestRevision:i.z.number().int().min(0),earliestRetainedRevision:i.z.number().int().min(0),syncRequired:i.z.boolean().default(!1),events:i.z.array(i.z.discriminatedUnion("type",[i.z.object({type:i.z.literal(os),payload:Ds}).strict(),i.z.object({type:i.z.literal("ai-session.patch"),payload:Cs}).strict(),i.z.object({type:i.z.literal("ai-session.removed"),payload:Ps}).strict()])).default([])}).strict(),Rs=i.z.object({source:ws,sourcePriority:i.z.number().int().min(0).max(100).optional(),observedAt:i.z.string().datetime().optional(),snapshotVersion:i.z.number().int().min(0).optional()}).strict(),Ms=Rs.extend({type:i.z.literal("snapshot"),agent:i.z.string().trim().min(1).max(80),appSessionId:i.z.string().trim().max(120).optional(),appId:i.z.string().trim().max(120).optional(),providerSessionId:i.z.string().trim().max(240).optional(),providerMeta:i.z.record(i.z.string(),i.z.unknown()).optional(),appBindingKeys:i.z.array(i.z.string().trim().min(1).max(240)).max(20).optional(),actions:ls.optional(),conversationId:i.z.number().int().positive().optional(),title:i.z.string().trim().max(240).optional(),cwd:i.z.string().trim().max(4096).optional(),activeTurnId:i.z.string().trim().max(240).optional(),userPrompt:i.z.string().trim().optional(),turns:i.z.array(Ts).max(50).optional(),status:ds.optional(),phase:cs.optional(),summary:i.z.string().trim().max(1e3).optional(),lastMessage:i.z.string().trim().optional(),transcriptPath:i.z.string().trim().max(4096).optional(),transcriptSize:i.z.number().int().min(0).optional(),replaceActivity:i.z.boolean().optional()}).strict(),js=Rs.extend({type:i.z.literal("event"),sessionId:i.z.string().trim().min(1).max(120),kind:i.z.enum(["lifecycle","send-ack","turn-started","user-message","assistant-message","approval-requested","turn-completed"]),activeTurnId:i.z.string().trim().max(240).optional(),providerTurnId:i.z.string().trim().max(240).optional(),userPrompt:i.z.string().trim().optional(),text:i.z.string().optional(),status:ds.optional(),phase:cs.optional(),summary:i.z.string().trim().max(1e3).optional(),error:i.z.string().trim().max(4e3).optional(),counters:i.z.object({toolCalls:i.z.number().int().min(0).optional(),edits:i.z.number().int().min(0).optional(),approvals:i.z.number().int().min(0).optional()}).strict().optional()}).strict();function Ls(e,t=500){const s=String(e??"").replace(/\s+/g," ").trim();return s.length>t?`${s.slice(0,t-3)}...`:s}function Hs(e){return String(e??"").trim()}i.z.discriminatedUnion("type",[Ms,js]);const $s={control:90,realtime:80,"adapter-snapshot":60,"transcript-tail":50,"app-session":40,"process-scan":30,"transcript-scan":20};function Us(e,t){return Math.max(0,Math.min(100,Number.isInteger(t)?Number(t):e?$s[e]:0))}function qs(e){const t={};return e.source&&(t.source=e.source,t.sourcePriority=Us(e.source,e.sourcePriority)),e.providerTurnId&&(t.providerTurnId=Ls(e.providerTurnId,240)),Number.isInteger(e.snapshotVersion)&&(t.snapshotVersion=Number(e.snapshotVersion)),e.observedAt&&(t.observedAt=e.observedAt),t}function Vs(e){const t=Ls(e,120),s=t.replace(/[^a-zA-Z0-9_.:-]+/g,"_").replace(/^_+|_+$/g,""),n=o.createHash("sha1").update(t).digest("hex").slice(0,10);return s?`${s}_${n}`:n}function Bs(e,t){return`turn_${Vs(e)}_${Vs(t)}`}function Ks(e,t,s=1){return Bs(e,t||`${e}:${s}`)}function Gs(e,t){return`turn_legacy_${t}_${Vs(e.userPrompt||e.updatedAt||e.lastMessage||e.summary)}`}function Ws(e,t={}){const s=[];for(const[n,r]of(e||[]).entries()){const e=r&&"object"==typeof r?r:void 0;if(!e)continue;const i={id:e.id?Ls(e.id,240):Gs(e,n),providerTurnId:e.providerTurnId?Ls(e.providerTurnId,240):t.providerTurnId,source:e.source||t.source,userPrompt:e.userPrompt?Hs(e.userPrompt):void 0,status:e.status||"completed",phase:e.phase,summary:e.summary?Ls(e.summary,1e3):void 0,lastMessage:e.lastMessage?Hs(e.lastMessage):void 0,revision:Math.max(0,Number(e.revision)||0),sourcePriority:Number.isInteger(e.sourcePriority)?Number(e.sourcePriority):t.sourcePriority,snapshotVersion:Number.isInteger(e.snapshotVersion)?Number(e.snapshotVersion):t.snapshotVersion,observedAt:e.observedAt||t.observedAt,startedAt:e.startedAt,updatedAt:e.updatedAt,completedAt:e.completedAt};(i.userPrompt||i.summary||i.lastMessage)&&s.push(i)}return s.slice(-50)}function Xs(e,t){if(!e)return!0;const s=Us(e.source,e.sourcePriority),n=Us(t.source,t.sourcePriority);if(n!==s)return n>s||Boolean(t.lastMessage||t.summary)&&!e.lastMessage&&!e.summary;const r=Number(e.snapshotVersion)||0,i=Number(t.snapshotVersion)||0;return i!==r?i>r:(t.revision||0)>=(e.revision||0)||Date.parse(t.observedAt||t.updatedAt||"")>=Date.parse(e.observedAt||e.updatedAt||"")}function Js(e,t){const s=function(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e))}(t);if(!e)return s;const n=e.userPrompt===(t.userPrompt??e.userPrompt)&&e.summary===(t.summary??e.summary)&&e.lastMessage===(t.lastMessage??e.lastMessage),r=e.status===(t.status??e.status)&&e.phase===(t.phase??e.phase);return n&&r&&(delete s.observedAt,delete s.updatedAt,delete s.completedAt),s}function Ys(e){return Boolean(e?.lastMessage||e?.summary)}function Qs(e){if(!e.activeTurnId||"running"!==e.status)return!1;const t=Ws(e.turns).find(t=>t.id===e.activeTurnId);return Boolean(!t||!Ys(t))}function Zs(e,t,s){return s?e.activeTurnId:"idle"!==t.status&&"failed"!==t.status?t.activeTurnId?Ls(t.activeTurnId,240):e.activeTurnId:void 0}function en(e,t,s,n={}){const r=function(e,t,s={}){const n=Ws(e),r=Ws(t,s);function i(e,t){const s=r.slice(0,t).reverse().find(e=>n.some(t=>t.id===e.id));if(s){const t=n.findIndex(e=>e.id===s.id);return void n.splice(t+1,0,e)}const i=r.slice(t+1).find(e=>n.some(t=>t.id===e.id));if(i){const t=n.findIndex(e=>e.id===i.id);return void n.splice(t,0,e)}n.push(e)}for(const[e,t]of r.entries()){let s=!1;for(const[e,r]of n.entries())if(r.id!==t.id&&r.userPrompt&&r.userPrompt===t.userPrompt&&!r.lastMessage&&!r.summary&&(t.lastMessage||t.summary)){const i={...r,...Js(r,t),id:r.id,providerTurnId:t.providerTurnId||t.id,revision:Math.max(r.revision||0,t.revision||0)};Xs(r,i)&&(n[e]=i),s=!0;break}if(s)continue;const r=n.findIndex(e=>e.id===t.id),o=r>=0?n[r]:void 0;if(Xs(o,t)){const s={...o,...Js(o,t),revision:Math.max(o?.revision||0,t.revision||0)};r>=0?n[r]=s:i(s,e)}}return n.slice(-50)}(e,t.turns,n),i=t.userPrompt?Hs(t.userPrompt):"",a=t.activeTurnId?Ls(t.activeTurnId,240):"";if(i){const e=r.at(-1),o=(a?r.find(e=>e.id===a):void 0)||[...r].reverse().find(e=>e.userPrompt===i&&!e.lastMessage&&!e.summary),d=Boolean(t.turns?.some(e=>e.userPrompt&&Hs(e.userPrompt)===i));o?(a&&o.id!==a&&(o.id=a),o.userPrompt=i,o.updatedAt=s,o.status="waiting"===t.status?"waiting":"running",o.phase=t.phase||o.phase||"thinking",Object.assign(o,n),o.revision+=1):!e||e.lastMessage||e.summary||e.userPrompt!==i?d||r.push({id:a||Bs(i,s),...n,userPrompt:i,status:"waiting"===t.status?"waiting":"running",phase:t.phase||"thinking",revision:0,startedAt:s,updatedAt:s}):(e.updatedAt=s,e.status="waiting"===t.status?"waiting":"running",e.phase=t.phase||e.phase||"thinking",Object.assign(e,n),e.revision+=1)}if(t.lastMessage||t.summary){let e=a?r.find(e=>e.id===a):r.at(-1);if(!e&&a){const t=[...r].reverse().find(e=>e.userPrompt&&!e.lastMessage&&!e.summary);t&&(t.id=a,e=t)}!e&&a&&(e={id:a,...n,status:"waiting"===t.status?"waiting":"failed"===t.status?"failed":"running",phase:t.phase||"unknown",revision:0,startedAt:s,updatedAt:s},r.push(e));const i={summary:t.summary?Ls(t.summary,1e3):e?.summary,lastMessage:t.lastMessage?Hs(t.lastMessage):e?.lastMessage,status:"idle"===t.status?"completed":"waiting"===t.status?"waiting":"failed"===t.status?"failed":e?.status||"running",phase:t.phase||e?.phase,updatedAt:s,completedAt:"idle"===t.status||"failed"===t.status?s:e?.completedAt,...n};if(e){const t=e.summary===i.summary&&e.lastMessage===i.lastMessage,s=e.status===i.status&&e.phase===i.phase,n=t&&s;Object.assign(e,{...i,observedAt:n?e.observedAt:i.observedAt,updatedAt:n||t?e.updatedAt:i.updatedAt,completedAt:n?e.completedAt:i.completedAt}),t&&s||(e.revision+=1)}else r.push({id:`turn_${o.randomUUID().replace(/-/g,"").slice(0,20)}`,...i,status:i.status||"running",revision:0,startedAt:s})}else if((t.status||t.phase)&&a){const e=r.find(e=>e.id===a);if(e){const r="idle"===t.status?"completed":"waiting"===t.status?"waiting":"failed"===t.status?"failed":e.status,i=t.phase||e.phase,o="idle"===t.status||"failed"===t.status?s:e.completedAt,a=e.status!==r||e.phase!==i||e.completedAt!==o;Object.assign(e,{status:r,phase:i,completedAt:o,updatedAt:a?s:e.updatedAt,...n}),a&&(e.revision+=1)}}if(("running"===t.status||"waiting"===t.status)&&a){const e=r.findIndex(e=>e.id===a);if(e>=0&&e!==r.length-1){const[t]=r.splice(e,1);r.push(t)}}return Ws(r)}function tn(){return(new Date).toISOString()}function sn(e){t.mkdirSync(e,{recursive:!0})}function nn(e){try{return JSON.parse(t.readFileSync(e,"utf8"))}catch{return}}function rn(e,t,s){if(!Array.isArray(e))return;const n=[...new Set(e.map(e=>Ls(e,s)).filter(Boolean))].slice(0,t);return n.length?n:void 0}function on(e){const t=e&&"object"==typeof e&&!Array.isArray(e)?e:{},s={send:"boolean"==typeof t.send?t.send:void 0,interrupt:"boolean"==typeof t.interrupt?t.interrupt:void 0,approval:"boolean"==typeof t.approval?t.approval:void 0};return void 0===s.send&&void 0===s.interrupt&&void 0===s.approval?void 0:s}function an(e){const t=e.map(cn).filter(e=>Boolean(e)).slice(0,100);return{pendingCount:t.filter(e=>"queued"===e.status||"sending"===e.status).length,items:t}}function dn(e){const t=e&&"object"==typeof e&&!Array.isArray(e)?e:{};return an(Array.isArray(t.items)?t.items:[])}function cn(e){const t=e&&"object"==typeof e&&!Array.isArray(e)?e:void 0;if(!(t?.id&&t.message&&t.createdAt&&t.updatedAt))return;const s="sending"===t.status||"failed"===t.status?t.status:"queued";return{id:Ls(t.id,120),message:Hs(t.message),attachments:pn(t.attachments),status:s,createdAt:t.createdAt,updatedAt:t.updatedAt,error:t.error?Ls(t.error,4e3):void 0}}function pn(e){return Array.isArray(e)?e.map(e=>{const t=hs.safeParse(e);return t.success?t.data:void 0}).filter(e=>Boolean(e)).slice(0,6):[]}function un(e=[]){return e.slice(0,6).map(e=>hs.parse({id:e.id,kind:e.kind,name:e.name,mime:e.mime,size:e.size}))}function ln(e){const t=e&&"object"==typeof e?e:void 0;var s;if(t?.id&&t.agent&&t.startedAt&&t.updatedAt)return{id:Ls(t.id,120),agent:Ls(t.agent,80),appSessionId:t.appSessionId?Ls(t.appSessionId,120):void 0,appId:t.appId?Ls(t.appId,120):void 0,providerSessionId:t.providerSessionId?Ls(t.providerSessionId,240):void 0,providerMeta:t.providerMeta&&"object"==typeof t.providerMeta&&!Array.isArray(t.providerMeta)?t.providerMeta:void 0,appBindingKeys:rn(t.appBindingKeys,20,240),actions:on(t.actions),activeTurnId:t.activeTurnId?Ls(t.activeTurnId,240):void 0,conversationId:Number.isInteger(t.conversationId)&&Number(t.conversationId)>0?Number(t.conversationId):void 0,title:t.title?Ls(t.title,240):void 0,cwd:t.cwd?Ls(t.cwd,4096):void 0,userPrompt:t.userPrompt?Hs(t.userPrompt):void 0,turns:Ws(t.turns),status:mn(t.status),phase:hn(t.phase),summary:t.summary?Ls(t.summary,1e3):void 0,lastMessage:t.lastMessage?Hs(t.lastMessage):void 0,currentTool:t.currentTool?.name?{name:Ls(t.currentTool.name,120),inputPreview:t.currentTool.inputPreview?Ls(t.currentTool.inputPreview,500):void 0,startedAt:t.currentTool.startedAt}:void 0,transcriptPath:t.transcriptPath?Ls(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?Ls(t.error,4e3):void 0,counters:(s=t.counters,{toolCalls:Math.max(0,Number(s?.toolCalls)||0),edits:Math.max(0,Number(s?.edits)||0),approvals:Math.max(0,Number(s?.approvals)||0)}),queue:dn(t.queue)}}function mn(e){const t=String(e||"").trim().toLowerCase();return"waiting"===t?"waiting":"failed"===t?"failed":"idle"===t||"completed"===t||"stale"===t||"stopped"===t||"exited"===t?"idle":"running"}function hn(e){return["thinking","tool","editing","approval","responding","unknown"].includes(String(e))?e:"unknown"}function gn(e){return e.appSessionId?`${e.agent}:app:${e.appSessionId}`:e.providerSessionId?`${e.agent}:provider:${e.providerSessionId}`:e.transcriptPath?`${e.agent}:transcript:${e.transcriptPath}`:`${e.agent}:id:${e.id}`}function fn(e,t){const s=Number(Boolean(e.userPrompt))+Number(Boolean(e.summary))+Number(Boolean(e.lastMessage))+(e.turns?.length||0),n=Number(Boolean(t.userPrompt))+Number(Boolean(t.summary))+Number(Boolean(t.lastMessage))+(t.turns?.length||0);return s!==n?s>n?e:t:Date.parse(e.updatedAt)>=Date.parse(t.updatedAt)?e:t}function yn(e){return{id:e.id,agent:e.agent,appSessionId:e.appSessionId,appId:e.appId,providerSessionId:e.providerSessionId,providerMeta:e.providerMeta,appBindingKeys:e.appBindingKeys,actions:vn(e),activeTurnId:e.activeTurnId,conversationId:e.conversationId,title:e.title,cwd:e.cwd,userPrompt:e.userPrompt,turns:e.turns,status:e.status,phase:e.phase,summary:e.summary,lastMessage:e.lastMessage,currentTool:e.currentTool,queue:e.queue,startedAt:e.startedAt,updatedAt:e.updatedAt,error:e.error}}function vn(e){const t="running"===e.status||"waiting"===e.status,s=e.actions||{};return{send:s.send??!0,interrupt:Boolean(t&&!1!==s.interrupt),approval:Boolean("waiting"===e.status&&"approval"===e.phase&&!1!==s.approval)}}function Sn(e,t){const s=Ls(e,1e3);return"user"===t?{userPrompt:Hs(e)}:"assistant"===t?{status:"running",phase:"responding",summary:s,lastMessage:Hs(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:Hs(e)}:{}}function In(e,t,s){const n=t.activeTurnId?Ls(t.activeTurnId,240):void 0;if("transcript-tail"!==t.source||!n||!e.activeTurnId||n===e.activeTurnId)return n||e.activeTurnId;const r=Ws(e.turns).find(t=>t.id===e.activeTurnId);if(!r||Ys(r))return n;const i=s?Hs(s):"";return i&&r.userPrompt&&r.userPrompt!==i?n:e.activeTurnId}function An(e,r,i){if(r)return"claude"===e?ns(r,i):function(e,r=s.join(n.homedir(),".codex")){const i=Yt(e,200);if(!i)return;const o=[s.join(r,"sessions")];for(;o.length>0;){const e=o.pop();if(!e)continue;let n;try{n=t.readdirSync(e,{withFileTypes:!0})}catch{continue}for(const t of n){const n=s.join(e,t.name);if(t.isDirectory())o.push(n);else if(t.isFile()&&t.name.endsWith(".jsonl")&&t.name.includes(i))return n}}}(r)}class bn{dir;retentionMs;idleAfterMs;staleAfterMs;orphanedAppSessionRetentionMs;orphanedAppSessionAt=new Map;queuedAttachmentPayloads=new Map;changes=new g.EventEmitter;constructor(e={}){this.dir=e.dir||function(){const e=process.env.TASK_HANDOFF_AI_SESSION_DIR;return e?.trim()?s.resolve(e.trim()):s.join(et().dataDir,"ai-sessions")}(),this.retentionMs=e.retentionMs??(Number(process.env.TASK_HANDOFF_AI_SESSION_RETENTION_MS)||864e5),this.idleAfterMs=e.idleAfterMs??(Number(process.env.TASK_HANDOFF_AI_SESSION_IDLE_AFTER_MS)||3e4),this.staleAfterMs=e.staleAfterMs??(Number(process.env.TASK_HANDOFF_AI_SESSION_STALE_AFTER_MS)||3e5),this.orphanedAppSessionRetentionMs=e.orphanedAppSessionRetentionMs??(Number(process.env.TASK_HANDOFF_AI_SESSION_ORPHAN_RETENTION_MS)||3e5)}sessionPath(e){return s.join(this.dir,`${e}.json`)}onChange(e){return this.changes.on("change",e),()=>{this.changes.off("change",e)}}start(e,t={}){const s=t.timestamp||tn(),n=t.meta||qs({source:"control",observedAt:s}),r={id:`ais_${o.randomUUID().replace(/-/g,"").slice(0,20)}`,agent:Ls(e.agent||"unknown",80),appSessionId:e.appSessionId?Ls(e.appSessionId,120):void 0,appId:e.appId?Ls(e.appId,120):void 0,providerSessionId:e.providerSessionId?Ls(e.providerSessionId,240):void 0,providerMeta:void 0,activeTurnId:void 0,conversationId:e.conversationId,title:e.title?Ls(e.title,240):void 0,cwd:e.cwd?Ls(e.cwd,4096):void 0,userPrompt:e.userPrompt?Hs(e.userPrompt):void 0,turns:en(void 0,{userPrompt:t.suppressPromptTurn?void 0:e.userPrompt,turns:e.turns},s,n),status:mn(e.status||"idle"),phase:hn(e.phase||"unknown"),summary:e.summary?Ls(e.summary,1e3):void 0,startedAt:s,updatedAt:s,counters:{toolCalls:0,edits:0,approvals:0},queue:{pendingCount:0,items:[]}};return this.put(r),r}get(e){return ln(nn(this.sessionPath(e)))}put(e){var t,n;return sn(this.dir),t=this.sessionPath(e.id),n=e,sn(s.dirname(t)),r.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||tn(),o=s.suppressPromptTurn?{...t,userPrompt:void 0}:t,a=s.suppressTurnUpdate?Ws(s.replaceTurns?void 0:n.turns):en(s.replaceTurns?void 0:n.turns,o,i,s.meta),d=t.userPrompt?Hs(t.userPrompt):"",c=a.at(-1),p=Boolean(d&&!t.lastMessage&&c?.userPrompt===d&&!c.summary&&!c.lastMessage),u={...n,...t,id:n.id,agent:n.agent,startedAt:n.startedAt,updatedAt:i,status:t.status?mn(t.status):n.status,phase:t.phase?hn(t.phase):n.phase,summary:s.replaceActivity?t.summary?Ls(t.summary,1e3):void 0:s.clearResponse?void 0:t.summary?Ls(t.summary,1e3):p?void 0:n.summary,lastMessage:s.replaceActivity?t.lastMessage?Hs(t.lastMessage):void 0:s.clearResponse?void 0:t.lastMessage?Hs(t.lastMessage):p?void 0:n.lastMessage,userPrompt:s.replaceActivity?t.userPrompt?Hs(t.userPrompt):void 0:t.userPrompt?Hs(t.userPrompt):n.userPrompt,turns:a,error:t.error?Ls(t.error,4e3):n.error,counters:r,queue:t.queue?dn(t.queue):n.queue};return this.put(u)}enqueueMessage(e,t,s=[]){const n=this.get(e);if(!n)return;const r=tn(),i={id:`aiq_${o.randomUUID().replace(/-/g,"").slice(0,20)}`,message:Hs(t),attachments:un(s),status:"queued",createdAt:r,updatedAt:r},a=[...n.queue?.items||[],i],d=this.update(e,{queue:an(a)},{updatedAt:r,suppressTurnUpdate:!0});return d&&s.length&&this.queuedAttachmentPayloads.set(i.id,s.slice(0,6)),d?{session:d,item:i}:void 0}queuedMessages(e){return this.get(e)?.queue||{pendingCount:0,items:[]}}nextQueuedMessage(e){return this.queuedMessages(e).items.find(e=>"queued"===e.status)}queuedMessageAttachments(e){return this.queuedAttachmentPayloads.get(e)||[]}markQueuedMessageSending(e,t){return this.patchQueuedMessage(e,t,{status:"sending",error:void 0})}markQueuedMessageFailed(e,t,s){const n=s instanceof Error?s.message:String(s);return this.patchQueuedMessage(e,t,{status:"failed",error:Ls(n,4e3)})}retryQueuedMessage(e,t){return this.patchQueuedMessage(e,t,{status:"queued",error:void 0})}removeQueuedMessage(e,t){const s=this.get(e);if(!s)return;const n=(s.queue?.items||[]).filter(e=>e.id!==t);return this.queuedAttachmentPayloads.delete(t),this.update(e,{queue:an(n)},{suppressTurnUpdate:!0})}reorderQueuedMessages(e,t){const s=this.get(e);if(!s)return;const n=s.queue?.items||[],r=new Map(n.map(e=>[e.id,e])),i=t.map(e=>r.get(e)).filter(e=>Boolean(e)),o=n.filter(e=>!t.includes(e.id));return this.update(e,{queue:an([...i,...o])},{suppressTurnUpdate:!0})}patchQueuedMessage(e,t,s){const n=this.get(e);if(!n)return;const r=tn();let i=!1;const o=(n.queue?.items||[]).map(e=>e.id!==t?e:(i=!0,{...e,...s,updatedAt:r}));return i?this.update(e,{queue:an(o)},{updatedAt:r,suppressTurnUpdate:!0}):void 0}bindProviderSession(e,t){const s=this.get(e),n=s?An(s.agent,t,s.cwd):void 0;return this.update(e,{providerSessionId:t,transcriptPath:n,status:"running",phase:"thinking",summary:`${s?.agent||"AI"} session ${t} started`})}apply(e){const t=e.observedAt||tn(),s={...e,observedAt:t,sourcePriority:Us(e.source,e.sourcePriority)};return"snapshot"===e.type?this.reduceSnapshotInput(s):this.reduceRealtimeInput(s)}applyRealtimeEvent(e,t){return this.apply({type:"event",sessionId:e,source:t.source||"realtime",...t})}reduceRealtimeInput(e){const t=e.sessionId,s=this.get(t);if(!s)return;const n=qs(e);if("send-ack"===e.kind){const s=e.observedAt||tn(),r=Hs(e.userPrompt);return this.update(t,{activeTurnId:e.activeTurnId||Bs(r,s),status:e.status||"running",phase:e.phase||"thinking",userPrompt:r},{updatedAt:s,meta:n})}if("lifecycle"===e.kind){const r=e.status||s.status;return"idle"!==r&&"failed"!==r||!Qs(s)?this.update(t,{activeTurnId:("running"===r||"waiting"===r)&&e.activeTurnId||s.activeTurnId,status:r,phase:e.phase||s.phase},{updatedAt:e.observedAt,meta:n}):s}if("turn-started"===e.kind)return this.update(t,{activeTurnId:e.activeTurnId||s.activeTurnId,status:e.status||"running",phase:e.phase||"thinking"},{updatedAt:e.observedAt,meta:n});if("user-message"===e.kind){const r=In(s,e,e.userPrompt);return this.update(t,{activeTurnId:r,status:e.status||"running",phase:e.phase||"thinking",userPrompt:e.userPrompt},{updatedAt:e.observedAt,meta:n})}if("assistant-message"===e.kind){const r=In(s,e),i="transcript-tail"===e.source;return this.update(t,{activeTurnId:r,status:e.status||(i?"idle":"running"),phase:e.phase||(i?"unknown":"responding"),summary:e.text,lastMessage:e.text},{updatedAt:e.observedAt,meta:n})}if("approval-requested"===e.kind)return this.update(t,{activeTurnId:e.activeTurnId||s.activeTurnId,status:e.status||"waiting",phase:e.phase||"approval",summary:e.summary||e.text,counters:e.counters||{approvals:1}},{updatedAt:e.observedAt,meta:n});if("turn-completed"===e.kind){const r=e.error?Ls(e.error,4e3):void 0,i=e.text||e.summary||("failed"===e.status?r:void 0),o=Boolean(i);return this.update(t,{activeTurnId:e.activeTurnId&&e.activeTurnId!==s.activeTurnId?s.activeTurnId:void 0,status:e.status||"idle",phase:e.phase||"unknown",summary:i,lastMessage:i,error:r},{updatedAt:e.observedAt,meta:n,clearResponse:!o})}}applyAdapterSnapshot(e){return this.apply({type:"snapshot",source:e.source||"control",...e})}reduceSnapshotInput(e){const t=qs(e),s=this.readSessions().find(t=>e.appSessionId&&t.appSessionId===e.appSessionId||e.providerSessionId&&t.providerSessionId===e.providerSessionId||e.transcriptPath&&t.transcriptPath===e.transcriptPath);if(!s){const s=this.start({agent:e.agent,appSessionId:e.appSessionId,appId:e.appId,providerSessionId:e.providerSessionId,conversationId:e.conversationId,title:e.title,cwd:e.cwd,userPrompt:e.userPrompt,turns:e.turns,status:e.status||"idle",phase:e.phase||"unknown",summary:e.summary},{meta:t,timestamp:e.observedAt,suppressPromptTurn:!e.turns?.length});return this.update(s.id,{providerMeta:e.providerMeta,appBindingKeys:e.appBindingKeys,actions:e.actions,lastMessage:e.lastMessage,transcriptPath:e.transcriptPath,transcriptSize:e.transcriptSize,status:e.status||s.status,phase:e.phase||"unknown"},{updatedAt:e.observedAt,meta:t,suppressTurnUpdate:!e.turns?.length})}return this.orphanedAppSessionAt.delete(s.id),this.reduceSnapshot(s.id,e)}reduceSnapshot(e,t){const s=this.get(e);if(!s)return;const n=qs(t),r=Ws(t.turns,n),i=function(e,t){if(!Qs(e))return!1;const s=Ws(e.turns).find(t=>t.id===e.activeTurnId);return!Ws(t).some(t=>t.id===e.activeTurnId||Boolean(s?.userPrompt&&t.userPrompt===s.userPrompt&&Ys(t)&&!Ys(s)))}(s,r),o=Boolean(s.activeTurnId&&r.some(e=>e.id===s.activeTurnId)),a=s.activeTurnId?r.find(e=>e.id===s.activeTurnId):void 0,d=Boolean(t.replaceActivity&&s.activeTurnId&&o&&!Ys(a)),c=function(e){return"app-session"===e.source||"adapter-snapshot"===e.source&&"codex"===e.agent&&"codex-app-server"===e.appId}(t);return this.update(e,{appSessionId:c?t.appSessionId:t.appSessionId||s.appSessionId,appId:t.appId||s.appId,providerSessionId:t.providerSessionId||s.providerSessionId,providerMeta:t.providerMeta||s.providerMeta,appBindingKeys:c?t.appBindingKeys:t.appBindingKeys||s.appBindingKeys,actions:t.actions||s.actions,activeTurnId:Zs(s,t,i),conversationId:t.conversationId||s.conversationId,title:t.title||s.title,cwd:t.cwd||s.cwd,userPrompt:i?s.userPrompt:t.userPrompt||s.userPrompt,turns:i?s.turns:t.turns,lastMessage:i?s.lastMessage:d?void 0:t.lastMessage||s.lastMessage,transcriptPath:t.transcriptPath||s.transcriptPath,transcriptSize:t.transcriptSize??s.transcriptSize,status:i?s.status:t.status||s.status,phase:i?s.phase:t.phase||s.phase,summary:i?s.summary:d?void 0:t.replaceActivity?t.summary:t.summary||s.summary},{updatedAt:t.observedAt,meta:n,replaceActivity:Boolean(t.replaceActivity),suppressPromptTurn:!r.length,suppressTurnUpdate:!r.length,replaceTurns:Boolean(t.replaceActivity&&!i&&0===r.length&&!t.userPrompt&&!t.summary&&!t.lastMessage)})}attachTranscript(e,t){if(!t){const s=this.get(e);t=s?An(s.agent,s.providerSessionId,s.cwd):void 0}const s=this.get(e);return t&&s?this.applyAdapterSnapshot({source:"transcript-scan",agent:s.agent,appId:s.appId,appSessionId:s.appSessionId,providerSessionId:s.providerSessionId,cwd:s.cwd,transcriptPath:t,status:s.status,phase:s.phase}):s}progress(e,t,s){if("user"===s)return this.applyRealtimeEvent(e,{kind:"user-message",userPrompt:t});if("assistant"===s)return this.applyRealtimeEvent(e,{kind:"assistant-message",text:t});const n=Sn(t,s);return this.applyRealtimeEvent(e,{kind:"waiting"===n.status?"approval-requested":"assistant-message",text:n.summary||t,status:n.status,phase:n.phase,counters:n.counters,source:"realtime"})}complete(e,t){return this.applyRealtimeEvent(e,{kind:"turn-completed",status:"idle",phase:"responding",text:t?Hs(t):"Completed",source:"control"})}fail(e,t){const s=t instanceof Error?t.message:String(t);return this.applyRealtimeEvent(e,{kind:"turn-completed",status:"failed",phase:"unknown",text:`Failed: ${s}`,source:"control"})}markWaitingByConversation(e,t){const s=this.list().filter(t=>t.conversationId===e&&!["idle","failed"].includes(t.status)).sort((e,t)=>Date.parse(t.updatedAt)-Date.parse(e.updatedAt))[0];return s?this.applyRealtimeEvent(s.id,{kind:"approval-requested",status:"waiting",phase:"approval",summary:t,counters:{approvals:1},source:"realtime"}):void 0}list(){return this.canonicalSessions(this.readSessions().filter(e=>!this.orphanedAppSessionAt.has(e.id)))}readSessions(){sn(this.dir);let e=[];try{e=t.readdirSync(this.dir).filter(e=>e.endsWith(".json"))}catch{return[]}const n=Date.now();return e.map(e=>ln(nn(s.join(this.dir,e)))).filter(e=>Boolean(e)).map(e=>this.withDerivedLifecycle(e,n)).sort((e,t)=>Date.parse(t.updatedAt)-Date.parse(e.updatedAt))}canonicalSessions(e){const t=new Map;for(const s of e){const e=gn(s),n=t.get(e);t.set(e,n?fn(n,s):s)}return[...t.values()].sort((e,t)=>Date.parse(t.updatedAt)-Date.parse(e.updatedAt))}reconcileAppSessionBindings(e=[],s=Date.now()){const n=new Set(e.filter(e=>"string"!=typeof e.status||"running"===e.status).map(e=>"string"==typeof e.id?e.id.trim():"").filter(Boolean));let r=0,i=0;for(const e of this.readSessions()){if(!e.appSessionId){this.orphanedAppSessionAt.delete(e.id);continue}if(n.has(e.appSessionId)){this.orphanedAppSessionAt.delete(e.id);continue}const o=this.orphanedAppSessionAt.get(e.id)??s;this.orphanedAppSessionAt.set(e.id,o),r+=1,s-o>=this.orphanedAppSessionRetentionMs&&(t.rmSync(this.sessionPath(e.id),{force:!0}),this.orphanedAppSessionAt.delete(e.id),i+=1,this.emitChange("delete"))}return{hidden:r,deleted:i}}reconcileAdapterSessions(e){const s=e.appSessionIds||new Set,n=e.providerSessionIds||new Set,r=e.providerShorts||new Set;let i=0;for(const o of this.readSessions()){if(o.agent!==e.agent)continue;if(!o.appSessionId&&!o.providerSessionId&&!o.providerMeta?.short)continue;if(o.appSessionId&&s.has(o.appSessionId)){this.orphanedAppSessionAt.delete(o.id);continue}if(o.providerSessionId&&n.has(o.providerSessionId)){this.orphanedAppSessionAt.delete(o.id);continue}const a="string"==typeof o.providerMeta?.short?o.providerMeta.short:"";a&&r.has(a)?this.orphanedAppSessionAt.delete(o.id):(t.rmSync(this.sessionPath(o.id),{force:!0}),this.orphanedAppSessionAt.delete(o.id),i+=1,this.emitChange("delete"))}return{deleted:i}}snapshot(e=20){const t=this.list().slice(0,e);return this.snapshotFromSessions(t)}boundSnapshot(e=[],t=20){const s=new Set(e.filter(e=>"string"!=typeof e.status||"running"===e.status).map(e=>"string"==typeof e.id?e.id.trim():"").filter(Boolean)),n=this.list().filter(e=>Boolean(e.appSessionId&&s.has(e.appSessionId))).slice(0,t);return this.snapshotFromSessions(n)}snapshotFromSessions(e){return{runningCount:e.filter(e=>"running"===e.status).length,waitingCount:e.filter(e=>"waiting"===e.status).length,staleCount:0,sessions:e.map(yn),updatedAt:tn()}}prune(){const e=new Set(this.canonicalSessions(this.readSessions()).map(e=>e.id));for(const s of this.readSessions())e.has(s.id)||(t.rmSync(this.sessionPath(s.id),{force:!0}),this.emitChange("delete"));const s=Date.now()-this.retentionMs;for(const e of this.readSessions())["idle","failed"].includes(e.status)&&Date.parse(e.updatedAt)<s&&t.rm(this.sessionPath(e.id),{force:!0},()=>this.emitChange("delete"))}ingestTranscriptLine(e,t,s){const n=rs(t,s);if(!n?.text)return this.get(e);const r=n.timestamp||tn();if("user"===n.kind){const t=Hs(n.text),i=n.key||n.timestamp;if(i)s.activeTurnId=Ks(t,i);else{s.promptCounts||=new Map;const e=(s.promptCounts.get(t)||0)+1;s.promptCounts.set(t,e),s.activeTurnId=Ks(t,void 0,e)}return this.applyRealtimeEvent(e,{kind:"user-message",activeTurnId:s.activeTurnId,providerTurnId:s.activeTurnId,userPrompt:t,observedAt:r,source:"transcript-tail"})}if("assistant"===n.kind)return this.applyRealtimeEvent(e,{kind:"assistant-message",activeTurnId:s.activeTurnId,providerTurnId:s.activeTurnId,text:n.text,observedAt:r,source:"transcript-tail"});const i=Sn(n.text,n.kind);return this.applyRealtimeEvent(e,{kind:"waiting"===i.status?"approval-requested":"assistant-message",activeTurnId:s.activeTurnId,providerTurnId:s.activeTurnId,text:i.summary||n.text,status:i.status,phase:i.phase,counters:i.counters,observedAt:r,source:"transcript-tail"})}createFromTranscript(e,s,n={}){const r=t.statSync(s),i=r.mtime.toISOString(),o=function(e,s=t.statSync(e)){const n={calls:new Map},r={};let i;const o=new Map;for(const a of function(e,s=t.statSync(e)){const n=Math.max(0,s.size-524288),r=t.openSync(e,"r");try{const e=Buffer.alloc(s.size-n);return t.readSync(r,e,0,e.length,n),e.toString("utf8")}finally{t.closeSync(r)}}(e,s).split(/\r?\n/)){const e=rs(a,n);if(!e?.text)continue;const t=e.timestamp||s.mtime.toISOString();if("user"===e.kind){const s=Hs(e.text);r.userPrompt=s;const n=e.key||e.timestamp;if(n)i=Ks(s,n);else{const e=(o.get(s)||0)+1;o.set(s,e),i=Ks(s,void 0,e)}r.turns=en(r.turns,{activeTurnId:i,userPrompt:s},t);continue}r.summary=Ls(e.text,1e3),r.lastMessage=Hs(e.text),r.turns=en(r.turns,{activeTurnId:i,summary:r.summary,lastMessage:r.lastMessage},t)}return r}(s,r),a=this.readSessions().find(e=>e.transcriptPath===s||n.providerSessionId&&e.providerSessionId===n.providerSessionId);if(a){const t=!a.appSessionId&&!a.conversationId,p=Number.isInteger(a.transcriptSize)&&r.size>Number(a.transcriptSize),u=t&&p?tn():t&&!p?a.updatedAt:(d=a.updatedAt,c=i,Date.parse(d)>=Date.parse(c)?d:c);return this.applyAdapterSnapshot({source:"transcript-scan",agent:e,transcriptPath:s,transcriptSize:r.size,providerSessionId:n.providerSessionId||a.providerSessionId,cwd:n.cwd||a.cwd,userPrompt:a.userPrompt||o.userPrompt,turns:o.turns?.length?o.turns:a.turns,summary:o.summary||a.summary,lastMessage:o.lastMessage||a.lastMessage,status:t&&p?"running":a.status,phase:t&&p&&"unknown"===a.phase?"responding":a.phase,observedAt:u,replaceActivity:Boolean(o.turns?.length)})||a}var d,c;const p=this.start({agent:e,providerSessionId:n.providerSessionId,cwd:n.cwd,userPrompt:o.userPrompt,turns:o.turns,status:this.lifecycleForTranscriptMtime(r.mtimeMs),phase:"unknown",summary:o.summary||`${e} transcript detected`},{meta:qs({source:"transcript-scan",observedAt:i}),timestamp:i,suppressPromptTurn:!o.turns?.length});return this.applyAdapterSnapshot({source:"transcript-scan",agent:p.agent,providerSessionId:p.providerSessionId,cwd:p.cwd,userPrompt:p.userPrompt,turns:p.turns,summary:p.summary,lastMessage:o.lastMessage,transcriptPath:s,transcriptSize:r.size,status:p.status,phase:p.phase,observedAt:i})||p}emitChange(e){this.changes.emit("change",e)}reconcileActiveProcesses(e){const t=new Set;for(const s of e){const e=this.list().find(e=>e.agent===s.agent&&(s.providerSessionId&&e.providerSessionId===s.providerSessionId||s.transcriptPath&&e.transcriptPath===s.transcriptPath));e&&(t.add(e.id),this.applyAdapterSnapshot({source:"process-scan",agent:e.agent,appId:e.appId,appSessionId:e.appSessionId,providerSessionId:s.providerSessionId||e.providerSessionId,cwd:s.cwd||e.cwd,title:e.title,userPrompt:e.userPrompt,turns:e.turns,summary:e.summary,lastMessage:e.lastMessage,status:"running",phase:"unknown"===e.phase?"thinking":e.phase,transcriptPath:s.transcriptPath||e.transcriptPath}))}return t}withDerivedLifecycle(e,t=Date.now()){if(["idle","failed","waiting"].includes(e.status))return e;const s=t-Date.parse(e.updatedAt);return s>this.staleAfterMs&&e.transcriptPath&&!e.conversationId||s>this.idleAfterMs&&"running"===e.status?{...e,status:"idle"}:e}lifecycleForTranscriptMtime(e){const t=Date.now()-e;return t>this.staleAfterMs||t>this.idleAfterMs?"idle":"running"}}function _n(e={}){return new bn(e)}function wn(e){const t=String(e||"").trim().toLowerCase();return t&&"idle"!==t?"stopped"===t||"exited"===t||"failed"===t?"failed"===t?"failed":"idle":["active","busy","running","thinking","working"].includes(t)?"running":"idle":"idle"}class Tn{providers=new Map;register(e){this.providers.set(e.id,e)}async refresh(e){for(const t of this.providers.values())await t.refresh(e)}}class Nn{id="claude-app-session-binding";refresh(e){!function(e=_n(),r=[],i=process.env.CLAUDE_HOME||s.join(n.homedir(),".claude")){const o=function(e){const r=function(e=process.env.CLAUDE_HOME||s.join(n.homedir(),".claude")){return s.join(e,"sessions")}(e);let i=[];try{i=t.readdirSync(r,{withFileTypes:!0})}catch{return new Map}const o=new Map;for(const e of i){if(!e.isFile()||!e.name.endsWith(".json"))continue;const t=nn(s.join(r,e.name)),n=Number(t?.pid||s.basename(e.name,".json"));t?.sessionId&&Number.isInteger(n)&&n>0&&o.set(n,t)}return o}(i);for(const t of r){const s=Ls(t.appId,120),n=Ls(t.id,120),r=Ls(t.status,80).toLowerCase(),a=Number(t.process?.pid);if("claude"!==s||!n||r&&"running"!==r||!Number.isInteger(a)||a<=0)continue;const d=o.get(a),c=Ls(d?.sessionId,240);if(!c)continue;const p=Ls(d?.cwd||t.tty?.cwd||t.launch?.cwd,4096);e.applyAdapterSnapshot({agent:"claude",appId:s,appSessionId:n,providerSessionId:c,title:Ls(t.title,240)||"Claude",cwd:p,transcriptPath:ns(c,p,i),status:wn(d?.status)})}e.snapshot()}(e.registry,e.appSessions)}}class zn{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 On=process.env.TASK_HANDOFF_RECEIVER_LOG||(process.env.TASK_HANDOFF_LOG_DIR?`${process.env.TASK_HANDOFF_LOG_DIR}/receiver.log`:void 0)||(En=S,xn="receiver.log",process.env.CODEX_SANDBOX?s.join(process.cwd(),".task-handoff",xn):s.join(s.dirname(En),xn));var En,xn;class kn{registry;client;id="claude-control-sock";agent="claude";subscriptions=new Map;textByShort=new Map;constructor(e,t={list:()=>ot({op:"list"},{timeoutMs:Number(process.env.TASK_HANDOFF_CLAUDE_CONTROL_TIMEOUT_MS)||5e3}),reply:at,kill:dt,subscribe:ct}){this.registry=e,this.client=t}async refresh(e){if(!Ln("TASK_HANDOFF_AI_SESSION_SCAN",!0)||!Ln("TASK_HANDOFF_CLAUDE_CONTROL_SCAN",!0))return;const t=await this.client.list(),s=t.ok&&Array.isArray(t.jobs)?t.jobs:[],n=e.appSessions.filter(Un),r=new Map;for(const e of n){const t=Fn(e.ai?.claude?.short,80);t&&r.set(t,e)}for(const e of n){const t=Fn(e.ai?.claude?.short,80);if(!t)continue;const n=s.find(e=>e.short===t);this.upsertJob(n||Hn(e)||{short:t},e)}for(const e of s)e.short&&!r.has(e.short)&&this.upsertJob(e);this.reconcileSubscriptions(new Set([...s.map(e=>Fn(e.short,80)).filter(Boolean),...Array.from(r.keys())])),e.registry.reconcileAdapterSessions({agent:this.agent,appSessionIds:new Set(n.map(e=>Fn(e.id,120)).filter(Boolean)),providerSessionIds:new Set(s.map(e=>Fn(e.sessionId,240)).filter(Boolean)),providerShorts:new Set([...s.map(e=>Fn(e.short,80)).filter(Boolean),...Array.from(r.keys())])})}async sendMessage(e,t){return this.startMessage(e,t)}async startMessage(e,t){const s=this.requireShort(e),n=await Mt(t.message,t.attachments,t=>this.client.reply(s,t.endsWith("\n")?t:`${t}\n`,{sockPath:this.controlSockForSession(e),timeoutMs:Number(process.env.TASK_HANDOFF_CLAUDE_CONTROL_TIMEOUT_MS)||5e3}));if(!n.ok)throw $t("AI_SESSION_SEND_FAILED",n.error||`Claude reply failed: ${n.code||"unknown"}`);const r=this.registry.applyRealtimeEvent(e.id,{kind:"send-ack",userPrompt:t.message,source:"control"})||e;return{session:r,provider:this.agent,action:"send",turnId:r.activeTurnId}}async steerMessage(e,t){return{...await this.startMessage(e,t),action:"steer"}}async interrupt(e){const t=this.requireShort(e),s=await this.client.kill(t,"SIGTERM",{sockPath:this.controlSockForSession(e),timeoutMs:Number(process.env.TASK_HANDOFF_CLAUDE_CONTROL_TIMEOUT_MS)||5e3});if(!s.ok)throw $t("AI_SESSION_INTERRUPT_FAILED",s.error||`Claude interrupt failed: ${s.code||"unknown"}`);return{session:this.registry.applyRealtimeEvent(e.id,{kind:"lifecycle",status:"running",phase:"unknown",source:"control"})||e,provider:this.agent,action:"interrupt"}}async resolveApproval(e,t){throw $t("AI_SESSION_APPROVAL_UNSUPPORTED","Claude daemon sessions do not expose structured approval control.",400)}stop(){for(const e of this.subscriptions.values())e();this.subscriptions.clear(),this.textByShort.clear()}upsertJob(e,t){const s=Fn(e.short,80);if(!s)return;const n=Fn(e.sessionId||t?.ai?.claude?.providerSessionId,240),r=Fn(e.cwd||t?.ai?.claude?.cwd||t?.tty?.cwd||t?.launch?.cwd,4096),i=this.sessionForShort(s),o=Dn(e.state||t?.ai?.claude?.state,{hasWorkSignal:Pn(e),isAppSession:Boolean(t||i?.appSessionId)}),a=Fn(t?.ai?.claude?.controlSock,4096)||it();this.registry.applyAdapterSnapshot({source:"adapter-snapshot",agent:"claude",appId:Fn(t?.appId,120)||(t?"claude":"claude-daemon"),appSessionId:Fn(t?.id,120),providerSessionId:n,appBindingKeys:$n(t,s),actions:Cn(o),providerMeta:{short:s,controlSock:a,pid:Number(e.pid||t?.ai?.claude?.pid)||void 0,state:Fn(e.state||t?.ai?.claude?.state,80),tempo:Fn(e.tempo||t?.ai?.claude?.tempo,80),cliVersion:Fn(e.cliVersion||t?.ai?.claude?.cliVersion,80),source:Fn(e.source||t?.ai?.claude?.source,80)},title:Fn(t?.title,240)||"Claude",cwd:r,transcriptPath:ns(n,r),status:o.status,phase:o.phase})&&this.ensureSubscription(s,a)}reconcileSubscriptions(e){for(const[t,s]of this.subscriptions)e.has(t)||(s(),this.subscriptions.delete(t),this.textByShort.delete(t))}ensureSubscription(e,t){if(this.subscriptions.has(e))return;this.subscriptions.set(e,()=>{});const s=this.client.subscribe(e,{tail:Number(process.env.TASK_HANDOFF_CLAUDE_SUBSCRIBE_TAIL_BYTES)||4096,options:{sockPath:t},onMessage:s=>this.applySubscribeMessage(e,t,s)});this.subscriptions.set(e,s)}applySubscribeMessage(e,t,s){const n=Rn(s.record);n&&this.upsertJob(n);const r=this.textFromSubscribeMessage(e,s);if(r){const t=this.sessionForShort(e);t&&this.registry.applyRealtimeEvent(t.id,{kind:"assistant-message",text:r,source:"realtime"})}const i=this.stateFromSubscribeMessage(s,n);if(i.observedState){const r=this.sessionForShort(e),o=i.lifecycleState?Dn(i.lifecycleState,{hasWorkSignal:!1,isAppSession:Boolean(r?.appSessionId)}):void 0;this.logSubscribeMessage(e,t,s,n,i,r,o),r&&this.registry.applyAdapterSnapshot({source:"adapter-snapshot",agent:r.agent,appId:r.appId,appSessionId:r.appSessionId,providerSessionId:r.providerSessionId,appBindingKeys:r.appBindingKeys,actions:Cn(o),providerMeta:{...r.providerMeta||{},short:e,controlSock:t,state:i.observedState,stateSource:i.source},status:o?.status,phase:o?.phase,cwd:r.cwd,title:r.title})}else this.logSubscribeMessage(e,t,s,n,i,this.sessionForShort(e))}sessionForShort(e){return this.registry.list().find(t=>"claude"===t.agent&&t.providerMeta?.short===e)}stateFromSubscribeMessage(e,t){const s=Rn(e.patch),n="settled"===Fn(e.type,80)?e.outcome:void 0,r=[{source:"message.state",value:e.state},{source:"patch.state",value:s?.state},{source:"record.state",value:t?.state},{source:"settled.outcome",value:n}].find(e=>Fn(e.value,80));return{observedState:Fn(r?.value,80),lifecycleState:Fn(n,80),source:r?.source,patch:s}}logSubscribeMessage(e,t,s,n,r,i,o){if(Ln("TASK_HANDOFF_DIAGNOSTIC_LOGS"))try{oe(On,{event:"claude_control_subscribe",short:e,controlSock:t,messageType:Fn(s.type,80)||void 0,state:r.observedState||void 0,lifecycleState:r.lifecycleState||void 0,stateSource:r.source,recordState:Fn(n?.state,80)||void 0,patchKeys:r.patch?Object.keys(r.patch).sort():void 0,outcome:Fn(s.outcome,80)||void 0,streamLineBytes:"string"==typeof s.line?Buffer.byteLength(s.line):void 0,streamTailCount:Mn(s.streamTail).length||void 0,aiSessionId:i?.id,appSessionId:i?.appSessionId,providerSessionId:i?.providerSessionId,mappedStatus:o?.status,mappedPhase:o?.phase})}catch{}}textFromSubscribeMessage(e,t){const s=[...Mn(t.streamTail).map(e=>String(e||"")),...Mn(t.output).map(e=>String(e||"")),jn(t.data),jn(t.text),jn(t.delta),jn(t.raw)].filter(Boolean);if(0===s.length)return"";const n=(r=s.join("\n"),String(r).replace(/\x1B\][^\x07]*(?:\x07|\x1B\\)?/g,"").replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,"").replace(/\x1B[\x30-\x7E]/g,"").replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g,"")).replace(/\u0007/g,"").split(/\r?\n/).map(e=>e.trim()).filter(Boolean).filter(e=>!function(e){const t=e.replace(/[─━═_\-]{3,}/g,"").replace(/[⏺●•·]/g,"").replace(/\s+/g," ").trim();return!t||[/^claude code\b/i,/\bapi usage billing\b/i,/\/effort\b/i,/\bauto mode on\b/i,/\bshift\+tab to cycle\b/i,/\bfor agents\b/i,/^log an error\??"?$/i,/^~\/\S+/,/^\S+\s+·\s+\S+.*\b\/project\/work\b/i,/^\S+\s+·\s+\/?(?:workspace|project|Users|home)\b/i,/^(?:high|medium|low)\s*·\s*\/?effort\b/i,/^[›>]\s*try\s+["'`]/i,/^try\s+["'`]/i].some(e=>e.test(t))}(e)).slice(-8).join("\n").trim();var r;return n&&this.textByShort.get(e)!==n?(this.textByShort.set(e,n),n):""}requireShort(e){const t="string"==typeof e.providerMeta?.short?e.providerMeta.short:void 0;if(!t)throw $t("AI_SESSION_CLAUDE_SHORT_NOT_FOUND","Claude session is not bound to a daemon worker.");return t}controlSockForSession(e){return"string"==typeof e.providerMeta?.controlSock?e.providerMeta.controlSock:void 0}}function Dn(e,t={}){const s=String(e||"").trim().toLowerCase();return s&&"idle"!==s?"blocked"===s?{status:"idle",phase:"unknown"}:"waiting"===s?{status:"waiting",phase:"unknown"}:"failed"===s?{status:"failed",phase:"unknown"}:["stopped","exited","completed","done"].includes(s)?{status:"idle",phase:"unknown"}:["active","busy","running","thinking","working"].includes(s)?t.isAppSession&&!t.hasWorkSignal?{status:"idle",phase:"unknown"}:{status:"running",phase:"thinking"}:{status:"idle",phase:"unknown"}:{status:"idle",phase:"unknown"}}function Cn(e){return{send:!0,interrupt:"running"===e?.status||"waiting"===e?.status,approval:!1}}function Pn(e){return Boolean(Fn(e.detail,500)||Fn(e.intent,500)||Fn(e.needs,500))}function Fn(e,t=500){const s=String(e??"").replace(/\s+/g," ").trim();return s.length>t?`${s.slice(0,t-3)}...`:s}function Rn(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:void 0}function Mn(e){return Array.isArray(e)?e:[]}function jn(e){return"string"==typeof e?e:""}function Ln(e,t=!1){const s=process.env[e];return void 0===s||""===s?t:!["0","false","no","off"].includes(String(s).toLowerCase())}function Hn(e){const t=e.ai?.claude,s=Fn(t?.short,80);if(s)return{short:s,sessionId:Fn(t?.providerSessionId,240)||void 0,pid:Number(t?.pid)||void 0,cwd:Fn(t?.cwd||e.tty?.cwd||e.launch?.cwd,4096)||void 0,state:Fn(t?.state,80)||void 0,tempo:Fn(t?.tempo,80)||void 0,cliVersion:Fn(t?.cliVersion,80)||void 0,source:Fn(t?.source,80)||void 0}}function $n(e,t){const s=[e?.id?`app:${Fn(e.id,120)}`:"",t?`claude-short:${t}`:""].filter(Boolean);return s.length?s:void 0}function Un(e){const t=Fn(e.status,80).toLowerCase();return!t||"running"===t}function qn(e){return"allow"===e?"allowed":"deny"===e?"denied":"skipped"}function Vn(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}function Bn(e){const t=e.turn&&"object"==typeof e.turn?e.turn:void 0;return"string"==typeof t?.id?t.id:void 0}function Kn(e){return e instanceof Error&&/no active turn/i.test(e.message)}function Gn(e){if(e instanceof Error)return e.message.match(/expected active turn id `[^`]+` but found `([^`]+)`/i)?.[1]}function Wn(e){const t=String(e.type||""),s=Array.isArray(e.activeFlags)?e.activeFlags.map(String):[];return"active"===t&&s.includes("waitingOnApproval")?{status:"waiting",phase:"approval"}:"active"===t&&s.includes("waitingOnUserInput")?{status:"waiting",phase:"thinking"}:"active"===t?{status:"running",phase:"thinking"}:"systemError"===t?{status:"failed",phase:"unknown"}:{status:"idle",phase:"unknown"}}function Xn(e,t){const s=e[t];return"string"==typeof s&&s.trim()?s:void 0}function Jn(e){const t=Vn(e);return"text"===t.type&&"string"==typeof t.text?t.text.trim():""}function Yn(e){return(Array.isArray(e.content)?e.content:[]).map(Jn).filter(Boolean).join("\n").trim()}class Qn extends g.EventEmitter{child;proxyChild;socket;buffer="";nextId=1;pending=new Map;mode;requestTimeoutMs;constructor(e={}){super(),this.mode=e.socketPath?{type:"unix",command:e.command||process.env.TASK_HANDOFF_CODEX_APP_SERVER_COMMAND||process.env.TASK_HANDOFF_CODEX_COMMAND||"codex",socketPath:e.socketPath}:{type:"stdio",command:e.command||process.env.TASK_HANDOFF_CODEX_APP_SERVER_COMMAND||process.env.TASK_HANDOFF_CODEX_COMMAND||"codex"},this.requestTimeoutMs=e.requestTimeoutMs||Number(process.env.TASK_HANDOFF_CODEX_APP_SERVER_TIMEOUT_MS)||5e3}get connected(){return Boolean(this.child&&!this.child.killed||this.proxyChild&&!this.proxyChild.killed||this.socket?.readyState===y.OPEN)}async start(){if(this.connected)return;if("unix"===this.mode.type)return void await this.startUnixSocket(this.mode.command,this.mode.socketPath);const e=h.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:Bn(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=Vn(e.params.permissions),n=Vn(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=h.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 d.Duplex({read(){e.stdout.resume()},write(t,s,n){e.stdin.write(t,n)},final(t){e.stdin.end(t)},destroy(t,s){e.killed||e.kill("SIGTERM"),s(t)}});e.stdout.on("data",s=>{t.push(s)||e.stdout.pause()}),e.stdout.on("end",()=>t.push(null)),e.stdout.on("error",e=>t.destroy(e)),e.stdin.on("error",e=>t.destroy(e));const s=t;return s.setTimeout=()=>t,s.setNoDelay=()=>t,s.setKeepAlive=()=>t,s}(r),perMessageDeflate:!1});this.socket=i;let o=!1;const a=e=>{o||(o=!0,this.socket=void 0,this.proxyChild=void 0,r.killed||r.kill("SIGTERM"),n(e))};r.once("error",a),r.once("exit",(e,t)=>{o?this.proxyChild===r&&(this.proxyChild=void 0,this.emit("disconnect")):a(new Error(`Codex app-server proxy exited before connect: code=${e??"null"} signal=${t??"null"}.`))}),i.once("error",a),i.once("open",()=>{o=!0,r.off("error",a),i.off("error",a),i.on("message",e=>this.handleLine(e.toString())),i.once("close",()=>{this.socket=void 0,this.proxyChild===r&&(this.proxyChild=void 0),r.killed||r.kill("SIGTERM");for(const[e,t]of this.pending)clearTimeout(t.timer),t.reject(new Error("Codex app-server disconnected.")),this.pending.delete(e);this.emit("disconnect")}),this.initialize().then(()=>s()).catch(e=>{i.close(),n(e)})})})}onData(e){this.buffer+=e.toString("utf8");let t=this.buffer.indexOf("\n");for(;t>=0;){const e=this.buffer.slice(0,t).trim();this.buffer=this.buffer.slice(t+1),e&&this.handleLine(e),t=this.buffer.indexOf("\n")}this.buffer.length>8388608&&(this.buffer="")}handleLine(e){let t;try{t=JSON.parse(e)}catch{return}const s=Number(t.id);if(Number.isInteger(s)){const e=this.pending.get(s);if(e){clearTimeout(e.timer),this.pending.delete(s);const n=t.error&&"object"==typeof t.error?t.error:void 0;return void(n?e.reject(new Error(String(n.message||"Codex app-server error."))):e.resolve(t.result&&"object"==typeof t.result?t.result:{}))}}const n=String(t.method||""),r=t.params&&"object"==typeof t.params?t.params:{};if(Number.isInteger(s)){const e=function(e,t,s){if("item/commandExecution/requestApproval"===t){const n=Xn(s,"threadId");if(!n)return;const r=Xn(s,"command"),i=Xn(s,"reason");return{id:e,method:t,kind:"command",threadId:n,turnId:Xn(s,"turnId"),itemId:Xn(s,"itemId"),summary:i||(r?`Approve command: ${r}`:"Codex is requesting command approval."),params:s}}if("item/fileChange/requestApproval"===t){const n=Xn(s,"threadId");if(!n)return;const r=Xn(s,"grantRoot");return{id:e,method:t,kind:"file-change",threadId:n,turnId:Xn(s,"turnId"),itemId:Xn(s,"itemId"),summary:Xn(s,"reason")||(r?`Approve file changes under ${r}`:"Codex is requesting file change approval."),params:s}}if("item/permissions/requestApproval"===t){const n=Xn(s,"threadId");if(!n)return;return{id:e,method:t,kind:"permissions",threadId:n,turnId:Xn(s,"turnId"),itemId:Xn(s,"itemId"),summary:Xn(s,"reason")||"Codex is requesting additional permissions.",params:s}}}(s,n,r);return void(e&&this.emit("event",{type:"approval-request",request:e}))}const i=function(e,t){if("thread/started"===e){const e=t.thread&&"object"==typeof t.thread?t.thread:void 0;return e?{type:"thread",thread:e}:void 0}if("thread/status/changed"===e&&"string"==typeof t.threadId)return{type:"thread-status",threadId:t.threadId,status:t.status||{}};if("thread/closed"===e&&"string"==typeof t.threadId)return{type:"thread-closed",threadId:t.threadId};if("turn/started"===e&&"string"==typeof t.threadId){const e=t.turn&&"object"==typeof t.turn?t.turn:{};return{type:"turn-started",threadId:t.threadId,turnId:"string"==typeof e.id?e.id:void 0}}if("turn/completed"===e&&"string"==typeof t.threadId){const e=t.turn&&"object"==typeof t.turn?t.turn:{},s=function(e){const t=Vn(e),s="string"==typeof t.message?t.message.trim():"",n="string"==typeof t.additionalDetails?t.additionalDetails.trim():"";return s&&n?`${s}\n\n${n}`:s||n||void 0}(e.error);return{type:"turn-completed",threadId:t.threadId,turnId:"string"==typeof e.id?e.id:void 0,status:"string"==typeof e.status?e.status:void 0,error:s}}if(("item/started"===e||"item/completed"===e)&&"string"==typeof t.threadId){const e=t.item&&"object"==typeof t.item?t.item:{};if("userMessage"===e.type){const s=Yn(e);return s?{type:"user-message",threadId:t.threadId,turnId:"string"==typeof t.turnId?t.turnId:void 0,text:s}:void 0}}if("item/agentMessage/delta"===e&&"string"==typeof t.threadId&&"string"==typeof t.delta)return{type:"agent-message-delta",threadId:t.threadId,turnId:"string"==typeof t.turnId?t.turnId:void 0,itemId:"string"==typeof t.itemId?t.itemId:void 0,delta:t.delta};if("item/completed"===e&&"string"==typeof t.threadId){const e=t.item&&"object"==typeof t.item?t.item:{};if("agentMessage"===e.type&&"string"==typeof e.text)return{type:"agent-message-completed",threadId:t.threadId,turnId:"string"==typeof t.turnId?t.turnId:void 0,text:e.text}}}(n,r);i&&this.emit("event",i)}}class Zn{registry;id="codex-app-server";agent="codex";client;started=!1;retryAfter=0;activeSocketPath;appSessions=[];agentMessageBuffers=new Map;approvals=new jt;injectedClient;options;constructor(e,t={}){this.registry=e,"start"in t&&"listLoadedThreadIds"in t?(this.injectedClient=t,this.options={allowSpawn:!0},this.attachClient(this.injectedClient)):this.options=t}async sync(e=[]){const t=this.setAppSessions(e),s=this.activeSocketPath;if(!this.injectedClient&&!t&&!this.options.allowSpawn)return void this.stop();this.injectedClient||this.client&&s===t||(this.stop(),this.client=this.createClient(t?{socketPath:t}:{}),this.attachClient(this.client)),this.activeSocketPath=t;const n=this.client;if(n){if(!this.started){if(Date.now()<this.retryAfter)return;try{await n.start(),this.started=!0}catch{return void(this.retryAfter=Date.now()+3e4)}}try{const e=await n.listLoadedThreadIds(),t=new Map;if(n.listThreads)for(const e of await n.listThreads()){const s="string"==typeof e.id?e.id:void 0;s&&t.set(s,e)}for(const s of e){let e=t.get(s);if(n.readThread)try{e={...e||{},...await n.readThread(s,{includeTurns:!0})}}catch{e||={id:s}}this.upsertThread(e||{id:s},{bindAppSession:!0})}}catch{this.started=!1,n.stop()}}}async refresh(e){await this.sync(e.appSessions)}stop(){this.client?.stop(),this.injectedClient||(this.client=void 0),this.started=!1,this.activeSocketPath=void 0,this.agentMessageBuffers.clear(),this.retryAfter=0}async sendMessage(e,t){const s=await this.requireReadyClient(),n=this.requireThreadId(e),r=await Mt(t.message,t.attachments,t=>this.steerOrStartTurnForCompatibility(s,n,e,t)),i=this.registry.applyRealtimeEvent(e.id,{kind:r.started?"send-ack":"user-message",activeTurnId:r.turnId,providerTurnId:r.turnId,userPrompt:t.message,source:"control"})||e;return{session:i,provider:this.agent,action:r.started?"send":"steer",turnId:i.activeTurnId,providerTurnId:r.turnId}}async startMessage(e,t){const s=await this.requireReadyClient(),n=this.requireThreadId(e),r=await Mt(t.message,t.attachments,e=>this.startTurn(s,n,e)),i=this.registry.applyRealtimeEvent(e.id,{kind:"send-ack",activeTurnId:r.turnId,providerTurnId:r.turnId,userPrompt:t.message,source:"control"})||e;return{session:i,provider:this.agent,action:"send",turnId:i.activeTurnId,providerTurnId:r.turnId}}async steerMessage(e,t){const s=await this.requireReadyClient(),n=this.requireThreadId(e),r=await Mt(t.message,t.attachments,t=>this.steerTurn(s,n,e,t)),i=this.registry.applyRealtimeEvent(e.id,{kind:"user-message",activeTurnId:r.turnId,providerTurnId:r.turnId,userPrompt:t.message,source:"control"})||e;return{session:i,provider:this.agent,action:"steer",turnId:i.activeTurnId,providerTurnId:r.turnId}}async steerTurn(e,t,s,n){if(!s.activeTurnId)throw $t("AI_SESSION_NO_ACTIVE_TURN","AI session has no active turn to steer.",409);if(!e.steerTurn)throw $t("AI_SESSION_STEER_UNSUPPORTED","Codex app-server client does not support turn steering.");try{return{turnId:(await e.steerTurn(t,s.activeTurnId,n)).turnId||s.activeTurnId}}catch(s){const r=Gn(s);if(r)return{turnId:(await e.steerTurn(t,r,n)).turnId||r};throw s}}async steerOrStartTurnForCompatibility(e,t,s,n){if(!Boolean(s.activeTurnId&&("running"===s.status||"waiting"===s.status)))return this.startTurn(e,t,n);try{return{...await this.steerTurn(e,t,s,n),started:!1}}catch(s){if(!Kn(s))throw s;return this.startTurn(e,t,n)}}async startTurn(e,t,s){if(!e.startTurn)throw $t("AI_SESSION_SEND_UNSUPPORTED","Codex app-server client does not support starting turns.");return{turnId:(await e.startTurn(t,s)).turnId,started:!0}}async interrupt(e){const t=await this.requireReadyClient(),s=this.requireThreadId(e),n=e.activeTurnId;if(!n)throw $t("AI_SESSION_NO_ACTIVE_TURN","AI session has no active turn to interrupt.");if(!t.interruptTurn)throw $t("AI_SESSION_INTERRUPT_UNSUPPORTED","Codex app-server client does not support turn interruption.");try{await t.interruptTurn(s,n)}catch(r){const i=Gn(r);if(i)return await t.interruptTurn(s,i),{session:this.registry.applyRealtimeEvent(e.id,{kind:"lifecycle",activeTurnId:i,status:"running",phase:"unknown",source:"control"})||e,provider:this.agent,action:"interrupt",providerTurnId:i};if(!Kn(r))throw r;return{session:this.registry.applyRealtimeEvent(e.id,{kind:"turn-completed",activeTurnId:void 0,status:"idle",phase:"unknown",text:"Codex turn is no longer active.",source:"control"})||e,provider:this.agent,action:"interrupt",providerTurnId:n}}return{session:this.registry.applyRealtimeEvent(e.id,{kind:"lifecycle",status:"running",phase:"unknown",source:"control"})||e,provider:this.agent,action:"interrupt",providerTurnId:n}}async resolveApproval(e,t){if(await this.resolveAttachedApproval(e,t))return{session:this.registry.applyRealtimeEvent(e.id,{kind:"assistant-message",status:"skip"===t?"idle":"running",phase:"skip"===t?"unknown":"thinking",text:`Codex approval ${qn(t)}.`,source:"control"})||e,provider:this.agent,action:"approval",decision:t};throw $t("AI_SESSION_APPROVAL_NOT_ATTACHED","Codex approval request is not attached to this control connection. The app-server did not replay a pending approval request for this session.",409)}async resolveAttachedApproval(e,t){return await this.approvals.resolveForSession(e.id,t)||(await this.attachPendingApprovalRequest(e),this.approvals.resolveForSession(e.id,t))}async attachPendingApprovalRequest(e){const t=await this.requireReadyClient();if(!t.resumeThread||this.approvals.latestForSession(e.id))return;const s=this.requireThreadId(e),n=await t.resumeThread(s);n&&this.upsertThread(n,{bindAppSession:!0}),await async function(e){const t=Date.now()+1e3;for(;Date.now()<t;){if(e())return!0;await new Promise(e=>setTimeout(e,25))}return e()}(()=>Boolean(this.approvals.latestForSession(e.id)))}attachClient(e){e.on("event",e=>this.applyProviderEvent(e)),e.on("disconnect",()=>{this.started=!1,this.retryAfter=Date.now()+3e4}),this.client=e}createClient(e){return this.options.createClient?this.options.createClient(e):new Qn(e)}codexAppServerSocketPath(e){return e.map(e=>e.ai?.appServer?.socketPath).find(e=>"string"==typeof e&&e.trim().length>0)}setAppSessions(e){return this.appSessions=e,this.codexAppServerSocketPath(e)}appSessionIdForThread(e){if(this.activeSocketPath)for(const t of this.appSessions)if("string"==typeof t.id&&"codex"===t.appId&&t.ai?.appServer?.socketPath===this.activeSocketPath&&"running"===t.status){if(t.ai?.activeThreadId===e)return t.id;if(Array.isArray(t.ai?.threadIds)&&t.ai.threadIds.includes(e))return t.id}}applyProviderEvent(e){if("thread"===e.type)return void this.upsertThread(e.thread,{bindAppSession:!0});if("approval-request"===e.type)return void this.applyApprovalRequest(e.request);const t=this.registry.list().find(t=>"codex"===t.agent&&t.providerSessionId===e.threadId);if(t)if("thread-closed"!==e.type){if("thread-status"===e.type){const s=Wn(e.status);return void this.registry.applyRealtimeEvent(t.id,{kind:"lifecycle",activeTurnId:t.activeTurnId,status:s.status,phase:s.phase,source:"realtime"})}if("turn-started"!==e.type)if("user-message"!==e.type)if("turn-completed"!==e.type){if("agent-message-delta"===e.type){const s=`${e.threadId}:${e.turnId||""}:${e.itemId||""}`,n=`${this.agentMessageBuffers.get(s)||""}${e.delta}`;return this.agentMessageBuffers.set(s,n),void this.registry.applyRealtimeEvent(t.id,{kind:"assistant-message",activeTurnId:e.turnId||t.activeTurnId,providerTurnId:e.turnId||t.activeTurnId,text:n,source:"realtime"})}"agent-message-completed"===e.type&&this.registry.applyRealtimeEvent(t.id,{kind:"assistant-message",activeTurnId:e.turnId||t.activeTurnId,providerTurnId:e.turnId||t.activeTurnId,text:e.text,status:t.status,source:"realtime"})}else this.registry.applyRealtimeEvent(t.id,{kind:"turn-completed",activeTurnId:e.turnId,providerTurnId:e.turnId,status:"failed"===e.status?"failed":"idle",error:"failed"===e.status?e.error:void 0,source:"realtime"});else this.registry.applyRealtimeEvent(t.id,{kind:"user-message",activeTurnId:e.turnId||t.activeTurnId,providerTurnId:e.turnId||t.activeTurnId,userPrompt:e.text,source:"realtime"});else this.registry.applyRealtimeEvent(t.id,{kind:"turn-started",activeTurnId:e.turnId,providerTurnId:e.turnId,source:"realtime"})}else this.registry.applyRealtimeEvent(t.id,{kind:"turn-completed",activeTurnId:t.activeTurnId,status:"idle",phase:"unknown",text:"Codex thread closed.",source:"realtime"})}upsertThread(e,t){const s="string"==typeof e.id?e.id:void 0;if(!s||!0===e.ephemeral)return;const n=Wn(e.status||{}),r=t.bindAppSession?this.appSessionIdForThread(s):void 0,i=function(e){let t,s;const n=[],r=Array.isArray(e.turns)?e.turns:[];for(const[e,i]of r.entries()){const r=Vn(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=Vn(e);if("userMessage"===n.type){const e=Yn(n);e&&!Ut(e)&&(t=e,o.userPrompt=e)}else"agentMessage"===n.type&&"string"==typeof n.text&&n.text.trim()&&(s=n.text.trim(),o.lastMessage=s,o.summary=s.length>1e3?`${s.slice(0,997)}...`:s)}(o.userPrompt||o.lastMessage||o.summary)&&n.push(o)}return{userPrompt:t,turns:n,summary:s,lastMessage:s}}(e);this.registry.applyAdapterSnapshot({source:"adapter-snapshot",agent:"codex",appId:r?"codex":"codex-app-server",appSessionId:r,providerSessionId:s,appBindingKeys:r?[`app:${r}`]:void 0,actions:{send:!0,interrupt:"running"===n.status||"waiting"===n.status,approval:"waiting"===n.status&&"approval"===n.phase},title:"string"==typeof e.name?e.name:void 0,cwd:"string"==typeof e.cwd?e.cwd:void 0,userPrompt:i.userPrompt,turns:i.turns,summary:i.summary,lastMessage:i.lastMessage,status:n.status,phase:n.phase,replaceActivity:!0})}applyApprovalRequest(e){const t=this.registry.list().find(t=>"codex"===t.agent&&t.providerSessionId===e.threadId);if(!t)return;const s=this.client;s?.respondToApproval&&(this.approvals.register({id:`${e.threadId}:${e.id}`,sessionId:t.id,provider:this.agent,summary:e.summary,metadata:{kind:e.kind,requestId:e.id,itemId:e.itemId},resolve:t=>s.respondToApproval?.(e,t)}),this.registry.applyRealtimeEvent(t.id,{kind:"approval-requested",activeTurnId:e.turnId||t.activeTurnId,providerTurnId:e.turnId||t.activeTurnId,status:"waiting",phase:"approval",summary:e.summary,counters:{approvals:1},source:"realtime"}))}async requireReadyClient(){const e=this.client;if(!e)throw $t("AI_SESSION_CONTROL_NOT_CONNECTED","Codex app-server is not connected.",503);return this.started||(await e.start(),this.started=!0),e}requireThreadId(e){if(!e.providerSessionId)throw $t("AI_SESSION_THREAD_NOT_FOUND","AI session is not bound to a Codex thread.");return e.providerSessionId}}class er{registeredInstanceId="";timer;config;snapshotProvider;fetchImpl;constructor(e,t,s=fetch){this.config=e,this.snapshotProvider=t,this.fetchImpl=s}enabled(){return Boolean("controlled"===this.config.controlMode&&this.config.nodeAgentUrl&&this.config.registrationToken&&this.config.instanceId)}async start(){this.enabled()&&(await this.register(),this.timer=setInterval(()=>{this.heartbeat().catch(e=>{console.warn(`node agent heartbeat failed: ${e instanceof Error?e.message:String(e)}`)})},this.config.heartbeatIntervalMs))}stop(){this.timer&&(clearInterval(this.timer),this.timer=void 0)}async register(){const e=await this.snapshotProvider(),t=this.requiredInstanceId(),s=await this.request(`node-agent/instances/${encodeURIComponent(t)}/register`,{instanceId:this.config.instanceId,name:this.config.instanceName,projectId:this.config.projectId,nodeId:this.config.nodeId,runtimeId:this.config.runtimeId,imageId:this.config.imageId,instanceVersion:e.instanceVersion,protocolVersion:e.protocolVersion,build:e.build,controlMode:"controlled",capabilities:e.capabilities,target:e.target,workspace:e.workspace});this.registeredInstanceId=String(s.id||t),await this.heartbeat()}async heartbeat(){const e=this.registeredInstanceId||this.config.instanceId;if(!e)return;const t=await this.snapshotProvider();await this.request(`node-agent/instances/${encodeURIComponent(e)}/heartbeat`,{status:t.status,health:t.health,protocolVersion:t.protocolVersion,build:t.build,capabilities:t.capabilities,receiver:t.receiver,apps:t.apps,aiSessions:t.aiSessions,workspace:t.workspace,target:t.target})}async request(e,t){const s=this.config.nodeAgentUrl?.replace(/\/$/,"");if(!s)throw new Error("Node agent URL is required.");const n=await this.fetchImpl(`${s}/api/${e}`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${this.config.registrationToken}`},body:JSON.stringify((r=t,Object.fromEntries(Object.entries(r).filter(([,e])=>void 0!==e))))});var r;const i=await n.json().catch(()=>({}));if(!n.ok)throw new Error(i.error?.message||`Node agent request failed with HTTP ${n.status}`);return i.data||{}}requiredInstanceId(){if(!this.config.instanceId)throw new Error("Instance id is required for controlled mode registration.");return this.config.instanceId}}function tr(e,t){return e&&"object"==typeof e&&"code"in e?String(e.code):t}function sr(e){return e instanceof Error?e.message:String(e)}const nr=/^(telegram|wechat|dingding)\.([^.]+)\.json$/;function rr(e){return("string"==typeof e?e.trim():"")||void 0}function ir(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e))}function or(e){const t=e.secrets||{};return"telegram"===e.channel?ir({enabled:e.enabled,token:rr(t.botToken),allowedUserIds:e.allowedUserIds,defaultChatId:rr(e.defaultChatId)}):"wechat"===e.channel?ir({enabled:e.enabled,token:rr(t.token)||rr(t.webhookUrl),baseUrl:rr(t.baseUrl),contextToken:rr(t.contextToken),updatesBuf:rr(e.state?.updatesBuf),defaultChatId:rr(e.defaultChatId)}):ir({enabled:e.enabled,clientId:rr(t.clientId),clientSecret:rr(t.clientSecret),corpId:rr(t.corpId),robotCode:rr(t.robotCode),cardTemplateId:rr(t.cardTemplateId),cardCallbackRouteKey:rr(t.cardCallbackRouteKey),cardUserIdType:t.cardUserIdType,allowedUserIds:e.allowedUserIds,defaultChatId:rr(e.defaultChatId)})}function ar(e){try{const s=JSON.parse(t.readFileSync(e,"utf8"));return s&&"object"==typeof s&&!Array.isArray(s)?s:{}}catch{return{}}}function dr(e,n){const i=ar(n),o=i.chatTools&&"object"==typeof i.chatTools&&!Array.isArray(i.chatTools)?i.chatTools:{},a=i.chatBindings&&"object"==typeof i.chatBindings&&!Array.isArray(i.chatBindings)?i.chatBindings:{},d={...o,[e.channel]:{...o[e.channel]||{},[e.instanceId]:or(e)}},c=function(e){const t=rr(e.defaultChatId),s=e.bindings||{},n={};for(const[e,t]of Object.entries(s))n[e]=ir({conversationId:t.conversationId,contextToken:rr(t.contextToken)});return t&&!n[t]&&(n[t]={conversationId:1}),Object.keys(n).length>0?n:void 0}(e),p={...a,[e.channel]:{...a[e.channel]||{},...c?{[e.instanceId]:c}:{}}},u={...i,chatTools:d,chatBindings:p};return function(e,n){t.mkdirSync(s.dirname(e),{recursive:!0}),r.sync(e,`${JSON.stringify(n,null,2)}\n`,{mode:384})}(n,u),u}function cr(e,n){if(!t.existsSync(e))return ar(n);let r=ar(n);for(const i of t.readdirSync(e,{withFileTypes:!0})){if(!i.isFile())continue;const o=i.name.match(nr);if(o)try{const a=JSON.parse(t.readFileSync(s.join(e,i.name),"utf8"));if(a.channel!==o[1]||a.instanceId!==o[2])continue;r=dr(a,n)}catch{continue}}return r}function pr(e){return e.startsWith("ai-session.")||e.startsWith("ai.session.")?"ai.sessions":e.startsWith("app-session.")?"app.sessions":e.startsWith("receiver.")?"receiver":e.startsWith("conversation.")?"conversations":e.startsWith("trigger.")?"triggers":e.startsWith("channel.")?"channels":e.startsWith("instance.")?"instances":e.startsWith("node.")?"nodes":e.startsWith("project.")?"projects":e.startsWith("model.")?"models":e.startsWith("image.")?"images":"system"}const ur=i.z.enum(["ai.sessions","app.sessions"]),lr=i.z.object({topic:ur,instanceId:i.z.string().trim().min(1).max(160),streamId:i.z.string().trim().min(1).max(240),latestRevision:i.z.number().int().min(0),earliestRetainedRevision:i.z.number().int().min(0)}).strict();i.z.object({protocolVersion:i.z.literal(1),streams:i.z.array(lr)}).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,r=JSON.stringify(s);for(const t of this.clients)t.readyState===t.OPEN&&hr(t.topics,n,e)&&t.send(r);return s}send(e,t,s){const n=this.createEvent(t,s);return e.send(JSON.stringify(n)),n}createEvent(e,t){return{v:1,id:`evt_${Date.now().toString(36)}_${Math.random().toString(16).slice(2)}`,seq:++this.seq,type:e,topic:pr(e),createdAt:(new Date).toISOString(),payload:t}}}function hr(e,t,s){return!e||e.has("*")||e.has(t)||e.has(s)}const gr=i.z.object({type:i.z.literal("result"),result:i.z.unknown(),attachments:i.z.array(i.z.object({id:i.z.string(),kind:i.z.enum(["image","file"]),path:i.z.string(),name:i.z.string(),mime:i.z.string().optional(),size:i.z.number().nonnegative().optional()})).optional(),conversationId:i.z.number().int().positive().optional(),timeoutMs:i.z.number().positive().optional(),source:i.z.enum(["cli","mcp"]).optional(),kind:i.z.enum(["task","approval"]).optional(),cwd:i.z.string().optional(),sessionIds:i.z.record(i.z.string(),i.z.string()).optional()}),fr=i.z.discriminatedUnion("action",[i.z.object({type:i.z.literal("control"),action:i.z.literal("pending.list"),requestId:i.z.string().optional()}),i.z.object({type:i.z.literal("control"),action:i.z.literal("pending.reply"),requestId:i.z.string().optional(),id:i.z.number().int().positive(),markdown:i.z.string()}),i.z.object({type:i.z.literal("control"),action:i.z.literal("pending.drop"),requestId:i.z.string().optional(),id:i.z.number().int().positive()}),i.z.object({type:i.z.literal("control"),action:i.z.literal("pending.approval"),requestId:i.z.string().optional(),id:i.z.number().int().positive(),decision:i.z.enum(["allow","deny","skip"])}),i.z.object({type:i.z.literal("control"),action:i.z.literal("receiver.message"),requestId:i.z.string().optional(),channel:i.z.string().trim().min(1).max(80),chatSessionId:i.z.string().trim().min(1).max(240),userId:i.z.string().trim().max(240).optional(),text:i.z.string().trim().min(1).max(2e4),attachments:i.z.array(i.z.record(i.z.string(),i.z.unknown())).default([]),conversationId:i.z.number().int().positive().optional()})]);i.z.union([gr,fr]);const yr=i.z.object({type:i.z.literal("reply"),value:i.z.string()}),vr=i.z.object({type:i.z.literal("error"),message:i.z.string()}),Sr=i.z.object({type:i.z.literal("control.response"),requestId:i.z.string().optional(),ok:i.z.boolean(),data:i.z.unknown().optional(),error:i.z.object({code:i.z.string(),message:i.z.string()}).optional()});function Ir(e){return`${JSON.stringify(e)}\n`}i.z.union([yr,vr,Sr]);class Ar{socketPath;constructor(e){this.socketPath=e}pendingList(){return this.request({type:"control",action:"pending.list"})}reply(e,t){return this.request({type:"control",action:"pending.reply",id:e,markdown:t})}drop(e){return this.request({type:"control",action:"pending.drop",id:e})}approval(e,t){return this.request({type:"control",action:"pending.approval",id:e,decision:t})}message(e){return this.request({type:"control",action:"receiver.message",channel:e.channel,chatSessionId:e.chatSessionId,userId:e.userId,text:e.text,attachments:e.attachments||[],conversationId:e.conversationId})}request(e){const t=o.randomUUID();return new Promise((s,n)=>{const r=a.createConnection(this.socketPath),i=setTimeout(()=>{r.destroy(),n(Object.assign(new Error("Receiver control request timed out."),{code:"RECEIVER_CONTROL_TIMEOUT"}))},5e3),o=e=>{clearTimeout(i),r.end(),e()};r.once("connect",()=>{r.write(Ir({...e,requestId:t}))}),function(e,t,s){let n="";e.on("data",r=>{n+=r.toString("utf8");let i=n.indexOf("\n");for(;-1!==i;){const r=n.slice(0,i);if(n=n.slice(i+1),i=n.indexOf("\n"),r.trim())try{const n=t.safeParse(JSON.parse(r));if(!n.success){e.write(Ir({type:"error",message:"Invalid message shape."}));continue}s(n.data)}catch(t){e.write(Ir({type:"error",message:"Invalid JSON message."}))}}})}(r,Sr,e=>{e.requestId===t&&o(()=>{if(e.ok)s(e.data);else{const t=Object.assign(new Error(e.error?.message||"Receiver control request failed."),{code:e.error?.code||"RECEIVER_CONTROL_FAILED"});n(t)}})}),r.once("error",e=>{o(()=>{n(Object.assign(new Error(`Receiver is not available at ${this.socketPath}: ${e.message}`),{code:"RECEIVER_UNAVAILABLE"}))})}),r.once("close",()=>{clearTimeout(i)})})}}class br extends g.EventEmitter{socketPath;child;statusValue={running:!1};logPath;exitPromise;constructor(e,t){super(),this.socketPath=e,this.logPath=t?s.join(t,"receiver.log"):void 0}status(){return{...this.statusValue}}start(){if(this.child&&!this.child.killed&&this.statusValue.running)return this.status();const e=process.env.TASK_HANDOFF_CLI_PATH||s.resolve(__dirname,"cli.js");let t;return this.child=h.spawn(process.execPath,[e,"receiver","--headless","--socket",this.socketPath],{env:{...process.env,TASK_HANDOFF_RECEIVER_HEADLESS:"1"},stdio:["ignore","pipe","pipe"]}),this.statusValue={running:!0,pid:this.child.pid,startedAt:(new Date).toISOString(),exitedAt:void 0,exitCode:void 0,signal:void 0},this.appendLog(`\n[${this.statusValue.startedAt}] receiver started pid=${this.child.pid}\n`),this.child.stdout?.on("data",e=>this.handleLog(e)),this.child.stderr?.on("data",e=>this.handleLog(e)),this.exitPromise=new Promise(e=>{t=e}),this.child.on("exit",(e,s)=>{const n=(new Date).toISOString();this.statusValue={...this.statusValue,running:!1,exitedAt:n,exitCode:e,signal:s},this.appendLog(`[${n}] receiver exited code=${e??"null"} signal=${s??"null"}\n`),this.emit("exit",this.status()),this.child=void 0,t?.(this.status())}),this.emit("start",this.status()),this.status()}stop(){return this.child&&this.statusValue.running?(this.child.kill("SIGTERM"),this.status()):this.status()}async stopAndWait(e=2e3){if(!this.child||!this.statusValue.running)return this.status();const t=this.exitPromise;return this.stop(),t?await Promise.race([t,new Promise(t=>{setTimeout(()=>t(this.status()),e)})]):this.status()}readLogs(e=65536){const s=this.logPath;if(!s||!t.existsSync(s))return{logPath:s,maxBytes:e,size:0,truncated:!1,content:""};const n=t.statSync(s),r=Math.max(0,n.size-e),i=t.openSync(s,"r");try{const o=Buffer.alloc(n.size-r);return t.readSync(i,o,0,o.length,r),{logPath:s,maxBytes:e,size:n.size,updatedAt:n.mtime.toISOString(),truncated:r>0,content:o.toString("utf8")}}finally{t.closeSync(i)}}handleLog(e){const t=String(e);this.appendLog(t),this.emit("log",t)}appendLog(e){this.logPath&&(t.mkdirSync(s.dirname(this.logPath),{recursive:!0}),t.appendFileSync(this.logPath,e))}}function _r(){return process.env.HOME||n.homedir()||"/home/agent"}function wr(){return process.env.TASK_HANDOFF_WORKSPACE||process.env.WORKSPACE||"/workspace"}function Tr(){const e=_r(),t=function(){const e=[s.join(_r(),".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 Nr(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 zr(e,t,n){const r=n||Tr().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(wr(),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:_r(),WORKSPACE:wr(),CODEX_HOME:process.env.CODEX_HOME||s.join(_r(),".codex"),CLAUDE_HOME:process.env.CLAUDE_HOME||s.join(_r(),".claude")};return e.replace(/\$\{([A-Z_]+)\}/g,(e,s)=>t[s]||e)}(e));if(![s.resolve(_r()),s.resolve(wr()),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:Nr(t.type,o,a)}}catch(e){return{...t,source:o,target:a,status:"failed",error:e instanceof Error?e.message:String(e)}}});return{preset:{id:r.id,label:r.label,projectRoot:r.projectRoot},direction:e,items:i}}const Or="2026-07-13",Er=i.z.string().trim().min(1).max(120).regex(/^[a-zA-Z0-9][a-zA-Z0-9_.:-]*$/),xr=i.z.string().datetime(),kr=i.z.record(i.z.string(),i.z.string()).default({}),Dr=i.z.record(i.z.string(),i.z.string()).default({}),Cr=i.z.object({codexModelId:Er.optional(),claudeModelId:Er.optional()}).strict().default({}),Pr=i.z.object({component:i.z.enum(["control-plane","node-agent","controlled-instance"]),packageName:i.z.string().trim().max(160).optional(),packageVersion:i.z.string().trim().max(80).optional(),protocolVersion:i.z.string().trim().max(80).optional(),buildId:i.z.string().trim().max(160).optional(),builtAt:i.z.string().trim().max(120).optional(),gitCommit:i.z.string().trim().max(120).optional(),imageRef:i.z.string().trim().max(512).optional(),imageDigest:i.z.string().trim().max(240).optional()}).strict(),Fr=i.z.enum(["stable","beta","alpha"]),Rr=i.z.discriminatedUnion("component",[i.z.object({component:i.z.literal("node-agent")}).strict(),i.z.object({component:i.z.literal("controlled-instance"),instanceId:Er}).strict()]);i.z.object({target:Rr,channel:Fr.default("stable")}).strict(),i.z.object({target:Rr,source:i.z.enum(["npm","docker-registry"]),channel:Fr,currentVersion:i.z.string().trim().max(240).optional(),availableVersion:i.z.string().trim().min(1).max(240),artifactRef:i.z.string().trim().min(1).max(512).optional(),updateAvailable:i.z.boolean(),supported:i.z.boolean().default(!0),reason:i.z.string().trim().max(2048).optional(),checkedAt:xr}).strict(),i.z.object({id:Er,nodeId:Er,target:Rr,source:i.z.enum(["npm","docker-registry"]),channel:Fr,fromVersion:i.z.string().trim().max(240).optional(),toVersion:i.z.string().trim().min(1).max(240),artifactRef:i.z.string().trim().min(1).max(512).optional(),status:i.z.enum(["queued","updating","restarting","succeeded","failed"]),error:i.z.string().trim().max(4096).optional(),startedAt:xr.optional(),completedAt:xr.optional(),createdAt:xr,updatedAt:xr}).strict();const Mr=i.z.object({type:i.z.enum(["branch","tag","commit"]),name:i.z.string().trim().min(1).max(240).optional(),commit:i.z.string().trim().max(80).optional()}).strict(),jr=i.z.object({type:i.z.enum(["none","ssh-key","https-token"]).default("none"),secretId:i.z.string().trim().min(1).max(120).optional()}).strict(),Lr=i.z.object({depth:i.z.number().int().positive().max(1e5).optional(),submodules:i.z.boolean().default(!1),lfs:i.z.boolean().default(!1),subdirectory:i.z.string().trim().max(240).default("")}).strict();i.z.object({id:Er,name:i.z.string().trim().min(1).max(160),url:i.z.string().trim().min(1).max(2048),provider:i.z.string().trim().max(80).optional(),ref:Mr.default({type:"branch",name:"main"}),auth:jr.default({type:"none"}),clone:Lr.default({submodules:!1,lfs:!1,subdirectory:""}),defaultImageId:Er.optional(),modelSelection:Cr,labels:kr,createdAt:xr,updatedAt:xr}).strict(),i.z.object({id:Er,nodeId:Er,name:i.z.string().trim().min(1).max(160),path:i.z.string().trim().min(1).max(4096),defaultImageId:Er.optional(),modelSelection:Cr,labels:kr,createdAt:xr,updatedAt:xr}).strict();const Hr=i.z.discriminatedUnion("type",[i.z.object({type:i.z.literal("git-repository"),repositoryId:Er.optional(),url:i.z.string().trim().min(1).max(2048),provider:i.z.string().trim().max(80).optional(),ref:Mr.default({type:"branch",name:"main"}),auth:jr.default({type:"none"}),clone:Lr.default({submodules:!1,lfs:!1,subdirectory:""})}).strict(),i.z.object({type:i.z.literal("git-template"),url:i.z.string().trim().min(1).max(2048),templateId:i.z.string().trim().min(1).max(120).optional(),ref:Mr.default({type:"branch",name:"main"}),auth:jr.default({type:"none"}),clone:Lr.default({submodules:!1,lfs:!1,subdirectory:""})}).strict(),i.z.object({type:i.z.literal("local-folder"),localFolderId:Er.optional(),path:i.z.string().trim().min(1).max(4096),ownerNodeId:Er.optional()}).strict()]),$r=i.z.object({mode:i.z.enum(["local-bind","git-clone","empty-volume","persistent-volume"]),path:i.z.string().trim().min(1).max(4096).default("/workspace"),volumeName:i.z.string().trim().max(240).optional(),readOnly:i.z.boolean().default(!1)}).strict(),Ur=i.z.enum(["codex","claude"]);i.z.object({id:Er,name:i.z.string().trim().min(1).max(160),source:Hr,defaultImageId:Er.optional(),defaultNodeId:Er.optional(),defaultRuntimeId:Er.optional(),modelSelection:Cr,workspacePolicy:$r,labels:kr,createdAt:xr,updatedAt:xr}).strict(),i.z.object({id:Er,name:i.z.string().trim().min(1).max(160),endpoint:i.z.string().trim().min(1).max(2048),key:i.z.string().trim().min(1).max(4096),model:i.z.string().trim().min(1).max(240),app:Ur,enabled:i.z.boolean().default(!0),order:i.z.number().int().min(0).max(1e6).default(0),labels:kr,createdAt:xr,updatedAt:xr}).strict();const qr=i.z.object({id:Er,name:i.z.string().trim().min(1).max(160),image:i.z.string().trim().min(1).max(512),registry:i.z.string().trim().min(1).max(160).default("local"),capabilities:i.z.array(i.z.string().trim().min(1).max(80)).default([]),optionalApps:i.z.array(i.z.string().trim().min(1).max(120)).default([]),defaultEnv:Dr,labels:kr,createdAt:xr,updatedAt:xr}).strict();i.z.object({id:Er,name:i.z.string().trim().min(1).max(160),connectionMode:i.z.enum(["local-ipc","local-loopback","direct-http","reverse-wss"]).default("direct-http"),auth:i.z.object({mode:i.z.enum(["local-static-key","paired-hmac"]).default("local-static-key"),keyId:Er.optional(),secret:i.z.string().trim().max(4096).optional(),pairedAt:xr.optional(),pairing:i.z.object({status:i.z.enum(["pending","paired","expired"]).default("pending"),joinToken:i.z.string().trim().max(4096).optional(),expiresAt:xr.optional()}).strict().optional()}).strict().default({mode:"local-static-key"}),endpoint:i.z.string().trim().max(2048).optional(),controlEndpoint:i.z.string().trim().max(2048).optional(),containerEndpoint:i.z.string().trim().max(2048).optional(),publicWebBase:i.z.string().trim().max(2048).optional(),status:i.z.enum(["unknown","online","offline","degraded"]).default("unknown"),health:i.z.enum(["unknown","ok","degraded","failed"]).default("unknown"),capabilities:i.z.record(i.z.string(),i.z.unknown()).default({}),labels:kr,lastSeenAt:xr.optional(),createdAt:xr,updatedAt:xr}).strict(),i.z.object({id:Er,nodeId:Er,name:i.z.string().trim().min(1).max(160),type:i.z.enum(["docker","kubernetes","local"]),status:i.z.enum(["unknown","online","offline","degraded"]).default("unknown"),accessStrategy:i.z.enum(["node-proxy","direct-port","kubernetes-ingress","kubernetes-port-forward"]).default("node-proxy"),capabilities:i.z.record(i.z.string(),i.z.unknown()).default({}),labels:kr,createdAt:xr,updatedAt:xr}).strict(),i.z.object({ok:i.z.boolean().optional(),role:i.z.string().optional(),nodeId:Er.optional()}).passthrough(),i.z.object({bindScope:i.z.enum(["loopback","all-ipv4"]),port:i.z.number().int().min(1).max(65535)}).strict().extend({host:i.z.enum(["127.0.0.1","0.0.0.0"]),status:i.z.enum(["listening","error"]),source:i.z.enum(["bootstrap","persisted"]),error:i.z.string().trim().max(2048).optional()}).strict(),i.z.object({nodeId:Er,joinToken:i.z.string().trim().min(1),expiresAt:xr}).passthrough(),i.z.object({id:Er,keyId:Er,url:i.z.string().trim().min(1).max(2048).optional(),name:i.z.string().trim().min(1).max(160).optional(),pairedAt:xr,updatedAt:xr.optional(),active:i.z.boolean().optional(),current:i.z.boolean().optional()}).passthrough(),i.z.object({remote:i.z.object({id:Er,url:i.z.string().trim().min(1).max(2048).optional(),keyId:Er,pairedAt:xr,active:i.z.boolean()}).passthrough(),tunnel:i.z.object({status:i.z.enum(["disabled","saved","connecting","connected","failed"]),error:i.z.string().trim().max(2048).optional()}).passthrough()}).passthrough(),i.z.object({deleted:i.z.boolean().optional()}).passthrough(),i.z.object({repository:i.z.string().trim().optional(),tag:i.z.string().trim().optional(),id:i.z.string().trim(),createdSince:i.z.string().trim().optional(),size:i.z.string().trim().optional(),reference:i.z.string().trim().min(1)}).passthrough();const Vr=i.z.lazy(()=>i.z.object({name:i.z.string().trim().min(1),path:i.z.string().trim().min(1).max(4096),children:i.z.array(Vr)}).passthrough());i.z.object({status:i.z.number().int().min(100).max(599).optional(),headers:i.z.record(i.z.string(),i.z.string()).optional(),bodyBase64:i.z.string().optional()}).passthrough();const Br=i.z.object({strategy:i.z.enum(["node-proxy","direct-port","kubernetes-ingress","kubernetes-port-forward"]).default("node-proxy"),web:i.z.string().trim().max(2048).optional(),api:i.z.string().trim().max(2048).optional(),vnc:i.z.string().trim().max(2048).optional(),tty:i.z.string().trim().max(2048).optional(),logs:i.z.string().trim().max(2048).optional(),status:i.z.enum(["unknown","reachable","endpoint-unreachable"]).default("unknown")}).strict(),Kr=i.z.object({strategy:i.z.enum(["control-plane-proxy","direct-port","node-proxy","kubernetes-ingress","kubernetes-port-forward"]).default("control-plane-proxy"),web:i.z.string().trim().max(2048).optional(),api:i.z.string().trim().max(2048).optional(),ws:i.z.string().trim().max(2048).optional(),status:i.z.enum(["unknown","reachable","endpoint-unreachable"]).default("unknown")}).strict().default({strategy:"control-plane-proxy",status:"unknown"}),Gr=i.z.object({mode:i.z.enum(["local-bind","git-clone","empty-volume","persistent-volume"]).optional(),status:i.z.enum(["unknown","pending","ready","failed"]).default("unknown"),path:i.z.string().trim().max(4096).optional(),resolvedCommit:i.z.string().trim().max(120).optional(),error:i.z.string().trim().max(2048).optional()}).passthrough(),Wr=i.z.object({id:Er,name:i.z.string().trim().min(1).max(160),projectId:Er.optional(),source:Hr,sourceSnapshot:i.z.record(i.z.string(),i.z.unknown()).default({}),nodeId:Er,runtimeId:Er,imageId:Er.optional(),imageSnapshot:qr.optional(),status:i.z.enum(["created","provisioning","starting","registering","registered","running","stopping","stopped","failed","unhealthy"]).default("created"),health:i.z.enum(["unknown","ok","degraded","failed"]).default("unknown"),connectionStatus:i.z.enum(["unknown","online","offline","endpoint-unreachable"]).default("unknown"),agentStatus:i.z.enum(["unknown","online","offline"]).default("unknown"),targetStatus:i.z.enum(["unknown","reachable","endpoint-unreachable"]).default("unknown"),uiAccessStatus:i.z.enum(["unknown","reachable","endpoint-unreachable"]).default("unknown"),controlMode:i.z.enum(["standalone","controlled"]).default("controlled"),protocolVersion:i.z.string().trim().max(80).optional(),instanceVersion:i.z.string().trim().max(80).optional(),build:Pr.optional(),capabilities:i.z.record(i.z.string(),i.z.unknown()).default({}),config:i.z.object({autoImportAgentConfigs:i.z.boolean().default(!0)}).strict().default({autoImportAgentConfigs:!0}),workspace:Gr.default({status:"unknown"}),target:Br.default({strategy:"direct-port",status:"unknown"}),access:Kr,receiver:i.z.object({status:i.z.string().trim().max(80).default("unknown"),pendingCount:i.z.number().int().min(0).default(0)}).strict().default({status:"unknown",pendingCount:0}),apps:i.z.object({runningCount:i.z.number().int().min(0).default(0),problemCount:i.z.number().int().min(0).default(0),updatedAt:xr.optional(),revision:i.z.number().int().min(0).optional()}).strict().default({runningCount:0,problemCount:0}),aiSessions:Es.default(()=>({runningCount:0,waitingCount:0,staleCount:0,sessions:[],updatedAt:(new Date).toISOString()})),triggers:i.z.object({enabledCount:i.z.number().int().min(0).default(0),runningCount:i.z.number().int().min(0).default(0),errorCount:i.z.number().int().min(0).default(0),configs:i.z.array(i.z.object({configHash:i.z.string().trim().min(1),config:$e,deployments:i.z.array(qe).default([]),runtime:i.z.array(Ve).default([])}).strict()).default([]),recentRuns:i.z.array(Be).default([])}).strict().optional(),runtime:i.z.object({kind:i.z.string().trim().max(80).optional(),containerName:i.z.string().trim().max(240).optional(),containerId:i.z.string().trim().max(240).optional(),workspacePath:i.z.string().trim().max(4096).optional(),pid:i.z.number().int().positive().optional(),port:i.z.number().int().positive().max(65535).optional(),labels:i.z.record(i.z.string(),i.z.string()).default({})}).strict().default({labels:{}}),registrationToken:i.z.string().trim().min(1).max(240).optional(),lastHeartbeatAt:xr.optional(),createdAt:xr,updatedAt:xr}).strict();i.z.object({instanceId:Er.optional(),name:i.z.string().trim().min(1).max(160),projectId:Er.optional(),source:Hr.optional(),nodeId:Er.optional(),runtimeId:Er.optional(),imageId:Er.optional(),instanceVersion:i.z.string().trim().max(80).optional(),protocolVersion:i.z.string().trim().max(80),build:Pr.optional(),controlMode:i.z.enum(["standalone","controlled"]).default("controlled"),capabilities:i.z.record(i.z.string(),i.z.unknown()).default({}),target:Br.default({strategy:"direct-port",status:"unknown"}),workspace:Gr.default({status:"unknown"}),registrationToken:i.z.string().trim().max(240).optional()}).strict(),i.z.object({status:Wr.shape.status.optional(),health:Wr.shape.health.optional(),protocolVersion:i.z.string().trim().max(80),build:Pr.optional(),capabilities:Wr.shape.capabilities.optional(),receiver:Wr.shape.receiver.optional(),apps:Wr.shape.apps.optional(),aiSessions:Wr.shape.aiSessions.optional(),triggers:Wr.shape.triggers.optional(),workspace:Gr.optional(),target:Br.partial().optional()}).strict();const Xr=i.z.enum(["web","telegram","wechat","dingding"]);function Jr(){try{const e=s.resolve(__dirname,"..","package.json");return JSON.parse(t.readFileSync(e,"utf8")).version||"unknown"}catch{return"unknown"}}function Yr(e){const t=process.env[e]?.trim();return t||void 0}function Qr(){return"controlled"===process.env.TASK_HANDOFF_CONTROL_MODE}function Zr(e,r){const i=[{name:"Xvfb",requiredFor:["gui-display"]},{name:"openbox",requiredFor:["gui-window-manager"]},{name:"picom",requiredFor:["gui-compositor"]},{name:"x11vnc",requiredFor:["vnc"]},{name:"websockify",requiredFor:["novnc-proxy"]},{name:"vncserver",requiredFor:["kasmvnc"]},{name:"vncpasswd",requiredFor:["kasmvnc-auth"]},{name:"openssl",requiredFor:["kasmvnc-cert"]},{name:"xrdb",requiredFor:["kasmvnc-hidpi"]},{name:"xrandr",requiredFor:["kasmvnc-resize"]},{name:process.env.TASK_HANDOFF_CHROMIUM_COMMAND||"chromium",label:"chromium",requiredFor:["browser"]},{name:process.env.TASK_HANDOFF_VSCODE_WEB_COMMAND||"code-server",label:"code-server",requiredFor:["vscode-web"]},{name:process.env.TASK_HANDOFF_XTERM_COMMAND||"xterm",label:"xterm",requiredFor:["gui-terminal"]},{name:"import",requiredFor:["screenshot"]},{name:process.env.TASK_HANDOFF_CODEX_COMMAND||"codex",label:"codex",requiredFor:["active-codex-agent"]},{name:process.env.TASK_HANDOFF_CLAUDE_COMMAND||process.env.CLAUDE_CLI_PATH||"claude",label:"claude",requiredFor:["active-claude-agent"]}].map(e=>{const t=It(e.name);return{name:e.label||e.name,command:e.name,available:Boolean(t),path:t,requiredFor:e.requiredFor}}),o=function(e){return Object.entries(e).map(([e,n])=>{const r=s.resolve(n),i=e.endsWith("Path"),o=i?s.dirname(r):r;let a=!1,d=!1,c="missing";try{const e=t.existsSync(r)?t.statSync(r):void 0;a=Boolean(e),c=e?.isFile()?"file":e?.isDirectory()?"directory":"missing";const n=a?i?r:o:(e=>{let n=e;for(;!t.existsSync(n);){const e=s.dirname(n);if(e===n)return n;n=e}return t.statSync(n).isDirectory()?n:s.dirname(n)})(o);t.accessSync(n,t.constants.W_OK),d=!0}catch{d=!1}return{key:e,path:r,exists:a,type:c,writable:d}})}(e),a="linux"===process.platform;return{ok:a&&i.every(e=>e.available)&&Boolean(r)&&o.every(e=>e.writable),runtime:{platform:process.platform,arch:process.arch,linuxRuntime:a,node:process.version,pid:process.pid,hostname:n.hostname(),uptimeSeconds:Math.round(process.uptime())},noVnc:{available:Boolean(r),root:r},commands:i,storage:o}}async function ei(e){try{const t=await e.pendingList();if(t&&"object"==typeof t&&"pending"in t&&Array.isArray(t.pending))return t.pending.length}catch{return 0}return 0}function ti(){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 si(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 ni(e){const t=e.catalog();return{protocolVersion:Or,apps:t.map(e=>({id:e.id,name:e.name,kind:e.kind,automation:e.automation})),features:{receiver:!0,appRuntime:!0,tty:t.some(e=>"tty"===e.kind),gui:t.some(e=>"gui"===e.kind),browser:t.some(e=>"browser"===e.id||"chromium"===e.id),screenshots:!0,logs:!0}}}function ri(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 ii(e,t,s,n,r=_n(),i){const o=t.status(),a=e.listSessions();return{status:"running",health:"ok",instanceVersion:Jr(),protocolVersion:Or,build:{component:"controlled-instance",packageName:"@task-handoff/controlled-instance",packageVersion:Jr(),protocolVersion:Or,buildId:Yr("TASK_HANDOFF_BUILD_ID"),builtAt:Yr("TASK_HANDOFF_BUILT_AT"),gitCommit:Yr("TASK_HANDOFF_GIT_COMMIT"),imageRef:Yr("TASK_HANDOFF_IMAGE_REF"),imageDigest:Yr("TASK_HANDOFF_IMAGE_DIGEST")},controlMode:Qr()?"controlled":"standalone",capabilities:ni(e),receiver:{status:o.running?"running":"stopped",pendingCount:await ei(s)},apps:{runningCount:e.runningSessionCount(),problemCount:e.problemSessionCount()},aiSessions:r.boundSnapshot(a),triggers:i?ri(i):void 0,workspace:si(n),target:ti()}}i.z.object({id:Er,channel:Xr,name:i.z.string().trim().min(1).max(160),enabled:i.z.boolean().default(!1),token:i.z.string().trim().max(4096).optional(),defaultChatId:i.z.string().trim().max(240).optional(),allowedUserIds:i.z.array(i.z.string().trim().min(1).max(240)).default([]),pollIntervalMs:i.z.number().int().positive().max(6e4).default(3e3),settings:i.z.record(i.z.string(),i.z.unknown()).default({}),createdAt:xr,updatedAt:xr}).strict(),i.z.object({id:Er,channel:Xr,bridgeId:Er.optional(),chatSessionId:i.z.string().trim().min(1).max(240),userId:i.z.string().trim().max(240).optional(),activeProjectId:Er.optional(),activeInstanceId:Er.optional(),activeAiSessionId:i.z.string().trim().min(1).max(120).optional(),lastUsedAt:xr,createdAt:xr,updatedAt:xr}).strict(),i.z.object({source:i.z.object({type:i.z.literal("chat-gateway").default("chat-gateway"),channel:Xr,bridgeId:Er.optional(),chatSessionId:i.z.string().trim().min(1).max(240),userId:i.z.string().trim().max(240).optional()}).strict(),message:i.z.object({text:i.z.string().trim().max(2e4).default(""),attachments:i.z.array(ms).max(6).default([])}).strict().superRefine((e,t)=>{e.attachments.reduce((e,t)=>e+t.size,0)>is&&t.addIssue({code:i.z.ZodIssueCode.custom,path:["attachments"],message:"Images must be 41943040 bytes or less in total."})}),target:i.z.object({instanceId:Er,aiSessionId:i.z.string().trim().min(1).max(120)}).strict().optional()}).strict(),i.z.object({id:Er,instanceId:Er,projectId:Er.optional(),aiSessionId:i.z.string().trim().min(1).max(120),providerSessionId:i.z.string().trim().max(240).optional(),result:i.z.string().default(""),timeoutMs:i.z.number().positive().optional(),source:i.z.string().trim().max(120).optional(),kind:i.z.enum(["task","approval"]).default("task"),status:i.z.enum(["pending","unreachable"]).default("pending"),error:i.z.string().trim().max(2048).optional(),lastSeenAt:xr}).strict();const oi=new Set(["ECONNREFUSED","ECONNRESET","EHOSTUNREACH"]);function ai(e){return new Promise(t=>setTimeout(t,e))}function di(e){const t=e?.code;return Boolean(t&&oi.has(t))}function ci(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 pi(){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 ui(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 li(e,t,s,n={}){return Object.fromEntries(Object.entries(ui(e,t,s,n)).filter(([e])=>{const t=e.toLowerCase();return!t.startsWith("sec-websocket-")||"sec-websocket-origin"===t}))}function mi(e,t){const s=e[t];return Array.isArray(s)?s.join(","):s||""}function hi(e){if(mi(e,"content-encoding"))return!1;const t=mi(e,"content-type").toLowerCase();return t.includes("text/css")||t.includes("text/html")}function gi(e,t){const s=mi(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 fi(e){const t={};e.forEach((e,s)=>{t[s]=e});const s=e.getSetCookie?.();return s?.length&&(t["set-cookie"]=s),t}function yi(e){const t={};e.forEach((e,s)=>{t[s]=e});const s=e.getSetCookie?.();return s?.length&&(t["set-cookie"]=s),t}const vi="app-session.snapshot",Si="app-session.patch",Ii="app-session.removed",Ai=36e5,bi=i.z.enum(["created","starting","running","stopping","stopped","exited","failed","closed","terminated","unknown"]),_i=i.z.object({type:i.z.enum(["app-session","provider-session","adapter-key"]),id:i.z.string().trim().min(1).max(240),agent:i.z.string().trim().min(1).max(80).optional(),adapter:i.z.string().trim().min(1).max(80).optional(),key:i.z.string().trim().min(1).max(240).optional()}).strict(),wi=i.z.record(i.z.string(),i.z.unknown()).and(i.z.object({id:i.z.string().trim().min(1).max(160),appId:i.z.string().trim().min(1).max(160).optional(),title:i.z.string().trim().max(240).optional(),kind:i.z.string().trim().max(80).optional(),status:bi.default("unknown"),bindings:i.z.array(_i).max(40).default([]),workspace:i.z.object({cwd:i.z.string().trim().max(4096).optional()}).strict().optional(),createdAt:i.z.string().datetime().optional(),updatedAt:i.z.string().datetime().optional()})),Ti=i.z.object({runningCount:i.z.number().int().min(0).default(0),problemCount:i.z.number().int().min(0).default(0),sessions:i.z.array(wi).default([]),updatedAt:i.z.string().datetime()}).strict();i.z.object({streamId:i.z.string().trim().min(1).max(240),revision:i.z.number().int().min(0),lastEventAt:i.z.string().datetime(),snapshot:Ti}).strict(),Ti.pick({runningCount:!0,problemCount:!0,updatedAt:!0}).extend({revision:i.z.number().int().min(0).optional()});const Ni=i.z.enum(["app-session-created","app-session-updated","app-session-deleted","app-session-recovered","control-action","heartbeat-sync","startup"]),zi=i.z.object({streamId:i.z.string().trim().min(1).max(240),instanceId:i.z.string().trim().min(1).max(160),nodeId:i.z.string().trim().min(1).max(160).optional(),revision:i.z.number().int().min(0),previousRevision:i.z.number().int().min(0).optional(),traceId:i.z.string().trim().min(1).max(160),generatedAt:i.z.string().datetime(),reason:Ni}).strict(),Oi=i.z.object({meta:zi,snapshot:Ti}).strict(),Ei=i.z.object({meta:zi,session:wi}).strict(),xi=i.z.object({meta:zi,sessionId:i.z.string().trim().min(1).max(160),tombstone:wi.optional(),expiresAt:i.z.string().datetime().optional()}).strict(),ki=i.z.object({streamId:i.z.string().trim().min(1).max(240),instanceId:i.z.string().trim().min(1).max(160),sinceRevision:i.z.number().int().min(0),latestRevision:i.z.number().int().min(0),earliestRetainedRevision:i.z.number().int().min(0),syncRequired:i.z.boolean().default(!1),events:i.z.array(i.z.discriminatedUnion("type",[i.z.object({type:i.z.literal(vi),payload:Oi}).strict(),i.z.object({type:i.z.literal(Si),payload:Ei}).strict(),i.z.object({type:i.z.literal(Ii),payload:xi}).strict()])).default([])}).strict();function Di(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":bi.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=Ri(e.workspace),s=Ri(e.tty),n=Ri(e.launch),r=Ri(e.ai),i=Ri(r.claude),o=Mi(t.cwd)||Mi(s.cwd)||Mi(i.cwd)||Mi(n.cwd);return o?{cwd:o}:void 0}(e),{workspace:r,...i}=e;return wi.parse({...i,status:t,bindings:Fi([...(o=e.bindings,Array.isArray(o)?o.flatMap(e=>{const t=_i.safeParse(e);return t.success?[t.data]:[]}):[]),...s?[{type:"app-session",id:s}]:[],...Pi(e)]),...n?{workspace:n}:{}});var o}(e));return Ti.parse({runningCount:s.filter(e=>"running"===e.status).length,problemCount:s.filter(e=>"failed"===e.status).length,sessions:s,updatedAt:t})}function Ci(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 Pi(e){const t=Ri(e.ai),s=Ri(t.claude),n=Ri(t.appServer),r=[],i=Mi(s.short);i&&r.push({type:"adapter-key",adapter:"claude",agent:"claude",id:`short:${i}`,key:`short:${i}`});const o=Mi(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=Mi(t.activeThreadId);for(const e of[...new Set([d,...a].filter(Boolean))])r.push({type:"provider-session",agent:"codex",id:e});const c=Mi(n.socketPath);return c&&r.push({type:"adapter-key",adapter:"codex-app-server",agent:"codex",id:`socket:${c}`,key:`socket:${c}`}),r}function Fi(e){const t=new Map;for(const s of e)t.set(Ci(s),s);return[...t.values()]}function Ri(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}function Mi(e){return"string"==typeof e&&e.trim()?e.trim():""}function ji(e){return e.readyState===(e.OPEN??1)}function Li(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 Hi(e,t){e.send(t.data,{binary:t.isBinary})}function $i(e,t){if(ji(e))for(const s of t.splice(0))Hi(e,s)}const Ui=require("ws");function qi(e){return{method:e.method,headers:e.headers,body:e.streamRawRequest?e.rawRequest:e.requestBody,...e.streamRawRequest?{duplex:"half"}:{}}}function Vi(e){return d.Readable.fromWeb(e)}class Bi{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}}}function Ki(e){const t=e();return{...t,secrets:t.secrets?Object.fromEntries(Object.entries(t.secrets).map(([e,t])=>[e,{configured:void 0!==t&&""!==t,preview:"string"==typeof t?`${t.slice(0,6)}***`:void 0}])):void 0}}const Gi=i.z.object({id:i.z.string().trim().min(1).max(120),label:i.z.string().trim().min(1).max(120),projectRoot:i.z.string().trim().min(1).max(500),items:i.z.array(i.z.object({id:i.z.string().trim().min(1).max(120),type:i.z.enum(["file","dir"]),projectPath:i.z.string().trim().min(1).max(500),containerPath:i.z.string().trim().min(1).max(500)}).strip()).min(1).max(50)}).strip(),Wi=i.z.object({preset:Gi.optional()}).strip().default({}),Xi=i.z.object({appId:i.z.string().min(1).max(80).regex(/^[a-z0-9][a-z0-9_.-]*$/).optional(),title:i.z.string().trim().min(1).max(120).optional(),args:i.z.array(i.z.string().max(4096)).max(64).optional(),cwd:i.z.string().trim().min(1).max(512).optional(),env:i.z.record(i.z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),i.z.string().max(4096)).optional(),display:i.z.object({width:i.z.number().int().min(320).max(7680).optional(),height:i.z.number().int().min(240).max(4320).optional(),depth:i.z.union([i.z.literal(16),i.z.literal(24),i.z.literal(32)]).optional()}).optional(),displayTarget:i.z.object({mode:i.z.enum(["isolated","shared"]),id:i.z.string().trim().min(1).max(80).regex(/^[a-z0-9][a-z0-9._-]*$/).optional(),autoCreate:i.z.boolean().optional()}).optional()}).strict(),Ji=i.z.object({width:i.z.number().int().min(320).max(7680).optional(),height:i.z.number().int().min(240).max(4320).optional(),depth:i.z.number().int().min(8).max(32).optional()}).strip(),Yi=i.z.object({title:i.z.string().trim().min(1).max(120)}).strict(),Qi=i.z.object({source:i.z.object({type:i.z.literal("chat-gateway").default("chat-gateway"),channel:i.z.enum(["web","telegram","wechat","dingding"]),chatSessionId:i.z.string().trim().min(1).max(240),userId:i.z.string().trim().max(240).optional()}).strict(),message:i.z.object({text:i.z.string().trim().max(2e4).default(""),attachments:i.z.array(i.z.record(i.z.string(),i.z.unknown())).default([])}).strict(),routing:i.z.object({projectId:i.z.string().trim().min(1).max(120),instanceId:i.z.string().trim().min(1).max(120),conversationId:i.z.number().int().positive().optional()}).strict()}).strict(),Zi=i.z.object({name:i.z.string().trim().min(1).max(160),description:i.z.string().trim().max(1e3).optional(),source:je,action:Le,policy:He.partial().optional(),deployment:i.z.object({deploymentId:i.z.string().trim().min(1).max(240).optional(),origin:i.z.enum(["control-plane","controlled-instance"]).optional(),enabled:i.z.boolean().optional(),target:Ue.optional(),localName:i.z.string().trim().min(1).max(160).optional()}).strict().optional()}).strict(),eo=i.z.object({name:i.z.string().trim().min(1).max(160).optional(),description:i.z.string().trim().max(1e3).nullable().optional()}).strict(),to=i.z.object({promptOverride:i.z.string().trim().min(1).max(2e4).optional(),eventSummary:i.z.string().trim().max(1e3).optional(),deploymentId:i.z.string().trim().min(1).max(240).optional()}).strict().default({});function so(e){return e instanceof i.z.ZodError?e.issues.map(e=>`${e.path.join(".")||"body"}: ${e.message}`).join("; "):e instanceof Error?e.message:String(e)}function no(e,t){if(t instanceof i.z.ZodError)return e.code(400).send({error:As.parse({code:"AI_SESSION_CONTROL_INVALID",message:t.issues.map(e=>`${e.path.join(".")||"body"}: ${e.message}`).join("; ")})});const s=t&&"object"==typeof t?t:{},n="string"==typeof s.code?s.code:"AI_SESSION_CONTROL_FAILED",r="number"==typeof s.statusCode?s.statusCode:"AI_SESSION_NOT_FOUND"===n?404:400;return e.code(r).send({error:As.parse({code:n,message:t instanceof Error?t.message:String(t)})})}function ro(e,t=!1){const s=process.env[e];return void 0===s||""===s?t:["1","true","yes","on"].includes(s.toLowerCase())}function io(e){return process.env.TASK_HANDOFF_RECEIVER_LOG||s.join(e,"receiver.log")}function oo(e){return Array.isArray(e)?e.map(oo):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,null===t?void 0:oo(t)])):e}function ao(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 co(e={}){const r=e.socketPath||N,d=(new Date).toISOString(),h=function(){const e=et();return{paths:e,channel:(t,n="default")=>new me(s.join(e.channelsDir,`${t}.${n}.json`),{schema:tt,defaultValue:()=>({schemaVersion:1,channel:t,instanceId:n,enabled:!1})}),conversationIndex:()=>new me(s.join(e.conversationsDir,"index.json"),{schema:st,defaultValue:()=>({schemaVersion:1,defaultConversationId:1,nextConversationId:2,items:[]})}),appSessionIndex:()=>new me(s.join(e.appSessionsDir,"index.json"),{schema:nt,defaultValue:()=>({schemaVersion:1,items:[]})})}}();!function(e,t){if(ro("TASK_HANDOFF_DIAGNOSTIC_LOGS"))try{oe(io(e),{event:"controlled_instance_start",component:"controlled-instance",controlMode:process.env.TASK_HANDOFF_CONTROL_MODE,diagnosticLogs:process.env.TASK_HANDOFF_DIAGNOSTIC_LOGS,dataDir:t,logDir:e,receiverLog:io(e),process:{pid:process.pid,ppid:process.ppid,cwd:process.cwd(),argv:process.argv,parent:ie(process.ppid),env:re()}})}catch{}}(h.paths.logDir,h.paths.dataDir);const g=function(e){if("off"===process.env.TASK_HANDOFF_WEB_AUTH)return{enabled:!1};const n=process.env.TASK_HANDOFF_WEB_TOKEN?.trim();if(n)return{enabled:!0,source:"env",token:n};const r=function(e){try{return t.readFileSync(e,"utf8").trim()||void 0}catch(e){if(e&&"object"==typeof e&&"code"in e&&"ENOENT"===e.code)return;throw e}}(e.webTokenPath);if(r)return{enabled:!0,source:"file",token:r,tokenFile:e.webTokenPath};if("required"===process.env.TASK_HANDOFF_WEB_AUTH){const n=o.randomBytes(24).toString("base64url");return function(e,n){t.mkdirSync(s.dirname(e),{recursive:!0}),t.writeFileSync(e,`${n}\n`,{mode:384})}(e.webTokenPath,n),{enabled:!0,source:"generated",token:n,tokenFile:e.webTokenPath}}return{enabled:!1,tokenFile:e.webTokenPath}}(h.paths),f=new mr,y=e.receiverProcess||new br(r,h.paths.logDir),v=new Ar(r),S=e.appRuntime||new Pt(h.paths),I=e.aiSessionRegistry||_n(),b=new Lt(I),w=new Ne(h.paths),z=new Qe(h.paths),O=new Oe(z,v,b),E=new Ee(z,O,h.paths,(e,t)=>f.publish(e,t)),x=new er(function(e=process.env){return{controlMode:"controlled"===e.TASK_HANDOFF_CONTROL_MODE?"controlled":"standalone",nodeAgentUrl:e.TASK_HANDOFF_NODE_AGENT_URL,registrationToken:e.TASK_HANDOFF_REGISTRATION_TOKEN,instanceId:e.TASK_HANDOFF_INSTANCE_ID,instanceName:e.TASK_HANDOFF_INSTANCE_NAME||e.HOSTNAME||"controlled-instance",projectId:e.TASK_HANDOFF_PROJECT_ID,nodeId:e.TASK_HANDOFF_NODE_ID,runtimeId:e.TASK_HANDOFF_RUNTIME_ID,imageId:e.TASK_HANDOFF_IMAGE_ID,heartbeatIntervalMs:Number(e.TASK_HANDOFF_HEARTBEAT_INTERVAL_MS)||1e4}}(),()=>ii(S,y,v,h.paths,I,z)),k=l({logger:e.logger??!0,bodyLimit:67108864});await k.register(u),function(e,t){e.addHook("preHandler",async(e,s)=>{if(t.enabled&&"/api/health"!==e.url&&"/api/auth/status"!==e.url&&e.url.startsWith("/api/")&&function(e){const t=(e.headers.authorization||"").match(/^Bearer\s+(.+)$/i);if(t?.[1])return t[1];try{return new URL(e.url,"http://localhost").searchParams.get("token")||void 0}catch{return}}(e)!==t.token)return s.code(401).send({error:{code:"UNAUTHORIZED",message:"Missing or invalid web token."}})})}(k,g),y.on("start",e=>f.publish("receiver.started",e)),y.on("exit",e=>f.publish("receiver.exited",e)),k.addHook("onReady",async()=>{x.enabled()&&await x.start()}),k.addHook("onClose",async()=>{x.stop(),E.stop()});let D="";const C=process.env.TASK_HANDOFF_INSTANCE_ID||"standalone",P=`ais_${C}_${o.randomUUID()}`,F=`aps_${C}_${o.randomUUID()}`;let R=0,M={runningCount:0,waitingCount:0,staleCount:0,sessions:[],updatedAt:d};const j=[],L=new Set,H=new Map;let $,U="",q=0;const V={aiDiscoveryUnchanged:0,aiDiscoveryCorrections:0,appUnchanged:0},B=[];let K=Di([]);const G=new Tn,W=new Zn(I),X=new kn(I);b.register(W),b.register(X),G.register(new Nn),G.register(X),G.register(new zn),G.register(W);const J=()=>{const e=S.sharedCodexAppServerInfo();return e?[...S.listSessions(),{id:"__shared_codex_app_server__",appId:"codex",title:"Codex app-server",status:"running",createdAt:d,ai:{appServer:e}}]:S.listSessions()},Y=new Bi(async()=>{const e=J();I.reconcileAppSessionBindings(e),await G.refresh({registry:I,appSessions:e})},e=>ee(e)),Q=(e="discovery-scan")=>Y.request(e),Z=()=>{const e=Date.now()-36e5;for(;j.length&&j[0].createdAtMs<e;)j.shift()},ee=(e="provider-event")=>{const t=I.boundSnapshot(J()),s=JSON.stringify(t.sessions);if(s!==D){D=s,M=t,R+=1;const n=((e,t)=>({meta:{streamId:P,instanceId:C,nodeId:process.env.TASK_HANDOFF_NODE_ID,revision:R,previousRevision:R>0?R-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=>{j.push({type:os,payload:e,createdAtMs:Date.now()}),Z()})(n),f.publish(os,n),k.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"),E.handleAiSessions(t),"discovery-scan"===e&&(V.aiDiscoveryCorrections+=1,k.log.info({instanceId:C,streamId:P,revision:R,correctionCount:V.aiDiscoveryCorrections},"ai-session.discovery.corrected"))}else"discovery-scan"===e&&(V.aiDiscoveryUnchanged+=1,k.log.info({instanceId:C,streamId:P,revision:R,unchangedCount:V.aiDiscoveryUnchanged},"ai-session.discovery.unchanged"))},te=()=>{const e=Date.now()-Ai;for(;B.length&&B[0].createdAtMs<e;)B.shift()},se=e=>({streamId:F,instanceId:C,nodeId:process.env.TASK_HANDOFF_NODE_ID,revision:q,previousRevision:q>0?q-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}),ae=(e,t,s)=>({meta:se(s),sessionId:e,tombstone:t,expiresAt:new Date(Date.now()+Ai).toISOString()}),de=(e,t,s)=>{(e=>{B.push({...e,createdAtMs:Date.now()}),te()})(e),f.publish(e.type,e.payload),k.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")},ce=(e,t)=>{te();const s=q,n=B[0]?.payload.meta.revision??s+1;if(e!==F||t>s)return ki.parse({streamId:F,instanceId:C,sinceRevision:t,latestRevision:s,earliestRetainedRevision:n,syncRequired:!0,events:[]});if(t===s)return ki.parse({streamId:F,instanceId:C,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 ki.parse({streamId:F,instanceId:C,sinceRevision:t,latestRevision:s,earliestRetainedRevision:n,syncRequired:o,events:o?[]:r.map(e=>({type:e.type,payload:e.payload}))})},pe=(e,t)=>{Z();const s=R,n=j[0]?.payload.meta.revision??s+1;if(e!==P||t>s)return Fs.parse({streamId:P,instanceId:C,sinceRevision:t,latestRevision:s,earliestRetainedRevision:n,syncRequired:!0,events:[]});if(t===s)return Fs.parse({streamId:P,instanceId:C,sinceRevision:t,latestRevision:s,earliestRetainedRevision:n,syncRequired:!1,events:[]});const r=j.filter(e=>e.payload.meta.revision>t),i=r[0]?.payload.meta.revision,o=!r.length||i!==t+1;return Fs.parse({streamId:P,instanceId:C,sinceRevision:t,latestRevision:s,earliestRetainedRevision:n,syncRequired:o,events:o?[]:r.map(e=>({type:e.type,payload:e.payload}))})},ue=async e=>{if(L.has(e))return;const t=I.get(e);if(t&&"idle"===t.status&&I.nextQueuedMessage(e)){L.add(e);try{await b.sendNextQueuedMessage(e)}catch(t){k.log.warn({err:t,sessionId:e},"failed to drain AI session message queue")}finally{L.delete(e),ee("control-action")}}};let le;const he=I.onChange(()=>{le||(le=setTimeout(()=>{le=void 0,ee()},Number(process.env.TASK_HANDOFF_AI_SESSION_PUBLISH_DEBOUNCE_MS)||50));for(const e of I.list()){const t=H.get(e.id);H.set(e.id,e.status),t&&"idle"!==t&&"idle"===e.status&&e.queue.pendingCount>0&&ue(e.id)}});k.addHook("onReady",async()=>{if(E.start(),ro("TASK_HANDOFF_CODEX_APP_SERVER",!1))try{S.ensureSharedCodexAppServer()}catch(e){k.log.warn({err:e},"failed to start shared Codex app-server")}}),k.addHook("onReady",async()=>{await Q("startup"),$=setInterval(()=>{Q()},Number(process.env.TASK_HANDOFF_AI_SESSION_SCAN_INTERVAL_MS)||3e4)}),k.addHook("onClose",async()=>{he(),le&&(clearTimeout(le),le=void 0),$&&(clearInterval($),$=void 0),W.stop(),X.stop()});const ge=(e,t)=>{(e=>{const t=Di(S.listSessions()),s=JSON.stringify(t.sessions);if(s===U)return V.appUnchanged+=1,void k.log.info({instanceId:C,streamId:F,revision:q,reason:e,sessionCount:t.sessions.length,unchangedCount:V.appUnchanged},"app-session.snapshot.skipped-unchanged");U=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===q||1!==n.length){q+=1;const s=((e,t)=>({meta:{streamId:F,instanceId:C,nodeId:process.env.TASK_HANDOFF_NODE_ID,revision:q,previousRevision:q>0?q-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);de({type:vi,payload:s},t,e)}else{q+=1;const s=n[0],r="removed"===s.type?{type:Ii,payload:ae(s.sessionId,s.tombstone,e)}:{type:Si,payload:ne(s.session,e)};de(r,t,e)}K=t})(e),Q("app-session-recovered"===e?"discovery-scan":e).catch(s=>{k.log.warn({err:s,reason:e,sessionId:t.id},"failed to refresh AI sessions after app session event")})};y.on("log",e=>f.publish("receiver.log",{message:e})),S.on("created",e=>ge("app-session-created",e)),S.on("updated",e=>ge("app-session-updated",e)),S.on("deleted",e=>ge("app-session-deleted",e)),k.addHook("onClose",async()=>{await y.stopAndWait(),S.stopAll()}),!Qr()&&(e.receiverAutoStart??ro("TASK_HANDOFF_RECEIVER_AUTO_START"))&&k.addHook("onReady",async()=>{cr(h.paths.channelsDir,h.paths.configPath),y.start()});const fe=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}}();fe?await k.register(p,{root:fe,prefix:"/api/novnc/",decorateReply:!1}):k.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 ye=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(ye)&&await k.register(p,{root:ye,prefix:"/"}),k.get("/api/health",async()=>({data:{ok:!0,version:Jr(),startedAt:d}})),k.get("/api/auth/status",async()=>({data:{enabled:g.enabled,source:g.source,tokenFile:g.tokenFile}})),k.get("/api/events",{websocket:!0},e=>{f.connect(e),f.send(e,"streams.hello",{protocolVersion:1,streams:[{topic:"ai.sessions",instanceId:C,streamId:P,latestRevision:R,earliestRetainedRevision:j[0]?.payload.meta.revision??R+1},{topic:"app.sessions",instanceId:C,streamId:F,latestRevision:q,earliestRetainedRevision:B[0]?.payload.meta.revision??q+1}]})}),k.get("/api/status",async()=>{const e=A();return{data:{receiverReady:y.status().running,receiver:y.status(),socketPath:r,defaultConversationId:Number(e.defaultConversationId)||T,pendingTaskCount:await ei(v),runningAppCount:S.runningSessionCount(),storage:h.paths}}}),k.get("/api/instance/status",async()=>{const e=A(),t=await ii(S,y,v,h.paths,I,z);return{data:{id:process.env.TASK_HANDOFF_INSTANCE_ID,name:process.env.TASK_HANDOFF_INSTANCE_NAME||n.hostname(),...t,defaultConversationId:Number(e.defaultConversationId)||T,startedAt:d}}}),k.get("/api/instance/capabilities",async()=>({data:ni(S)})),k.get("/api/workspace/status",async()=>({data:si(h.paths)})),k.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:pe(e.query.streamId,s)}:t.code(400).send({error:{code:"AI_SESSION_DELTA_INVALID",message:"streamId is required with sinceRevision."}}):{data:{streamId:P,revision:R,lastEventAt:j.at(-1)?.payload.meta.generatedAt||d,snapshot:M}}}),k.get("/api/ai-sessions/state",async()=>({data:{streamId:P,revision:R,lastEventAt:j.at(-1)?.payload.meta.generatedAt||d,snapshot:M}})),k.get("/api/triggers",async()=>({data:z.list()})),k.get("/api/triggers/:configHash",async(e,t)=>{const s=z.get(e.params.configHash);return s?{data:s}:t.code(404).send({error:{code:"TRIGGER_NOT_FOUND",message:"Trigger not found."}})}),k.post("/api/triggers",async(e,t)=>{try{const t=Zi.parse(e.body||{}),s=z.create(t);return E.restart(),f.publish("trigger.created",s),f.publish("trigger.updated",ri(z)),{data:s}}catch(e){return t.code(400).send({error:{code:"TRIGGER_INVALID",message:so(e)}})}}),k.patch("/api/triggers/:configHash",async(e,t)=>{try{const s=eo.parse(e.body||{}),n=z.patch(e.params.configHash,s);return n?(E.restart(),f.publish("trigger.updated",z.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:so(e)}})}}),k.delete("/api/triggers/:configHash",async(e,t)=>{const s=z.delete(e.params.configHash);return s?(E.restart(),f.publish("trigger.deleted",{configHash:e.params.configHash}),f.publish("trigger.updated",ri(z)),{data:{deleted:s}}):t.code(404).send({error:{code:"TRIGGER_NOT_FOUND",message:"Trigger not found."}})}),k.delete("/api/triggers/:configHash/deployments/:deploymentId",async(e,t)=>{const s=z.deleteDeployment(e.params.configHash,e.params.deploymentId);return s?(E.restart(),f.publish("trigger.deployment.deleted",{configHash:e.params.configHash,deploymentId:e.params.deploymentId}),f.publish("trigger.updated",ri(z)),{data:{deleted:s}}):t.code(404).send({error:{code:"TRIGGER_DEPLOYMENT_NOT_FOUND",message:"Trigger deployment not found."}})}),k.post("/api/triggers/:configHash/enable",async(e,t)=>{const s=z.setEnabled(e.params.configHash,!0);return s?(E.restart(),f.publish("trigger.enabled",s),f.publish("trigger.updated",ri(z)),{data:s}):t.code(404).send({error:{code:"TRIGGER_NOT_FOUND",message:"Trigger not found."}})}),k.post("/api/triggers/:configHash/disable",async(e,t)=>{const s=z.setEnabled(e.params.configHash,!1);return s?(E.restart(),f.publish("trigger.disabled",s),f.publish("trigger.updated",ri(z)),{data:s}):t.code(404).send({error:{code:"TRIGGER_NOT_FOUND",message:"Trigger not found."}})}),k.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=to.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})}(z,O,e.params.configHash,e.body||{});return f.publish("trigger.run.completed",t),f.publish("trigger.updated",ri(z)),{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:so(s)}),t.code("TRIGGER_NOT_FOUND"===n?404:"RECEIVER_UNAVAILABLE"===n?503:400).send({error:{code:n,message:so(s)}})}}),k.get("/api/triggers/runs",async()=>({data:z.list().recentRuns})),k.get("/api/ai-sessions/:id",async(e,t)=>{const s=I.get(e.params.id);return s?{data:s}:t.code(404).send({error:{code:"AI_SESSION_NOT_FOUND",message:"AI session not found."}})}),k.get("/api/ai-sessions/:id/turns",async(e,t)=>{const s=I.get(e.params.id);if(!s)return t.code(404).send({error:{code:"AI_SESSION_NOT_FOUND",message:"AI session not found."}});const n=String(e.query.afterTurnId||"").trim(),r=Number(e.query.afterRevision),i=s.turns||[],o=n?i.findIndex(e=>e.id===n):-1,a=i.filter(e=>!n||o<0||(e.id!==n?i.findIndex(t=>t.id===e.id)>o:!!Number.isFinite(r)&&e.revision>r)),d=a.at(-1);return{data:{sessionId:s.id,turns:a,nextCursor:d?{turnId:d.id,revision:d.revision}:n?{turnId:n,revision:Number.isFinite(r)?r:0}:void 0}}}),k.get("/api/ai-sessions/:id/transcript",async(e,t)=>{const s=I.get(e.params.id);if(!s?.transcriptPath)return t.code(404).send({error:{code:"AI_SESSION_TRANSCRIPT_NOT_FOUND",message:"AI session transcript not found."}});try{return{data:ao(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)}})}}),k.post("/api/ai-sessions/:id/messages",async(e,t)=>{try{const t=vs.parse(e.body||{}),s=zs.parse(await b.sendMessage(e.params.id,t));return ee("control-action"),{data:s}}catch(e){return no(t,e)}}),k.get("/api/ai-sessions/:id/queue",async(e,t)=>{const s=I.get(e.params.id);return s?{data:s.queue}:t.code(404).send({error:{code:"AI_SESSION_NOT_FOUND",message:"AI session not found."}})}),k.post("/api/ai-sessions/:id/queue/:queueId/steer",async(e,t)=>{try{const t=zs.parse(await b.steerQueuedMessage(e.params.id,e.params.queueId));return ee("control-action"),{data:t}}catch(e){return no(t,e)}}),k.post("/api/ai-sessions/:id/queue/:queueId/retry",async(e,t)=>{try{const t=b.retryQueuedMessage(e.params.id,e.params.queueId);return ee("control-action"),{data:t}}catch(e){return no(t,e)}}),k.delete("/api/ai-sessions/:id/queue/:queueId",async(e,t)=>{try{const t=b.removeQueuedMessage(e.params.id,e.params.queueId);return ee("control-action"),{data:t}}catch(e){return no(t,e)}}),k.patch("/api/ai-sessions/:id/queue/reorder",async(e,t)=>{try{const t=Is.parse(e.body||{}),s=b.reorderQueuedMessages(e.params.id,t.queueIds);return ee("control-action"),{data:s}}catch(e){return no(t,e)}}),k.post("/api/ai-sessions/:id/interrupt",async(e,t)=>{try{const t=zs.parse(await b.interrupt(e.params.id));return ee("control-action"),{data:t}}catch(e){return no(t,e)}}),k.post("/api/ai-sessions/:id/approval",async(e,t)=>{try{const t=Ss.parse(e.body||{}),s=zs.parse(await b.resolveApproval(e.params.id,t.decision));return ee("control-action"),{data:s}}catch(e){return no(t,e)}}),k.get("/api/diagnostics",async()=>({data:{...Zr(h.paths,fe),sessionStreams:{ai:{streamId:P,revision:R,retainedEventCount:j.length,discoveryUnchanged:V.aiDiscoveryUnchanged,discoveryCorrections:V.aiDiscoveryCorrections},app:{streamId:F,revision:q,retainedEventCount:B.length,unchangedRefreshes:V.appUnchanged}}}})),k.get("/api/settings",async()=>({data:A()})),function(e,{conversations:t,events:s}){e.get("/api/conversations",async()=>({data:t.list()})),e.post("/api/conversations",async(e,n)=>{try{const n=t.create(e.body||{});return s.publish("conversation.created",n),{data:n}}catch(e){const t=tr(e,"CONVERSATION_CREATE_FAILED");return n.code("CONVERSATION_EXISTS"===t?409:400).send({error:{code:t,message:sr(e)}})}}),e.get("/api/conversations/:id",async(e,s)=>{try{const n=t.get(ze(e.params.id));return n?{data:n}:s.code(404).send({error:{code:"CONVERSATION_NOT_FOUND",message:"Conversation not found."}})}catch(e){const t=tr(e,"CONVERSATION_GET_FAILED");return s.code("CONVERSATION_ID_INVALID"===t?400:404).send({error:{code:t,message:sr(e)}})}}),e.patch("/api/conversations/:id",async(e,n)=>{try{const n=t.update(ze(e.params.id),e.body||{});return s.publish("conversation.updated",n),{data:n}}catch(e){const t=tr(e,"CONVERSATION_UPDATE_FAILED");return n.code("CONVERSATION_NOT_FOUND"===t?404:400).send({error:{code:t,message:sr(e)}})}}),e.post("/api/conversations/:id/use",async(e,n)=>{try{const n=t.use(ze(e.params.id));return s.publish("conversation.default.updated",n),{data:n}}catch(e){const t=tr(e,"CONVERSATION_USE_FAILED");return n.code("CONVERSATION_NOT_FOUND"===t?404:400).send({error:{code:t,message:sr(e)}})}}),e.post("/api/conversations/:id/close",async(e,n)=>{try{const n=t.close(ze(e.params.id));return s.publish("conversation.closed",n),{data:n}}catch(e){const t=tr(e,"CONVERSATION_CLOSE_FAILED");return n.code("CONVERSATION_NOT_FOUND"===t?404:400).send({error:{code:t,message:sr(e)}})}}),e.post("/api/conversations/:id/reopen",async(e,n)=>{try{const n=t.reopen(ze(e.params.id));return s.publish("conversation.reopened",n),{data:n}}catch(e){const t=tr(e,"CONVERSATION_REOPEN_FAILED");return n.code("CONVERSATION_NOT_FOUND"===t?404:400).send({error:{code:t,message:sr(e)}})}}),e.delete("/api/conversations/:id",async(e,n)=>{try{const n=t.delete(ze(e.params.id));return s.publish("conversation.deleted",n),{data:n}}catch(e){const t=tr(e,"CONVERSATION_DELETE_FAILED"),s="CONVERSATION_NOT_FOUND"===t?404:"CONVERSATION_DEFAULT"===t?409:400;return n.code(s).send({error:{code:t,message:sr(e)}})}})}(k,{conversations:w,events:f}),k.post("/api/receiver/start",async(e,t)=>Qr()?t.code(409).send({error:{code:"RECEIVER_MANAGED_BY_CONTROL_PLANE",message:"Receiver chat bindings are managed by the control plane while this instance is node-agent controlled."}}):(cr(h.paths.channelsDir,h.paths.configPath),{data:y.start()})),k.post("/api/receiver/stop",async()=>({data:y.stop()})),k.get("/api/receiver/logs",async e=>{const t=Number(e.query.maxBytes||65536),s=Number.isFinite(t)?Math.min(Math.max(1024,t),524288):65536;return{data:y.readLogs(s)}}),k.get("/api/receiver/status",async()=>({data:{...y.status(),pendingCount:await ei(v)}})),k.post("/api/receiver/messages",async(e,t)=>{try{const s=Qi.parse(e.body);return s.message.text.trim()?{data:await v.message({channel:s.source.channel,chatSessionId:s.source.chatSessionId,userId:s.source.userId,text:s.message.text,attachments:s.message.attachments,conversationId:s.routing.conversationId})}:t.code(400).send({error:{code:"RECEIVER_MESSAGE_INVALID",message:"Message text is required."}})}catch(e){const s=e&&"object"==typeof e&&"code"in e?String(e.code):"RECEIVER_MESSAGE_INVALID";return t.code("RECEIVER_UNAVAILABLE"===s?503:400).send({error:{code:s,message:so(e)}})}});const ve=async(e,t)=>{try{return{data:await v.pendingList()}}catch(e){const s=e&&"object"==typeof e&&"code"in e?String(e.code):"RECEIVER_CONTROL_FAILED";return t.code("RECEIVER_UNAVAILABLE"===s?503:400).send({error:{code:s,message:e instanceof Error?e.message:String(e)}})}};k.get("/api/tasks/pending",ve),k.get("/api/receiver/pending",ve),k.post("/api/tasks/:id/reply",async(e,t)=>{const s=Number(e.params.id),n=e.body?.markdown;if(!Number.isInteger(s)||s<=0||!n?.trim())return t.code(400).send({error:{code:"TASK_REPLY_INVALID",message:"Task id and markdown are required."}});try{return{data:await v.reply(s,n)}}catch(e){const s=e&&"object"==typeof e&&"code"in e?String(e.code):"RECEIVER_CONTROL_FAILED";return t.code("PENDING_TASK_NOT_FOUND"===s?404:"RECEIVER_UNAVAILABLE"===s?503:400).send({error:{code:s,message:e instanceof Error?e.message:String(e)}})}}),k.post("/api/receiver/pending/:id/reply",async(e,t)=>{const s=Number(e.params.id),n=e.body?.markdown;if(!Number.isInteger(s)||s<=0||!n?.trim())return t.code(400).send({error:{code:"TASK_REPLY_INVALID",message:"Task id and markdown are required."}});try{return{data:await v.reply(s,n)}}catch(e){const s=e&&"object"==typeof e&&"code"in e?String(e.code):"RECEIVER_CONTROL_FAILED";return t.code("PENDING_TASK_NOT_FOUND"===s?404:"RECEIVER_UNAVAILABLE"===s?503:400).send({error:{code:s,message:e instanceof Error?e.message:String(e)}})}}),k.post("/api/tasks/:id/drop",async(e,t)=>{const s=Number(e.params.id);if(!Number.isInteger(s)||s<=0)return t.code(400).send({error:{code:"TASK_ID_INVALID",message:"Task id must be a positive integer."}});try{return{data:await v.drop(s)}}catch(e){const s=e&&"object"==typeof e&&"code"in e?String(e.code):"RECEIVER_CONTROL_FAILED";return t.code("PENDING_TASK_NOT_FOUND"===s?404:"RECEIVER_UNAVAILABLE"===s?503:400).send({error:{code:s,message:e instanceof Error?e.message:String(e)}})}});for(const[e,t]of[["approve","allow"],["deny","deny"],["skip","skip"]])k.post(`/api/tasks/:id/${e}`,async(e,s)=>{const n=Number(e.params.id);if(!Number.isInteger(n)||n<=0)return s.code(400).send({error:{code:"TASK_ID_INVALID",message:"Task id must be a positive integer."}});try{return{data:await v.approval(n,t)}}catch(e){const t=e&&"object"==typeof e&&"code"in e?String(e.code):"RECEIVER_CONTROL_FAILED";return s.code("PENDING_TASK_NOT_FOUND"===t?404:"RECEIVER_UNAVAILABLE"===t?503:400).send({error:{code:t,message:e instanceof Error?e.message:String(e)}})}}),k.post(`/api/receiver/pending/:id/${e}`,async(e,s)=>{const n=Number(e.params.id);if(!Number.isInteger(n)||n<=0)return s.code(400).send({error:{code:"TASK_ID_INVALID",message:"Task id must be a positive integer."}});try{return{data:await v.approval(n,t)}}catch(e){const t=e&&"object"==typeof e&&"code"in e?String(e.code):"RECEIVER_CONTROL_FAILED";return s.code("PENDING_TASK_NOT_FOUND"===t?404:"RECEIVER_UNAVAILABLE"===t?503:400).send({error:{code:t,message:e instanceof Error?e.message:String(e)}})}});k.post("/api/receiver/pending/:id/approval",async(e,t)=>{const s=Number(e.params.id),n=e.body?.decision;if(!Number.isInteger(s)||s<=0||!n)return t.code(400).send({error:{code:"TASK_APPROVAL_INVALID",message:"Task id and approval decision are required."}});try{return{data:await v.approval(s,n)}}catch(e){const s=e&&"object"==typeof e&&"code"in e?String(e.code):"RECEIVER_CONTROL_FAILED";return t.code("PENDING_TASK_NOT_FOUND"===s?404:"RECEIVER_UNAVAILABLE"===s?503:400).send({error:{code:s,message:e instanceof Error?e.message:String(e)}})}}),k.get("/api/apps/catalog",async()=>({data:S.catalog()})),k.get("/api/config-sync/presets",async()=>({data:Tr()})),k.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=Wi.parse(e.body||{});return{data:zr(s,e.params.preset,t.preset)}}catch(e){const s=e&&"object"==typeof e?e:{};return t.code("number"==typeof s.statusCode?s.statusCode:500).send({error:{code:"string"==typeof s.code?s.code:"CONFIG_SYNC_FAILED",message:e instanceof Error?e.message:String(e)}})}}),k.get("/api/apps/catalog/custom",async(e,t)=>{const s=S.customCatalog();return s.error||!s.data?t.code(400).send({error:s.error||{code:"APP_CATALOG_INVALID",message:"Custom app catalog is invalid."}}):{data:s.data}}),k.patch("/api/apps/catalog/custom",async(e,t)=>{try{return{data:S.saveCustomCatalog(e.body?.items||[])}}catch(e){return t.code(400).send({error:{code:"APP_CATALOG_INVALID",message:e instanceof Error?e.message:String(e)}})}}),k.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:ce(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:q,lastEventAt:B.at(-1)?.payload.meta.generatedAt||d,snapshot:Di(S.listSessions())}}}),k.get("/api/apps/sessions/state",async()=>({data:{streamId:F,revision:q,lastEventAt:B.at(-1)?.payload.meta.generatedAt||d,snapshot:Di(S.listSessions())}})),k.post("/api/apps/sessions",async(e,t)=>{try{const t=function(e={}){const t=Xi.parse(e||{}),s={};return t.title&&(s.title=t.title),t.args&&(s.args=t.args),t.cwd&&(s.cwd=t.cwd),t.env&&(s.env=t.env),t.display&&(s.display=t.display),t.displayTarget&&(s.displayTarget=t.displayTarget),{appId:t.appId||"terminal-tty",options:s}}(e.body);return{data:S.start(t.appId,t.options)}}catch(e){if(e instanceof i.z.ZodError)return t.code(400).send({error:{code:"APP_LAUNCH_INVALID",message:so(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)}})}}),k.get("/api/apps/sessions/:id",async(e,t)=>{const s=S.getSession(e.params.id);return s?{data:s}:t.code(404).send({error:{code:"APP_SESSION_NOT_FOUND",message:"App session not found."}})}),k.patch("/api/apps/sessions/:id",async(e,t)=>{try{const{title:t}=Yi.parse(e.body||{});return{data:S.rename(e.params.id,t)}}catch(e){if(e instanceof i.z.ZodError)return t.code(400).send({error:{code:"APP_SESSION_UPDATE_INVALID",message:so(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)}})}}),k.post("/api/apps/sessions/:id/stop",async(e,t)=>{try{return{data:S.stop(e.params.id)}}catch(e){return t.code(404).send({error:{code:"APP_SESSION_NOT_FOUND",message:e instanceof Error?e.message:String(e)}})}}),k.post("/api/apps/sessions/:id/restart",async(e,t)=>{try{return{data:S.restart(e.params.id)}}catch(e){const s=e&&"object"==typeof e&&"code"in e?String(e.code):"APP_RESTART_FAILED";return t.code("APP_SESSION_NOT_FOUND"===s?404:400).send({error:{code:s,message:e instanceof Error?e.message:String(e)}})}}),k.post("/api/apps/sessions/:id/display",async(e,t)=>{try{return{data:S.resizeDisplay(e.params.id,Ji.parse(e.body||{}))}}catch(e){const s=e&&"object"==typeof e&&"code"in e?String(e.code):"APP_DISPLAY_RESIZE_FAILED";return e instanceof i.z.ZodError?t.code(400).send({error:{code:"APP_DISPLAY_INVALID",message:so(e)}}):t.code("APP_DISPLAY_NOT_FOUND"===s?404:400).send({error:{code:s,message:e instanceof Error?e.message:String(e)}})}}),k.delete("/api/apps/sessions/:id",async(e,t)=>{try{return{data:await S.delete(e.params.id)}}catch(e){const s=e&&"object"==typeof e&&"code"in e?String(e.code):"APP_DELETE_FAILED";return t.code("APP_SESSION_NOT_FOUND"===s?404:400).send({error:{code:s,message:e instanceof Error?e.message:String(e)}})}}),k.get("/api/apps/sessions/:id/logs",async(e,t)=>{try{const t=Number(e.query.maxBytes||65536),s=Number.isFinite(t)?Math.min(Math.max(1024,t),524288):65536;return{data:S.readLogs(e.params.id,s)}}catch(e){const s=e&&"object"==typeof e&&"code"in e?String(e.code):"APP_LOGS_FAILED";return t.code("APP_SESSION_NOT_FOUND"===s?404:400).send({error:{code:s,message:e instanceof Error?e.message:String(e)}})}}),k.get("/api/apps/sessions/:id/screenshot",async(e,t)=>{try{const s=S.screenshot(e.params.id);return t.header("Cache-Control","no-store").type("image/png").send(s)}catch(e){const s=e&&"object"==typeof e&&"code"in e?String(e.code):"APP_SCREENSHOT_FAILED",n="APP_SESSION_NOT_FOUND"===s?404:"APP_SCREENSHOT_UNAVAILABLE"===s?409:400;return t.code(n).send({error:{code:s,message:e instanceof Error?e.message:String(e)}})}}),k.get("/api/apps/sessions/:id/snapshot",async(e,t)=>{try{const s=S.screenshot(e.params.id);return t.header("Cache-Control","no-store").type("image/png").send(s)}catch(e){const s=e&&"object"==typeof e&&"code"in e?String(e.code):"APP_SNAPSHOT_FAILED",n="APP_SESSION_NOT_FOUND"===s?404:"APP_SCREENSHOT_UNAVAILABLE"===s?409:400;return t.code(n).send({error:{code:s,message:e instanceof Error?e.message:String(e)}})}}),k.get("/api/apps/sessions/:id/automation",async(e,t)=>{try{return{data:await S.automationStatus(e.params.id)}}catch(e){const s=e&&"object"==typeof e&&"code"in e?String(e.code):"APP_AUTOMATION_FAILED",n="APP_SESSION_NOT_FOUND"===s?404:"APP_AUTOMATION_UNAVAILABLE"===s?409:400;return t.code(n).send({error:{code:s,message:e instanceof Error?e.message:String(e)}})}}),k.get("/api/apps/sessions/:id/tty",{websocket:!0},(e,t)=>{S.attachTty(t.params.id,e)}),k.get("/api/apps/sessions/:id/vnc",{websocket:!0},(e,t)=>{const s=S.vncTarget(t.params.id);if(!s)return e.send(JSON.stringify({error:{code:"VNC_SESSION_NOT_FOUND",message:"VNC session not found."}})),void e.close();const n=a.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 Se=async(e,t)=>{const s=S.webTarget(e.params.id);if(!s)return function(e,t,s,n=502){return e.code(n).send({error:{code:t,message:s}})}(t,"WEB_SESSION_NOT_FOUND","Web session not found.",404);const n="kasmvnc"===S.getSession(e.params.id)?.vnc?.backend,r=n?{authorization:pi()}:{};t.hijack();const i=function(e){if(void 0!==e)return Buffer.isBuffer(e)||"string"==typeof e?e:JSON.stringify(e)}(e.body),o=void 0!==i||"GET"===e.method||"HEAD"===e.method||"OPTIONS"===e.method,a=Date.now(),d=`http://${s.host}:${s.port}`,p=new URL(ci(e.params.id,e.raw.url),`${d}/`).toString();for(;;)try{const a=await m.proxyFetch(d,p,qi({method:e.method,headers:ui(e.headers,s.host,s.port,r),requestBody:i,rawRequest:e.raw,streamRawRequest:void 0===i&&!o})),u=fi(a.headers);if("HEAD"!==e.method&&n&&hi(u)){const e=Buffer.from(gi(Buffer.from(await a.arrayBuffer()),u),"utf8"),s={...u,"content-length":String(e.byteLength)};delete s.etag,t.raw.writeHead(a.status||502,a.statusText,s),t.raw.end(e);break}if(t.raw.writeHead(a.status||502,a.statusText,yi(a.headers)),!a.body||"HEAD"===e.method){t.raw.end();break}await c.pipeline(Vi(a.body),t.raw);break}catch(e){if(o&&di(e)&&Date.now()-a<8e3){await ai(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};k.route({method:"GET",url:"/api/apps/sessions/:id/web/*",wsHandler:(e,t)=>{const s=S.webTarget(t.params.id);if(!s)return e.send(JSON.stringify({error:{code:"WEB_SESSION_NOT_FOUND",message:"Web session not found."}})),void e.close();const n=`http://${s.host}:${s.port}`,r="kasmvnc"===S.getSession(t.params.id)?.vnc?.backend?{authorization:pi(),origin:n,"sec-websocket-origin":t.headers.origin||n}:{origin:n},i=Date.now(),o=`ws://${s.host}:${s.port}${ci(t.params.id,t.raw.url)}`,a=function(e){const t=e["sec-websocket-protocol"],s=(Array.isArray(t)?t:t?[t]:[]).flatMap(e=>e.split(",").map(e=>e.trim()).filter(Boolean));return s.length?s:void 0}(t.headers)||("kasmvnc"===S.getSession(t.params.id)?.vnc?.backend?["binary"]:void 0),d=()=>{if(e.readyState!==e.OPEN)return;const n=new Ui(o,a,{headers:li(t.headers,s.host,s.port,r)});!function(e,t,s={}){const n=s.pendingFrameLimit??256;let r=!1,i=ji(t);const o=[],a=[];let d;const c=()=>{d&&(clearTimeout(d),d=void 0)},p=(s,r)=>{if(s.length>=n)return Li(e,1011,"WebSocket bridge pending frame limit exceeded."),void Li(t,1011,"WebSocket bridge pending frame limit exceeded.");s.push(r)};s.upstreamOpenTimeoutMs&&!i&&(d=setTimeout(()=>{i||r||(Li(e,1011,"Upstream websocket did not open."),Li(t))},s.upstreamOpenTimeoutMs)),e.on("open",()=>$i(e,a)),t.on("open",()=>{c(),i=!0,s.onUpstreamOpen?.(),$i(t,o)}),e.on("message",(e,s=!1)=>{const n={data:e,isBinary:Boolean(s)};ji(t)?Hi(t,n):p(o,n)}),t.on("message",(t,s=!1)=>{const n={data:t,isBinary:Boolean(s)};ji(e)?Hi(e,n):p(a,n)}),t.on("close",(t,n)=>{c(),s.onUpstreamClose?.(t,n),(i||r||!s.onUpstreamCloseBeforeOpen?.())&&Li(e,t,n)}),t.on("error",t=>{s.onUpstreamError?.(t),(i||r||!s.onUpstreamErrorBeforeOpen?.(t))&&Li(e)}),e.on("close",(e,n)=>{c(),r=!0,s.onClientClose?.(e,n),Li(t,e,n)}),e.on("error",e=>{c(),r=!0,s.onClientError?.(e),Li(t,1011,"WebSocket bridge client failed.")})}(e,n,{onUpstreamCloseBeforeOpen:()=>Date.now()-i<8e3&&(ai(200).then(d),!0),onUpstreamErrorBeforeOpen:e=>di(e)})};d()},handler:Se});for(const e of["DELETE","OPTIONS","PATCH","POST","PUT"])k.route({method:e,url:"/api/apps/sessions/:id/web/*",handler:Se});return k.get("/api/apps/sessions/:id/novnc/vnc.html",async(e,t)=>{const s=S.getSession(e.params.id);if(!s?.vnc)return t.code(404).send({error:{code:"VNC_SESSION_NOT_FOUND",message:"VNC session not found."}});const n="remote"===e.query.resize?"remote":"scale",r=new URLSearchParams({path:s.vnc.webPath.replace(/^\//,""),autoconnect:"1",resize:n});return t.redirect(`/api/novnc/vnc.html?${r.toString()}`)}),k.patch("/api/settings",async(e,t)=>{try{const s=e.body||{},n=Number(s.defaultConversationId);if(Object.prototype.hasOwnProperty.call(s,"defaultConversationId")){if(!Number.isInteger(n)||n<=0)return t.code(400).send({error:{code:"SETTINGS_INVALID_CONVERSATION",message:"Default conversation id must be a positive integer."}});if(!w.get(n))return t.code(404).send({error:{code:"CONVERSATION_NOT_FOUND",message:"Default conversation does not exist."}})}const r=_(s);return Number.isInteger(n)&&n>0&&w.use(n),{data:r}}catch(e){return t.code(400).send({error:{code:"SETTINGS_UPDATE_FAILED",message:e instanceof Error?e.message:String(e)}})}}),k.get("/api/channels",async()=>({data:[Ki(h.channel("telegram").load.bind(h.channel("telegram"))),Ki(h.channel("wechat").load.bind(h.channel("wechat"))),Ki(h.channel("dingding").load.bind(h.channel("dingding")))]})),k.get("/api/channels/:channel/:instanceId",async(e,t)=>{const s=e.params.channel;if(!["telegram","wechat","dingding"].includes(s))return t.code(404).send({error:{code:"CHANNEL_NOT_FOUND",message:"Channel not found."}});const n=h.channel(s,e.params.instanceId);return{data:Ki(n.load.bind(n))}}),k.patch("/api/channels/:channel/:instanceId",async(e,t)=>{const s=e.params.channel;if(!["telegram","wechat","dingding"].includes(s))return t.code(404).send({error:{code:"CHANNEL_NOT_FOUND",message:"Channel not found."}});const n=h.channel(s,e.params.instanceId).patch({...oo(e.body),channel:s,instanceId:e.params.instanceId,schemaVersion:1});return dr(n,h.paths.configPath),{data:Ki(()=>n)}}),k.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(ye,"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.")}),k}function po(e){const t=Number(e);if(!Number.isInteger(t)||t<=0)throw new Error("Conversation id must be a positive integer.");return t}function uo(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",uo,Number(process.env.TASK_HANDOFF_WEB_PORT)||8080).option("-s, --socket <path>","Unix socket path",N).option("--static-dir <path>","Web UI static directory",process.env.TASK_HANDOFF_WEB_STATIC_DIR||s.resolve(__dirname,"..","ui")).option("--receiver-auto-start","Start the receiver runtime with the web server.").action(async e=>{await async function(e={}){const t=e.host||process.env.TASK_HANDOFF_WEB_HOST||"127.0.0.1",s=Number(e.port||process.env.TASK_HANDOFF_WEB_PORT||8080),n=await co(e);return function(e){let t=!1;const s=async s=>{if(!t){t=!0;try{await e.close()}finally{process.exitCode=s?0:process.exitCode}}},n=()=>{s("SIGINT")},r=()=>{s("SIGTERM")};process.once("SIGINT",n),process.once("SIGTERM",r),e.addHook("onClose",async()=>{process.off("SIGINT",n),process.off("SIGTERM",r)})}(n),await n.listen({host:t,port:s}),n}({host:e.host,port:e.port,socketPath:e.socket,staticDir:e.staticDir,receiverAutoStart:e.receiverAutoStart})}),n.command("receiver").description("Run the controlled instance receiver.").option("-s, --socket <path>","Unix socket path",N).option("--telegram-token <token>","Telegram bot token",D).option("--telegram-chat-id <id>","Telegram target chat id",k).option("--telegram-allowed-user-ids <ids>","Comma-separated Telegram user ids allowed to control the bot",C.join(",")).option("--telegram-conversation <id>","Telegram passive conversation id",po,P).option("--wechat-token <token>","Wechat iLink bot token",L).option("--wechat-base-url <url>","Wechat iLink base URL",R).option("--wechat-chat-id <id>","Wechat target chat id",M).option("--wechat-conversation <id>","Wechat passive conversation id",po,$).option("--wechat-context-token <token>","Wechat conversation context token",j).option("--wechat-updates-buf <cursor>","Wechat getupdates cursor",H).option("--dingding-client-id <id>","DingDing stream client id",B).option("--dingding-client-secret <secret>","DingDing stream client secret",K).option("--dingding-corp-id <id>","DingDing corp id",G).option("--dingding-robot-code <code>","DingDing robot code",W).option("--dingding-card-template-id <id>","DingDing interactive card template id",X).option("--dingding-card-callback-route-key <key>","DingDing interactive card callback route key",J).option("--dingding-card-user-id-type <type>","DingDing interactive card user id type",Number,Y).option("--dingding-chat-id <id>","DingDing target conversation id",Q).option("--dingding-allowed-user-ids <ids>","Comma-separated DingDing user ids allowed to control the bot",Z.join(",")).option("--dingding-conversation <id>","DingDing passive conversation id",po,ee).option("--headless","Run receiver without interactive terminal input.").action(async e=>{await async function(e){const t=new Function("specifier","return import(specifier)"),{runReceiverInk:n}=await t(v.pathToFileURL(s.join(__dirname,"receiver-ink.mjs")).href);return n(e)}({socketPath:e.socket,telegramToken:e.telegramToken,telegramChatId:e.telegramChatId,telegramAllowedUserIds:e.telegramAllowedUserIds,telegramConversationId:e.telegramConversation,wechatToken:e.wechatToken,wechatBaseUrl:e.wechatBaseUrl,wechatChatId:e.wechatChatId,wechatConversationId:e.wechatConversation,wechatContextToken:e.wechatContextToken,wechatUpdatesBuf:e.wechatUpdatesBuf,dingdingClientId:e.dingdingClientId,dingdingClientSecret:e.dingdingClientSecret,dingdingCorpId:e.dingdingCorpId,dingdingRobotCode:e.dingdingRobotCode,dingdingCardTemplateId:e.dingdingCardTemplateId,dingdingCardCallbackRouteKey:e.dingdingCardCallbackRouteKey,dingdingCardUserIdType:e.dingdingCardUserIdType,dingdingChatId:e.dingdingChatId,dingdingAllowedUserIds:e.dingdingAllowedUserIds,dingdingConversationId:e.dingdingConversation,headless:e.headless})}),void 0===(r=process.argv)[2]&&r.push("web"),await n.parseAsync(process.argv)})().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exitCode=1});
1
+ "use strict";var e=require("commander"),t=require("node:fs"),s=require("node:path"),n=require("node: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().trim().regex(/^\d{4}-\d{2}-\d{2}$/,"Protocol version must use YYYY-MM-DD format."),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});