agentix-cli 0.46.0 → 0.46.2

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 (46) hide show
  1. package/apps/mac-voice/Sources/AgentXVoice/Speech.swift +7 -5
  2. package/apps/mac-voice/Sources/AgentXVoice/main.swift +9 -2
  3. package/dist/{agent-LI3AZQBC.js → agent-WT4RB5SO.js} +2 -2
  4. package/dist/{board-dashboard-IE2P6QFU.js → board-dashboard-IXCW2KIV.js} +3 -3
  5. package/dist/{board-dashboard-IE2P6QFU.js.map → board-dashboard-IXCW2KIV.js.map} +1 -1
  6. package/dist/{chunk-Q6EBTCEZ.js → chunk-5ZWNGD5D.js} +108 -108
  7. package/dist/chunk-5ZWNGD5D.js.map +1 -0
  8. package/dist/{chunk-GAUQOIEE.js → chunk-7KED5NB2.js} +3 -3
  9. package/dist/chunk-7L6M3P2N.js +13 -0
  10. package/dist/chunk-7L6M3P2N.js.map +1 -0
  11. package/dist/{chunk-TCJ3SMOF.js → chunk-HA6RYFST.js} +2 -2
  12. package/dist/{chunk-Y3SVZ6VS.js → chunk-L3A2LVWC.js} +123 -123
  13. package/dist/chunk-L3A2LVWC.js.map +1 -0
  14. package/dist/chunk-L53FTKEP.js +3 -0
  15. package/dist/chunk-L53FTKEP.js.map +1 -0
  16. package/dist/chunk-LGBBKLUO.js +7 -0
  17. package/dist/chunk-LGBBKLUO.js.map +1 -0
  18. package/dist/chunk-LUSFRS7R.js +25 -0
  19. package/dist/chunk-LUSFRS7R.js.map +1 -0
  20. package/dist/{chunk-NVVXVUQU.js → chunk-NWOGPKD7.js} +2 -2
  21. package/dist/cli.js +1 -1
  22. package/dist/cli.js.map +1 -1
  23. package/dist/doctor-7Z4VLXC4.js +2 -0
  24. package/dist/index.d.ts +2 -0
  25. package/dist/index.js +1 -1
  26. package/dist/index.js.map +1 -1
  27. package/dist/program-AHTQMAKN.js +2 -0
  28. package/dist/{registry-STML35CV.js → registry-FBWGWB5K.js} +2 -2
  29. package/dist/shutdown-6GCMKYAD.js +2 -0
  30. package/dist/shutdown-6GCMKYAD.js.map +1 -0
  31. package/package.json +1 -1
  32. package/dist/chunk-MX5GCR7Y.js +0 -36
  33. package/dist/chunk-MX5GCR7Y.js.map +0 -1
  34. package/dist/chunk-Q6EBTCEZ.js.map +0 -1
  35. package/dist/chunk-Y3SVZ6VS.js.map +0 -1
  36. package/dist/chunk-YQVR2HQS.js +0 -7
  37. package/dist/chunk-YQVR2HQS.js.map +0 -1
  38. package/dist/doctor-5HDW5F66.js +0 -2
  39. package/dist/program-BIMB44HN.js +0 -2
  40. /package/dist/{agent-LI3AZQBC.js.map → agent-WT4RB5SO.js.map} +0 -0
  41. /package/dist/{chunk-GAUQOIEE.js.map → chunk-7KED5NB2.js.map} +0 -0
  42. /package/dist/{chunk-TCJ3SMOF.js.map → chunk-HA6RYFST.js.map} +0 -0
  43. /package/dist/{chunk-NVVXVUQU.js.map → chunk-NWOGPKD7.js.map} +0 -0
  44. /package/dist/{doctor-5HDW5F66.js.map → doctor-7Z4VLXC4.js.map} +0 -0
  45. /package/dist/{program-BIMB44HN.js.map → program-AHTQMAKN.js.map} +0 -0
  46. /package/dist/{registry-STML35CV.js.map → registry-FBWGWB5K.js.map} +0 -0
@@ -1,4 +1,4 @@
1
- import{a as En,g as Un,m as Bn}from"./chunk-TCJ3SMOF.js";import{a as wt}from"./chunk-QLTM3F7M.js";import{b as Nn}from"./chunk-DP7RTNDM.js";import{b as Fn}from"./chunk-BIFJSQB5.js";import{a as It,b as Ln}from"./chunk-WPMX3VGI.js";import{a as St,b as Hn}from"./chunk-K33GIBSE.js";import{a as jn}from"./chunk-W4YR2RO2.js";import{a as kn}from"./chunk-ICZPZYYR.js";import{a as In,b as Sn,c as vn,d as Cn,f as An}from"./chunk-DWADWDMU.js";import{a as $n,b as Mn,c as xt,d as Tt,e as Pn,f as kt,g as Rn}from"./chunk-CQR6C5FU.js";import{a as On}from"./chunk-RY2EULHS.js";import{b as _n,c as Dn}from"./chunk-SGFXE5FP.js";import{a as Je,c as Ae}from"./chunk-2GIDVZ4H.js";import{q as wn,t as xn,v as me,w as Tn}from"./chunk-6HMZ5TTM.js";import{a as Ce,b as Ge,f as bt}from"./chunk-F4HZTZHW.js";import{a as he,b as ft}from"./chunk-ZTEU5JVQ.js";import{c as Ke,d as qe}from"./chunk-QOYAX2FT.js";import{e as ue}from"./chunk-DSYKYZMT.js";import{d as fn,e as re,f as yn,g as bn,h as yt}from"./chunk-QJANPP4C.js";Tn();bt();var Wn="session-continuity",Kn={continues:Ce("The new request continues the task the user was already working on in the previous request, rather than starting a separate one.",{true:`The new request advances, narrows, corrects or follows up on the previous request's task \u2014 including terse replies such as "and the cost?" or "why?" that mean nothing on their own.`,false:"The new request opens a subject that could be answered without having seen the previous request, even if it arrived seconds later or belongs to the same broad field."}),needsHistory:Ce("Does the new request refer to something stated earlier in the conversation?")};function qn(s){let e=(s.recentRequests??[]).filter(Boolean);return{newRequest:vt(s.message,1200),previousRequest:s.previousMessage?vt(s.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>vt(t,400))}:{},minutesSinceLastTurn:s.minutesSinceLastTurn,turnsSoFar:s.turnCount,currentContextTokens:s.lastTurnContextTokens,agent:s.agentId,channel:s.channel}}function Gn(s,e){if(e.mechanicalRotation)return!1;let t=e.maxContinuity??.2,n=s.continues.noul,r=s.needsHistory.noul;return n<=t&&r<=t}function vt(s,e){let t=String(s??"");return t.length>e?t.slice(0,e):t}import{spawn as Hr,execFile as jr}from"node:child_process";import{createHash as Ur,randomBytes as Br}from"node:crypto";import{createInterface as Wr}from"node:readline";import{promisify as Kr}from"node:util";var qr=Kr(jr),oe=class extends Error{constructor(t,n=!1){super(t);this.standalone=n}},Ct=class{constructor(e=8,t=3e5){this.capacity=e;this.idleMs=t}entries=new Map;versions=new Map;close(e){if(e.dead)return;e.dead=!0,clearTimeout(e.idle),e.child.kill("SIGTERM"),setTimeout(()=>{e.child.exitCode===null&&e.child.kill("SIGKILL")},3e3).unref()}stop(){for(let e of this.entries.values())this.close(e);this.entries.clear(),this.versions.clear()}async acquire(e){if(e.signal?.aborted)throw new Error("task cancelled by operator");let t=e.env.PATH||"",n=this.versions.get(t);if(n||(n=qr("opencode",["--version"],{env:e.env,timeout:5e3}).then(({stdout:l})=>/^(?:opencode\s+)?v?2\./.test(l.trim())).catch(()=>!1),this.versions.set(t,n),setTimeout(()=>this.versions.delete(t),6e4).unref()),!await n)throw new oe("Warm servers require OpenCode v2; using the CLI path");if(e.signal?.aborted)throw new Error("task cancelled by operator");let r=Ur("sha256").update(JSON.stringify([e.cwd,e.model,e.permission,Object.entries(e.env).sort(([u],[l])=>u.localeCompare(l))])).digest("hex"),o=this.entries.get(e.key);if(o?.busy)throw new oe("Conversation already running",!0);o&&(o.dead||o.fingerprint!==r||e.fresh)&&(this.close(o),this.entries.delete(e.key),o=void 0);let i=!!o;if(!o){if(this.entries.size>=this.capacity){let p=[...this.entries].find(([,h])=>!h.busy);if(!p)throw new oe("Warm server capacity reached",!0);this.close(p[1]),this.entries.delete(p[0])}let u={...e.env,OPENCODE_SERVER_USERNAME:"opencode",OPENCODE_SERVER_PASSWORD:Br(32).toString("hex")},l=Hr("opencode",["serve","--hostname","127.0.0.1","--port","0","--stdio"],{cwd:e.cwd,env:u,stdio:["pipe","pipe","pipe"]});o={child:l,env:u,fingerprint:r,url:"",busy:!0,dead:!1},this.entries.set(e.key,o);let d=o;l.stderr.resume(),l.on("exit",()=>this.close(d)),l.on("error",()=>this.close(d));try{await new Promise((p,h)=>{let x=Wr({input:l.stdout}),T=()=>g(new oe("OpenCode server failed before dispatch",!0)),w=()=>g(new Error("task cancelled by operator")),I=setTimeout(T,15e3),g=_=>{clearTimeout(I),l.removeListener("exit",T),l.removeListener("error",T),e.signal?.removeEventListener("abort",w),x.close(),l.stdout.resume(),_?h(_):p()};l.once("exit",T),l.once("error",T),e.signal?.addEventListener("abort",w,{once:!0}),x.on("line",_=>{try{let A=new URL(JSON.parse(_).url);if(A.protocol!=="http:"||A.hostname!=="127.0.0.1"||!A.port||A.username||A.password)return;d.url=A.origin,g()}catch{}}),e.signal?.aborted&&w()})}catch(p){throw this.close(o),this.entries.get(e.key)===o&&this.entries.delete(e.key),p}}let a=o;clearTimeout(a.idle),a.busy=!0;let c=!1;return{url:a.url,env:a.env,reused:i,invalidate:()=>this.close(a),release:(u=!1)=>{c||(c=!0,a.busy=!1,u||a.dead?(this.close(a),this.entries.get(e.key)===a&&this.entries.delete(e.key)):(a.idle=setTimeout(()=>{this.close(a),this.entries.get(e.key)===a&&this.entries.delete(e.key)},this.idleMs),a.idle.unref()))}}}},Jn=new Ct;import{execa as Ze}from"execa";import{spawn as Gr}from"node:child_process";import{createHash as Jr}from"node:crypto";import{createInterface as Qr}from"node:readline";var ie=class extends Error{},zr=s=>Gr("codex",["app-server",...s.args],{cwd:s.cwd,env:s.env,stdio:["pipe","pipe","pipe"]}),At=class{child;pending=new Map;nextId=0;dead=!1;busy=!1;threadId;idle;notify;failTurn;constructor(e,t){this.child=t(e),this.child.stderr.resume(),Qr({input:this.child.stdout}).on("line",r=>{let o;try{o=JSON.parse(r)}catch{return}if(o.method&&o.id!==void 0)this.write({id:o.id,error:{code:-32601,message:"Interactive requests are not supported by AgentX"}});else if(o.id!==void 0){let i=this.pending.get(o.id);if(!i)return;this.pending.delete(o.id),o.error?i.reject(new Error(o.error.message||"Codex RPC failed")):i.resolve(o.result)}else o.method&&this.notify?.(o.method,o.params)}),this.child.on("error",r=>this.close(r)),this.child.stdin.on("error",r=>this.close(r)),this.child.on("exit",()=>this.close(new Error("Codex app-server exited")))}write(e){this.dead||this.child.stdin.write(JSON.stringify(e)+`
1
+ import{a as En,g as Un,m as Bn}from"./chunk-HA6RYFST.js";import{a as wt}from"./chunk-QLTM3F7M.js";import{b as Nn}from"./chunk-DP7RTNDM.js";import{b as Fn}from"./chunk-BIFJSQB5.js";import{a as It,b as Ln}from"./chunk-WPMX3VGI.js";import{a as St,b as Hn}from"./chunk-K33GIBSE.js";import{a as jn}from"./chunk-W4YR2RO2.js";import{a as kn}from"./chunk-ICZPZYYR.js";import{a as In,b as Sn,c as vn,d as Cn,f as An}from"./chunk-DWADWDMU.js";import{a as $n,b as Mn,c as xt,d as Tt,e as Pn,f as kt,g as Rn}from"./chunk-CQR6C5FU.js";import{a as On}from"./chunk-RY2EULHS.js";import{b as _n,c as Dn}from"./chunk-SGFXE5FP.js";import{a as Je,c as Ae}from"./chunk-2GIDVZ4H.js";import{q as wn,t as xn,v as me,w as Tn}from"./chunk-6HMZ5TTM.js";import{a as Ce,b as Ge,f as bt}from"./chunk-F4HZTZHW.js";import{a as he,b as ft}from"./chunk-ZTEU5JVQ.js";import{c as Ke,d as qe}from"./chunk-QOYAX2FT.js";import{e as ue}from"./chunk-DSYKYZMT.js";import{d as fn,e as re,f as yn,g as bn,h as yt}from"./chunk-QJANPP4C.js";Tn();bt();var Wn="session-continuity",Kn={continues:Ce("The new request continues the task the user was already working on in the previous request, rather than starting a separate one.",{true:`The new request advances, narrows, corrects or follows up on the previous request's task \u2014 including terse replies such as "and the cost?" or "why?" that mean nothing on their own.`,false:"The new request opens a subject that could be answered without having seen the previous request, even if it arrived seconds later or belongs to the same broad field."}),needsHistory:Ce("Does the new request refer to something stated earlier in the conversation?")};function qn(s){let e=(s.recentRequests??[]).filter(Boolean);return{newRequest:vt(s.message,1200),previousRequest:s.previousMessage?vt(s.previousMessage,800):null,...e.length?{earlierRequests:e.map(t=>vt(t,400))}:{},minutesSinceLastTurn:s.minutesSinceLastTurn,turnsSoFar:s.turnCount,currentContextTokens:s.lastTurnContextTokens,agent:s.agentId,channel:s.channel}}function Gn(s,e){if(e.mechanicalRotation)return!1;let t=e.maxContinuity??.2,n=s.continues.noul,r=s.needsHistory.noul;return n<=t&&r<=t}function vt(s,e){let t=String(s??"");return t.length>e?t.slice(0,e):t}import{spawn as Hr,execFile as jr}from"node:child_process";import{createHash as Ur,randomBytes as Br}from"node:crypto";import{createInterface as Wr}from"node:readline";import{promisify as Kr}from"node:util";var qr=Kr(jr),oe=class extends Error{constructor(t,n=!1){super(t);this.standalone=n}},Ct=class{constructor(e=8,t=3e5){this.capacity=e;this.idleMs=t}entries=new Map;versions=new Map;close(e){if(e.dead)return;e.dead=!0,clearTimeout(e.idle),e.child.kill("SIGTERM"),setTimeout(()=>{e.child.exitCode===null&&e.child.kill("SIGKILL")},3e3).unref()}stop(){for(let e of this.entries.values())this.close(e);this.entries.clear(),this.versions.clear()}async acquire(e){if(e.signal?.aborted)throw new Error("task cancelled by operator");let t=e.env.PATH||"",n=this.versions.get(t);if(n||(n=qr("opencode",["--version"],{env:e.env,timeout:5e3}).then(({stdout:l})=>/^(?:opencode\s+)?v?2\./.test(l.trim())).catch(()=>!1),this.versions.set(t,n),setTimeout(()=>this.versions.delete(t),6e4).unref()),!await n)throw new oe("Warm servers require OpenCode v2; using the CLI path");if(e.signal?.aborted)throw new Error("task cancelled by operator");let r=Ur("sha256").update(JSON.stringify([e.cwd,e.model,e.permission,Object.entries(e.env).sort(([u],[l])=>u.localeCompare(l))])).digest("hex"),o=this.entries.get(e.key);if(o?.busy)throw new oe("Conversation already running",!0);o&&(o.dead||o.fingerprint!==r||e.fresh)&&(this.close(o),this.entries.delete(e.key),o=void 0);let i=!!o;if(!o){if(this.entries.size>=this.capacity){let p=[...this.entries].find(([,h])=>!h.busy);if(!p)throw new oe("Warm server capacity reached",!0);this.close(p[1]),this.entries.delete(p[0])}let u={...e.env,OPENCODE_SERVER_USERNAME:"opencode",OPENCODE_SERVER_PASSWORD:Br(32).toString("hex")},l=Hr("opencode",["serve","--hostname","127.0.0.1","--port","0","--stdio"],{cwd:e.cwd,env:u,stdio:["pipe","pipe","pipe"]});o={child:l,env:u,fingerprint:r,url:"",busy:!0,dead:!1},this.entries.set(e.key,o);let d=o;l.stderr.resume(),l.on("exit",()=>this.close(d)),l.on("error",()=>this.close(d));try{await new Promise((p,h)=>{let x=Wr({input:l.stdout}),T=()=>g(new oe("OpenCode server failed before dispatch",!0)),w=()=>g(new Error("task cancelled by operator")),I=setTimeout(T,15e3),g=_=>{clearTimeout(I),l.removeListener("exit",T),l.removeListener("error",T),e.signal?.removeEventListener("abort",w),x.close(),l.stdout.resume(),_?h(_):p()};l.once("exit",T),l.once("error",T),e.signal?.addEventListener("abort",w,{once:!0}),x.on("line",_=>{try{let A=new URL(JSON.parse(_).url);if(A.protocol!=="http:"||A.hostname!=="127.0.0.1"||!A.port||A.username||A.password)return;d.url=A.origin,g()}catch{}}),e.signal?.aborted&&w()})}catch(p){throw this.close(o),this.entries.get(e.key)===o&&this.entries.delete(e.key),p}}let a=o;clearTimeout(a.idle),a.busy=!0;let c=!1;return{url:a.url,env:a.env,reused:i,invalidate:()=>this.close(a),release:(u=!1)=>{c||(c=!0,a.busy=!1,u||a.dead?(this.close(a),this.entries.get(e.key)===a&&this.entries.delete(e.key)):(a.idle=setTimeout(()=>{this.close(a),this.entries.get(e.key)===a&&this.entries.delete(e.key)},this.idleMs),a.idle.unref()))}}}},Jn=new Ct;import{execa as Ze}from"execa";import{spawn as Gr}from"node:child_process";import{createHash as Jr}from"node:crypto";import{createInterface as Qr}from"node:readline";var ie=class extends Error{},zr=s=>Gr("codex",["app-server",...s.args],{cwd:s.cwd,env:s.env,stdio:["pipe","pipe","pipe"]}),At=class{child;pending=new Map;nextId=0;dead=!1;busy=!1;threadId;idle;notify;failTurn;constructor(e,t){this.child=t(e),this.child.stderr.resume(),Qr({input:this.child.stdout}).on("line",r=>{let o;try{o=JSON.parse(r)}catch{return}if(o.method&&o.id!==void 0)this.write({id:o.id,error:{code:-32601,message:"Interactive requests are not supported by AgentX"}});else if(o.id!==void 0){let i=this.pending.get(o.id);if(!i)return;this.pending.delete(o.id),o.error?i.reject(new Error(o.error.message||"Codex RPC failed")):i.resolve(o.result)}else o.method&&this.notify?.(o.method,o.params)}),this.child.on("error",r=>this.close(r)),this.child.stdin.on("error",r=>this.close(r)),this.child.on("exit",()=>this.close(new Error("Codex app-server exited")))}write(e){this.dead||this.child.stdin.write(JSON.stringify(e)+`
2
2
  `)}rpc(e,t){if(this.dead)return Promise.reject(new Error("Codex connection closed"));let n=++this.nextId;return new Promise((r,o)=>{this.pending.set(n,{resolve:r,reject:o}),this.write({id:n,method:e,params:t})})}close(e=new Error("Codex connection closed")){if(this.dead)return;this.dead=!0,clearTimeout(this.idle);for(let n of this.pending.values())n.reject(e);this.pending.clear(),this.failTurn?.(e),this.child.kill("SIGTERM"),setTimeout(()=>{this.child.exitCode===null&&this.child.kill("SIGKILL")},5e3).unref()}},$t=class{constructor(e=zr,t=8,n=3e5){this.launchProcess=e;this.capacity=t;this.idleMs=n}entries=new Map;stop(){for(let{connection:e}of this.entries.values())e.close();this.entries.clear()}async run(e){let t=Date.now();if(e.signal?.aborted)return{content:"",error:"task cancelled by operator",duration:0};let n=Jr("sha256").update(JSON.stringify([e.cwd,e.model,e.bypass,e.args,Object.entries(e.env).sort(([w],[I])=>w.localeCompare(I))])).digest("hex"),r=this.entries.get(e.key);if(r?.connection.busy)throw new ie("Conversation already running");r&&(r.fingerprint!==n||e.fresh||r.connection.dead)&&(r.connection.close(),this.entries.delete(e.key),r=void 0);let o=!!r;if(!r){if(this.entries.size>=this.capacity){let w=[...this.entries].find(([,I])=>!I.connection.busy);if(!w)throw new ie("Codex warm process capacity reached");w[1].connection.close(),this.entries.delete(w[0])}try{r={fingerprint:n,connection:new At(e,this.launchProcess)}}catch{throw new ie("Could not start Codex app-server")}this.entries.set(e.key,r)}let i=r.connection;i.busy=!0,clearTimeout(i.idle);let a=!1,c="",u,l,d,p=!1,h=()=>i.close(new Error("task cancelled by operator"));e.signal?.addEventListener("abort",h,{once:!0});let x=setTimeout(()=>i.close(new Error("Codex turn timed out")),e.timeoutMs),T=setTimeout(()=>i.close(new Error("Codex initialization timed out")),15e3);try{o||(await i.rpc("initialize",{clientInfo:{name:"agentx",version:"1.0.0"},capabilities:{}}),i.write({method:"initialized",params:{}})),i.threadId&&i.threadId!==e.resume&&(await i.rpc("thread/unsubscribe",{threadId:i.threadId}),i.threadId=void 0);let w={cwd:e.cwd,model:e.model,approvalPolicy:"never",sandbox:e.bypass?"danger-full-access":"workspace-write"};l=(await i.rpc(e.resume&&!e.fresh?"thread/resume":"thread/start",{...w,...e.resume&&!e.fresh?{threadId:e.resume}:{}})).thread.id,i.threadId=l,clearTimeout(T),e.onEvent?.({type:"codex.ready",reused:o,startupMs:Date.now()-t,model:e.model});let g=new Promise((_,A)=>{i.failTurn=A,i.notify=(S,y)=>{if(y?.threadId!==l)return;let O=y.item,C={agentMessage:"agent_message",commandExecution:"command_execution",fileChange:"file_change",mcpToolCall:"mcp_tool_call"};if(e.onEvent?.({...y,type:S.replace("/","."),...O?{item:{...O,type:C[O.type]||O.type}}:{}}),S==="item/completed"&&O?.type==="agentMessage"&&O.phase==="final_answer"&&(u=O.text),S==="item/agentMessage/delta"&&(p||(p=!0,e.onEvent?.({type:"codex.first_output",elapsedMs:Date.now()-t,reused:o})),c+=y.delta,e.onDelta?.(y.delta,c)),S==="thread/tokenUsage/updated"){let E=y.tokenUsage.last,F=E.cachedInputTokens||0;d={inputTokens:(d?.inputTokens||0)+Math.max(0,(E.inputTokens||0)-F),outputTokens:(d?.outputTokens||0)+(E.outputTokens||0),cacheReadTokens:(d?.cacheReadTokens||0)+F,cacheCreateTokens:(d?.cacheCreateTokens||0)+(E.cacheWriteInputTokens||0)}}S==="turn/completed"&&(y.turn.status==="completed"?_():A(new Error(y.turn.error?.message||`Codex turn ${y.turn.status}`)))}});return g.catch(()=>{}),a=!0,await i.rpc("turn/start",{threadId:l,input:[{type:"text",text:e.prompt,text_elements:[]}]}),await g,{content:u??c,codexSessionId:l,billedModel:e.model,usage:d,duration:Date.now()-t}}catch(w){if(i.close(),!a&&!e.signal?.aborted)throw new ie(w.message);return{content:c,codexSessionId:l,usage:d,error:w.message,duration:Date.now()-t}}finally{clearTimeout(T),clearTimeout(x),e.signal?.removeEventListener("abort",h),i.notify=void 0,i.failTurn=void 0,i.busy=!1,i.dead?this.entries.get(e.key)?.connection===i&&this.entries.delete(e.key):(i.idle=setTimeout(()=>{i.close(),this.entries.delete(e.key)},this.idleMs),i.idle.unref())}}},Qn=new $t;import{execFile as uo}from"child_process";import{StringDecoder as Pe}from"string_decoder";import{mkdtempSync as cs,readFileSync as ds,rmSync as us}from"fs";import{join as Ye}from"path";import{tmpdir as ls}from"os";function Qe(s){let e=(s||"").trim();if(!e)return{message:"Unknown error from the model.",kind:"unknown",retryable:!1};if(/timed out after/i.test(e))return{message:e.slice(0,300),kind:"timeout",retryable:!0,raw:e};if(/not logged in|please run \/login/i.test(e))return{kind:"auth",retryable:!0,message:"The agent's Claude Code session is logged out.",fix:"Usually a transient OAuth refresh race under concurrent load \u2014 retry in a moment. If it persists, run `/login` in the agent's workspace.",raw:e};if(/specified API usage limits/i.test(e)){let u=e.match(/regain access on ([^.\n]+?)(?:\.|$)/i);return{kind:"usage_cap",retryable:!1,message:`Claude Code subscription /usage cap exhausted.${u?` Resets ${u[1].trim()}.`:""}`,fix:"Raise the cap at https://claude.ai/settings/usage (this is the user-set monthly limit on the OAuth account, not Anthropic API billing). If the daemon is using a different account than expected, check CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_API_KEY in the spawn env \u2014 capped keys leak the same error.",raw:e}}if(/out of extra usage/i.test(e))return{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e};if(/credit balance (is )?too low|out of credit|credit(s)? exhausted|insufficient credit/i.test(e))return{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e};let t=e.match(/\{.*\}\s*$/s)||e.match(/\{[\s\S]*\}/),n;if(t)try{n=JSON.parse(t[0])}catch{}let r=n?.error||n,o=typeof r?.type=="string"?r.type:void 0,i=typeof r?.message=="string"?r.message:void 0,a=e.match(/API Error:\s*(\d{3})/i),c=a?parseInt(a[1],10):void 0;return i&&/out of extra usage/i.test(i)?{kind:"overage_disabled",retryable:!0,message:"Claude Max-plan overage is unavailable (disabled or depleted at the org level).",fix:"Enable overage / extra usage at https://claude.ai/settings/usage (this is the subscription account's toggle \u2014 not Anthropic API billing). Warm sessions can still succeed via prompt cache; cold dispatches will keep failing until overage is re-enabled.",raw:e}:i&&/out of (extra )?usage|out of credit|credit(s)? exhausted|insufficient credit|credit balance (is )?too low|low credit balance/i.test(i)?{kind:"out_of_credits",retryable:!1,message:"The agent is out of Anthropic credits.",fix:"Top up at https://console.anthropic.com/settings/billing (or claude.ai/settings/usage for Max subscribers), then retry.",raw:e}:i&&/context|prompt is too long|too many tokens|maximum context length/i.test(i)?{kind:"context_too_large",retryable:!1,message:"The conversation has grown past what the model can hold.",fix:"Clear session history or switch the agent to a bigger context model.",raw:e}:o==="authentication_error"||i&&/authentication|invalid.*api.*key|no api key|not authenticated/i.test(i)?{kind:"auth",retryable:!1,message:"Authentication failed talking to Anthropic.",fix:"Check ANTHROPIC_API_KEY in .env (or the Claude Code login for claude-code tier agents).",raw:e}:o==="permission_error"||c===403?{kind:"permission",retryable:!1,message:i||"The API key doesn't have permission for this request.",raw:e}:o==="rate_limit_error"||c===429?{kind:"rate_limit",retryable:!0,message:"Anthropic's API rate-limited this request.",fix:"AgentX will retry automatically. If it recurs, lower the agent's concurrency or spread scheduled jobs.",raw:e}:o==="overloaded_error"||c===529||c===503?{kind:"overloaded",retryable:!0,message:"Anthropic's API is temporarily overloaded.",fix:"AgentX will retry in a moment.",raw:e}:o==="invalid_request_error"||c===400?{kind:"invalid_request",retryable:!1,message:i||"The model rejected the request as invalid.",raw:e}:c&&c>=500?{kind:"upstream_api",retryable:!0,message:i||`Anthropic API error (HTTP ${c}).`,fix:"Transient \u2014 retry. Check https://status.anthropic.com if it persists.",raw:e}:{kind:"unknown",retryable:!1,message:e.replace(/\s+/g," ").slice(0,220),raw:e}}function ze(s){return s.fix?`${s.message} \u2014 ${s.fix}`:s.message}var zn=null;function Xe(){return zn}function aa(s){zn=s}function $e(s){return`${s.agentId}:${s.channel}:${s.chatId}`}var fe=class extends Error{constructor(t,n,r){super(t);this.scope=n;this.cap=r;this.name="RegistryCapExceeded"}},Xn=class{handles=new Map;sweeper;handleWorkspace=new Map;cfg;constructor(e){this.cfg={maxProcessesGlobal:e.maxProcessesGlobal??64,maxProcessesPerAgent:e.maxProcessesPerAgent??16,idleTimeoutMs:e.idleTimeoutMs??3e4,staleTimeoutMs:e.staleTimeoutMs??45*60*1e3,sweepIntervalMs:e.sweepIntervalMs??5e3,factory:e.factory,log:e.log??(()=>{}),currentWorkspaceHash:e.currentWorkspaceHash}}start(){this.sweeper||(this.sweeper=setInterval(()=>this.sweepIdle(),this.cfg.sweepIntervalMs),typeof this.sweeper.unref=="function"&&this.sweeper.unref())}async stop(){this.sweeper&&(clearInterval(this.sweeper),this.sweeper=void 0);let e=Array.from(this.handles.values());this.handles.clear(),await Promise.allSettled(e.map(t=>t.kill("registry-stop")))}acquire(e,t){let n=$e(e),r=this.handles.get(n);if(r&&r.state()!=="dead")return r.claim?.(),r;if(this.handles.size>=this.cfg.maxProcessesGlobal&&this.evictOldestIdle({scope:"global"}),this.countForAgent(e.agentId)>=this.cfg.maxProcessesPerAgent&&this.evictOldestIdle({scope:"agent",agentId:e.agentId}),this.handles.size>=this.cfg.maxProcessesGlobal)throw new fe(`process registry at global cap (${this.cfg.maxProcessesGlobal}) and no idle handle to evict`,"global",this.cfg.maxProcessesGlobal);if(this.countForAgent(e.agentId)>=this.cfg.maxProcessesPerAgent)throw new fe(`process registry at per-agent cap for ${e.agentId} (${this.cfg.maxProcessesPerAgent}) and no idle handle to evict`,"agent",this.cfg.maxProcessesPerAgent);let i=this.cfg.factory.spawn(e,t);return this.handles.set(n,i),this.handleWorkspace.set(n,t.workspace),this.cfg.log(`[process-registry] spawned ${n}`),i}release(e,t={}){let n=$e(e),r=this.handles.get(n);r&&(this.handles.delete(n),this.handleWorkspace.delete(n),t.kill&&r.kill(t.reason??"release"))}list(){return Array.from(this.handles.values()).map(e=>e.snapshot())}hasLive(e){let t=$e(e),n=this.handles.get(t);return n!=null&&n.state()!=="dead"}async kill(e,t="operator"){let n=$e(e),r=this.handles.get(n);r&&(this.handles.delete(n),this.handleWorkspace.delete(n),await r.kill(t))}countForAgent(e){let t=0;for(let n of this.handles.values())n.key.agentId===e&&n.state()!=="dead"&&(t+=1);return t}evictOldestIdle(e){let t,n=Number.POSITIVE_INFINITY;for(let o of this.handles.values()){if(o.state()!=="idle"||e.scope==="agent"&&o.key.agentId!==e.agentId)continue;let i=o.snapshot().lastTurnAt;i<n&&(n=i,t=o)}if(!t)return!1;let r=$e(t.key);return this.handles.delete(r),t.kill("evicted (cap reached)"),this.cfg.log(`[process-registry] evicted ${r} (cap)`),!0}sweepIdle(){let e=Date.now();for(let[t,n]of this.handles.entries()){let r=n.snapshot();if(n.state()==="dead"){this.handles.delete(t),this.handleWorkspace.delete(t),this.cfg.log(`[process-registry] reaped dead ${t}`);continue}if(n.state()!=="idle")continue;let o=e-r.lastTurnAt;if(o>=this.cfg.staleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),n.kill(`stale (idle ${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed stale ${t}`);continue}if(o>=this.cfg.idleTimeoutMs){this.handles.delete(t),this.handleWorkspace.delete(t),n.kill(`idle (${Math.round(o/1e3)}s)`),this.cfg.log(`[process-registry] killed idle ${t}`);continue}if(this.cfg.currentWorkspaceHash){let i=this.handleWorkspace.get(t);if(i){let a=null;try{a=this.cfg.currentWorkspaceHash(n.key,i)}catch(c){this.cfg.log(`[process-registry] drift-check failed for ${t}: ${c?.message||c}`);continue}if(a!==r.claudeMdHash){this.handles.delete(t),this.handleWorkspace.delete(t);let c=r.claudeMdHash??"unmarked",u=a??"unmarked";n.kill(`claude-md drifted (${c} \u2192 ${u})`),this.cfg.log(`[process-registry] killed drifted ${t} (${c} \u2192 ${u})`)}}}}}};import{spawn as Xr}from"child_process";import{existsSync as Yr,readFileSync as Vr}from"fs";import{resolve as Zr}from"path";function eo(s){let e=Zr(s,"CLAUDE.md");if(!Yr(e))return null;try{let t=Vr(e,"utf8");return An(t)}catch{return null}}var to=20*60*1e3,no=5e3,Me=class extends Error{constructor(t){super(`turn exceeded its ${Math.round(t/6e4)}m budget`);this.budgetMs=t}},Yn=class{constructor(e={}){this.opts=e}spawn(e,t){return new Mt(e,t,this.opts)}},Mt=class{constructor(e,t,n){this.key=e;this.spawnOpts=t;this.factoryOpts=n;let r=n.binary??"claude",o=this.buildArgs(t),i=n.log??(()=>{});this.child=Xr(r,o,{cwd:t.workspace,env:Ae({...process.env},t.billing),stdio:["pipe","pipe","pipe"]}),this.snap={key:e,pid:this.child.pid??null,claudeSessionId:t.resumeSessionId??null,state:"warm-cold",spawnedAt:Date.now(),lastTurnAt:Date.now(),turnCount:0,lastInputTokens:0,pendingTaskId:null,claudeMdHash:eo(t.workspace)},this.child.stdout.setEncoding("utf8"),this.child.stdout.on("data",a=>this.onStdout(a)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",a=>i(`[claude pid=${this.snap.pid}] stderr: ${a.trim()}`)),this.child.on("exit",a=>{this.exited=!0,this.exitCode=a,this.snap={...this.snap,state:"dead",deadReason:this.killReason??`exit=${a}`};let c=this.waiters.splice(0);for(let u of c)u(null)}),this.child.on("error",a=>{i(`[claude pid=${this.snap.pid}] spawn error: ${a.message}`),this.killReason=`spawn-error: ${a.message}`})}child;buf="";pendingEvents=[];waiters=[];exited=!1;exitCode=null;killReason;turnQueue=Promise.resolve();snap;state(){return this.snap.state}snapshot(){return{...this.snap}}async*runTurn(e){let t,n=new Promise(l=>{t=l}),r=this.turnQueue;if(this.turnQueue=r.then(()=>n),await r,this.exited||this.snap.state==="dead")throw t(),new Error(`claude process for ${this.key.agentId}:${this.key.chatId} is dead (${this.snap.deadReason??"?"})`);let o=Date.now();this.snap={...this.snap,state:"busy",pendingTaskId:e.taskId,lastTurnAt:o};let i=JSON.stringify({type:"user",message:{role:"user",content:e.message}});this.child.stdin.write(i+`
3
3
  `);let a=e.deadlineMs??to,c=o+a,u=()=>(this.kill(`turn deadline (${Math.round(a/6e4)}m)`),new Me(a));try{for(;;){let l=c-Date.now();if(l<=0)throw u();let d=await this.nextEvent(l);if(d===null&&!this.exited)throw u();if(d===null)throw new Error(`claude process exited mid-turn (code=${this.exitCode}, reason=${this.snap.deadReason??"?"})`);if(yield{type:d.type,raw:d},d.type==="result"){this.onResultEvent(d);return}}}finally{let l=this.snap.state==="busy";this.snap={...this.snap,...l?{state:"idle",lastTurnAt:Date.now()}:{},pendingTaskId:null},t()}}claim(){this.snap.state!=="dead"&&(this.snap={...this.snap,lastTurnAt:Date.now()})}async kill(e){if(this.exited)return;this.killReason=e,this.snap={...this.snap,state:"dead",deadReason:e};try{this.child.kill("SIGTERM")}catch{}let t=this.waiters.splice(0);for(let r of t)r(null);let n=await new Promise(r=>{let o=setTimeout(()=>{try{this.child.kill("SIGKILL")}catch{}r(!0)},no);this.child.once("exit",()=>{clearTimeout(o),r(!1)})})}buildArgs(e){let t=["-p","--input-format","stream-json","--output-format","stream-json","--verbose"];return e.model&&t.push("--model",e.model),e.permissionMode==="bypassPermissions"&&t.push("--dangerously-skip-permissions"),e.resumeSessionId&&t.push("--resume",e.resumeSessionId),e.systemPromptAppend&&e.systemPromptAppend.trim().length>0&&t.push("--append-system-prompt",e.systemPromptAppend),this.factoryOpts.extraArgs&&t.push(...this.factoryOpts.extraArgs),t}onStdout(e){this.buf+=e;let t;for(;(t=this.buf.indexOf(`
4
4
  `))!==-1;){let n=this.buf.slice(0,t);if(this.buf=this.buf.slice(t+1),!n.trim())continue;let r;try{r=JSON.parse(n)}catch{continue}this.waiters.length>0?this.waiters.shift()(r):this.pendingEvents.push(r)}}nextEvent(e){return this.pendingEvents.length>0?Promise.resolve(this.pendingEvents.shift()):this.exited?Promise.resolve(null):new Promise(t=>{let n=!1,r=setTimeout(()=>{if(n)return;n=!0;let i=this.waiters.indexOf(o);i>=0&&this.waiters.splice(i,1),t(null)},e),o=i=>{n||(n=!0,clearTimeout(r),t(i))};this.waiters.push(o)})}onResultEvent(e){let t=e.usage??{},n=typeof e.session_id=="string"?e.session_id:this.snap.claudeSessionId;this.snap={...this.snap,lastTurnAt:Date.now(),turnCount:this.snap.turnCount+1,lastInputTokens:typeof t.input_tokens=="number"?t.input_tokens:this.snap.lastInputTokens,claudeSessionId:n,state:"idle"}}};yt();import{resolve as Vn,join as Zn}from"path";ft();var so=4e3;function es(s){try{let e=Zn(Vn(s.root),".agentx","db.sqlite"),t=wt({path:e});if(!t)return null;try{t.pragma("busy_timeout = 3000")}catch{}let n=he(),r=s.input.command?s.input.command.slice(0,so):s.input.filePath??null;return t.prepare(`INSERT INTO guardrail_decisions
@@ -27,7 +27,7 @@ ${s}`}function lo(s,e,t,n,r){let o=["run","--format","json","--thinking"],i=t||s
27
27
  `,d)}};A.stdout?.on("data",b=>{C+=F.write(b);let k=C.split(`
28
28
  `);C=k.pop()||"";for(let R of k)L(R)}),A.stderr?.on("data",b=>{E+=D.write(b)});let v=await A;if(i&&i.removeEventListener("abort",O),C+=F.end(),C.trim()&&L(C),E+=D.end(),S)return{content:"",error:y||"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c,opencodeSessionId:h};if(v.exitCode!==0||x){let b=v,k;return b.timedOut?k=`OpenCode timed out after ${Math.round(g/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`:x?k=x:b.code==="ENOENT"||/ENOENT|spawn opencode/i.test((b.shortMessage||"")+" "+E)?k=os():k=E.trim()||`OpenCode exited with code ${b.exitCode??"unknown"}`,{content:"",...q(k),duration:Date.now()-c,usage:p,opencodeSessionId:h}}return w=!1,{content:d.trim(),duration:Date.now()-c,usage:p,billedModel:e.model||s.model,opencodeSessionId:h}}catch(g){if(i?.aborted)return{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-c};let _=/ENOENT|spawn opencode/i.test(g?.message||"")?os():g?.message;return{content:d,...q(_||"OpenCode failed"),duration:Date.now()-c,usage:p,opencodeSessionId:h}}finally{I?.(),T?.release(w)}}async function ko(s,e,t,n){let r=Date.now();try{let o=await import("@anthropic-ai/claude-agent-sdk"),{query:i}=o,a=ce(s,e,n),c="",u=i({prompt:a,options:{model:e.model||s.model,cwd:s.workspace,permissionMode:"bypassPermissions"}});for await(let l of u)l.type==="result"&&l.subtype==="success"&&(c=l.result||"");return{content:c,duration:Date.now()-r}}catch(o){return{content:"",...q(`SDK error: ${o.message}`),duration:Date.now()-r}}}async function Io(s,e,t,n,r,o,i,a,c){let u=Date.now(),l=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4),d=new AbortController,p=!1,h=()=>{let w=a.reason?.message||(typeof a.reason=="string"?a.reason:"task cancelled by operator");try{d.abort(new Error(w))}catch{}};a&&(a.aborted?h():a.addEventListener("abort",h,{once:!0}));let x=setTimeout(()=>{p=!0;try{d.abort(new Error(`orchestrator timed out after ${Math.round(l/6e4)}m`))}catch{}},l);x.unref?.();let T=()=>({content:"",...q(`Orchestrator timed out after ${Math.round(l/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||"this agent"}" if tasks need longer.`),duration:Date.now()-u});try{let w=s.provider||"claude-code",I=n?`${n}
29
29
 
30
- ${e.message}`:e.message,g=e.context?.sender,_=typeof g=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(g),A=e.context?.channel==="web-chat"&&_?{userId:g,agentId:e.agentId||"acme-public"}:void 0,S=Cn(s),y=Object.keys(S).length>0,O={task:I,cwd:s.workspace,provider:w,model:e.model||s.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:A,providerOpts:o,abortSignal:d.signal,mcpServers:y?S:void 0};if(r){let{generateStream:L}=await import("./agent-LI3AZQBC.js"),v="",b,k,R,U;for await(let P of L(O)){if(c)try{c(P)}catch{}if(P.type==="text_delta")v+=P.text,r(P.text,v);else if(P.type==="thinking_delta")P.text&&i&&i(P.text);else if(P.type==="generate_result"){if(P.result.content&&P.result.content!==v){let z=P.result.content.slice(v.length);z?(v=P.result.content,r(z,v)):v=P.result.content}b=P.result.tokensUsed,P.result.inputTokens!=null&&(k=P.result.inputTokens),P.result.outputTokens!=null&&(R=P.result.outputTokens)}else if(P.type==="done"){if(P.result.content&&P.result.content!==v){let z=P.result.content.slice(v.length);z?(v=P.result.content,r(z,v)):v=P.result.content}P.result.tokensUsed!=null&&(b=P.result.tokensUsed)}else P.type==="error"&&(U=P.error)}return U&&!v?p?T():U==="cancelled"||a?.aborted||d.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-u}:{content:"",...q(`Orchestrator error: ${U}`),duration:Date.now()-u}:((k===void 0||R===void 0)&&b&&(k=Math.round(b*.7),R=b-k),{content:v||"Done.",tokensUsed:b,usage:k!==void 0||R!==void 0?{inputTokens:k||0,outputTokens:R||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-u})}let{generate:C}=await import("./agent-LI3AZQBC.js"),E=await C(O),F=E.inputTokens,D=E.outputTokens;if((F===void 0||D===void 0)&&E.tokensUsed){let L=E.tokensUsed;F=Math.round(L*.7),D=L-F}return{content:E.content||"Done.",tokensUsed:E.tokensUsed,usage:F!==void 0||D!==void 0?{inputTokens:F||0,outputTokens:D||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-u}}catch(w){return p?T():w?.message==="cancelled"||a?.aborted||d.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-u}:{content:"",...q(`Orchestrator error: ${w.message}`),duration:Date.now()-u}}finally{clearTimeout(x),a&&a.removeEventListener("abort",h)}}async function So(s,e,t,n,r,o,i){let a=Xe();if(!a)return null;let c=Date.now(),u=e.context?.channel||"api",l=e.context?.chatId||e.context?.group||e.context?.sender||"default",d={agentId:e.agentId,channel:u,chatId:l};if(e.freshSession)try{await a.kill(d,"freshSession=true")}catch{}let p,h=!1;try{let v=a.list().length;p=a.acquire(d,{agentId:e.agentId,channel:u,chatId:l,workspace:s.workspace,model:e.model||s.model,permissionMode:s.permissionMode,billing:s.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:n}),h=a.list().length>v}catch(v){return v instanceof fe,null}h&&Et(e.agentId,s,e.model,n,"persistent");let x=ce(s,e,t),T="",w,I,g,_,A,S,y,O="",C="",E=v=>{if(!i||!v)return;let b;if(C&&v.startsWith(C)?b=v.slice(C.length):b=O&&!O.endsWith(`
30
+ ${e.message}`:e.message,g=e.context?.sender,_=typeof g=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(g),A=e.context?.channel==="web-chat"&&_?{userId:g,agentId:e.agentId||"acme-public"}:void 0,S=Cn(s),y=Object.keys(S).length>0,O={task:I,cwd:s.workspace,provider:w,model:e.model||s.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1,acmeContext:A,providerOpts:o,abortSignal:d.signal,mcpServers:y?S:void 0};if(r){let{generateStream:L}=await import("./agent-WT4RB5SO.js"),v="",b,k,R,U;for await(let P of L(O)){if(c)try{c(P)}catch{}if(P.type==="text_delta")v+=P.text,r(P.text,v);else if(P.type==="thinking_delta")P.text&&i&&i(P.text);else if(P.type==="generate_result"){if(P.result.content&&P.result.content!==v){let z=P.result.content.slice(v.length);z?(v=P.result.content,r(z,v)):v=P.result.content}b=P.result.tokensUsed,P.result.inputTokens!=null&&(k=P.result.inputTokens),P.result.outputTokens!=null&&(R=P.result.outputTokens)}else if(P.type==="done"){if(P.result.content&&P.result.content!==v){let z=P.result.content.slice(v.length);z?(v=P.result.content,r(z,v)):v=P.result.content}P.result.tokensUsed!=null&&(b=P.result.tokensUsed)}else P.type==="error"&&(U=P.error)}return U&&!v?p?T():U==="cancelled"||a?.aborted||d.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-u}:{content:"",...q(`Orchestrator error: ${U}`),duration:Date.now()-u}:((k===void 0||R===void 0)&&b&&(k=Math.round(b*.7),R=b-k),{content:v||"Done.",tokensUsed:b,usage:k!==void 0||R!==void 0?{inputTokens:k||0,outputTokens:R||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-u})}let{generate:C}=await import("./agent-WT4RB5SO.js"),E=await C(O),F=E.inputTokens,D=E.outputTokens;if((F===void 0||D===void 0)&&E.tokensUsed){let L=E.tokensUsed;F=Math.round(L*.7),D=L-F}return{content:E.content||"Done.",tokensUsed:E.tokensUsed,usage:F!==void 0||D!==void 0?{inputTokens:F||0,outputTokens:D||0,cacheReadTokens:0,cacheCreateTokens:0}:void 0,duration:Date.now()-u}}catch(w){return p?T():w?.message==="cancelled"||a?.aborted||d.signal.aborted?{content:"",error:"task cancelled by operator",errorKind:"cancelled",duration:Date.now()-u}:{content:"",...q(`Orchestrator error: ${w.message}`),duration:Date.now()-u}}finally{clearTimeout(x),a&&a.removeEventListener("abort",h)}}async function So(s,e,t,n,r,o,i){let a=Xe();if(!a)return null;let c=Date.now(),u=e.context?.channel||"api",l=e.context?.chatId||e.context?.group||e.context?.sender||"default",d={agentId:e.agentId,channel:u,chatId:l};if(e.freshSession)try{await a.kill(d,"freshSession=true")}catch{}let p,h=!1;try{let v=a.list().length;p=a.acquire(d,{agentId:e.agentId,channel:u,chatId:l,workspace:s.workspace,model:e.model||s.model,permissionMode:s.permissionMode,billing:s.billing,systemPromptAppend:e.systemPromptAppend,resumeSessionId:n}),h=a.list().length>v}catch(v){return v instanceof fe,null}h&&Et(e.agentId,s,e.model,n,"persistent");let x=ce(s,e,t),T="",w,I,g,_,A,S,y,O="",C="",E=v=>{if(!i||!v)return;let b;if(C&&v.startsWith(C)?b=v.slice(C.length):b=O&&!O.endsWith(`
31
31
  `)?`
32
32
 
33
33
  ${v}`:v,C=v,!!b){O+=b;try{i(b,O)}catch{}}},F=!1,D=()=>{F=!0,a.kill(d,"operator-cancel").catch(()=>{})};o&&(o.aborted?D():o.addEventListener("abort",D,{once:!0}));let L=!1;try{let v=Math.max(6e4,(s.maxExecutionMinutes??20)*6e4);for await(let b of p.runTurn({message:x,taskId:e.taskId??"unknown",deadlineMs:v})){if(L=!0,r)try{r(b.raw)}catch{}if(b.type==="assistant"){let k=b.raw.message?.content??[];for(let U of k)U.type==="text"&&typeof U.text=="string"?(T=U.text,E(U.text)):U.type==="tool_use"&&(C="");let R=b.raw.message?.usage;if(R){let U=(R.input_tokens||0)+(R.cache_read_input_tokens||0)+(R.cache_creation_input_tokens||0);U>0&&(_=U)}}if(b.type==="result"){let k=b.raw;if(k.is_error){let R=q(typeof k.result=="string"?k.result:"claude error");w=R.error,I=R.errorKind}else typeof k.result=="string"&&k.result.length>0&&(T=k.result,O||E(k.result));typeof k.session_id=="string"&&(y=k.session_id),k.usage&&(g={inputTokens:k.usage.input_tokens||0,outputTokens:k.usage.output_tokens||0,cacheReadTokens:k.usage.cache_read_input_tokens||0,cacheCreateTokens:k.usage.cache_creation_input_tokens||0}),typeof k.num_turns=="number"&&(A=k.num_turns),typeof k.message?.model=="string"?S=k.message.model:typeof k.model=="string"&&(S=k.model)}}}catch(v){if(F)w="task cancelled by operator",I="cancelled";else if(L)if(v instanceof Me){let b=q(`Claude Code timed out after ${Math.round(v.budgetMs/6e4)}m. Bump agent.maxExecutionMinutes for "${s.name||e.agentId}" if tasks need longer.`);w=b.error,I=b.errorKind}else{let b=q(`persistent claude process error: ${v?.message||String(v)}`);w=b.error,I=b.errorKind}else return console.error(`[runtime] persistent handle unusable before first event (${v?.message||v}); falling back to spawn-per-task`),a.release(d,{kill:!0,reason:"pre-turn failure"}),o&&o.removeEventListener("abort",D),null}finally{o&&o.removeEventListener("abort",D)}return F&&!w&&(w="task cancelled by operator",I="cancelled"),{content:F?"":T,error:w,errorKind:I,duration:Date.now()-c,usage:g,contextTokens:_,numTurns:A,billedModel:S,claudeSessionId:y}}function xs(s){return re(s.autonomy)?s.taskId?ns(s.autonomy,s.agentId,s.taskId):{error:`autonomy "${s.autonomy}" requires a task id to enforce`}:{args:[]}}async function vo(s,e,t,n,r,o,i){let a=e.autonomy,c=ss(a,s.tier);if(c)return{content:"",error:c,autonomy:a};let u=e.taskId||`autonomy-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`,l={...e,taskId:u,message:`${bn(a)}
@@ -157,4 +157,4 @@ ${X}`),f+=X.length}catch{}}}let Er=ut.length>0?ut.join(`
157
157
  Agent: ${$.content}`,meta:qi(D,e.context)})}catch{}Rn(e.agentId,e.message,$.content,{channel:g,chatId:y,sender:O},this.memoryStore).catch(()=>{}),Hs(e.agentId,e.message,$.content,{channel:g,date:new Date().toISOString().slice(0,10)},this.patternStore).catch(()=>{})}let Q=$.billedModel||e.model||a.def.model,se=e.context?.channel,We=se&&(e.context?.chatId||e.context?.group||e.context?.sender)?`${se}:${e.context?.chatId||e.context?.group||e.context?.sender}`:void 0;this.tokenTracker.record(e.agentId,$.duration||0,$.usage,e.message.length,$.content.length,!1,Q,se,We),this.log(`[${e.agentId}] completed in ${$.duration}ms`+($.tokensUsed?` (${$.tokensUsed} tokens)`:""))}return $}catch(m){a.errors++,this.log(`[${e.agentId}] unexpected error: ${m.message}`);let f=Qe(m.message);return Z={content:"",error:ze(f),errorKind:f.kind},Z}finally{mn.stop(),a.activeTasks--;let m=a.runningTasks.findIndex(f=>f.id===d.id);m!==-1&&a.runningTasks.splice(m,1),this.taskAborts.delete(d.id),h.done=!0,h.endedAt=new Date;for(let f of h.subscribers)try{f(`
158
158
  [task finished]
159
159
  `)}catch{}h.subscribers.clear(),setTimeout(()=>this.taskOutputs.delete(d.id),Wi).unref?.();try{let f=h.endedAt,M={id:d.id,agentId:e.agentId,channel:d.channel,chatId:d.chatId,sender:d.sender,message:e.message||"",startedAt:d.startedAt.toISOString(),endedAt:f.toISOString(),durationMs:f.getTime()-d.startedAt.getTime(),ok:!Z?.error,error:Z?.error,responseText:Z?.content||"",transcript:h.buffer};this.persistTaskRecord(M);let N=(M.responseText||M.error||"").trim();if(N){let W=N.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(e.agentId,{text:W,at:f,ok:M.ok})}}catch(f){this.log(`[${e.agentId}] task history persist failed: ${f?.message}`)}this.messageQueue.markDone(e.agentId,c,u).then(f=>{if(f.length!==0){this.log(`[${e.agentId}] flushing ${f.length} queued message(s)`);for(let M of f){let N=M.originalContext||{channel:M.channel,sender:M.sender,chatId:M.chatId};this.execute({message:M.text,agentId:e.agentId,context:N}).then(W=>this.postQueuedResponseToChannel(e.agentId,N,W)).catch(W=>{this.log(`[${e.agentId}] queued message failed: ${W.message}`)})}}}).catch(f=>{this.log(`[${e.agentId}] queue flush failed: ${f.message}`)})}}getActiveTaskCount(){let e=0;for(let t of this.agents.values())e+=t.activeTasks;return e}list(){return Array.from(this.agents.values()).map(e=>{let t=this.lastSummaries.get(e.id);return{id:e.id,name:e.def.name,tier:e.def.tier,model:e.def.model,workspace:e.def.workspace,active:e.activeTasks,total:e.totalTasks,errors:e.errors,lastActive:e.lastActive,runningTasks:e.runningTasks,lastSummary:t?{text:t.text,at:t.at.toISOString(),ok:t.ok}:void 0,hourlyTasks:this.getHourlySparkline(e.id,24)}})}persistTaskRecord(e){let t=e.endedAt.slice(0,10),n=B(process.cwd(),Ie,this.safe(e.agentId),t);Y(n)||ji(n,{recursive:!0});let r=B(n,`${this.safe(e.id)}.json`);Bi(r,JSON.stringify(e,null,2),"utf-8")}getHourlySparkline(e,t=24){let n=Date.now(),r=this.sparklineCache.get(e);if(r&&n-r.at<6e4&&r.hourly.length===t)return r.hourly;let o=new Array(t).fill(0),i=n-t*36e5,a=B(process.cwd(),Ie,this.safe(e));if(!Y(a))return this.sparklineCache.set(e,{hourly:o,at:n}),o;let c=new Date(n).toISOString().slice(0,10),u=new Date(n-864e5).toISOString().slice(0,10);new Date(n).setUTCHours(0,0,0,0);for(let d of[u,c]){let p=B(a,d);if(Y(p))try{for(let h of ne(p)){if(!h.endsWith(".json"))continue;let x=h.split("-")[0],T=parseInt(x,10);if(!Number.isFinite(T)||T<i||T>n)continue;let w=Math.floor((n-T)/36e5),I=t-1-w;I>=0&&I<t&&o[I]++}}catch{}}return this.sparklineCache.set(e,{hourly:o,at:n}),o}hydrateLastSummariesFromDisk(){let e=B(process.cwd(),Ie);if(!Y(e))return 0;let t=0;for(let n of ne(e)){let r=B(e,n),o;try{o=ne(r).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse()}catch{continue}e:for(let i of o){let a=B(r,i),c;try{c=ne(a).filter(u=>u.endsWith(".json")).sort().reverse()}catch{continue}for(let u of c)try{let l=JSON.parse(Ne(B(a,u),"utf-8")),d=(l.responseText||l.error||"").trim();if(!d)continue;let p=d.split(/\r?\n/)[0].slice(0,140);this.lastSummaries.set(l.agentId,{text:p,at:new Date(l.endedAt),ok:l.ok}),t++;break e}catch{}}}return t}pruneTaskHistory(e=Ki){let t=B(process.cwd(),Ie);if(!Y(t))return 0;let n=Date.now()-e*24*60*60*1e3,r=0;for(let o of ne(t)){let i=B(t,o),a;try{a=ne(i)}catch{continue}for(let c of a){let u=Date.parse(c+"T00:00:00Z");if(!(Number.isNaN(u)||u>=n))try{Ui(B(i,c),{recursive:!0,force:!0}),r++}catch{}}}return r}listTaskHistory(e,t=50){let n=B(process.cwd(),Ie,this.safe(e));if(!Y(n))return[];let r=ne(n).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse(),o=[];for(let i of r){if(o.length>=t)break;let a=B(n,i),c;try{c=ne(a).filter(u=>u.endsWith(".json"))}catch{continue}c.sort().reverse();for(let u of c){if(o.length>=t)break;try{let l=JSON.parse(Ne(B(a,u),"utf-8")),{transcript:d,responseText:p,...h}=l;o.push(h)}catch{}}}return o}getTaskRecord(e,t){let n=B(process.cwd(),Ie,this.safe(e));if(!Y(n))return null;let r=this.safe(t),o=ne(n).filter(i=>/^\d{4}-\d{2}-\d{2}$/.test(i)).sort().reverse();for(let i of o){let a=B(n,i,`${r}.json`);if(Y(a))try{return JSON.parse(Ne(a,"utf-8"))}catch{return null}}return null}safe(e){return e.replace(/[^a-zA-Z0-9_.:-]/g,"_")}postQueuedResponseToChannel(e,t,n){let r=jn();if(!r)return;let o=t?.channel,i=t?.chatId;if(!o||!i||n.errorKind==="cancelled"||n.error?.startsWith("__queued__"))return;let a=n.error?`Error: ${n.error}`:(n.content||"").trim();a&&r.sendOutbound({channel:o,chatId:i,text:a,agentId:e}).catch(c=>this.log(`[${e}] queued response post failed: ${c?.message??c}`))}runningTaskOwner(e){for(let t of this.agents.values()){let n=t.runningTasks.find(r=>r.id===e);if(n)return{agentId:t.id,channel:n.channel,chatId:n.chatId}}return null}cancelRunningTask(e,t="operator"){let n=this.taskAborts.get(e);if(!n)return null;try{n.controller.abort(new Error(t))}catch{}return this.log(`[${n.agentId}] task ${e} cancelled \u2014 ${t}`),{agentId:n.agentId,channel:n.channel,chatId:n.chatId}}queueFollowUp(e,t,n,r={}){let o=this.taskAborts.get(e);if(!o)return null;let{agentId:i,channel:a,chatId:c,originalMessage:u}=o,l=o.controller.signal.aborted,d=!1;l&&u&&(d=this.sessions.removeLastUserMessageIfMatches(i,a,c,u)),this.messageQueue.enqueue(i,a,c,{text:t,sender:n,timestamp:Date.now(),channel:a,chatId:c,originalContext:{channel:a,chatId:c,sender:n}});let p=this.messageQueue.pendingCount(i,a,c),h=!1;if(r.replace){let x=r.reason||`replaced by follow-up from ${n}`;try{o.controller.abort(new Error(x))}catch{}this.log(`[${i}] task ${e} replaced by follow-up \u2014 ${x}`),h=!0}else this.log(`[${i}] follow-up queued for task ${e} (pending=${p}${d?", edited cancelled turn":""})`);return{agentId:i,channel:a,chatId:c,replaced:h,edited:d,pending:p}}async continueFinishedTask(e,t,n,r,o={}){let i=this.getTaskRecord(e,t);if(!i)return{ok:!1,status:404,error:`no task ${t} for agent ${e}`};if(i.channel!=="cron"||!i.chatId)return{ok:!1,status:409,error:`task ${t} is finished; only scheduled (cron) runs can be resumed from the dashboard`};let a=i.channel,c=i.chatId;return new Promise(u=>{let l=!1,d=p=>{l||(l=!0,u(p))};this.log(`[${e}] operator resumed ${a}:${c} from finished task ${t}`),this.execute({message:n,agentId:e,model:o.model?.(c),context:{channel:a,chatId:c,sender:r},onStart:p=>d({ok:!0,agentId:e,channel:a,chatId:c,taskId:p,queued:!1})}).then(p=>{p.error?.startsWith("__queued__")?d({ok:!0,agentId:e,channel:a,chatId:c,queued:!0}):p.error?d({ok:!1,status:500,error:p.error||"run did not start"}):d({ok:!0,agentId:e,channel:a,chatId:c,queued:!1,answeredBy:p.viaAttachedSession?"attached":"other"})}).catch(p=>d({ok:!1,status:500,error:p?.message??String(p)}))})}subscribeToTaskOutput(e,t){let n=this.taskOutputs.get(e);return n?n.done?{initial:n.buffer,done:!0,unsubscribe:()=>{}}:(n.subscribers.add(t),{initial:n.buffer,done:!1,unsubscribe:()=>{n.subscribers.delete(t)}}):null}getUsage(e=7){return this.tokenTracker.summary(e)}getTodayUsage(){return this.tokenTracker.today()}getTokenTracker(){return this.tokenTracker}};export{Jn as a,Qn as b,aa as c,Xn as d,eo as e,Yn as f,es as g,wa as h,Ia as i,Sa as j,fo as k,bs as l,To as m,ko as n,Io as o,Ts as p,tt as q,nt as r,st as s,te as t,js as u,si as v,Us as w,Ee as x,Ai as y,$i as z,Mi as A,Pi as B,Ri as C,zt as D,Od as E,Ed as F,qi as G,Gi as H,tn as I,wr as J,xr as K,Ji as L,Tr as M,kr as N};
160
- //# sourceMappingURL=chunk-GAUQOIEE.js.map
160
+ //# sourceMappingURL=chunk-7KED5NB2.js.map
@@ -0,0 +1,13 @@
1
+ import{existsSync as l}from"node:fs";import{dirname as a,join as i}from"node:path";var p="tn.acme.agentx.voice",A="AgentX Desktop.app",c="AgentX Helper.app";function d(t,n,r){return t!=="darwin"||n!=="arm64"||Number(r.split(".")[0])<23?"AgentX Desktop currently requires Apple Silicon and macOS 14 or newer.":null}function f(t,n){if(n&&!Object.hasOwn(t,n))throw new Error(`Unknown agent: ${n}. Run agentx agent list.`);let r=n||Object.keys(t)[0];if(!r)throw new Error("No agents configured. Run agentx setup first.");return r}function g(t){return`'${t.replace(/'/g,"'\\''")}'`}var o="/usr/bin:/bin:/usr/sbin:/sbin";function m(t,n){return n||[...new Set([...t?[a(t)]:[],...o.split(":")])].join(":")}function x(t){let n=t.match(/<key>PATH<\/key>\s*<string>([^<]*)<\/string>/);if(!n)return o;let r={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};return n[1].replace(/&(amp|lt|gt|quot|apos);/g,(e,s)=>r[s])}function P(t,n,r){for(let e of n.split(":"))if(e&&r(i(e,t)))return i(e,t);return null}function E(t){let n=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"),r={PATH:t.path,AGENTX_VOICE_AGENT:t.agent,AGENTX_DAEMON_URL:t.url,AGENTX_MAC_HELPER:t.helper,AGENTX_PASTE_COMMAND:`cd ${g(t.cwd)} && ${g(t.node)} ${g(t.cli)} paste`};return`<?xml version="1.0" encoding="UTF-8"?>
2
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
+ <plist version="1.0"><dict>
4
+ <key>Label</key><string>${p}</string>
5
+ <key>ProgramArguments</key><array><string>${n(t.executable)}</string></array>
6
+ <key>WorkingDirectory</key><string>${n(t.cwd)}</string>
7
+ <key>EnvironmentVariables</key><dict>${Object.entries(r).map(([e,s])=>`<key>${e}</key><string>${n(s)}</string>`).join("")}</dict>
8
+ <key>RunAtLoad</key><true/><key>KeepAlive</key><true/>
9
+ <key>ProcessType</key><string>Interactive</string>
10
+ <key>StandardErrorPath</key><string>${n(t.log)}</string>
11
+ </dict></plist>
12
+ `}function h(t){return t?["--icon",t]:[]}function u(t){return i(t,"Applications",c,"Contents/MacOS/agentx-mac-helper")}function T(t,n,r){if(r)return r;let e=u(n);return l(e)?e:i(t,"apps/mac-helper/build/AgentX Helper.app/Contents/MacOS/agentx-mac-helper")}export{p as a,A as b,c,d,f as e,m as f,x as g,P as h,E as i,h as j,u as k,T as l};
13
+ //# sourceMappingURL=chunk-7L6M3P2N.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/desktop/install.ts"],"sourcesContent":["import { existsSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\n\nexport const DESKTOP_LABEL = 'tn.acme.agentx.voice'\nexport const DESKTOP_APP = 'AgentX Desktop.app'\nexport const HELPER_APP = 'AgentX Helper.app'\nexport function desktopPlatformError(platform: string, arch: string, release: string): string | null {\n if (platform !== 'darwin' || arch !== 'arm64' || Number(release.split('.')[0]) < 23)\n return 'AgentX Desktop currently requires Apple Silicon and macOS 14 or newer.'\n return null\n}\nexport function selectDesktopAgent(agents: Record<string, unknown>, requested?: string): string {\n if (requested && !Object.hasOwn(agents, requested)) throw new Error(`Unknown agent: ${requested}. Run agentx agent list.`)\n const id = requested || Object.keys(agents)[0]\n if (!id) throw new Error('No agents configured. Run agentx setup first.')\n return id\n}\nexport function shellQuote(value: string): string { return `'${value.replace(/'/g, \"'\\\\''\")}'` }\n/** launchd's default PATH, which is all a login item gets unless the plist sets one. */\nexport const LAUNCHD_PATH = '/usr/bin:/bin:/usr/sbin:/sbin'\n/** PATH for the login item: AGENTX_VOICE_PATH when set, else the folder of\n * the ffmpeg found at install time (mlx_whisper needs it) ahead of launchd's default. */\nexport function desktopPath(ffmpeg: string | null, override?: string): string {\n if (override) return override\n return [...new Set([...(ffmpeg ? [dirname(ffmpeg)] : []), ...LAUNCHD_PATH.split(':')])].join(':')\n}\n/** The PATH a login item plist sets, or launchd's default when it sets none. */\nexport function plistPathEnv(plist: string): string {\n const m = plist.match(/<key>PATH<\\/key>\\s*<string>([^<]*)<\\/string>/)\n if (!m) return LAUNCHD_PATH\n const ents: Record<string, string> = { amp: '&', lt: '<', gt: '>', quot: '\"', apos: \"'\" }\n return m[1].replace(/&(amp|lt|gt|quot|apos);/g, (_, e) => ents[e])\n}\n/** The file that a process with this PATH would run, or null. */\nexport function findOnPath(bin: string, path: string, isExecutable: (file: string) => boolean): string | null {\n for (const dir of path.split(':')) if (dir && isExecutable(join(dir, bin))) return join(dir, bin)\n return null\n}\nexport function desktopPlist(opts: { executable: string; cwd: string; agent: string; url: string; helper: string; cli: string; node: string; log: string; path: string }): string {\n const xml = (s: string) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;').replace(/'/g, '&apos;')\n const env = {\n PATH: opts.path,\n AGENTX_VOICE_AGENT: opts.agent,\n AGENTX_DAEMON_URL: opts.url,\n AGENTX_MAC_HELPER: opts.helper,\n AGENTX_PASTE_COMMAND: `cd ${shellQuote(opts.cwd)} && ${shellQuote(opts.node)} ${shellQuote(opts.cli)} paste`,\n }\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\"><dict>\n<key>Label</key><string>${DESKTOP_LABEL}</string>\n<key>ProgramArguments</key><array><string>${xml(opts.executable)}</string></array>\n<key>WorkingDirectory</key><string>${xml(opts.cwd)}</string>\n<key>EnvironmentVariables</key><dict>${Object.entries(env).map(([k,v]) => `<key>${k}</key><string>${xml(v)}</string>`).join('')}</dict>\n<key>RunAtLoad</key><true/><key>KeepAlive</key><true/>\n<key>ProcessType</key><string>Interactive</string>\n<key>StandardErrorPath</key><string>${xml(opts.log)}</string>\n</dict></plist>\\n`\n}\n/** build.sh arguments for the helper: the banner icon from\n * notifications.local.icon, or none for the bundled AgentX logo. */\nexport function helperBuildArgs(icon?: string): string[] {\n return icon ? ['--icon', icon] : []\n}\nexport function installedHelper(home: string): string {\n return join(home, 'Applications', HELPER_APP, 'Contents/MacOS/agentx-mac-helper')\n}\nexport function resolveHelper(cwd: string, home: string, override?: string): string {\n if (override) return override\n const installed = installedHelper(home)\n return existsSync(installed) ? installed : join(cwd, 'apps/mac-helper/build/AgentX Helper.app/Contents/MacOS/agentx-mac-helper')\n}\n"],"mappings":"AAAA,OAAS,cAAAA,MAAkB,UAC3B,OAAS,WAAAC,EAAS,QAAAC,MAAY,YAEvB,IAAMC,EAAgB,uBAChBC,EAAc,qBACdC,EAAa,oBACnB,SAASC,EAAqBC,EAAkBC,EAAcC,EAAgC,CACnG,OAAIF,IAAa,UAAYC,IAAS,SAAW,OAAOC,EAAQ,MAAM,GAAG,EAAE,CAAC,CAAC,EAAI,GACxE,yEACF,IACT,CACO,SAASC,EAAmBC,EAAiCC,EAA4B,CAC9F,GAAIA,GAAa,CAAC,OAAO,OAAOD,EAAQC,CAAS,EAAG,MAAM,IAAI,MAAM,kBAAkBA,2BAAmC,EACzH,IAAMC,EAAKD,GAAa,OAAO,KAAKD,CAAM,EAAE,CAAC,EAC7C,GAAI,CAACE,EAAI,MAAM,IAAI,MAAM,+CAA+C,EACxE,OAAOA,CACT,CACO,SAASC,EAAWC,EAAuB,CAAE,MAAO,IAAIA,EAAM,QAAQ,KAAM,OAAO,IAAK,CAExF,IAAMC,EAAe,gCAGrB,SAASC,EAAYC,EAAuBC,EAA2B,CAC5E,OAAIA,GACG,CAAC,GAAG,IAAI,IAAI,CAAC,GAAID,EAAS,CAACjB,EAAQiB,CAAM,CAAC,EAAI,CAAC,EAAI,GAAGF,EAAa,MAAM,GAAG,CAAC,CAAC,CAAC,EAAE,KAAK,GAAG,CAClG,CAEO,SAASI,EAAaC,EAAuB,CAClD,IAAMC,EAAID,EAAM,MAAM,8CAA8C,EACpE,GAAI,CAACC,EAAG,OAAON,EACf,IAAMO,EAA+B,CAAE,IAAK,IAAK,GAAI,IAAK,GAAI,IAAK,KAAM,IAAK,KAAM,GAAI,EACxF,OAAOD,EAAE,CAAC,EAAE,QAAQ,2BAA4B,CAACE,EAAGC,IAAMF,EAAKE,CAAC,CAAC,CACnE,CAEO,SAASC,EAAWC,EAAaC,EAAcC,EAAwD,CAC5G,QAAWC,KAAOF,EAAK,MAAM,GAAG,EAAG,GAAIE,GAAOD,EAAa3B,EAAK4B,EAAKH,CAAG,CAAC,EAAG,OAAOzB,EAAK4B,EAAKH,CAAG,EAChG,OAAO,IACT,CACO,SAASI,EAAaC,EAAqJ,CAChL,IAAMC,EAAOC,GAAcA,EAAE,QAAQ,KAAM,OAAO,EAAE,QAAQ,KAAM,MAAM,EAAE,QAAQ,KAAM,MAAM,EAAE,QAAQ,KAAM,QAAQ,EAAE,QAAQ,KAAM,QAAQ,EACxIC,EAAM,CACV,KAAMH,EAAK,KACX,mBAAoBA,EAAK,MACzB,kBAAmBA,EAAK,IACxB,kBAAmBA,EAAK,OACxB,qBAAsB,MAAMlB,EAAWkB,EAAK,GAAG,QAAQlB,EAAWkB,EAAK,IAAI,KAAKlB,EAAWkB,EAAK,GAAG,SACrG,EACA,MAAO;AAAA;AAAA;AAAA,0BAGiB7B;AAAA,4CACkB8B,EAAID,EAAK,UAAU;AAAA,qCAC1BC,EAAID,EAAK,GAAG;AAAA,uCACV,OAAO,QAAQG,CAAG,EAAE,IAAI,CAAC,CAACC,EAAEC,CAAC,IAAM,QAAQD,kBAAkBH,EAAII,CAAC,YAAY,EAAE,KAAK,EAAE;AAAA;AAAA;AAAA,sCAGxFJ,EAAID,EAAK,GAAG;AAAA;AAAA,CAElD,CAGO,SAASM,EAAgBC,EAAyB,CACvD,OAAOA,EAAO,CAAC,SAAUA,CAAI,EAAI,CAAC,CACpC,CACO,SAASC,EAAgBC,EAAsB,CACpD,OAAOvC,EAAKuC,EAAM,eAAgBpC,EAAY,kCAAkC,CAClF,CACO,SAASqC,EAAcC,EAAaF,EAActB,EAA2B,CAClF,GAAIA,EAAU,OAAOA,EACrB,IAAMyB,EAAYJ,EAAgBC,CAAI,EACtC,OAAOzC,EAAW4C,CAAS,EAAIA,EAAY1C,EAAKyC,EAAK,0EAA0E,CACjI","names":["existsSync","dirname","join","DESKTOP_LABEL","DESKTOP_APP","HELPER_APP","desktopPlatformError","platform","arch","release","selectDesktopAgent","agents","requested","id","shellQuote","value","LAUNCHD_PATH","desktopPath","ffmpeg","override","plistPathEnv","plist","m","ents","_","e","findOnPath","bin","path","isExecutable","dir","desktopPlist","opts","xml","s","env","k","v","helperBuildArgs","icon","installedHelper","home","resolveHelper","cwd","installed"]}
@@ -1,4 +1,4 @@
1
- import{a as $e,b as Pe}from"./chunk-VMDA2SX2.js";import{a as ee}from"./chunk-QLTM3F7M.js";import{b as Ie,c as Se,e as Ae,f as Re,i as Te}from"./chunk-BIFJSQB5.js";import{b as te}from"./chunk-AFRHKA7B.js";import{v as ve,w as gt}from"./chunk-6HMZ5TTM.js";import{b as be,f as ft}from"./chunk-F4HZTZHW.js";import{existsSync as mt,mkdirSync as Ne,readFileSync as ht,writeFileSync as wt,renameSync as yt}from"fs";import{resolve as xe,dirname as kt}from"path";var We=class{filePath;log;constructor(e={}){let t=e.baseDir??xe(process.cwd(),".agentx");this.filePath=xe(t,"handover.json"),this.log=e.log??console.error.bind(console,"[handover]"),Ne(t,{recursive:!0})}key(e,t,r){return`${e}::${t}::${r||"-"}`}load(){if(!mt(this.filePath))return{version:1,overrides:{}};try{let e=ht(this.filePath,"utf-8"),t=JSON.parse(e);return!t||typeof t!="object"?{version:1,overrides:{}}:(t.overrides||(t.overrides={}),t)}catch(e){return this.log(`load failed, starting empty: ${e?.message||e}`),{version:1,overrides:{}}}}save(e){Ne(kt(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp-${process.pid}`;wt(t,JSON.stringify(e,null,2)),yt(t,this.filePath)}get(e,t,r){let i=this.load().overrides[this.key(e,t,r)];if(i&&!(i.expiresAt&&Date.parse(i.expiresAt)<Date.now()))return i}set(e){if(!e.channel||!e.chatId||!e.toAgent)throw new Error("channel, chatId and toAgent are required");let t=this.load(),r={...e,createdAt:e.createdAt??new Date().toISOString()};return t.overrides[this.key(r.channel,r.chatId,r.accountId)]=r,this.save(t),r}remove(e,t,r){let o=this.load(),i=this.key(e,t,r);return i in o.overrides?(delete o.overrides[i],this.save(o),!0):!1}consumeSummary(e,t,r){let o=this.load(),i=o.overrides[this.key(e,t,r)];if(!i||!i.summary||i.summaryConsumedAt)return;let s=i.summary;return i.summaryConsumedAt=new Date().toISOString(),this.save(o),s}listActive(){let e=this.load(),t=Date.now();return Object.values(e.overrides).filter(r=>!r.expiresAt||Date.parse(r.expiresAt)>=t)}listByAgent(e){let t=this.listActive();return{incoming:t.filter(r=>r.toAgent===e),outgoing:t.filter(r=>r.fromAgent===e)}}};import{existsSync as I,mkdirSync as _t,readdirSync as U,readFileSync as K,unlinkSync as B,writeFileSync as oe}from"fs";import{resolve as R,relative as ie}from"path";import{z as l}from"zod";var bt=l.enum(["trigger.channel","trigger.manual","trigger.cron","trigger.hook","trigger.form","agent","transform","classify","branch","gateway.parallel","rule","action.send","action.createIssue","action.setLabel","action.readLabel","action.react","action.editMessage","action.logTime","action.callHTTP","action.run","action.builtin","subProcess","signal.emit","signal.wait","timer.boundary","checkpoint","end"]),vt=l.enum(["equals","contains","matches","exists"]),It=l.object({kind:vt,params:l.record(l.unknown()).default({})}),Ee=l.object({maxAttempts:l.number().int().min(1).max(10).default(1),backoffMs:l.number().int().min(0).max(6e4).default(1e3)}).default({maxAttempts:1,backoffMs:1e3}),je=l.object({id:l.string().min(1).regex(/^[a-zA-Z_][a-zA-Z0-9_-]*$/,"node id must be identifier-safe"),type:bt,config:l.record(l.unknown()).default({}),retry:Ee,position:l.object({x:l.number(),y:l.number()}).optional()}),Fe=l.object({from:l.string(),fromPort:l.string().optional(),to:l.string(),toPort:l.string().optional(),label:l.string().optional()}),Oe=l.union([l.string(),l.date().transform(n=>n.toISOString())]),$=l.object({id:l.string().regex(/^[a-z0-9][a-z0-9_-]*$/,"workflow id must be lower-kebab"),version:l.literal(2).default(2),title:l.string().min(1),description:l.string().optional(),status:l.enum(["draft","review","active","deprecated"]).default("active"),tags:l.array(l.string()).default([]),project:l.string().optional(),entity:l.string().optional(),intentPath:l.array(l.string()).default([]),generatedFrom:l.string().optional(),sourceTaskIds:l.array(l.string()).default([]),confidence:l.number().min(0).max(1).optional(),workflowVersion:l.string().optional(),ownerAgent:l.string().optional(),lastMatchedAt:l.string().optional(),matchCount:l.number().int().min(0).default(0),state:l.enum(["active","disabled","quarantined"]).default("active"),priority:l.number().int().default(0),fanOut:l.boolean().default(!1),nodes:l.array(je).refine(n=>n.length>0,{message:"workflow must have at least one node"}),edges:l.array(Fe).default([]),envAllow:l.array(l.string()).default([]),retention:l.object({maxRuns:l.number().int().positive().default(500),maxDays:l.number().int().positive().default(90)}).default({maxRuns:500,maxDays:90}),maxChildDepth:l.number().int().positive().default(5),mesh:l.object({allowRemote:l.boolean().default(!1),peers:l.array(l.string()).optional()}).default({allowRemote:!1}),created:Oe.optional(),updated:Oe.optional()});function ne(n){let e=[],t=new Map(n.nodes.map(s=>[s.id,s])),r=n.nodes.filter(s=>s.type.startsWith("trigger."));r.length===0&&e.push("workflow must have exactly one trigger.* node (found 0)"),r.length>1&&e.push(`workflow has ${r.length} trigger.* nodes; v1 supports exactly one`);for(let s of n.edges)t.has(s.from)||e.push(`edge references missing node: from="${s.from}"`),t.has(s.to)||e.push(`edge references missing node: to="${s.to}"`);let o=r[0];if(o){let s=new Map;for(let u of n.edges)s.has(u.from)||s.set(u.from,[]),s.get(u.from).push(u.to);let a=new Set,d=[o.id];for(;d.length;){let u=d.pop();if(!a.has(u)){a.add(u);for(let c of s.get(u)??[])d.push(c)}}for(let u of n.nodes)a.has(u.id)||e.push(`node "${u.id}" is unreachable from trigger "${o.id}"`);n.nodes.some(u=>a.has(u.id)&&St(u.type))||e.push("no reachable `end`, `checkpoint`, `subProcess`, `signal.wait`, or `timer.boundary` node \u2014 the run cannot terminate or pause")}for(let s of n.nodes){if(s.type!=="branch"&&s.type!=="rule")continue;let a=s.type==="branch"?s.config.cases??[]:(s.config.rules??[]).filter(p=>typeof p.to=="string"),d=s.type==="branch"?s.config.default:s.config.default?.to,u=new Set(a.map(p=>p.to));d&&u.add(d);let c=n.edges.filter(p=>p.from===s.id);for(let p of c){let f=p.fromPort??"";u.has(f)||e.push(`${s.type} "${s.id}" has outgoing edge with port "${f}" not declared in cases or default`)}}let i=Rt(n);for(let s of i)e.push(`cycle without agent/checkpoint: ${s.join(" -> ")}`);return e}function St(n){return n==="end"||n==="checkpoint"||n==="subProcess"||n==="signal.wait"||n==="timer.boundary"}function At(n){return n==="agent"||n==="checkpoint"||n==="subProcess"||n==="signal.wait"||n==="timer.boundary"}function Rt(n){let e=new Map;for(let a of n.edges)e.has(a.from)||e.set(a.from,[]),e.get(a.from).push(a.to);let t=new Map(n.nodes.map(a=>[a.id,a])),r=[],o=new Map,i=[],s=a=>{if(o.get(a)===1){let d=i.indexOf(a);if(d>=0){let u=i.slice(d).concat(a);u.some(p=>{let f=t.get(p)?.type;return f?At(f):!1})||r.push(u)}return}if(o.get(a)!==2){o.set(a,1),i.push(a);for(let d of e.get(a)??[])s(d);i.pop(),o.set(a,2)}};for(let a of n.nodes)o.get(a.id)!==2&&s(a.id);return r}var Ce=l.enum(["running","paused","completed","failed","canceled"]),$t=l.enum(["ok","failed","timeout","skipped","paused","resumed"]),Pt=l.object({at:l.string(),nodeId:l.string(),inputKeys:l.array(l.string()).default([]),status:$t,output:l.record(l.unknown()).optional(),idempotencyKey:l.string(),note:l.string().optional()}),Tt=l.object({backend:l.string(),id:l.string()}),Nt=l.discriminatedUnion("kind",[l.object({kind:l.literal("checkpoint"),nodeId:l.string(),checkpointName:l.string(),resumeMatch:l.record(l.unknown()).default({})}),l.object({kind:l.literal("subProcess"),nodeId:l.string(),childRunId:l.string(),childWorkflowId:l.string()}),l.object({kind:l.literal("signalWait"),nodeId:l.string(),signalName:l.string(),match:l.record(l.unknown()).default({}),scope:l.enum(["workflow","global"]).default("workflow")}),l.object({kind:l.literal("timerWait"),nodeId:l.string(),fireAt:l.string()})]),xt=l.object({id:l.string(),workflowId:l.string(),workflowVersion:l.literal(2),homeNode:l.string(),status:Ce,pausedAt:Nt.optional(),context:l.record(l.record(l.unknown())).default({}),pending:l.array(l.string()).default([]),joinCounters:l.record(l.array(l.string())).default({}),entityRef:Tt,history:l.array(Pt).default([]),parentRunId:l.string().nullable().default(null),parentNodeId:l.string().nullable().default(null),rootRunId:l.string().nullable().default(null),depth:l.number().int().min(0).default(0),createdAt:l.string(),updatedAt:l.string()});import Me from"js-yaml";var Wt=new Set(["branch","gateway.parallel","rule","signal.wait","subProcess","timer.boundary","checkpoint"]),v=class extends Error{constructor(t,r){super(t);this.mark=r;this.name="WorkflowYamlError"}};function L(n,e={}){if(!n||n.trim()==="")throw new v(`${P(e)}empty file \u2014 workflow YAML must contain at least an id, version, title, and one node.`);let t;try{t=Me.loadAll(n)}catch(o){let i=o?.mark;throw new v(`${P(e)}YAML parse error: ${o?.reason??o?.message??o}`+(i?` (line ${i.line+1}, column ${i.column+1})`:""),i)}if(t.length===0||t.length===1&&t[0]==null)throw new v(`${P(e)}YAML produced no document.`);if(t.length>1)throw new v(`${P(e)}multi-document YAML is not supported in v1; one workflow per file.`);let r=t[0];if(typeof r!="object"||r===null||Array.isArray(r)){let o=Array.isArray(r)?"array":typeof r;throw new v(`${P(e)}top-level YAML must be a mapping (got ${o}).`)}return _e(r,e)}function _e(n,e={}){if(!("flow"in n))return n;let t=n.flow;if(t==null){let p={...n};return delete p.flow,p}if(!Array.isArray(t))throw new v(`${P(e)}flow must be an array of node ids (got ${typeof t}).`);for(let p of t)if(typeof p!="string")throw new v(`${P(e)}flow entries must be strings (got ${typeof p}).`);let r=t,o=Array.isArray(n.nodes)?n.nodes:[],i=new Map;for(let p of o)p&&typeof p=="object"&&typeof p.id=="string"&&typeof p.type=="string"&&i.set(p.id,p.type);for(let p of r){if(!i.has(p))throw new v(`${P(e)}flow references unknown node "${p}".`);let f=i.get(p);if(Wt.has(f))throw new v(`${P(e)}flow cannot include ${f} node "${p}"; use explicit edges for ${f} nodes.`)}let s=[];for(let p=0;p<r.length-1;p++)s.push({from:r[p],to:r[p+1]});let a=Array.isArray(n.edges)?n.edges:[],d=new Set,u=[];for(let p of a){if(!p||typeof p!="object")continue;let f=De(p.from,p.fromPort,p.to);f&&!d.has(f)?(d.add(f),u.push(p)):f||u.push(p)}for(let p of s){let f=De(p.from,void 0,p.to);f&&!d.has(f)&&(d.add(f),u.push(p))}let c={...n,edges:u};return delete c.flow,c}function De(n,e,t){return typeof n!="string"||typeof t!="string"?null:`${n}::${typeof e=="string"?e:""}::${t}`}function P(n){return n.filePath?`${n.filePath}: `:""}function Ot(n){return Me.dump(n,{noRefs:!0,lineWidth:100,sortKeys:!1})}import{Document as Et,isMap as H,isSeq as jt,isScalar as Le,parseDocument as Ft}from"yaml";function He(n,e){let t=Ft(n);if(!t.contents||!H(t.contents)){let r=new Et(e);return t.commentBefore&&(r.commentBefore=t.commentBefore),String(r)}return re(t,t.contents,e),String(t)}function re(n,e,t){let r=Object.keys(t),o=new Set(r),i=new Map;for(let a of e.items){let d=Mt(a);d!==null&&i.set(d,a)}let s=[];for(let a of r){let d=t[a],u=i.get(a);u?(Ct(n,u,d),s.push(u)):s.push(n.createPair(a,d))}e.items=s}function Ct(n,e,t){let r=e.value;if(t==null){e.value=n.createNode(null);return}if(typeof t!="object"){e.value=n.createNode(t);return}if(Array.isArray(t)){jt(r)?Dt(n,r,t):e.value=n.createNode(t);return}H(r)?re(n,r,t):e.value=n.createNode(t)}function Dt(n,e,t){if(!(t.length>0&&t.every(s=>s&&typeof s=="object"&&typeof s.id=="string"))){let s=n.createNode(t);e.items=s.items;return}let o=new Map;for(let s of e.items)if(H(s)){let a=s.get("id",!0);Le(a)&&typeof a.value=="string"&&o.set(a.value,s)}let i=[];for(let s of t){let a=s.id,d=o.get(a);d&&H(d)?(re(n,d,s),i.push(d)):i.push(n.createNode(s))}e.items=i}function Mt(n){let e=n.key;return Le(e)&&typeof e.value=="string"?e.value:typeof e=="string"?e:null}var se=class{baseDir;constructor(e={}){this.baseDir=e.baseDir??R(process.cwd(),".agentx/workflows"),_t(this.baseDir,{recursive:!0})}pathFor(e){return this.pathForJson(e)}pathForJson(e){return R(this.baseDir,`${e}.json`)}pathForYaml(e){return R(this.baseDir,`${e}.yaml`)}isWorkflowFile(e){return e.startsWith("_")?!1:e.endsWith(".json")||e.endsWith(".yaml")||e.endsWith(".yml")}idFromFilename(e){return e.replace(/\.(json|ya?ml)$/,"")}readAndParse(e){let t=R(this.baseDir,e),r=K(t,"utf-8");return e.endsWith(".json")?JSON.parse(r):L(r,{filePath:e})}list(){if(!I(this.baseDir))return[];let e=new Map;for(let r of U(this.baseDir,{withFileTypes:!0})){if(!r.isFile()||!this.isWorkflowFile(r.name))continue;let o=this.idFromFilename(r.name),i=e.get(o)??[];i.push(r.name),e.set(o,i)}let t=[];for(let[,r]of e)if(!(r.length>1))try{let o=this.readAndParse(r[0]),i=$.safeParse(o);i.success&&t.push(i.data)}catch{}return t.sort((r,o)=>r.id.localeCompare(o.id))}validateAll(){let e=[];if(!I(this.baseDir))return e;let t=new Map;for(let r of U(this.baseDir,{withFileTypes:!0})){if(!r.isFile()||!this.isWorkflowFile(r.name))continue;let o=this.idFromFilename(r.name),i=t.get(o)??[];i.push(r.name),t.set(o,i)}for(let[r,o]of t){if(o.length>1){let p=[...o].sort();for(let f of p)e.push({id:r,path:ie(this.baseDir,R(this.baseDir,f)),issues:[`duplicate workflow id "${r}" \u2014 found ${p.join(" and ")}; delete one to disambiguate`],isValid:!1});continue}let i=o[0],s=R(this.baseDir,i),a=ie(this.baseDir,s),d;try{d=this.readAndParse(i)}catch(p){let f=p instanceof v?p.message:`parse error: ${p?.message??p}`;e.push({id:r,path:a,issues:[f],isValid:!1});continue}let u=$.safeParse(d);if(!u.success){let p=u.error.issues.map(f=>`${f.path.join(".")||"<root>"}: ${f.message}`);e.push({id:String(d?.id??r),path:a,issues:p,isValid:!1});continue}let c=ne(u.data);e.push({workflow:u.data,issues:c,isValid:c.length===0})}return e}get(e){let t=this.pathForJson(e),r=this.pathForYaml(e),o=R(this.baseDir,`${e}.yml`),i=I(t),s=I(r)||I(o);if(i&&s)return null;if(i)try{let d=JSON.parse(K(t,"utf-8")),u=$.safeParse(d);return u.success?u.data:null}catch{return null}let a=I(r)?r:I(o)?o:null;if(a)try{let d=K(a,"utf-8"),u=L(d,{filePath:ie(this.baseDir,a)}),c=$.safeParse(u);return c.success?c.data:null}catch{return null}if(!I(this.baseDir))return null;for(let d of U(this.baseDir,{withFileTypes:!0}))if(!(!d.isFile()||!this.isWorkflowFile(d.name)||this.idFromFilename(d.name)===e))try{let c=this.readAndParse(d.name),p=$.safeParse(c);if(p.success&&p.data.id===e)return p.data}catch{}return null}save(e,t={}){let r=new Date().toISOString().slice(0,10),o=$.parse({...e,created:e.created||r,updated:r}),i=this.pathForYaml(o.id),s=R(this.baseDir,`${o.id}.yml`),a=I(i)?i:I(s)?s:null;if(!a&&I(this.baseDir)){for(let d of U(this.baseDir,{withFileTypes:!0}))if(!(!d.isFile()||!this.isWorkflowFile(d.name))&&!d.name.endsWith(".json"))try{let u=this.readAndParse(d.name),c=$.safeParse(u);if(c.success&&c.data.id===o.id){a=R(this.baseDir,d.name);break}}catch{}}if(a&&t.convertFromYaml)return B(a),oe(this.pathForJson(o.id),JSON.stringify(o,null,2)+`
1
+ import{a as ee}from"./chunk-QLTM3F7M.js";import{a as $e,b as Pe}from"./chunk-VMDA2SX2.js";import{b as Ie,c as Se,e as Ae,f as Re,i as Te}from"./chunk-BIFJSQB5.js";import{b as te}from"./chunk-AFRHKA7B.js";import{v as ve,w as gt}from"./chunk-6HMZ5TTM.js";import{b as be,f as ft}from"./chunk-F4HZTZHW.js";import{existsSync as mt,mkdirSync as Ne,readFileSync as ht,writeFileSync as wt,renameSync as yt}from"fs";import{resolve as xe,dirname as kt}from"path";var We=class{filePath;log;constructor(e={}){let t=e.baseDir??xe(process.cwd(),".agentx");this.filePath=xe(t,"handover.json"),this.log=e.log??console.error.bind(console,"[handover]"),Ne(t,{recursive:!0})}key(e,t,r){return`${e}::${t}::${r||"-"}`}load(){if(!mt(this.filePath))return{version:1,overrides:{}};try{let e=ht(this.filePath,"utf-8"),t=JSON.parse(e);return!t||typeof t!="object"?{version:1,overrides:{}}:(t.overrides||(t.overrides={}),t)}catch(e){return this.log(`load failed, starting empty: ${e?.message||e}`),{version:1,overrides:{}}}}save(e){Ne(kt(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp-${process.pid}`;wt(t,JSON.stringify(e,null,2)),yt(t,this.filePath)}get(e,t,r){let i=this.load().overrides[this.key(e,t,r)];if(i&&!(i.expiresAt&&Date.parse(i.expiresAt)<Date.now()))return i}set(e){if(!e.channel||!e.chatId||!e.toAgent)throw new Error("channel, chatId and toAgent are required");let t=this.load(),r={...e,createdAt:e.createdAt??new Date().toISOString()};return t.overrides[this.key(r.channel,r.chatId,r.accountId)]=r,this.save(t),r}remove(e,t,r){let o=this.load(),i=this.key(e,t,r);return i in o.overrides?(delete o.overrides[i],this.save(o),!0):!1}consumeSummary(e,t,r){let o=this.load(),i=o.overrides[this.key(e,t,r)];if(!i||!i.summary||i.summaryConsumedAt)return;let s=i.summary;return i.summaryConsumedAt=new Date().toISOString(),this.save(o),s}listActive(){let e=this.load(),t=Date.now();return Object.values(e.overrides).filter(r=>!r.expiresAt||Date.parse(r.expiresAt)>=t)}listByAgent(e){let t=this.listActive();return{incoming:t.filter(r=>r.toAgent===e),outgoing:t.filter(r=>r.fromAgent===e)}}};import{existsSync as I,mkdirSync as _t,readdirSync as U,readFileSync as K,unlinkSync as B,writeFileSync as oe}from"fs";import{resolve as R,relative as ie}from"path";import{z as l}from"zod";var bt=l.enum(["trigger.channel","trigger.manual","trigger.cron","trigger.hook","trigger.form","agent","transform","classify","branch","gateway.parallel","rule","action.send","action.createIssue","action.setLabel","action.readLabel","action.react","action.editMessage","action.logTime","action.callHTTP","action.run","action.builtin","subProcess","signal.emit","signal.wait","timer.boundary","checkpoint","end"]),vt=l.enum(["equals","contains","matches","exists"]),It=l.object({kind:vt,params:l.record(l.unknown()).default({})}),Ee=l.object({maxAttempts:l.number().int().min(1).max(10).default(1),backoffMs:l.number().int().min(0).max(6e4).default(1e3)}).default({maxAttempts:1,backoffMs:1e3}),je=l.object({id:l.string().min(1).regex(/^[a-zA-Z_][a-zA-Z0-9_-]*$/,"node id must be identifier-safe"),type:bt,config:l.record(l.unknown()).default({}),retry:Ee,position:l.object({x:l.number(),y:l.number()}).optional()}),Fe=l.object({from:l.string(),fromPort:l.string().optional(),to:l.string(),toPort:l.string().optional(),label:l.string().optional()}),Oe=l.union([l.string(),l.date().transform(n=>n.toISOString())]),$=l.object({id:l.string().regex(/^[a-z0-9][a-z0-9_-]*$/,"workflow id must be lower-kebab"),version:l.literal(2).default(2),title:l.string().min(1),description:l.string().optional(),status:l.enum(["draft","review","active","deprecated"]).default("active"),tags:l.array(l.string()).default([]),project:l.string().optional(),entity:l.string().optional(),intentPath:l.array(l.string()).default([]),generatedFrom:l.string().optional(),sourceTaskIds:l.array(l.string()).default([]),confidence:l.number().min(0).max(1).optional(),workflowVersion:l.string().optional(),ownerAgent:l.string().optional(),lastMatchedAt:l.string().optional(),matchCount:l.number().int().min(0).default(0),state:l.enum(["active","disabled","quarantined"]).default("active"),priority:l.number().int().default(0),fanOut:l.boolean().default(!1),nodes:l.array(je).refine(n=>n.length>0,{message:"workflow must have at least one node"}),edges:l.array(Fe).default([]),envAllow:l.array(l.string()).default([]),retention:l.object({maxRuns:l.number().int().positive().default(500),maxDays:l.number().int().positive().default(90)}).default({maxRuns:500,maxDays:90}),maxChildDepth:l.number().int().positive().default(5),mesh:l.object({allowRemote:l.boolean().default(!1),peers:l.array(l.string()).optional()}).default({allowRemote:!1}),created:Oe.optional(),updated:Oe.optional()});function ne(n){let e=[],t=new Map(n.nodes.map(s=>[s.id,s])),r=n.nodes.filter(s=>s.type.startsWith("trigger."));r.length===0&&e.push("workflow must have exactly one trigger.* node (found 0)"),r.length>1&&e.push(`workflow has ${r.length} trigger.* nodes; v1 supports exactly one`);for(let s of n.edges)t.has(s.from)||e.push(`edge references missing node: from="${s.from}"`),t.has(s.to)||e.push(`edge references missing node: to="${s.to}"`);let o=r[0];if(o){let s=new Map;for(let u of n.edges)s.has(u.from)||s.set(u.from,[]),s.get(u.from).push(u.to);let a=new Set,d=[o.id];for(;d.length;){let u=d.pop();if(!a.has(u)){a.add(u);for(let c of s.get(u)??[])d.push(c)}}for(let u of n.nodes)a.has(u.id)||e.push(`node "${u.id}" is unreachable from trigger "${o.id}"`);n.nodes.some(u=>a.has(u.id)&&St(u.type))||e.push("no reachable `end`, `checkpoint`, `subProcess`, `signal.wait`, or `timer.boundary` node \u2014 the run cannot terminate or pause")}for(let s of n.nodes){if(s.type!=="branch"&&s.type!=="rule")continue;let a=s.type==="branch"?s.config.cases??[]:(s.config.rules??[]).filter(p=>typeof p.to=="string"),d=s.type==="branch"?s.config.default:s.config.default?.to,u=new Set(a.map(p=>p.to));d&&u.add(d);let c=n.edges.filter(p=>p.from===s.id);for(let p of c){let f=p.fromPort??"";u.has(f)||e.push(`${s.type} "${s.id}" has outgoing edge with port "${f}" not declared in cases or default`)}}let i=Rt(n);for(let s of i)e.push(`cycle without agent/checkpoint: ${s.join(" -> ")}`);return e}function St(n){return n==="end"||n==="checkpoint"||n==="subProcess"||n==="signal.wait"||n==="timer.boundary"}function At(n){return n==="agent"||n==="checkpoint"||n==="subProcess"||n==="signal.wait"||n==="timer.boundary"}function Rt(n){let e=new Map;for(let a of n.edges)e.has(a.from)||e.set(a.from,[]),e.get(a.from).push(a.to);let t=new Map(n.nodes.map(a=>[a.id,a])),r=[],o=new Map,i=[],s=a=>{if(o.get(a)===1){let d=i.indexOf(a);if(d>=0){let u=i.slice(d).concat(a);u.some(p=>{let f=t.get(p)?.type;return f?At(f):!1})||r.push(u)}return}if(o.get(a)!==2){o.set(a,1),i.push(a);for(let d of e.get(a)??[])s(d);i.pop(),o.set(a,2)}};for(let a of n.nodes)o.get(a.id)!==2&&s(a.id);return r}var Ce=l.enum(["running","paused","completed","failed","canceled"]),$t=l.enum(["ok","failed","timeout","skipped","paused","resumed"]),Pt=l.object({at:l.string(),nodeId:l.string(),inputKeys:l.array(l.string()).default([]),status:$t,output:l.record(l.unknown()).optional(),idempotencyKey:l.string(),note:l.string().optional()}),Tt=l.object({backend:l.string(),id:l.string()}),Nt=l.discriminatedUnion("kind",[l.object({kind:l.literal("checkpoint"),nodeId:l.string(),checkpointName:l.string(),resumeMatch:l.record(l.unknown()).default({})}),l.object({kind:l.literal("subProcess"),nodeId:l.string(),childRunId:l.string(),childWorkflowId:l.string()}),l.object({kind:l.literal("signalWait"),nodeId:l.string(),signalName:l.string(),match:l.record(l.unknown()).default({}),scope:l.enum(["workflow","global"]).default("workflow")}),l.object({kind:l.literal("timerWait"),nodeId:l.string(),fireAt:l.string()})]),xt=l.object({id:l.string(),workflowId:l.string(),workflowVersion:l.literal(2),homeNode:l.string(),status:Ce,pausedAt:Nt.optional(),context:l.record(l.record(l.unknown())).default({}),pending:l.array(l.string()).default([]),joinCounters:l.record(l.array(l.string())).default({}),entityRef:Tt,history:l.array(Pt).default([]),parentRunId:l.string().nullable().default(null),parentNodeId:l.string().nullable().default(null),rootRunId:l.string().nullable().default(null),depth:l.number().int().min(0).default(0),createdAt:l.string(),updatedAt:l.string()});import Me from"js-yaml";var Wt=new Set(["branch","gateway.parallel","rule","signal.wait","subProcess","timer.boundary","checkpoint"]),v=class extends Error{constructor(t,r){super(t);this.mark=r;this.name="WorkflowYamlError"}};function L(n,e={}){if(!n||n.trim()==="")throw new v(`${P(e)}empty file \u2014 workflow YAML must contain at least an id, version, title, and one node.`);let t;try{t=Me.loadAll(n)}catch(o){let i=o?.mark;throw new v(`${P(e)}YAML parse error: ${o?.reason??o?.message??o}`+(i?` (line ${i.line+1}, column ${i.column+1})`:""),i)}if(t.length===0||t.length===1&&t[0]==null)throw new v(`${P(e)}YAML produced no document.`);if(t.length>1)throw new v(`${P(e)}multi-document YAML is not supported in v1; one workflow per file.`);let r=t[0];if(typeof r!="object"||r===null||Array.isArray(r)){let o=Array.isArray(r)?"array":typeof r;throw new v(`${P(e)}top-level YAML must be a mapping (got ${o}).`)}return _e(r,e)}function _e(n,e={}){if(!("flow"in n))return n;let t=n.flow;if(t==null){let p={...n};return delete p.flow,p}if(!Array.isArray(t))throw new v(`${P(e)}flow must be an array of node ids (got ${typeof t}).`);for(let p of t)if(typeof p!="string")throw new v(`${P(e)}flow entries must be strings (got ${typeof p}).`);let r=t,o=Array.isArray(n.nodes)?n.nodes:[],i=new Map;for(let p of o)p&&typeof p=="object"&&typeof p.id=="string"&&typeof p.type=="string"&&i.set(p.id,p.type);for(let p of r){if(!i.has(p))throw new v(`${P(e)}flow references unknown node "${p}".`);let f=i.get(p);if(Wt.has(f))throw new v(`${P(e)}flow cannot include ${f} node "${p}"; use explicit edges for ${f} nodes.`)}let s=[];for(let p=0;p<r.length-1;p++)s.push({from:r[p],to:r[p+1]});let a=Array.isArray(n.edges)?n.edges:[],d=new Set,u=[];for(let p of a){if(!p||typeof p!="object")continue;let f=De(p.from,p.fromPort,p.to);f&&!d.has(f)?(d.add(f),u.push(p)):f||u.push(p)}for(let p of s){let f=De(p.from,void 0,p.to);f&&!d.has(f)&&(d.add(f),u.push(p))}let c={...n,edges:u};return delete c.flow,c}function De(n,e,t){return typeof n!="string"||typeof t!="string"?null:`${n}::${typeof e=="string"?e:""}::${t}`}function P(n){return n.filePath?`${n.filePath}: `:""}function Ot(n){return Me.dump(n,{noRefs:!0,lineWidth:100,sortKeys:!1})}import{Document as Et,isMap as H,isSeq as jt,isScalar as Le,parseDocument as Ft}from"yaml";function He(n,e){let t=Ft(n);if(!t.contents||!H(t.contents)){let r=new Et(e);return t.commentBefore&&(r.commentBefore=t.commentBefore),String(r)}return re(t,t.contents,e),String(t)}function re(n,e,t){let r=Object.keys(t),o=new Set(r),i=new Map;for(let a of e.items){let d=Mt(a);d!==null&&i.set(d,a)}let s=[];for(let a of r){let d=t[a],u=i.get(a);u?(Ct(n,u,d),s.push(u)):s.push(n.createPair(a,d))}e.items=s}function Ct(n,e,t){let r=e.value;if(t==null){e.value=n.createNode(null);return}if(typeof t!="object"){e.value=n.createNode(t);return}if(Array.isArray(t)){jt(r)?Dt(n,r,t):e.value=n.createNode(t);return}H(r)?re(n,r,t):e.value=n.createNode(t)}function Dt(n,e,t){if(!(t.length>0&&t.every(s=>s&&typeof s=="object"&&typeof s.id=="string"))){let s=n.createNode(t);e.items=s.items;return}let o=new Map;for(let s of e.items)if(H(s)){let a=s.get("id",!0);Le(a)&&typeof a.value=="string"&&o.set(a.value,s)}let i=[];for(let s of t){let a=s.id,d=o.get(a);d&&H(d)?(re(n,d,s),i.push(d)):i.push(n.createNode(s))}e.items=i}function Mt(n){let e=n.key;return Le(e)&&typeof e.value=="string"?e.value:typeof e=="string"?e:null}var se=class{baseDir;constructor(e={}){this.baseDir=e.baseDir??R(process.cwd(),".agentx/workflows"),_t(this.baseDir,{recursive:!0})}pathFor(e){return this.pathForJson(e)}pathForJson(e){return R(this.baseDir,`${e}.json`)}pathForYaml(e){return R(this.baseDir,`${e}.yaml`)}isWorkflowFile(e){return e.startsWith("_")?!1:e.endsWith(".json")||e.endsWith(".yaml")||e.endsWith(".yml")}idFromFilename(e){return e.replace(/\.(json|ya?ml)$/,"")}readAndParse(e){let t=R(this.baseDir,e),r=K(t,"utf-8");return e.endsWith(".json")?JSON.parse(r):L(r,{filePath:e})}list(){if(!I(this.baseDir))return[];let e=new Map;for(let r of U(this.baseDir,{withFileTypes:!0})){if(!r.isFile()||!this.isWorkflowFile(r.name))continue;let o=this.idFromFilename(r.name),i=e.get(o)??[];i.push(r.name),e.set(o,i)}let t=[];for(let[,r]of e)if(!(r.length>1))try{let o=this.readAndParse(r[0]),i=$.safeParse(o);i.success&&t.push(i.data)}catch{}return t.sort((r,o)=>r.id.localeCompare(o.id))}validateAll(){let e=[];if(!I(this.baseDir))return e;let t=new Map;for(let r of U(this.baseDir,{withFileTypes:!0})){if(!r.isFile()||!this.isWorkflowFile(r.name))continue;let o=this.idFromFilename(r.name),i=t.get(o)??[];i.push(r.name),t.set(o,i)}for(let[r,o]of t){if(o.length>1){let p=[...o].sort();for(let f of p)e.push({id:r,path:ie(this.baseDir,R(this.baseDir,f)),issues:[`duplicate workflow id "${r}" \u2014 found ${p.join(" and ")}; delete one to disambiguate`],isValid:!1});continue}let i=o[0],s=R(this.baseDir,i),a=ie(this.baseDir,s),d;try{d=this.readAndParse(i)}catch(p){let f=p instanceof v?p.message:`parse error: ${p?.message??p}`;e.push({id:r,path:a,issues:[f],isValid:!1});continue}let u=$.safeParse(d);if(!u.success){let p=u.error.issues.map(f=>`${f.path.join(".")||"<root>"}: ${f.message}`);e.push({id:String(d?.id??r),path:a,issues:p,isValid:!1});continue}let c=ne(u.data);e.push({workflow:u.data,issues:c,isValid:c.length===0})}return e}get(e){let t=this.pathForJson(e),r=this.pathForYaml(e),o=R(this.baseDir,`${e}.yml`),i=I(t),s=I(r)||I(o);if(i&&s)return null;if(i)try{let d=JSON.parse(K(t,"utf-8")),u=$.safeParse(d);return u.success?u.data:null}catch{return null}let a=I(r)?r:I(o)?o:null;if(a)try{let d=K(a,"utf-8"),u=L(d,{filePath:ie(this.baseDir,a)}),c=$.safeParse(u);return c.success?c.data:null}catch{return null}if(!I(this.baseDir))return null;for(let d of U(this.baseDir,{withFileTypes:!0}))if(!(!d.isFile()||!this.isWorkflowFile(d.name)||this.idFromFilename(d.name)===e))try{let c=this.readAndParse(d.name),p=$.safeParse(c);if(p.success&&p.data.id===e)return p.data}catch{}return null}save(e,t={}){let r=new Date().toISOString().slice(0,10),o=$.parse({...e,created:e.created||r,updated:r}),i=this.pathForYaml(o.id),s=R(this.baseDir,`${o.id}.yml`),a=I(i)?i:I(s)?s:null;if(!a&&I(this.baseDir)){for(let d of U(this.baseDir,{withFileTypes:!0}))if(!(!d.isFile()||!this.isWorkflowFile(d.name))&&!d.name.endsWith(".json"))try{let u=this.readAndParse(d.name),c=$.safeParse(u);if(c.success&&c.data.id===o.id){a=R(this.baseDir,d.name);break}}catch{}}if(a&&t.convertFromYaml)return B(a),oe(this.pathForJson(o.id),JSON.stringify(o,null,2)+`
2
2
  `),o;if(a){let d=K(a,"utf-8");try{let u=He(d,o);return oe(a,u),o}catch(u){let c=new Error(`yaml round-trip failed for "${o.id}" at ${a}: ${u?.message??u}`);throw c.yamlPath=a,c}}return oe(this.pathForJson(o.id),JSON.stringify(o,null,2)+`
3
3
  `),o}delete(e){let t=this.pathForJson(e),r=this.pathForYaml(e),o=R(this.baseDir,`${e}.yml`),i=!1;return I(t)&&(B(t),i=!0),I(r)&&(B(r),i=!0),I(o)&&(B(o),i=!0),i}};import{createHash as Lt,randomUUID as Ht}from"crypto";import{appendFileSync as Ue,existsSync as E,mkdirSync as Ke,readdirSync as Be,readFileSync as ae,statSync as ze,unlinkSync as qe,writeFileSync as Ut}from"fs";import{resolve as O}from"path";function Kt(n){return n.replace(/[^a-zA-Z0-9._:#@-]/g,"_").slice(0,200)}function N(n,e,t){return Lt("sha1").update(`${n}|${e}|${t}`).digest("hex").slice(0,16)}var de=class{baseDir;runsDir;indexDir;nodeId;constructor(e){this.baseDir=e.baseDir??O(process.cwd(),".agentx/workflows"),this.runsDir=O(this.baseDir,"_runs"),this.indexDir=O(this.baseDir,"_index"),this.nodeId=e.nodeId,Ke(this.runsDir,{recursive:!0}),Ke(this.indexDir,{recursive:!0})}runPath(e){return O(this.runsDir,`${e}.jsonl`)}indexPath(e){return O(this.indexDir,`${e.backend}__${Kt(e.id)}.json`)}create(e){let t=new Date().toISOString(),r=Ht(),o={id:r,workflowId:e.workflowId,workflowVersion:2,homeNode:this.nodeId,status:"running",pausedAt:void 0,context:e.initialContext??{},pending:e.initialPending,entityRef:e.entityRef,history:[],parentRunId:e.parentRunId??null,parentNodeId:e.parentNodeId??null,rootRunId:e.rootRunId??r,depth:e.depth??0,joinCounters:{},createdAt:t,updatedAt:t};return this.appendSnapshot(o),this.writeIndex(e.entityRef,o.id),o}get(e){let t=this.runPath(e);if(!E(t))return null;let r=ae(t,"utf-8").trim();if(!r)return null;let o=null;for(let i of r.split(`
4
4
  `)){let s;try{s=JSON.parse(i)}catch{continue}if(s.v===2){if(s.kind==="snapshot")o=s.run;else if(s.kind==="exec"&&o&&o.id===s.runId){let a=o;o={...a,history:[...a.history,s.entry],pending:s.pending,status:s.status??a.status,pausedAt:s.pausedAt===null?void 0:s.pausedAt??a.pausedAt,context:s.context??a.context,joinCounters:s.joinCounters??a.joinCounters,updatedAt:s.entry.at}}}}return o}getActiveByEntity(e){let t=this.indexPath(e);if(!E(t))return null;try{return JSON.parse(ae(t,"utf-8")).runId}catch{return null}}getHomeNodeByEntity(e){let t=this.indexPath(e);if(!E(t))return null;try{return JSON.parse(ae(t,"utf-8")).homeNode}catch{return null}}recordExecution(e){let t=this.get(e.runId);if(!t)return null;if(t.history.some(i=>i.idempotencyKey===e.entry.idempotencyKey))return t;let r={v:2,kind:"exec",runId:e.runId,entry:e.entry,pending:e.nextPending,status:e.status,pausedAt:e.pausedAt===null?null:e.pausedAt,context:e.context,joinCounters:e.joinCounters};Ue(this.runPath(e.runId),JSON.stringify(r)+`
@@ -6,4 +6,4 @@ import{a as $e,b as Pe}from"./chunk-VMDA2SX2.js";import{a as ee}from"./chunk-QLT
6
6
  `)}writeIndex(e,t){Ut(this.indexPath(e),JSON.stringify({runId:t,homeNode:this.nodeId,updatedAt:new Date().toISOString()},null,2)+`
7
7
  `)}clearIndex(e){let t=this.indexPath(e);if(E(t))try{qe(t)}catch{}}};import{existsSync as Ye,mkdirSync as Bt,readFileSync as zt,unlinkSync as qt,writeFileSync as Yt}from"fs";import{resolve as ue}from"path";import{z as j}from"zod";var Je=j.object({version:j.literal(1),nodes:j.record(j.object({x:j.number(),y:j.number()}))}),le=class{baseDir;layoutsDir;constructor(e={}){this.baseDir=e.baseDir??ue(process.cwd(),".agentx/workflows"),this.layoutsDir=ue(this.baseDir,"_layouts"),Bt(this.layoutsDir,{recursive:!0})}pathFor(e){let t=e.replace(/[^a-zA-Z0-9._-]/g,"_");return ue(this.layoutsDir,`${t}.json`)}get(e){let t=this.pathFor(e);if(!Ye(t))return null;try{let r=Je.safeParse(JSON.parse(zt(t,"utf-8")));return r.success?r.data:null}catch{return null}}save(e,t){let r=Je.parse(t);return Yt(this.pathFor(e),JSON.stringify(r,null,2)+`
8
8
  `),r}sync(e,t){let r=this.get(e);if(!r)return null;let o={};for(let s of t)r.nodes[s]&&(o[s]=r.nodes[s]);let i={version:1,nodes:o};return this.save(e,i)}delete(e){let t=this.pathFor(e);return Ye(t)?(qt(t),!0):!1}};function Ge(n){return new Set(n.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(e=>e.length>3))}function Jt(n,e){if(n.size===0||e.size===0)return 0;let t=0;for(let r of n)e.has(r)&&t++;return t/Math.max(n.size,e.size)}function Gt(n,e){let t=Ge(n.message),r=e.filter(i=>i.state==="active"&&(i.status??"active")==="active"),o=null;for(let i of r){let s=0,a=[];if(i.ownerAgent&&i.ownerAgent===n.agentId&&(s+=.25,a.push("owner-agent")),n.channel&&i.tags.includes(n.channel)&&(s+=.15,a.push("channel-tag")),n.intentPath?.length&&i.intentPath.length){let p=n.intentPath.filter((f,m)=>i.intentPath[m]===f).length;p>0&&(s+=Math.min(.3,p*.1),a.push("intent-path"))}let d=[i.id,i.title,i.description??"",...i.tags].join(" "),u=Jt(t,Ge(d));u>0&&(s+=Math.min(.35,u),a.push("text-similarity")),(i.matchCount??0)>0&&(s+=Math.min(.1,i.matchCount*.01),a.push("prior-matches"));let c=Math.max(0,Math.min(1,s));(!o||c>o.confidence)&&(o={workflow:i,confidence:c,reasons:a})}return o&&o.confidence>0?o:null}function ce(n){let{workflow:e,fromNodeId:t,selectedPort:r}=n,o=e.nodes.find(a=>a.id===t);if(!o)return{nextPending:[]};let i=e.edges.filter(a=>a.from===t);return{nextPending:(o.type==="branch"?i.filter(a=>(a.fromPort??"")===(r??"")):i).map(a=>a.to)}}function pe(n,e){let t=n.config.cases??[],r=n.config.default??"";for(let o of t)if(Vt(o.when,e))return o.to;return r}function Vt(n,e){let t=n.params??{},r=String(t.path??""),o=z(e,r);switch(n.kind){case"equals":return o===t.value;case"contains":return typeof o=="string"?o.includes(String(t.value??"")):Array.isArray(o)?o.some(i=>i===t.value):!1;case"matches":{if(typeof o!="string")return!1;try{return new RegExp(String(t.regex??"")).test(o)}catch{return!1}}case"exists":return o!=null&&o!=="";default:return!1}}function z(n,e){if(!e)return;let t=e.split("."),r=n;for(let o of t){if(r==null||typeof r!="object")return;r=r[o]}return r}function q(n){let e=n.nodes.find(r=>r.type.startsWith("trigger."));if(!e)return null;let t=n.edges.filter(r=>r.from===e.id).map(r=>r.to);return{triggerId:e.id,pending:t}}function x(n,e){return n.nodes.find(t=>t.id===e)}ft();gt();function Zt(n,e,t){let r=n.split(".");if(r[0]==="env"){if(r.length!==2)return"";let i=r[1];if(!t.has(i))return"";let s=process.env[i];return typeof s=="string"?s:""}let o=e;for(let i of r){if(o==null||typeof o!="object")return"";o=o[i]}return o==null?"":typeof o=="object"?JSON.stringify(o):String(o)}function S(n,e,t={}){let r=new Set(t.envAllow||[]);return n.replace(/\{\{\s*([a-zA-Z_][a-zA-Z0-9_.-]*)\s*\}\}/g,(o,i)=>Zt(i,e,r))}function b(n,e,t={}){let r={};for(let[o,i]of Object.entries(n))typeof i=="string"?r[o]=S(i,e,t):Array.isArray(i)?r[o]=i.map(s=>typeof s=="string"?S(s,e,t):s):i&&typeof i=="object"?r[o]=b(i,e,t):r[o]=i;return r}var Ve="workflow-classify",Y="unsure",Ze=async n=>{let e=n.node.config,t=n.run.context,r={envAllow:n.workflow.envAllow},o=S(String(e.input??""),t,r).trim();if(!o)return{error:`classify node "${n.node.id}" missing config.input`};let i=e.labels,s=Array.isArray(i)?Object.fromEntries(i.map(g=>[String(g),null])):typeof i=="object"&&i?Object.fromEntries(Object.entries(i).map(([g,y])=>[g,y==null?null:String(y)])):{},a=Object.keys(s);if(a.length<2)return{error:`classify node "${n.node.id}" needs at least two labels`};if(a.includes(Y))return{error:`classify node "${n.node.id}": "${Y}" is reserved for the low-confidence port`};let d=typeof e.minConfidence=="number"?e.minConfidence:.7,u=e.instructions?S(String(e.instructions),t,r):void 0,c={input:o};if(e.state&&typeof e.state=="object")for(let[g,y]of Object.entries(e.state)){let w=typeof y=="string"?S(y,t,r):y;(w===null||["string","number","boolean"].includes(typeof w))&&(c[g]=w)}let p=await ve(Ve,c,{label:be(s,u)},{features:{workflow:n.workflow.id,node:n.node.id}});if(!p)return{error:`classify node "${n.node.id}": decision seat unavailable (set decisions.seats.${Ve}.mode)`};let f=p.answers.label,m=f.confidence>=d,h=m?f.choice:Y;return n.log(`[node:${n.node.id}] classify \u2192 ${f.choice} (${f.confidence.toFixed(2)})${m?"":` \u2014 below ${d}, routing to ${Y}`}`),{output:{result:f.choice,label:f.choice,confidence:f.confidence,probabilities:f.probabilities,unsure:!m,port:h},port:h}};var fe=class{active=new Map;waiters=new Map;async acquire(e,t){let r=this.active.get(e)??0;if(r<t){this.active.set(e,r+1);return}return new Promise(o=>{let i=this.waiters.get(e)??[];i.push({resolve:()=>{this.active.set(e,(this.active.get(e)??0)+1),o()}}),this.waiters.set(e,i)})}release(e){let t=this.active.get(e)??0;this.active.set(e,Math.max(0,t-1));let r=this.waiters.get(e);r&&r.length>0&&r.shift().resolve()}stats(e){return{active:this.active.get(e)??0,waiting:this.waiters.get(e)?.length??0}}},J=new fe;function Qe(n,e){return`${n}:${e}`}var F=async n=>({output:n.run.context[n.node.id]??{}}),Qt=async n=>{let e=n.node.config,t=String(e.agentId??""),r=String(e.prompt??"");if(!t)return{error:`agent node "${n.node.id}" missing config.agentId`};let o=S(r,n.run.context,{envAllow:n.workflow.envAllow}),i=typeof e.timeoutMinutes=="number"?e.timeoutMinutes:void 0,s=e.autonomy===void 0||e.autonomy===null?void 0:String(e.autonomy);if(s!==void 0&&s!=="report"&&s!=="propose"&&s!=="act")return{error:`agent node "${n.node.id}" has invalid autonomy "${s}" (expected report, propose or act)`};let a=typeof e.maxConcurrent=="number"&&e.maxConcurrent>0?e.maxConcurrent:null,d=a?Qe(n.workflow.id,n.node.id):null;if(d&&a){let c=J.stats(d);c.active>=a&&n.log(`[node:${n.node.id}] gated: ${c.active} active (cap ${a}), ${c.waiting+1} waiting`),await J.acquire(d,a)}let u=Date.now();try{let c=await n.agents.execute({agentId:t,message:o,workflowRunId:n.run.id,timeoutMinutes:i,...s?{autonomy:s}:{}}),p=Date.now()-u;if(c.error){let h=c.errorKind??"unknown";return n.log(`[node:${n.node.id}] agent "${t}" failed (${h}): ${c.error}`),{error:`[${h}] ${c.error}`}}let m=String(e.resultParser??"acme-result-token")==="json"?Sn(c.content):et(c.content);return{output:{reply:c.content,result:m.result,json:m.json,taskId:c.taskId,durationMs:p,...c.autonomyBlocks?.length?{autonomyBlocks:c.autonomyBlocks}:{}}}}catch(c){return n.log(`[node:${n.node.id}] agent "${t}" threw: ${c.message}`),{error:c.message}}finally{d&&J.release(d)}},Xt=async n=>{let e=pe(n.node,n.run.context);return e?{output:{port:e},port:e}:(n.log(`[node:${n.node.id}] branch matched no case and no default port`),{output:{port:null}})},en=async n=>{let e=b(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.channel??""),r=String(e.chatId??""),o=String(e.text??"");if(!t||!r){let a=String(n.node.config.chatId??""),d=String(n.node.config.channel??""),u=[];return t||u.push(`channel config="${d}" rendered=""`),r||u.push(`chatId config="${a}" rendered=""`),(/\{\{\s*env\./.test(a)||/\{\{\s*env\./.test(d))&&u.push("(env.* templates only resolve for names listed in workflow.envAllow and actually set in process.env)"),{error:`action.send "${n.node.id}" needs channel + chatId \u2014 ${u.join("; ")}`}}let i=me(n,e.accountId),s=n.channels[t];if(s?.send)try{return{output:{messageId:await s.send({channel:t,chatId:r,text:o,...i?{accountId:i}:{}})??null}}}catch(a){return{error:`action.send failed: ${a.message}`}}if(n.forwardChannelSend)try{return{output:{messageId:(await n.forwardChannelSend({channel:t,chatId:r,text:o,accountId:i})).messageId,viaMesh:!0}}}catch(a){return n.log(`[node:${n.node.id}] mesh-forward of "${t}" send failed: ${a.message}`),{error:`action.send via mesh failed: ${a.message}`}}return n.log(`[node:${n.node.id}] adapter "${t}" not available locally and no mesh forwarder`),{error:`channel "${t}" not available (no local adapter, no mesh route)`}},tn=async n=>{let e=b(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.channel??"gitlab"),r=String(e.project??""),o=String(e.title??""),i=String(e.description??""),s=Array.isArray(e.labels)?e.labels.map(String):[],a=Array.isArray(e.assignees)?e.assignees.map(String):[];if(!r||!o)return{error:`action.createIssue "${n.node.id}" needs project + title`};let d=he(n),u=n.channels[t];if(!u?.createIssue)return{error:`channel "${t}" does not support createIssue`};try{let c=await u.createIssue({project:r,title:o,description:i,labels:s,assignees:a,agentId:d});return c?{output:{issue:{iid:c.iid,url:c.url,webUrl:c.url}}}:{error:"createIssue returned null (see adapter log)"}}catch(c){return{error:`action.createIssue failed: ${c.message}`}}},nn=async()=>({output:{}}),rn=async n=>{let e=n.node.config,t=String(e.name??n.node.id),r=e.waitFor??{},o=e.resumeMatch??{};return{paused:!0,pausedAt:{kind:"checkpoint",nodeId:n.node.id,checkpointName:t,resumeMatch:{...r,...o}}}},on=async n=>{let e=b(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.channel??"gitlab"),r=String(e.project??""),o=String(e.iid??""),i=Array.isArray(e.add)?e.add.map(String):[],s=Array.isArray(e.remove)?e.remove.map(String):[];if(!r||!o)return{error:`action.setLabel "${n.node.id}" needs project + iid (try {{trigger.project}} / {{trigger.issue.iid}})`};if(i.length===0&&s.length===0)return{output:{skipped:!0,reason:"no labels to add or remove"}};let a=n.channels[t];if(!a?.setLabels)return{error:`channel "${t}" does not support setLabels`};let d=he(n),u=e.kind==="merge_request"?"merge_request":"issue";return{output:{labels:await a.setLabels({project:r,kind:u,iid:o,add:i,remove:s,agentId:d})??[],add:i,remove:s}}},sn=async n=>{let e=b(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.channel??"gitlab"),r=String(e.project??""),o=String(e.iid??"");if(!r||!o)return{error:`action.readLabel "${n.node.id}" needs project + iid`};let i=n.channels[t];if(!i?.getLabels)return{error:`channel "${t}" does not support getLabels`};let s=e.kind==="merge_request"?"merge_request":"issue";return{output:{labels:await i.getLabels({project:r,kind:s,iid:o})??[]}}},an=async n=>{let e=b(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.channel??""),r=String(e.chatId??""),o=String(e.messageId??""),i=String(e.emoji??"\u{1F440}");if(!t||!r||!o)return{error:`action.react "${n.node.id}" needs channel + chatId + messageId`};let s=me(n,e.accountId),a=n.channels[t];if(!a?.react)return{error:`channel "${t}" does not support react`};try{return await a.react(r,o,i,s),{output:{emoji:i}}}catch(d){return{error:`action.react failed: ${d.message}`}}},dn=async n=>{let e=b(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.channel??""),r=String(e.chatId??""),o=String(e.messageId??""),i=String(e.text??""),s=e.parseMode?String(e.parseMode):void 0;if(!t||!r||!o||!i)return{error:`action.editMessage "${n.node.id}" needs channel + chatId + messageId + text`};let a=me(n,e.accountId),d=n.channels[t];if(!d?.editMessage)return{error:`channel "${t}" does not support editMessage`};try{return{output:{edited:await d.editMessage(r,o,i,s,a)}}}catch(u){return{error:`action.editMessage failed: ${u.message}`}}},un=async n=>{let e=b(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.channel??"gitlab"),r=String(e.chatId??""),o=Number(e.durationMs??0);if(!r||!o)return{error:`action.logTime "${n.node.id}" needs chatId + durationMs`};let i=n.channels[t];if(!i?.logTimeSpent)return{error:`channel "${t}" does not support logTimeSpent`};let s=he(n);try{return await i.logTimeSpent(r,o,s),{output:{durationMs:o}}}catch(a){return{error:`action.logTime failed: ${a.message}`}}},ln=async n=>{let e=b(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.url??"");if(!t)return{error:`action.callHTTP "${n.node.id}" needs url`};let r=String(e.method??"POST").toUpperCase(),o=e.headers&&typeof e.headers=="object"?e.headers:{"Content-Type":"application/json"},i;e.body!==void 0&&(i=typeof e.body=="string"?e.body:JSON.stringify(e.body));try{let s=await fetch(t,{method:r,headers:o,body:i}),a=await s.text(),d=a;try{d=JSON.parse(a)}catch{}return{output:{ok:s.ok,status:s.status,body:d}}}catch(s){return{error:`action.callHTTP failed: ${s.message}`}}},cn=async n=>{let e=b(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.actionId??e.id??"");if(!t)return{error:`action.run "${n.node.id}" needs actionId`};let r=e.inputs&&typeof e.inputs=="object"?e.inputs:{},{ActionStore:o}=await import("./store-MCOA6N4F.js"),{runAction:i}=await import("./runner-YRBVNYTY.js"),s=new o().get(t);if(!s)return{error:`action.run "${n.node.id}": no action "${t}" in registry`};try{let a=await i(s,r),d={ok:a.ok,output:a.output,status:a.status,durationMs:a.durationMs};return a.errors!==void 0&&(d.errors=a.errors),a.ok?{output:d}:{output:d,error:`action "${t}" failed (status=${a.status})`}}catch(a){return{error:`action.run failed: ${a.message}`}}},pn=async n=>{let e=b(n.node.config,n.run.context,{envAllow:n.workflow.envAllow}),t=String(e.name??"");if(!t)return{error:`action.builtin "${n.node.id}" needs a "name" (e.g. "http.fetch")`};let r=e.input&&typeof e.input=="object"?e.input:{},{runBuiltin:o,getBuiltin:i}=await import("./builtin-B67DMJ3M.js");if(!i(t))return{error:`action.builtin "${n.node.id}": unknown built-in "${t}"`};try{return{output:await o(t,r)}}catch(s){let a=s?.name==="ZodError"?`validation: ${s.message}`:s?.message||String(s);return{error:`action.builtin "${t}" failed: ${a}`}}},fn=async n=>{let e=n.node.config,t=n.run.context;return typeof e.path=="string"&&e.path?{output:{value:z(t,e.path)}}:e.template&&typeof e.template=="object"?{output:b(e.template,t,{envAllow:n.workflow.envAllow})}:{output:{}}};function gn(n){if(n!=null){if(typeof n=="number")return new Date(Date.now()+n*6e4).toISOString();if(typeof n=="object"&&n&&"minutes"in n){let e=Number(n.minutes);if(Number.isFinite(e))return new Date(Date.now()+e*6e4).toISOString()}if(typeof n=="string"){let e=/^P(?:([0-9]+)D)?(?:T(?:([0-9]+)H)?(?:([0-9]+)M)?(?:([0-9]+)S)?)?$/.exec(n);if(e){let t=Number(e[1]??0),r=Number(e[2]??0),o=Number(e[3]??0),i=Number(e[4]??0),s=((t*24+r)*60+o)*6e4+i*1e3;if(s>0)return new Date(Date.now()+s).toISOString()}}}}var mn=async n=>{let e=n.node.config,t=b(e,n.run.context,{envAllow:n.workflow.envAllow}),r=String(t.workflowId??"");if(!r)return{error:`subProcess "${n.node.id}" missing config.workflowId`};let o=n.run.depth??0,i=n.workflow.maxChildDepth??5;if(o+1>=i)return{error:`max child workflow depth ${i} exceeded at ${n.workflow.id} \u2192 ${r} (parent depth ${o})`};let s=e.inputMap,a={};if(s==="*")a={...n.run.context};else if(s&&typeof s=="object")for(let[d,u]of Object.entries(s))u&&typeof u=="object"&&!Array.isArray(u)?a[d]=b(u,n.run.context,{envAllow:n.workflow.envAllow}):typeof u=="string"&&(a[d]={value:S(u,n.run.context,{envAllow:n.workflow.envAllow})});return{paused:!0,pausedAt:{kind:"subProcess",nodeId:n.node.id,childRunId:"",childWorkflowId:r},spawnChild:{workflowId:r,input:a}}},hn=F,wn=async n=>{let e=n.node.config,t=b(e,n.run.context,{envAllow:n.workflow.envAllow}),r=String(t.name??"");if(!r)return{error:`signal.emit "${n.node.id}" missing config.name`};let o=t.scope==="global"?"global":"workflow",i=t.payload&&typeof t.payload=="object"?t.payload:{};return{output:{emittedAt:new Date().toISOString(),name:r,scope:o,payload:i},emitSignal:{name:r,scope:o,payload:i}}},yn=async n=>{let e=n.node.config,t=b(e,n.run.context,{envAllow:n.workflow.envAllow}),r=String(t.name??"");if(!r)return{error:`signal.wait "${n.node.id}" missing config.name`};let o=t.scope==="global"?"global":"workflow",i=e.match&&typeof e.match=="object"?e.match:{};return{paused:!0,pausedAt:{kind:"signalWait",nodeId:n.node.id,signalName:r,match:i,scope:o}}},kn=async n=>{let e=n.node.config,t=b(e,n.run.context,{envAllow:n.workflow.envAllow}),r=gn(t.after??e.after);return r?{paused:!0,pausedAt:{kind:"timerWait",nodeId:n.node.id,fireAt:r}}:{error:`timer.boundary "${n.node.id}" needs config.after (duration or minutes)`}},bn=async()=>({output:{}}),vn=async n=>{let e=n.node.config,r=(Array.isArray(e.inputs)?e.inputs:[]).map(s=>typeof s=="string"?S(s,n.run.context,{envAllow:n.workflow.envAllow}):s),o=Array.isArray(e.rules)?e.rules:[];for(let s of o){let a=Array.isArray(s.when)?s.when:[];if(a.length!==r.length)continue;let d=!0;for(let u=0;u<a.length;u++)if(!In(a[u],r[u])){d=!1;break}if(d)return{output:{...s.output??{},matchedPort:s.to??""},port:s.to}}let i=e.default;return{output:{...i?.output??{},matchedPort:i?.to??""},port:i?.to}};function In(n,e){if(n==null||n==="*")return!0;let t=String(n),r=typeof e=="number"?e:String(e??""),o=/^(>=|<=|>|<)\s*(-?\d+(?:\.\d+)?)$/.exec(t);if(o){let i=o[1],s=Number(o[2]),a=typeof r=="number"?r:Number(r);if(Number.isNaN(a))return!1;switch(i){case">":return a>s;case"<":return a<s;case">=":return a>=s;case"<=":return a<=s}}if(t.startsWith("!="))return String(r)!==t.slice(2);if(t.startsWith("/")&&t.endsWith("/")&&t.length>2)try{return new RegExp(t.slice(1,-1)).test(String(r))}catch{return!1}return String(r)===t}var Xe={"trigger.channel":F,"trigger.manual":F,"trigger.cron":F,"trigger.hook":F,"trigger.form":hn,agent:Qt,classify:Ze,branch:Xt,transform:fn,"gateway.parallel":bn,rule:vn,"action.send":en,"action.createIssue":tn,"action.setLabel":on,"action.readLabel":sn,"action.react":an,"action.editMessage":dn,"action.logTime":un,"action.callHTTP":ln,"action.run":cn,"action.builtin":pn,subProcess:mn,"signal.emit":wn,"signal.wait":yn,"timer.boundary":kn,checkpoint:rn,end:nn};function ge(n){return Xe[n]}function me(n,e){if(typeof e=="string"&&e)return e;let t=n.workflow.nodes.find(i=>i.type.startsWith("trigger."));if(!t)return;let o=n.run.context[t.id]?.accountId;return typeof o=="string"&&o?o:void 0}function he(n){for(let e=n.run.history.length-1;e>=0;e--){let t=n.run.history[e],r=n.workflow.nodes.find(o=>o.id===t.nodeId);if(r?.type==="agent")return r.config.agentId??void 0}}function et(n){if(!n)return{};let e=n.match(/\bRESULT:\s*([a-z][a-z0-9_-]*)/i);if(e)return{result:e[1].toLowerCase()};let t=n.match(/\[(APPROVED|REJECTED|CHANGES[-_]REQUESTED|DONE|FAILED|SKIPPED)\]/i);return t?{result:t[1].toLowerCase().replace("_","-")}:{}}function Sn(n){let{result:e}=et(n);if(!n)return{result:e};let t=n.match(/```(?:json)?\s*([\s\S]*?)```/);if(!t)return{result:e};try{return{result:e,json:JSON.parse(t[1])}}catch{return{result:e}}}var C=class{handlers=new Set;subscribe(e){return this.handlers.add(e),()=>this.handlers.delete(e)}emit(e){for(let t of this.handlers)try{Promise.resolve(t(e)).catch(()=>{})}catch{}}};function G(n,e){if(n.name!==e.name||n.scope==="workflow"&&n.workflowId!==e.workflowId)return!1;for(let[t,r]of Object.entries(n.match??{}))if(!(r===void 0||r===""||r==="*")&&e.payload[t]!==r)return!1;return!0}function An(n,e,t=Date.now){return{ts:t(),source:"workflow",sourceEventId:`${n.workflowId}:${n.eventId}`,project:n.project,subject:`workflow:${n.workflowId}:entity:${n.entityRef.backend}:${n.entityRef.id}`,intent:`workflow.${n.triggerSource}`,rawJson:e}}function Rn(n){return n.claimed&&n.runId?{agentId:`workflow-run:${n.runId}`,outcome:"dispatched",reason:n.reason??"claimed"}:n.claimed&&!n.runId?{agentId:null,outcome:"halted",reason:n.reason??"claimed-but-no-run"}:{agentId:null,outcome:"halted",reason:n.reason??"not-claimed"}}function $n(n){return{decidedBy:"workflow-dispatcher",decide:()=>({agentId:n.agentId,outcome:n.outcome==="deduped"?"halted":n.outcome,reason:n.outcome==="deduped"?`legacy-dedup: ${n.reason??""}`.trim():n.reason??null})}}function tt(n,e,t,r,o=Date.now){let i=An(e,t,o),s=Rn(r),a=$n(s),d=Ae(n,i,a,o);return Re(n,"workflow",d,s,o),d}var Pn=4e3,Tn=8,we=class{store;runs;nodeId;forwarder;channels;agents;log;timers;signals;events;ackTypingTimers=new Map;commitChains=new Map;constructor(e){this.store=e.store,this.runs=e.runs,this.nodeId=e.nodeId,this.forwarder=e.forwarder,this.channels=e.channels,this.agents=e.agents,this.log=e.log??(()=>{}),this.timers=e.timers??new te({log:t=>this.log(t)}),this.signals=e.signals??new C,this.events=e.events,this.timers.onFire(t=>this.resumeFromTimer(t)),this.signals.subscribe(t=>this.resumeFromSignal(t))}emitRunEvent(e){if(this.events)try{this.events.publish({kind:"run",runId:e.runId,workflowId:e.workflowId,nodeId:e.nodeId,phase:e.phase,status:e.status,note:e.note,homeNode:e.homeNode})}catch{}}async commit(e,t){let o=(this.commitChains.get(e)??Promise.resolve()).then(()=>t(),()=>t());return this.commitChains.set(e,o.then(()=>{},()=>{})),o}emitSignal(e){let t={name:e.name,scope:e.scope??"global",workflowId:e.workflowId??"",payload:e.payload??{},emittedAt:new Date().toISOString()};if(this.signals.emit(t),this.events)try{this.events.publish({kind:"signal",name:t.name,scope:t.scope,workflowId:t.workflowId||void 0,payload:t.payload})}catch{}return t}async resumeFromSignal(e){let t=this.runs.list({limit:500});for(let r of t){if(r.status!=="paused"||!r.pausedAt||r.pausedAt.kind!=="signalWait")continue;let o={name:r.pausedAt.signalName,scope:r.pausedAt.scope,workflowId:r.workflowId,match:r.pausedAt.match??{}};if(!G(o,e))continue;let i=this.store.list().find(s=>s.id===r.workflowId);i&&(await this.commit(r.id,()=>{let s=this.runs.get(r.id);if(!s||s.status!=="paused"||!s.pausedAt||s.pausedAt.kind!=="signalWait"||!G({name:s.pausedAt.signalName,scope:s.pausedAt.scope,workflowId:s.workflowId,match:s.pausedAt.match??{}},e))return;let a=x(i,s.pausedAt.nodeId),d=a?i.edges.filter(c=>c.from===a.id).map(c=>c.to):[],u={receivedAt:new Date().toISOString(),name:e.name,payload:e.payload};this.runs.recordExecution({runId:s.id,entry:{at:u.receivedAt,nodeId:s.pausedAt.nodeId,inputKeys:[],status:"resumed",output:u,idempotencyKey:N(s.id,s.pausedAt.nodeId,`signal:${e.name}:${e.emittedAt}`)},nextPending:d,status:"running",pausedAt:null,context:{...s.context,[s.pausedAt.nodeId]:u}}),this.log(`[workflow:${i.id}] run ${s.id} resumed from signal "${e.name}"`),this.emitRunEvent({runId:s.id,workflowId:i.id,nodeId:s.pausedAt.nodeId,phase:"resumed",status:"running",note:`signal:${e.name}`})}),this.walk(i,r.id,`signal:${e.name}`).catch(s=>this.log(`[workflow:${i.id}] walk-after-signal failed: ${s.message}`)))}}async resumeFromTimer(e){let t=this.store.list().find(r=>r.id===(this.runs.get(e.runId)?.workflowId??""));t&&(await this.commit(e.runId,()=>{let r=this.runs.get(e.runId);if(!r||r.status!=="paused"||!r.pausedAt||r.pausedAt.kind!=="timerWait"||r.pausedAt.nodeId!==e.nodeId)return;let o=x(t,e.nodeId),i=o?t.edges.filter(d=>d.from===o.id).map(d=>d.to):[],s=new Date().toISOString(),a={firedAt:s,scheduledFor:e.fireAt};this.runs.recordExecution({runId:r.id,entry:{at:s,nodeId:e.nodeId,inputKeys:[],status:"resumed",output:a,idempotencyKey:N(r.id,e.nodeId,`timer:${e.id}`)},nextPending:i,status:"running",pausedAt:null,context:{...r.context,[e.nodeId]:a}}),this.log(`[workflow:${t.id}] run ${r.id} resumed from timer "${e.nodeId}" (fired ${s})`),this.emitRunEvent({runId:r.id,workflowId:t.id,nodeId:e.nodeId,phase:"resumed",status:"running",note:`timer:${e.id}`})}),this.walk(t,e.runId,`timer:${e.id}`).catch(r=>this.log(`[workflow:${t.id}] walk-after-timer failed: ${r.message}`)))}async dispatchWorkflow(e){let t=this.store.list().find(s=>s.id===e.workflowId);if(!t)return this.log(`[workflows] dispatchWorkflow: workflow "${e.workflowId}" not found`),{claimed:!1,run:null};let o=t.nodes.find(s=>s.type.startsWith("trigger."))?.config??{},i={source:e.trigger?.source??o.source??"hook",project:e.trigger?.project,repo:e.trigger?.repo,chat:e.trigger?.chat,labels:e.trigger?.labels};return this.dispatchOne(t,e.entityRef,e.event,i)}startChannelAck(e,t){let r=String(t.channel??""),o=String(t.chatId??"");if(!r||!o)return;let i=this.channels[r];if(!i)return;let s=typeof t.accountId=="string"?t.accountId:void 0,a=t.event,d=typeof a?.id=="string"?a.id:a?.id!=null?String(a.id):void 0;if(d&&i.react)try{Promise.resolve(i.react(o,d,"\u{1F440}",s)).catch(()=>{})}catch{}if(this.ackTypingTimers.has(e)||!i.sendTyping)return;let u=()=>{try{Promise.resolve(i.sendTyping(o,s)).catch(()=>{})}catch{}};u();let c=setInterval(u,Pn);this.ackTypingTimers.set(e,c)}stopChannelAck(e){let t=this.ackTypingTimers.get(e);t&&(clearInterval(t),this.ackTypingTimers.delete(e))}async dispatch(e){let t=this.matchByTrigger(e.trigger,e.fromRemote),o=t.some(a=>a.fanOut)?t:t.slice(0,1),i=[],s=[];for(let a of o){let d=await this.dispatchOne(a,e.entityRef,e.event,e.trigger);d.claimed&&i.push(a),d.run&&s.push(d.run)}return!e.fromRemote&&this.forwarder?.broadcastTrigger&&Promise.resolve(this.forwarder.broadcastTrigger({trigger:e.trigger,entityRef:e.entityRef,event:e.event})).catch(a=>this.log(`[mesh-broadcast] ${a?.message??a}`)),{claimed:i,runs:s}}matchByTrigger(e,t){let r=this.store.list(),o=[];for(let i of r){if(i.state&&i.state!=="active")continue;if(t){if(!i.mesh?.allowRemote)continue;let u=i.mesh.peers;if(u&&u.length>0&&!u.includes(t.peer))continue}let s=i.nodes.find(u=>u.type.startsWith("trigger."));if(!s)continue;let a=s.config;if(a.source!==e.source||i.project&&e.project&&i.project!==e.project)continue;let d=a.filter;if(d){if(d.project&&d.project!=="*"&&d.project!==e.project||d.repo&&d.repo!=="*"&&d.repo!==e.repo||d.chat&&d.chat!=="*"&&V(e.source,d.chat)!==V(e.source,e.chat))continue;if(d.labels?.length){let u=new Set(e.labels??[]);if(!d.labels.some(p=>u.has(p)))continue}}o.push(i)}return o.sort((i,s)=>s.priority-i.priority||i.id.localeCompare(s.id))}async dispatchOne(e,t,r,o){let i=await this.dispatchOneLegacy(e,t,r,o);if(Se("workflow")!=="off")try{tt(Ie(),{workflowId:e.id,eventId:r.id,triggerSource:o.source,project:o.project??null,entityRef:t},JSON.stringify({event:r,trigger:o,entityRef:t}),{claimed:i.claimed,runId:i.run?.id??null})}catch(s){this.log(`[ledger] workflow ${e.id} run ${i.run?.id??"?"} record failed: ${s?.message??s}`)}return i}async dispatchOneLegacy(e,t,r,o){let i=this.runs.getActiveByEntity(t),s=i?this.runs.getHomeNodeByEntity(t):null;if(i&&s&&s!==this.nodeId){if(!this.forwarder)return this.log(`[workflow:${e.id}] run ${i} home'd on "${s}" but no forwarder \u2014 dropping`),{claimed:!1,run:null};try{await this.forwarder.forwardTransition(s,{workflowId:e.id,event:r,entityRef:t})}catch(d){this.log(`[workflow:${e.id}] forward to "${s}" failed: ${d.message}`)}return{claimed:!0,run:null}}let a=i?this.runs.get(i):null;if(a)if(a.status==="paused"&&a.pausedAt){if(a.pausedAt.kind!=="checkpoint")return this.log(`[workflow:${e.id}] run ${a.id} paused on ${a.pausedAt.kind} \u2014 channel event bypasses workflow`),{claimed:!1,run:null};if(!xn(a.pausedAt.resumeMatch,o,r))return this.log(`[workflow:${e.id}] run ${a.id} paused but event doesn't match resumeMatch \u2014 dropping`),{claimed:!1,run:null};let d=x(e,a.pausedAt.nodeId),u=d?e.edges.filter(h=>h.from===d.id).map(h=>h.to):[],c={at:new Date().toISOString(),nodeId:a.pausedAt.nodeId,inputKeys:[],status:"resumed",output:{event:r.payload},idempotencyKey:N(a.id,a.pausedAt.nodeId,`resume:${r.id}`)},p={...a.context,[a.pausedAt.nodeId]:{event:r.payload}},f=a.pausedAt.checkpointName,m=this.runs.recordExecution({runId:a.id,entry:c,nextPending:u,status:"running",pausedAt:null,context:p});m&&(a=m),this.log(`[workflow:${e.id}] run ${a.id} resumed from checkpoint "${f}"`),o.source.endsWith("-message")&&this.startChannelAck(a.id,r.payload)}else return a.status==="running"?(this.log(`[workflow:${e.id}] run ${a.id} already running; dropping concurrent event ${r.id}`),{claimed:!0,run:null}):(this.log(`[workflow:${e.id}] run ${a.id} is ${a.status}; dropping event ${r.id}`),{claimed:!1,run:null});else{let d=q(e);if(!d)return this.log(`[workflow:${e.id}] no trigger node found`),{claimed:!1,run:null};a=this.runs.create({workflowId:e.id,initialPending:d.pending,entityRef:t,initialContext:{[d.triggerId]:r.payload}}),this.log(`[workflow:${e.id}] run ${a.id} created from trigger "${d.triggerId}" for ${t.id}`),this.emitRunEvent({runId:a.id,workflowId:e.id,phase:"created",status:a.status,homeNode:a.homeNode}),o.source.endsWith("-message")&&this.startChannelAck(a.id,r.payload)}return this.walk(e,a.id,r.id),{claimed:!0,run:a}}async walk(e,t,r){try{await this.walkInner(e,t,r)}finally{this.stopChannelAck(t)}}async walkInner(e,t,r){let o=this.runs.get(t);if(o)for(;o.status==="running"&&o.pending.length>0;){let i=o.pending.slice(0,Tn);await Promise.allSettled(i.map(a=>this.executeNodeAndCommit(e,t,a,r)));let s=this.runs.get(t);if(!s||(o=s,o.status!=="running"))return}}async executeNodeAndCommit(e,t,r,o){let i=N(t,r,o),s=await this.commit(t,()=>{let g=this.runs.get(t);if(!g)return{kind:"done"};if(g.status!=="running")return{kind:"done"};let y=x(e,r);if(!y)return this.log(`[workflow:${e.id}] missing node "${r}" \u2014 marking run failed`),this.runs.recordExecution({runId:t,entry:{at:new Date().toISOString(),nodeId:r,inputKeys:[],status:"failed",idempotencyKey:i,note:"node definition missing from workflow"},nextPending:g.pending.filter(A=>A!==r),status:"failed"}),{kind:"done"};let w=ge(y.type);return w?g.history.some(A=>A.idempotencyKey===i)?(this.runs.recordExecution({runId:t,entry:{at:new Date().toISOString(),nodeId:r,inputKeys:[],status:"skipped",idempotencyKey:i+"_dedup",note:"duplicate execution dropped"},nextPending:g.pending.filter(A=>A!==r)}),{kind:"done"}):{kind:"go",run:g,node:y,handler:w}:(this.log(`[workflow:${e.id}] no handler for node type "${y.type}"`),this.runs.recordExecution({runId:t,entry:{at:new Date().toISOString(),nodeId:r,inputKeys:[],status:"failed",idempotencyKey:i,note:`no handler for node type "${y.type}"`},nextPending:g.pending.filter(A=>A!==r),status:"failed"}),{kind:"done"})});if(s.kind==="done")return;let{run:a,node:d,handler:u}=s,c=e.edges.filter(g=>g.to===r).map(g=>g.from),p;if(d.type!=="agent"){let g=ee();if(g)try{p=$e(g,{agentId:`workflow:${d.type}`,channel:"workflow",chatId:`${e.id}:${r}`,workflowRunId:t,workflowId:e.id,workflowNodeId:r,messagePreview:`${d.type} ${r}`})}catch{}}let f=d.retry??{maxAttempts:1,backoffMs:1e3},m={error:"retry-loop did not run"},h=0;for(;h<f.maxAttempts;){h++;try{m=await u({workflow:e,run:a,node:d,channels:this.channels,agents:this.agents,forwardChannelSend:this.forwarder?.forwardChannelSend?.bind(this.forwarder),log:this.log})}catch(g){this.log(`[workflow:${e.id}] handler "${d.type}" threw: ${g.message}`),m={error:g.message}}if(!m.error||m.paused)break;if(h<f.maxAttempts){let g=f.backoffMs*Math.pow(2,h-1);this.log(`[workflow:${e.id}] node "${r}" failed (attempt ${h}/${f.maxAttempts}): ${m.error.slice(0,120)} \u2014 retrying in ${g}ms`),await new Promise(y=>setTimeout(y,g))}}if(p){let g=ee();if(g)try{Pe(g,p,{status:m.error?"error":"ok",error:m.error??null})}catch{}}await this.commit(t,async()=>{let g=this.runs.get(t);if(!g)return;let y=new Date().toISOString(),w=g.pending.filter(k=>k!==r);if(m.error){let k=g.status==="running"?"failed":void 0;this.runs.recordExecution({runId:t,entry:{at:y,nodeId:r,inputKeys:c,status:"failed",idempotencyKey:i,note:m.error.slice(0,200)},nextPending:w,status:k}),this.emitRunEvent({runId:t,workflowId:e.id,nodeId:r,phase:"failed",status:k??g.status,note:m.error.slice(0,200)});return}if(m.paused&&m.pausedAt){let k=m.pausedAt,T=null;if(m.spawnChild&&k.kind==="subProcess"){if(T=await this.spawnChild({parent:g,parentNodeId:r,childWorkflowId:m.spawnChild.workflowId,input:m.spawnChild.input}),!T){this.runs.recordExecution({runId:t,entry:{at:y,nodeId:r,inputKeys:c,status:"failed",idempotencyKey:i,note:`subProcess: child workflow "${m.spawnChild.workflowId}" not found`},nextPending:w,status:"failed"});return}k={...k,childRunId:T.id}}if(this.runs.recordExecution({runId:t,entry:{at:y,nodeId:r,inputKeys:c,status:"paused",idempotencyKey:i},nextPending:w,status:"paused",pausedAt:k}),this.emitRunEvent({runId:t,workflowId:e.id,nodeId:r,phase:"paused",status:"paused",note:k.kind}),T&&this.kickChildWalk(T),k.kind==="timerWait")try{this.timers.schedule({runId:t,workflowId:e.id,nodeId:k.nodeId,fireAt:k.fireAt,cancelKey:`${t}:${k.nodeId}`})}catch(ke){this.log(`[workflow:${e.id}] timer schedule failed: ${ke.message}`)}return}let A=m.output??{},at={...g.context,[r]:A},{nextPending:dt}=ce({workflow:e,fromNodeId:r,selectedPort:m.port}),X=[],D={...g.joinCounters??{}};for(let k of dt){let T=x(e,k);if(!(T?.type==="gateway.parallel"&&String(T.config?.mode??"fanOut")==="join")){X.push(k);continue}let _=D[k]??[];_.includes(r)||_.push(r),D[k]=_;let ct=e.edges.filter(pt=>pt.to===k).length;_.length>=ct&&(X.push(k),delete D[k])}let ut=[...w,...X],M=d.type==="end",lt=g.status==="running"?M?String(d.config.status??"completed"):"running":void 0,W=this.runs.recordExecution({runId:t,entry:{at:y,nodeId:r,inputKeys:c,status:"ok",output:A,idempotencyKey:i},nextPending:M?[]:ut,status:lt,context:at,joinCounters:D});this.emitRunEvent({runId:t,workflowId:e.id,nodeId:r,phase:M?"completed":"ok",status:W?.status??g.status}),m.emitSignal&&this.emitSignal({name:m.emitSignal.name,scope:m.emitSignal.scope,workflowId:e.id,payload:m.emitSignal.payload}),M&&W&&W.parentRunId&&W.parentNodeId&&this.resumeParent({parentRunId:W.parentRunId,parentNodeId:W.parentNodeId,childRun:W}).catch(k=>this.log(`[workflow:${e.id}] resumeParent failed: ${k.message}`))})}async spawnChild(e){let t=this.store.list().find(a=>a.id===e.childWorkflowId);if(!t)return null;let r=q(t);if(!r)return this.log(`[workflow:${t.id}] no trigger node \u2014 cannot spawn as child`),null;let o={...e.input};o[r.triggerId]={...o[r.triggerId]??{},parentRunId:e.parent.id,parentNodeId:e.parentNodeId};let i={backend:"agentx-internal",id:`subprocess:${e.parent.id}:${e.parentNodeId}`},s=this.runs.create({workflowId:t.id,initialPending:r.pending,entityRef:i,initialContext:o,parentRunId:e.parent.id,parentNodeId:e.parentNodeId,rootRunId:e.parent.rootRunId??e.parent.id,depth:(e.parent.depth??0)+1});return this.log(`[workflow:${t.id}] child run ${s.id} spawned from ${e.parent.id}/${e.parentNodeId} (depth ${s.depth})`),s}kickChildWalk(e){let t=this.store.list().find(r=>r.id===e.workflowId);t&&this.walk(t,e.id,`spawn:${e.parentRunId}:${e.parentNodeId}`).catch(r=>this.log(`[workflow:${t.id}] child walk failed: ${r.message}`))}async resumeParent(e){let t=this.runs.get(e.parentRunId);if(!t)return;let r=this.store.list().find(o=>o.id===t.workflowId);r&&(await this.commit(e.parentRunId,()=>{let o=this.runs.get(e.parentRunId);if(!o||o.status!=="paused"||!o.pausedAt||o.pausedAt.kind!=="subProcess"||o.pausedAt.nodeId!==e.parentNodeId||o.pausedAt.childRunId!==e.childRun.id)return;let i=x(r,e.parentNodeId),s=i?r.edges.filter(d=>d.from===i.id).map(d=>d.to):[],a={childRunId:e.childRun.id,status:e.childRun.status,output:Nn(e.childRun)};this.runs.recordExecution({runId:o.id,entry:{at:new Date().toISOString(),nodeId:e.parentNodeId,inputKeys:[],status:"resumed",output:a,idempotencyKey:N(o.id,e.parentNodeId,`child:${e.childRun.id}`)},nextPending:s,status:"running",pausedAt:null,context:{...o.context,[e.parentNodeId]:a}}),this.log(`[workflow:${r.id}] parent run ${o.id} resumed from subProcess child ${e.childRun.id}`),this.emitRunEvent({runId:o.id,workflowId:r.id,nodeId:e.parentNodeId,phase:"resumed",status:"running",note:`child:${e.childRun.id}`})}),this.walk(r,e.parentRunId,`child:${e.childRun.id}`))}};function Nn(n){for(let e=n.history.length-1;e>=0;e--){let t=n.history[e];if(t.status==="ok"&&t.output&&Object.keys(t.output).length>0)return t.output}return{}}function xn(n,e,t){let r=i=>{let s=n[i];if(s===void 0||s===""||s==="*")return!0;if(Array.isArray(s)){let a=new Set(e.labels??[]);return s.some(d=>a.has(String(d)))}return i==="chat"?V(e.source,String(s))===V(e.source,e.chat):e[i]===s};if(!r("source")||!r("project")||!r("repo")||!r("chat"))return!1;let o=n.eventIdLike;return!(typeof o=="string"&&o&&!t.id.includes(o))}function V(n,e){return e==null?"":n==="whatsapp-message"?e.replace(/@s\.whatsapp\.net$|@g\.us$/i,"").replace(/[\s+()]/g,""):e}function Wn(n){return{"pre:channel-message":async e=>{let t=e.msg;if(!t)return{};let r=On(t.channel);if(!r)return{};let o=t.group?.id??t.sender.id,i={backend:t.channel,id:`${t.channel}:${o}`},{claimed:s}=await n.dispatch({trigger:{source:r,chat:o},entityRef:i,event:{id:`${t.channel}:${t.accountId}:${t.id}`,payload:En(t)}});return s.length===0?{}:s.every(d=>d.nodes.find(c=>c.type.startsWith("trigger."))?.config?.passthrough===!0)?{}:{blocked:!0,message:`handled by workflow${s.length>1?"s":""}: ${s.map(d=>d.id).join(", ")}`}},"on:gitlab-issue":async e=>{let t=e.project,r=e.iid,o=e.issueEvent;if(!t||r===void 0)return{};let i=Array.isArray(o?.object_attributes?.labels)?o.object_attributes.labels.map(d=>typeof d=="string"?d:d?.title).filter(Boolean):o?.labels?.map(d=>d?.title)??[],s=o?.assignees??o?.object_attributes?.assignee_ids??[],a={backend:"gitlab",id:`${t}#${r}`};return await n.dispatch({trigger:{source:"gitlab-issue",project:t,labels:i},entityRef:a,event:{id:`gitlab-issue:${t}:${r}:${o?.object_attributes?.updated_at||o?.object_attributes?.action||"evt"}`,payload:{issue:{iid:r,title:o?.object_attributes?.title,description:o?.object_attributes?.description,url:o?.object_attributes?.url,action:o?.object_attributes?.action,labels:i,assignees:s},project:t,channel:"gitlab",chatId:`${t}:issue:${r}`}}}),{}},"on:gitlab-mr":async e=>{let t=e.project,r=e.iid,o=e.mrEvent;if(!t||r===void 0)return{};let i=Array.isArray(e.labels)?e.labels:Array.isArray(o?.object_attributes?.labels)?o.object_attributes.labels.map(u=>typeof u=="string"?u:u?.title).filter(Boolean):[],s=o?.assignees??o?.object_attributes?.assignee_ids??[],a=o?.reviewers??[],d={backend:"gitlab",id:`${t}!${r}`};return await n.dispatch({trigger:{source:"gitlab-mr",project:t,labels:i},entityRef:d,event:{id:`gitlab-mr:${t}:${r}:${o?.object_attributes?.updated_at||o?.object_attributes?.action||"evt"}`,payload:{mr:{iid:r,title:e.title,description:e.description,url:e.url,action:e.action,state:e.state,source_branch:e.source_branch,target_branch:e.target_branch,labels:i,assignees:s,reviewers:a},project:t,channel:"gitlab",chatId:`${t}:merge_request:${r}`,iid:r,title:e.title,description:e.description,url:e.url,action:e.action,state:e.state,source_branch:e.source_branch,target_branch:e.target_branch,labels:i}}}),{}},"on:gitlab-note":async e=>{let t=e.project,r=e.noteId,o=e.noteableType,i=e.noteableIid,s=e.text,a=e.authorUsername,d=e.mentions??[];if(!t||!r||!o||!i)return{};let u=o==="merge_request"?{backend:"gitlab",id:`${t}!${i}`}:{backend:"gitlab",id:`${t}#${i}`};return await n.dispatch({trigger:{source:"gitlab-note",project:t},entityRef:u,event:{id:`gitlab-note:${t}:${o}:${i}:${r}`,payload:{note:{id:r,text:s,author:a,mentions:d,noteableType:o,noteableIid:i,noteableTitle:e.noteableTitle},project:t,channel:"gitlab",chatId:`${t}:${o}:${i}`,noteId:r,noteableType:o,noteableIid:i,text:s,author:a,mentions:d}}}),{}},"on:gitlab-pipeline":async e=>{let t=e.project,r=e.pipelineId,o=e.status,i=e.ref;if(!t||!o)return{};let a=e.raw?.merge_request?.iid;if(!a)return{};let d={backend:"gitlab",id:`${t}!${a}`};return await n.dispatch({trigger:{source:"gitlab-pipeline",project:t},entityRef:d,event:{id:`gitlab-pipeline:${t}:${r}:${o}`,payload:{pipeline:{id:r,status:o,ref:i},project:t,channel:"gitlab",chatId:`${t}:merge_request:${a}`}}}),{}}}}function On(n){switch(n){case"telegram":return"telegram-message";case"whatsapp":return"whatsapp-message";case"discord":return"discord-message";case"slack":return"slack-message";default:return null}}function En(n){let e=n.group?.id??n.sender.id;return{channel:n.channel,chatId:e,accountId:n.accountId,text:n.text,fromJid:n.sender.id,sender:{id:n.sender.id,name:n.sender.name,username:n.sender.username},contact:n.channelMeta?.facts?{facts:n.channelMeta.facts}:void 0,group:n.group?{id:n.group.id,name:n.group.name}:void 0,channelMeta:n.channelMeta,replyTo:n.replyTo,replyToText:n.replyToText,media:n.media,event:{id:n.id,timestamp:n.timestamp?.toISOString?.()??new Date().toISOString()}}}var Z=n=>n.trim().toLowerCase().replace(/^@/,"");function jn(n){let e=typeof n.author=="string"?n.author:typeof n.authorUsername=="string"?n.authorUsername:void 0;if(e)return Z(e);let r=n.payload?.sender?.login;return typeof r=="string"&&r?Z(r):void 0}function Fn(n,e){let t=typeof e.project=="string"?e.project:"";if(n==="on:gitlab-issue"||n==="on:gitlab-mr")return!t||e.iid==null?void 0:`gitlab:${t}${n==="on:gitlab-issue"?"#":"!"}${String(e.iid)}`;if(n==="on:gitlab-note"){let r=e.noteableIid!=null?String(e.noteableIid):"",o=typeof e.noteableType=="string"?e.noteableType:"";return!t||!r||!o?void 0:`gitlab:${t}${o==="issue"?"#":"!"}${r}`}if(n==="on:github-issue"||n==="on:github-pr"){let r=e.payload??{},o=typeof e.repo=="string"?e.repo:r.repository?.full_name,i=e.number??r.issue?.number??r.pull_request?.number;return typeof o!="string"||!o||i==null?void 0:`github:${o}#${String(i)}`}}function Cn(n){let e=new Set;for(let t of n.nodes){let r=t.type==="agent"?t.config.agentId:void 0;typeof r=="string"&&r&&e.add(r)}return[...e]}var Q=class{constructor(e=2e3){this.maxKeys=e}fires=new Map;tryFire(e,t,r,o=Date.now()){let i=(this.fires.get(e)??[]).filter(s=>o-s<r);if(i.length>=t)return this.fires.set(e,i),!1;for(i.push(o),this.fires.delete(e),this.fires.set(e,i);this.fires.size>this.maxKeys;){let s=this.fires.keys().next().value;if(s===void 0)break;this.fires.delete(s)}return!0}get size(){return this.fires.size}};function ye(n,e,t){let r=n.logged??(n.logged=new Set);r.has(e)||(r.add(e),n.log(t))}function nt(n,e,t,r,o){let i=jn(t);if(i&&Array.isArray(r?.ignoreAuthors)&&r.ignoreAuthors.length>0&&r.ignoreAuthors.map(Z).includes(i))return{skip:!0,reason:"ignored-author",detail:`author @${i} is in filter.ignoreAuthors`};if(r?.skipSelfAuthored===!0){let a=Cn(n),d=typeof t.authorAgent=="string"?t.authorAgent:void 0;if(d&&a.includes(d))return{skip:!0,reason:"self-authored",detail:`author @${i??"?"} is agent "${d}" which this workflow runs`};if(i){let u=new Set(a.flatMap(c=>(o.forgeUsernames?.(c)??[]).map(Z)));if(u.has(i))return{skip:!0,reason:"self-authored",detail:`author @${i} is this workflow's own bot identity`};a.length===0?ye(o,`noagents:${n.id}`,`[workflows] ${n.id} has no agent node \u2014 self-authored skip can't resolve a bot identity; only filter.ignoreAuthors applies`):u.size===0&&!("authorAgent"in t)&&ye(o,`noident:${n.id}:${e}`,`[workflows] ${n.id} no forge username known for agent(s) ${a.join(", ")} on ${e} \u2014 self-authored skip inactive; only filter.ignoreAuthors applies`)}}let s=r?.maxFiresPerTarget;if(s&&typeof s.count=="number"&&s.count>0){let a=Fn(e,t);if(a){let d=typeof s.windowMinutes=="number"&&s.windowMinutes>0?s.windowMinutes:60,u=o.now?.()??Date.now();if(!o.fireWindow.tryFire(`${n.id}|${a}`,s.count,d*6e4,u))return{skip:!0,reason:"chain-limit",detail:`${a} already fired ${s.count}x within ${d}m (filter.maxFiresPerTarget)`}}else ye(o,`notarget:${n.id}:${e}`,`[workflows] ${n.id} filter.maxFiresPerTarget has no target key for ${e} \u2014 limit not applied`)}return{skip:!1}}function Dn(n){let e=n.store.list(),t={fireWindow:new Q,log:n.log,forgeUsernames:n.forgeUsernames,logged:new Set},r=0,o=0;for(let i of e){if(i.state&&i.state!=="active"){n.log(`[workflows] ${i.id} state=${i.state} \u2014 skipping trigger registration`);continue}let s=i.nodes.find(a=>a.type.startsWith("trigger."));if(s){if(s.type==="trigger.cron"){let a=s.config;if(!a.spec){n.log(`[workflows] ${i.id} trigger.cron missing config.spec \u2014 skipping`);continue}_n({workflowId:i.id,triggerNodeId:s.id,spec:a.spec,timezone:a.timezone??"UTC"},n.dispatcher,n.log),r++}else if(s.type==="trigger.hook"){let a=s.config;if(!a.event||!a.event.startsWith("on:")){n.log(`[workflows] ${i.id} trigger.hook config.event must start with "on:" \u2014 skipping`);continue}n.hooks.registerHandler(a.event,`workflows:${i.id}`,async d=>{try{let u=typeof d.project=="string"?d.project:void 0;if(i.project&&u&&i.project!==u)return{};if(a.filter){if(Array.isArray(a.filter.topic)&&a.filter.topic.length>0){let h=typeof d.topic=="string"?d.topic.toLowerCase():void 0;if(!h||!a.filter.topic.map(g=>g.toLowerCase()).includes(h))return{}}if(Array.isArray(a.filter.action)&&a.filter.action.length>0){let h=typeof d.action=="string"?d.action:void 0;if(!h||!a.filter.action.includes(h))return{}}if(Array.isArray(a.filter.mentions)&&a.filter.mentions.length>0){let h=Array.isArray(d.mentions)?d.mentions.map(w=>w.toLowerCase().replace(/^@/,"")):[];if(!a.filter.mentions.map(w=>w.toLowerCase().replace(/^@/,"")).some(w=>h.includes(w)))return{}}if(Array.isArray(a.filter.noteableType)&&a.filter.noteableType.length>0){let h=typeof d.noteableType=="string"?d.noteableType.toLowerCase():void 0,g=a.filter.noteableType.map(y=>y.toLowerCase());if(!h||!g.includes(h))return{}}if(Array.isArray(a.filter.assigneesAdded)&&a.filter.assigneesAdded.length>0){let h=Array.isArray(d.assigneesAdded)?d.assigneesAdded.map(w=>w.toLowerCase().replace(/^@/,"")):[];if(!a.filter.assigneesAdded.map(w=>w.toLowerCase().replace(/^@/,"")).some(w=>h.includes(w)))return{}}if(Array.isArray(a.filter.reviewersAdded)&&a.filter.reviewersAdded.length>0){let h=Array.isArray(d.reviewersAdded)?d.reviewersAdded.map(w=>w.toLowerCase().replace(/^@/,"")):[];if(!a.filter.reviewersAdded.map(w=>w.toLowerCase().replace(/^@/,"")).some(w=>h.includes(w)))return{}}if(Array.isArray(a.filter.labelsAdded)&&a.filter.labelsAdded.length>0){let h=Array.isArray(d.labelsAdded)?d.labelsAdded.map(w=>w.toLowerCase()):[];if(!a.filter.labelsAdded.map(w=>w.toLowerCase()).some(w=>h.includes(w)))return{}}}let c=nt(i,a.event,d,a.filter,t);if(c.skip){if(n.log(`[workflows] ${i.id} skipping ${a.event} (${c.reason}): ${c.detail}`),a.passthrough)return{};let h=d.__workflowClaimed;return{modified:{__workflowClaimed:[...Array.isArray(h)?h:[],i.id]}}}let p=Mn(i.id,a.event,d);if(await n.dispatcher.dispatchWorkflow({workflowId:i.id,entityRef:{backend:"hook",id:p},event:{id:`hook:${a.event}:${Date.now().toString(36)}`,payload:{hookEvent:a.event,...d}}}),a.passthrough)return{};let f=d.__workflowClaimed;return{modified:{__workflowClaimed:[...Array.isArray(f)?f:[],i.id]}}}catch(u){return n.log(`[workflows] ${i.id} hook dispatch failed: ${u.message}`),{}}},60),o++}}}return{cronTimers:r,hookSubscribers:o}}function Mn(n,e,t){let r=typeof t.project=="string"?t.project:"",o=t.iid!=null?String(t.iid):"";if(e==="on:gitlab-issue"&&r&&o)return`${n}:${e}:${r}#${o}`;if(e==="on:gitlab-mr"&&r&&o)return`${n}:${e}:${r}!${o}`;if(e==="on:gitlab-pipeline"&&r){let i=t.pipelineId!=null?String(t.pipelineId):"";if(i)return`${n}:${e}:${r}@pipeline:${i}`}return`${n}:${e}:${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function _n(n,e,t){let r=()=>{let o;try{o=Te(n.spec,new Date,n.timezone)}catch(s){t(`[workflows] ${n.workflowId} cron spec invalid: ${s.message}`);return}let i=Math.max(1e3,o.getTime()-Date.now());setTimeout(()=>{(async()=>{let s=`cron:${n.workflowId}:${o.toISOString()}`;try{await e.dispatchWorkflow({workflowId:n.workflowId,trigger:{source:"cron"},entityRef:{backend:"cron",id:`${n.workflowId}@${o.toISOString()}`},event:{id:s,payload:{now:o.toISOString(),spec:n.spec,workflowId:n.workflowId}}})}catch(a){t(`[workflows] ${n.workflowId} cron dispatch failed: ${a.message}`)}finally{r()}})()},i)};r()}function rt(n){return n.nodes.find(r=>r.type.startsWith("trigger."))?.config?.inputSchema??null}function ot(n,e){if(!n||!e?.properties)return{};let t=n.match(/^([^:]+\/[^:]+):([^:]+):(.+)$/);if(!t)return{};let[,r,o,i]=t,s={};if(e.properties.project&&(s.project=r),o==="push"){let a=i.match(/^refs\/heads\/(.+)$/);a&&e.properties.ref&&(s.ref=a[1])}else{let a=Number(i);Number.isFinite(a)&&(e.properties.id&&(s.id=a),e.properties.iid&&(s.iid=a),e.properties.mrId&&(s.mrId=a),e.properties.issueId&&(s.issueId=a),e.properties.prId&&(s.prId=a))}return s}function it(n,e){if(!n?.properties)return e;let t={...e};for(let[r,o]of Object.entries(n.properties))t[r]===void 0&&o&&"default"in o&&(t[r]=o.default);return t}function st(n,e){return!n?.required||!Array.isArray(n.required)?[]:n.required.filter(t=>{let r=e[t];return r===void 0||r===""||r===null})}function Hn(n,e){let t=rt(n);if(!t?.properties){let d={};for(let[u,c]of Object.entries(e))c!==void 0&&(d[u]=c);return{inputs:d,missing:[],filledFrom:{passthrough:Object.keys(d),chatId:[],defaults:[]}}}let r={};for(let d of["message","agentId","channel","chatId","senderId","senderUsername"])t.properties[d]&&e[d]!==void 0&&(r[d]=e[d]);let o=ot(e.chatId,t),i={...r,...o},s={...i};i=it(t,i);let a=Object.keys(i).filter(d=>s[d]===void 0&&i[d]!==void 0);return{inputs:i,missing:st(t,i),filledFrom:{passthrough:Object.keys(r),chatId:Object.keys(o),defaults:a}}}export{We as a,$ as b,ne as c,v as d,L as e,Ot as f,se as g,de as h,le as i,we as j,Wn as k,Dn as l,Gt as m,Hn as n};
9
- //# sourceMappingURL=chunk-TCJ3SMOF.js.map
9
+ //# sourceMappingURL=chunk-HA6RYFST.js.map